Last active
March 7, 2022 10:13
-
-
Save stellasia/e0a1db3031e5e68a4132b8203f02c207 to your computer and use it in GitHub Desktop.
Cypher Map Projection Example: OGM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"), | |
| ) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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