|
| 1 | +""" |
| 2 | +Simple knowledge-graph multi-hop traversal with lance-graph Python bindings. |
| 3 | +
|
| 4 | +Requirements: |
| 5 | +- Build/install the Python extension first (from repo root): |
| 6 | + maturin develop -m python/Cargo.toml |
| 7 | +- Python deps: pyarrow |
| 8 | +
|
| 9 | +Run: |
| 10 | + python examples/kg_traversal.py |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import pyarrow as pa |
| 16 | + |
| 17 | +from lance_graph import GraphConfigBuilder, CypherQuery |
| 18 | + |
| 19 | + |
| 20 | +def make_people_batch(n: int = 6) -> pa.RecordBatch: |
| 21 | + return pa.record_batch( |
| 22 | + [ |
| 23 | + pa.array(list(range(1, n + 1)), type=pa.int32()), |
| 24 | + pa.array([f"P{i}" for i in range(1, n + 1)], type=pa.string()), |
| 25 | + ], |
| 26 | + names=["person_id", "name"], |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def make_friendship_batch(n: int = 6) -> pa.RecordBatch: |
| 31 | + # Create a simple ring: 1->2->3->...->n->1 |
| 32 | + src = list(range(1, n + 1)) |
| 33 | + dst = [i + 1 if i < n else 1 for i in src] |
| 34 | + return pa.record_batch( |
| 35 | + [pa.array(src, type=pa.int32()), pa.array(dst, type=pa.int32())], |
| 36 | + names=["person1_id", "person2_id"], |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +def main() -> None: |
| 41 | + config = ( |
| 42 | + GraphConfigBuilder() |
| 43 | + .with_node_label("Person", "person_id") |
| 44 | + .with_relationship("FRIEND_OF", "person1_id", "person2_id") |
| 45 | + .build() |
| 46 | + ) |
| 47 | + |
| 48 | + # Two-hop traversal from a person to friend-of-a-friend |
| 49 | + query = ( |
| 50 | + CypherQuery( |
| 51 | + "MATCH (a:Person)-[:FRIEND_OF]->(b:Person)-[:FRIEND_OF]->(c:Person) RETURN a.name, c.name" |
| 52 | + ) |
| 53 | + .with_config(config) |
| 54 | + ) |
| 55 | + |
| 56 | + datasets = { |
| 57 | + "Person": make_people_batch(), |
| 58 | + "FRIEND_OF": make_friendship_batch(), |
| 59 | + } |
| 60 | + result = query.execute(datasets) |
| 61 | + print(result.to_pydict()) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main() |
0 commit comments