|
4 | 4 |
|
5 | 5 | import networkx as nx
|
6 | 6 | from pydantic import BaseModel
|
| 7 | +from neo4j import GraphDatabase |
7 | 8 |
|
8 | 9 |
|
9 | 10 | class SemanticMatchGraph(nx.DiGraph):
|
@@ -53,6 +54,34 @@ def from_file(cls, filename: str) -> "SemanticMatchGraph":
|
53 | 54 | )
|
54 | 55 | return graph
|
55 | 56 |
|
| 57 | + def to_neo4j(self, url: str, user: str, password: str): |
| 58 | + driver = GraphDatabase.driver(url, auth=(user, password)) |
| 59 | + with driver.session() as session: |
| 60 | + # Optional: clear previous graph |
| 61 | + session.run("MATCH (n) DETACH DELETE n") |
| 62 | + |
| 63 | + for u, v, data in self.edges(data=True): |
| 64 | + session.run(""" |
| 65 | + MERGE (a:Semantic {id: $u}) |
| 66 | + MERGE (b:Semantic {id: $v}) |
| 67 | + MERGE (a)-[:MATCH {score: $score}]->(b) |
| 68 | + """, u=u, v=v, score=data["weight"]) |
| 69 | + driver.close() |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def from_neo4j(cls, url: str, user: str, password: str) -> "SemanticMatchGraph": |
| 73 | + graph = cls() |
| 74 | + driver = GraphDatabase.driver(url, auth=(user, password)) |
| 75 | + with driver.session() as session: |
| 76 | + result = session.run(""" |
| 77 | + MATCH (a:Semantic)-[r:MATCH]->(b:Semantic) |
| 78 | + RETURN a.id AS u, b.id AS v, r.score AS score |
| 79 | + """) |
| 80 | + for record in result: |
| 81 | + graph.add_semantic_match(record["u"], record["v"], record["score"]) |
| 82 | + driver.close() |
| 83 | + return graph |
| 84 | + |
56 | 85 |
|
57 | 86 | class SemanticMatch(BaseModel):
|
58 | 87 | base_semantic_id: str
|
@@ -145,3 +174,17 @@ def find_semantic_matches(
|
145 | 174 | heapq.heappush(pq, (-new_score, neighbor, path + [node])) # Push updated path
|
146 | 175 |
|
147 | 176 | return results
|
| 177 | + |
| 178 | + |
| 179 | +if __name__ == '__main__': |
| 180 | + graph_complex = SemanticMatchGraph() |
| 181 | + graph_complex.add_edge("A", "B", weight=0.9) |
| 182 | + graph_complex.add_edge("A", "C", weight=0.8) |
| 183 | + graph_complex.add_edge("B", "D", weight=0.7) |
| 184 | + graph_complex.add_edge("C", "D", weight=0.6) |
| 185 | + graph_complex.add_edge("D", "E", weight=0.5) |
| 186 | + graph_complex.to_neo4j( |
| 187 | + url="bolt://localhost:7687", |
| 188 | + user="neo4j", |
| 189 | + password="your_password" |
| 190 | + ) |
0 commit comments