You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3 KiB

5 months ago
from Util import *
5 months ago
from py2neo import RelationshipMatcher
5 months ago
# 连接数据库
5 months ago
db = Graph("neo4j://10.10.21.20:7687", auth=("neo4j", "DsideaL4r5t6y7u"))
5 months ago
# 清空
clear(db)
5 months ago
5 months ago
# ====== 第一部分:基础数据 ======
node_1 = Node("英雄", name="张无忌", power=180)
5 months ago
node_2 = Node("英雄", name="杨逍", power=100)
node_3 = Node("派别", name="明教")
5 months ago
base_relations = [
5 months ago
(node_1, '教主', node_2),
5 months ago
(node_1, '统领', node_3),
5 months ago
(node_2, '师出', node_3)
]
5 months ago
5 months ago
base_subgraph = Subgraph(
5 months ago
nodes=[node_1, node_2, node_3],
5 months ago
relationships=[Relationship(r[0], r[1], r[2]) for r in base_relations]
5 months ago
)
5 months ago
db.create(base_subgraph)
# ====== 第二部分:家庭关系 ======
try:
tx = db.begin()
node_7 = Node('英雄', name='张翠山')
node_8 = Node('英雄', name='殷素素')
node_9 = Node('英雄', name='狮王')
tx.create(Relationship(node_1, '生父', node_7))
tx.create(Relationship(node_1, '生母', node_8))
tx.create(Relationship(node_1, '义父', node_9))
node_10 = Node('武当', name='张三丰')
tx.create(node_10)
tx.create(Relationship(node_1, '师公', node_10))
tx.create(Relationship(node_7, '妻子', node_8))
db.commit(tx)
except Exception as e:
db.rollback(tx)
print("家庭关系事务失败:", e)
# ====== 第三部分:感情关系 ======
try:
tx = db.begin()
node_100 = Node('巾帼', name='赵敏')
node_101 = Node('巾帼', name='周芷若')
node_102 = Node('巾帼', name='小昭')
node_103 = Node('巾帼', name='蛛儿')
tx.create(Relationship(node_1, 'Love', node_100))
tx.create(Relationship(node_1, 'knows', node_101))
tx.create(Relationship(node_101, 'hate', node_100))
tx.create(Relationship(node_1, 'knows', node_102))
tx.create(Relationship(node_103, 'Love', node_1))
tx.create(Relationship(node_101, '情敌', node_102))
tx.create(Relationship(node_102, '情敌', node_103))
db.commit(tx)
except Exception as e:
db.rollback(tx)
print("感情关系事务失败:", e)
# ====== 第四部分:查询 ======
5 months ago
relation = RelationshipMatcher(db)
5 months ago
print('=' * 20, 'hate关系', '=' * 20)
for rel in relation.match(r_type='hate'):
print(rel)
5 months ago
5 months ago
print('\n' + '=' * 20, '情敌关系', '=' * 20)
for rel in relation.match(r_type='情敌'):
print(rel)