| 1 | from falkordb import Graph |
| 2 | from .entity import Entity |
| 3 | from .relation import Relation |
| 4 | |
| 5 | import builtins |
| 6 | |
| 7 | # Create a schema from an ontology graph |
| 8 | def schema_from_graph(s, g:Graph): |
| 9 | # Validate arguments |
| 10 | if not isinstance(g, Graph): |
| 11 | raise Exception("Invalid argument, g is expected to be a Graph") |
| 12 | |
| 13 | # Fetch entities |
| 14 | q = "MATCH (n) RETURN n" |
| 15 | res = g.query(q).result_set |
| 16 | |
| 17 | for row in res: |
| 18 | n = row[0] |
| 19 | name = n.labels[0] |
| 20 | |
| 21 | e = s.add_entity(name) |
| 22 | for prop in n.properties: |
| 23 | name = prop |
| 24 | prop = n.properties[prop] |
| 25 | |
| 26 | type = getattr(builtins, prop[0]) |
| 27 | desc = prop[1] |
| 28 | unique = prop[2] |
| 29 | mandatory = prop[3] |
| 30 | |
| 31 | e.add_attribute(name, type, desc, unique, mandatory) |
| 32 | |
| 33 | # Fetch relations |
| 34 | q = "MATCH (src)-[e]->(dest) RETURN src, e, dest" |
| 35 | res = g.query(q).result_set |
| 36 | |
| 37 | for row in res: |
| 38 | src = row[0].labels[0] |
| 39 | r = row[1].relation |
| 40 | dest = row[2].labels[0] |
| 41 | |
| 42 | src = s.get_entity(src) |
| 43 | dest = s.get_entity(dest) |
| 44 | |
| 45 | s.add_relation(r, src, dest) |
| 46 | |
| 47 | # Make sure schema is valid |
| 48 | s.validate() |