使用neo4j实现商品购买python代码实现
时间: 2024-01-01 17:04:07 浏览: 146
好的,下面是一份使用 Neo4j 实现商品购买关系的 Python 代码示例:
```python
from neo4j import GraphDatabase
# 连接到 Neo4j 数据库
uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("username", "password"))
# 创建节点和关系
def create_node(tx, name, label):
tx.run("MERGE (n:%s {name: $name})" % label, name=name)
def create_relationship(tx, name1, name2):
tx.run("MATCH (n1), (n2) WHERE n1.name = $name1 AND n2.name = $name2 CREATE (n1)-[:PURCHASED]->(n2)", name1=name1, name2=name2)
# 添加节点和关系
def add_purchase(tx, customer_name, product_name):
tx.run("MERGE (c:Customer {name: $customer_name})", customer_name=customer_name)
tx.run("MERGE (p:Product {name: $product_name})", product_name=product_name)
tx.run("MATCH (c:Customer {name: $customer_name}), (p:Product {name: $product_name}) CREATE (c)-[:PURCHASED]->(p)", customer_name=customer_name, product_name=product_name)
# 查询购买关系
def find_purchases(tx, customer_name):
result = tx.run("MATCH (c:Customer {name: $customer_name})-[:PURCHASED]->(p:Product) RETURN p.name", customer_name=customer_name)
return [record["p.name"] for record in result]
# 测试代码
with driver.session() as session:
# 添加节点和关系
session.write_transaction(create_node, "Alice", "Customer")
session.write_transaction(create_node, "Bob", "Customer")
session.write_transaction(create_node, "iPhone", "Product")
session.write_transaction(create_node, "MacBook", "Product")
session.write_transaction(create_relationship, "Alice", "iPhone")
session.write_transaction(create_relationship, "Bob", "MacBook")
session.write_transaction(create_relationship, "Alice", "MacBook")
# 添加购买记录
session.write_transaction(add_purchase, "Alice", "iPhone")
session.write_transaction(add_purchase, "Bob", "MacBook")
session.write_transaction(add_purchase, "Alice", "MacBook")
# 查询购买记录
result = session.read_transaction(find_purchases, "Alice")
print(result)
```
这个示例代码包括了 Neo4j 数据库的连接和节点/关系的创建,以及添加购买记录和查询购买记录等操作。你可以根据你的具体需求进行修改和调整。
阅读全文