Elffuss BraidHub

kikocis/GraphRAG-SDK public

ca14f368bce9 · 1.3 KiBRawPermalink
1from falkordb import Graph
2from .entity import Entity
3from .relation import Relation
4
5# Save schema as graph
6def schema_to_graph(s, g:Graph) -> None:
7 # Validate arguments
8 if not isinstance(g, Graph):
9 raise Exception("Invalid argument, g is expected to be a Graph")
10
11 # Make sure schema is valid
12 s.validate()
13
14 # Clear graph
15 try:
16 g.delete()
17 except:
18 pass
19
20 # Create graph entities
21 entity_ids = {}
22 for e in s.entities:
23 # Construct entity creation query
24 q = f"""CREATE (n:{e.name})
25 SET n = $args
26 RETURN ID(n)"""
27
28 # Build query arguments
29 args = {}
30 for attr in e.attributes:
31 args[attr.name] = [attr.type.__name__, attr.desc, attr.unique, attr.mandatory]
32
33 # Run query and get entity id
34 id = g.query(q, params={'args': args}).result_set[0][0]
35
36 # Save
37 entity_ids[e.name] = id
38
39 # Create graph relations
40 for r in s.relations:
41 # Construct relationship creation query
42 q = f"""MATCH (src), (dest)
43 WHERE ID(src) = $src AND ID(dest) = $dest
44 CREATE (src)-[:{r.name}]->(dest)"""
45
46 # Build query arguments
47 args = {'src': entity_ids[r.src.name], 'dest':entity_ids[r.dest.name]}
48
49 # Run query and get entity id
50 g.query(q, params=args)