设计phython用Neo4j 图数据库显示自黑客帝国这部电影的任务关系。 1、在图 1 所示关系中,实现如下查询:谁是 Neo 的朋友?Neo 朋友的朋友?谁在恋爱?
时间: 2024-10-12 12:14:25 浏览: 15
phyton-project1:我的phython项目的存储库
在Python中使用Neo4j图数据库来表示《黑客帝国》电影中的任务关系,首先需要创建节点(Nodes)代表人物角色,如Neo、Morpheus、Trinity等,并创建关系(Relationships)表示他们之间的友谊、爱情或其他关联。假设我们已经有一张`Person`表作为节点,以及一张`Friendship`表和`Lovers`表作为关系。
以下是创建基本数据结构的伪代码:
```python
from neo4j import GraphDatabase
# 创建连接到Neo4j数据库
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
def create_movie_data(tx):
# 添加角色节点
with tx.session() as session:
session.run(
"""
CREATE (:Person {name: 'Neo', role: 'Protagonist'}),
(:Person {name: 'Morpheus', role: 'Guide'}),
(:Person {name: 'Trinity', role: 'Warrior'})
"""
)
# 添加友谊关系
with tx.session() as session:
session.run(
"""
MATCH (a:Person), (b:Person)
WHERE a.name IN ['Neo', 'Morpheus'] AND b.name IN ['Morpheus', 'Trinity']
CREATE (a)-[:FRIEND]->(b)
"""
)
# 添加恋爱关系
with tx.session() as session:
session.run(
"""
MATCH (a:Person {name: 'Neo'}), (b:Person {name: 'Trinity'})
CREATE (a)-[:LOVER]->(b)
"""
)
# 执行上述操作
with driver.session() as session:
session.write_transaction(create_movie_data)
# 实现查询
def get_friends_and_lovers(tx, person_name):
with tx.session() as session:
# 查询Neo的朋友
friends_query = """
MATCH (person:Person {name: $person_name})-[:FRIEND*]-(friend)
RETURN friend.name AS friend_name
"""
friends_results = session.run(friends_query, person_name=person_name)
# 查询Neo的朋友的朋友
friends_of_friends_query = """
MATCH (person:Person {name: $person_name})-[:FRIEND*]->(friend_of_friend)
RETURN friend_of_friend.name AS friend_of_friend_name
"""
friends_of_friends_results = session.run(friends_of_friends_query, person_name=person_name)
# 查询恋爱关系
lovers_query = """
MATCH (person:Person {name: $person_name})-[:LOVER]->(lover)
RETURN lover.name AS lover_name
"""
lovers_results = session.run(lovers_query, person_name=person_name)
return {
"friends": [record["friend_name"] for record in friends_results],
"friends_of_friends": [record["friend_of_friend_name"] for record in friends_of_friends_results],
"lovers": [record["lover_name"] for record in lovers_results]
}
# 查询Neo的相关信息
neo_friends_data = get_friends_and_lovers(session, "Neo")
```
阅读全文