|
|
|
from Util import *
|
|
|
|
from py2neo import RelationshipMatcher
|
|
|
|
|
|
|
|
# 连接数据库
|
|
|
|
db = Graph("neo4j://10.10.21.20:7687", auth=("neo4j", "DsideaL4r5t6y7u"))
|
|
|
|
# 清空
|
|
|
|
clear(db)
|
|
|
|
|
|
|
|
# ====== 第一部分:基础数据 ======
|
|
|
|
node_1 = Node("英雄", name="张无忌", power=180)
|
|
|
|
node_2 = Node("英雄", name="杨逍", power=100)
|
|
|
|
node_3 = Node("派别", name="明教")
|
|
|
|
|
|
|
|
base_relations = [
|
|
|
|
(node_1, '教主', node_2),
|
|
|
|
(node_1, '统领', node_3),
|
|
|
|
(node_2, '师出', node_3)
|
|
|
|
]
|
|
|
|
|
|
|
|
base_subgraph = Subgraph(
|
|
|
|
nodes=[node_1, node_2, node_3],
|
|
|
|
relationships=[Relationship(r[0], r[1], r[2]) for r in base_relations]
|
|
|
|
)
|
|
|
|
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)
|
|
|
|
|
|
|
|
# ====== 第四部分:查询 ======
|
|
|
|
relation = RelationshipMatcher(db)
|
|
|
|
|
|
|
|
print('=' * 20, 'hate关系', '=' * 20)
|
|
|
|
for rel in relation.match(r_type='hate'):
|
|
|
|
print(rel)
|
|
|
|
|
|
|
|
print('\n' + '=' * 20, '情敌关系', '=' * 20)
|
|
|
|
for rel in relation.match(r_type='情敌'):
|
|
|
|
print(rel)
|