import json from Neo4j.Neo4jExecutor import * def json_to_cypher(data): """将知识体系JSON转换为Cypher插入脚本""" cypher = [] seen = set() def process_node(node, parent_id=None): nonlocal seen node_id = node['value'] node_name = node['title'].replace("'", "''") # 创建当前节点 if node_id not in seen: cypher.append(f"MERGE (n:KnowledgePoint {{id: '{node_id}'}}) SET n.name = '{node_name}';") seen.add(node_id) # 创建父子关系 if parent_id: cypher.append(f""" MATCH (parent:KnowledgePoint {{id: '{parent_id}'}}), (child:KnowledgePoint {{id: '{node_id}'}}) MERGE (parent)-[:HAS_SUB_POINT]->(child);""") # 递归处理子节点 if 'children' in node and not node['isLeaf']: for child in node['children']: process_node(child, parent_id=node_id) # 处理根节点 for root in data['data']['tree']: process_node(root) # 处理根节点的父级关系(如果有) if root.get('parentValue'): cypher.append(f"MERGE (parent:KnowledgePoint {{id: '{root['parentValue']}'}});") cypher.append(f""" MATCH (parent:KnowledgePoint {{id: '{root['parentValue']}'}}), (child:KnowledgePoint {{id: '{root['value']}'}}) MERGE (parent)-[:HAS_SUB_POINT]->(child);""") return '\n'.join(cypher) # 使用示例 if __name__ == '__main__': executor = Neo4jExecutor( uri=NEO4J_URI, auth=NEO4J_AUTH ) # 清库 clear(executor.graph) # 这里替换成你的JSON数据变量 with open('小学数学知识点体系.json', 'r',encoding='utf-8') as f: your_json_data = json.load(f) cypherText=json_to_cypher(your_json_data) executor.execute_cypher_text(cypherText)