1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| from neo4j import GraphDatabase import json
class KnowledgeGraphBuilder: def __init__(self, uri, user, password): self.conn = Neo4jConnection(uri, user, password) def build_from_json(self, data: list): """从 JSON 数据构建知识图谱""" self.conn.query("MATCH (n) DETACH DELETE n") for item in data: self.conn.query(f""" CREATE (:{item['type']} {{name: $name, id: $id, properties: $props}}) """, { "name": item['name'], "id": item['id'], "props": json.dumps(item.get('properties', {})) }) for rel in item.get('relations', []): self.conn.query(f""" MATCH (a:{item['type']} {id: $from_id}), (b:{rel['target_type']} {id: $to_id}) CREATE (a)-[:{rel['type']}]->(b) """, { "from_id": item['id'], "to_id": rel['target_id'] }) self.conn.query("CREATE INDEX FOR (n:Person) ON (n.name)") self.conn.query("CREATE INDEX FOR (n:Company) ON (n.name)") return "知识图谱构建完成" def query_path(self, from_entity: str, to_entity: str, max_hops: int = 5): """查询两个实体间的最短路径""" result = self.conn.query(f""" MATCH path = shortestPath( (a {{name: $from}})-[*1..{max_hops}]-(b {{name: $to}}) ) RETURN path """, {"from": from_entity, "to": to_entity}) return result
data = [ { "type": "Person", "id": "p1", "name": "马化腾", "properties": {"born": 1971, "nationality": "中国"}, "relations": [ {"type": "FOUNDED", "target_type": "Company", "target_id": "c1"} ] }, { "type": "Company", "id": "c1", "name": "腾讯", "properties": {"founded": 1998, "industry": "互联网"}, "relations": [ {"type": "HEADQUARTERED_IN", "target_type": "City", "target_id": "city1"} ] }, { "type": "City", "id": "city1", "name": "深圳", "properties": {"province": "广东", "population": 17660000} } ]
builder = KnowledgeGraphBuilder("bolt://localhost:7687", "neo4j", "password") builder.build_from_json(data)
path = builder.query_path("马化腾", "深圳") print(path)
|