Skip to content

Instantly share code, notes, and snippets.

@stellasia
Last active March 7, 2022 10:13
Show Gist options
  • Select an option

  • Save stellasia/e0a1db3031e5e68a4132b8203f02c207 to your computer and use it in GitHub Desktop.

Select an option

Save stellasia/e0a1db3031e5e68a4132b8203f02c207 to your computer and use it in GitHub Desktop.
Cypher Map Projection Example: OGM
class Product:
"""The Product object as needed by my application"""
def __init__(self, name: str, price: float, category: str):
self.name = name
self.price = price
self.category_name = category
def __repr__(self):
# string representation for debugging
return f"<Product {self.name=}, {self.price=}, {self.category=}>"
@classmethod
def from_neo4j_record(cls, record):
return cls(
name=record.get("name"),
price=record.get("price"),
category=record.get("category"),
)
from neo4j import GraphDatabase
def get_products(driver, product_ids: list[str]):
query = """
MATCH (p:Product)-[:IS_IN_CATEGORY]->(c:Category)
WHERE p.id IN $ids
RETURN p {.*, category: c.name }
"""
products = []
with driver.session() as s:
result = s.run(query, {ids: product_ids})
for record in result:
product_object = Product.from_neo4j_record(record.get("p"))
products.append(product_object)
return products
if __name__ == '__main__':
uri = "bolt://localhost:7687"
user = "neo4j"
password = "neo4j"
driver = GraphDatabase.driver(uri, auth=(user, password))
product_ids = ["PRODUCT_001", "PRODUCT_005", ]
products = get_products(driver, product_ids)
print(products)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment