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.

54 lines
1.8 KiB

4 weeks ago
from py2neo import Graph, Node, Relationship
3 weeks ago
from Config import Config
4 weeks ago
# 1. 连接Neo4j数据库
3 weeks ago
graph = Graph(Config.NEO4J_URI, auth=Config.NEO4J_AUTH)
4 weeks ago
4 weeks ago
# 清空数据库
graph.delete_all()
print("数据库已清空")
4 weeks ago
# 2. 创建化学物质节点 (三种反应物+一种生成物)
reactant_A = Node("Chemical", name="", formula="Fe")
reactant_B = Node("Chemical", name="氧气", formula="O2")
reactant_C = Node("Chemical", name="", formula="H2O")
product = Node("Chemical", name="氧化铁", formula="Fe2O3")
# 3. 创建反应节点并添加属性
reaction = Node("Reaction",
name="铁锈蚀反应",
equation="4Fe + 3O2 + 6H2O → 4Fe(OH)3",
condition="常温常压"
)
# 4. 建立反应物与反应的关系(带计量系数属性)
4 weeks ago
rel_A = Relationship(reactant_A, "参与反应", reaction, coefficient=4)
rel_B = Relationship(reactant_B, "参与反应", reaction, coefficient=3)
rel_C = Relationship(reactant_C, "参与反应", reaction, coefficient=6)
4 weeks ago
# 5. 建立反应与生成物的关系
4 weeks ago
rel_product = Relationship(reaction, "生成", product, yield_rate="98%")
4 weeks ago
# 6. 将节点和关系提交到数据库
graph.create(reactant_A)
graph.create(reactant_B)
graph.create(reactant_C)
graph.create(product)
graph.create(reaction)
graph.create(rel_A)
graph.create(rel_B)
graph.create(rel_C)
graph.create(rel_product)
# 7. 查询示例:查找所有参与铁锈蚀反应的物质
query = """
MATCH (c:Chemical)-[r:PARTICIPATES_IN]->(re:Reaction {name:'铁锈蚀反应'})
RETURN c.name AS chemical, r.coefficient AS coefficient, re.equation AS equation
"""
result = graph.run(query)
for record in result:
print(f"化学物质: {record['chemical']}, 计量系数: {record['coefficient']}")
4 weeks ago
print(f"反应方程式: {record['equation']}")