Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 1.4 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 e = s.entities[e]
24
25 # Construct entity creation query
26 q = f"""CREATE (n:{e.name})
27 SET n = $args
28 RETURN ID(n)"""
29
30 # Build query arguments
31 args = {}
32 for attr in e.attributes:
33 args[attr.name] = [attr.type.__name__, attr.desc, attr.unique, attr.mandatory]
34
35 # Run query and get entity id
36 id = g.query(q, params={'args': args}).result_set[0][0]
37
38 # Save
39 entity_ids[e.name] = id
40
41 # Create graph relations
42 for r in s.relations:
43 r = s.relations[r]
44
45 # Construct relationship creation query
46 q = f"""MATCH (src), (dest)
47 WHERE ID(src) = $src AND ID(dest) = $dest
48 CREATE (src)-[:{r.name}]->(dest)"""
49
50 # Build query arguments
51 args = {'src': entity_ids[r.src.name], 'dest':entity_ids[r.dest.name]}
52
53 # Run query and get entity id
54 g.query(q, params=args)