Skip to content

Instantly share code, notes, and snippets.

@tmasjc
Created October 4, 2023 08:44
Show Gist options
  • Save tmasjc/141a97fb3640ecd1553c5a95352c3192 to your computer and use it in GitHub Desktop.
Save tmasjc/141a97fb3640ecd1553c5a95352c3192 to your computer and use it in GitHub Desktop.
from getpass import getpass
from pprint import pprint
from neo4j import GraphDatabase
from pymongo import MongoClient
## get data from document database ----
mongodb_password = getpass("Enter Atlas password:")
client = MongoClient(
f"mongodb+srv://admin:{mongodb_password}@serverlessinstance0.9vrdx.mongodb.net"
)
recipes = list(client["testonly"]["recipes"].find())
client.close()
## transform data ----
new_recipes = []
for dish in recipes:
new_recipes.append(
{
"recipe": dish["name"],
"ingredient": dish["ingredients"],
"num_of_ingredients": len(dish["ingredients"]),
"prep_time": dish["prep_time"],
}
)
pprint(new_recipes[0])
URI, AUTH = "neo4j://localhost", ("neo4j", "neo4j")
with GraphDatabase.driver(URI, auth=AUTH) as driver:
try:
for recipe in new_recipes:
records, summary, keys = driver.execute_query(
"""
MERGE (r:Recipe {
name: $recipe.recipe,
no_ingredients: $recipe.num_of_ingredients,
prep_time: $recipe.prep_time
})
WITH r, $recipe.ingredient as ingredients
UNWIND ingredients as ingredient
MERGE (ingr:Ingredient {name: ingredient})
MERGE (r)-[:contains]->(ingr)
""",
recipe=recipe,
database_="neo4j",
)
# summary information
print(f"Returned {summary.counters} for recipe {recipe}")
except Exception as e:
print(e) # further logging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment