main
黄海 5 months ago
parent 7dc4c02572
commit 9fa53453e2

@ -1,75 +1,48 @@
from py2neo import Graph, Transaction
from pathlib import Path
# K2_Neo4jExecutor.py
from py2neo import Graph
import re
class Neo4jExecutor:
def __init__(self, uri, auth):
self.graph = Graph(uri, auth=auth)
self.batch_size = 5 # 每批执行的语句数量
self.delay = 0.1 # 批处理间隔(秒)
def execute_cypher_file(self, file_path: str) -> dict:
"""执行Cypher脚本文件"""
stats = {
'total': 0,
'success': 0,
'failed': 0,
'duration': 0
}
def execute_cypher_file(self, file_path: str) -> dict: # 确保方法名称正确
"""执行Cypher文件"""
stats = {'total': 0, 'success': 0, 'failed': 0}
try:
cypher_script = Path(file_path).read_text(encoding='utf-8')
return self.execute_cypher(cypher_script, stats)
except Exception as e:
print(f"文件读取失败: {str(e)}")
return stats
with open(file_path, 'r', encoding='utf-8') as f:
cypher_script = f.read()
statements = re.split(r';\s*\n', cypher_script)
statements = [s.strip() for s in statements if s.strip()]
# 在Neo4jExecutor类中添加参数处理
def execute_cypher(self, cypher_script: str, params: dict = None) -> dict:
"""支持参数化查询"""
if params is None:
params = {}
stats['total'] = len(statements)
try:
result = self.graph.run(cypher_script, parameters=params)
return result.stats()
except Exception as e:
print(f"执行失败: {str(e)}")
return {}
for stmt in statements:
try:
self.graph.run(stmt)
stats['success'] += 1
except Exception as e:
stats['failed'] += 1
print(f"执行失败: {stmt[:50]}... \n错误: {str(e)[:100]}")
def _execute_single(self, tx: Transaction, stmt: str):
"""执行单个语句"""
try:
tx.run(stmt)
except Exception as e:
if 'already exists' in str(e):
print(f"忽略已存在的约束: {stmt[:50]}...")
else:
raise
return stats
def _retry_single(self, stmt: str) -> bool:
"""重试单个语句"""
try:
self.graph.run(stmt)
return True
except Exception as e:
print(f"语句执行失败: {stmt[:60]}... \n错误信息: {str(e)}")
return False
print(f"文件错误: {str(e)}")
return stats
# 使用示例
if __name__ == "__main__":
# 初始化执行器
if __name__ == '__main__':
executor = Neo4jExecutor(
uri="neo4j://10.10.21.20:7687",
auth=("neo4j", "DsideaL4r5t6y7u")
)
# 执行Cypher文件
# 确保调用名称与方法定义一致
result = executor.execute_cypher_file("knowledge_graph.cypher")
print(f"\n执行结果:")
print(f"- 总语句数: {result['total']}")
print(f"- 成功: {result['success']}")
print(f"- 失败: {result['failed']}")
print(f"- 耗时: {result['duration']}")
print(f"- 总语句数: {result.get('total', 0)}")
print(f"- 成功: {result.get('success', 0)}")
print(f"- 失败: {result.get('failed', 0)}")

@ -2,10 +2,25 @@ CREATE CONSTRAINT IF NOT EXISTS FOR (kp:KnowledgePoint) REQUIRE kp.id IS UNIQUE;
CREATE CONSTRAINT IF NOT EXISTS FOR (ab:AbilityPoint) REQUIRE ab.id IS UNIQUE;
MERGE (kp:KnowledgePoint {id: "KP_101"})
SET kp.name = "长方形周长计算",
kp.level = "小学"
kp.level = "小学";
MERGE (q:Question {id: "66c060a1"})
SET q.content = "巧求周长7个相同小长方形拼图求周长",
q.difficulty = 3
q.difficulty = 3;
MERGE (ab1:AbilityPoint {id: "AB_201"})
SET ab1.name = "图形分析能力";
MERGE (ab2:AbilityPoint {id: "AB_202"})
SET ab2.name = "计算能力";
MERGE (ab3:AbilityPoint {id: "AB_203"})
SET ab3.name = "逻辑推理能力";
MATCH (q:Question {id: "66c060a1"}), (kp:KnowledgePoint {id: "KP_101"})
MERGE (q)-[r:TESTS_KNOWLEDGE]->(kp)
SET r.weight = 0.8
SET r.weight = 0.8;
MATCH (q:Question {id: "66c060a1"}), (ab1:AbilityPoint {id: "AB_201"})
MERGE (q)-[r1:REQUIRES_ABILITY]->(ab1)
SET r1.weight = 0.7;
MATCH (q:Question {id: "66c060a1"}), (ab2:AbilityPoint {id: "AB_202"})
MERGE (q)-[r2:REQUIRES_ABILITY]->(ab2)
SET r2.weight = 0.8;
MATCH (q:Question {id: "66c060a1"}), (ab3:AbilityPoint {id: "AB_203"})
MERGE (q)-[r3:REQUIRES_ABILITY]->(ab3)
SET r3.weight = 0.6;
Loading…
Cancel
Save