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.

44 lines
1.3 KiB

5 months ago
from py2neo import Graph, Node, Relationship, Subgraph
5 months ago
5 months ago
# 连接数据库
5 months ago
db = Graph("neo4j://127.0.0.1:7687", auth=("neo4j", "DsideaL4r5t6y7u"))
5 months ago
# 修正版本查询代码
version = db.run("CALL dbms.components() YIELD versions UNWIND versions AS version RETURN version").evaluate()
print(f"Neo4j 版本: {version}")
# 清空数据
db.run("MATCH (n) DETACH DELETE n")
# 分步删除约束和索引
try:
# 删除约束
constraints = db.run("SHOW CONSTRAINTS YIELD name").data()
for constr in constraints:
db.run(f"DROP CONSTRAINT `{constr['name']}`")
# 删除索引
indexes = db.run("SHOW INDEXES YIELD name, type WHERE type <> 'LOOKUP'").data()
for idx in indexes:
db.run(f"DROP INDEX `{idx['name']}`")
except Exception as e:
print(f"删除操作失败: {e}")
# 创建节点
5 months ago
node_1 = Node("英雄", name="张无忌")
node_2 = Node("英雄", name="杨逍", power=100)
node_3 = Node("派别", name="明教")
5 months ago
# 创建关系
relations = [
(node_1, '教主', node_2),
(node_3, '统领', node_1), # 修正原代码可能的逻辑关系
(node_2, '师出', node_3)
]
5 months ago
5 months ago
# 构建子图并提交
subgraph = Subgraph(
nodes=[node_1, node_2, node_3],
relationships=[Relationship(r[0], r[1], r[2]) for r in relations]
)
db.create(subgraph)