Navegador

navegador / navegador / graph / store.py
Source Blame History 125 lines
5e4b8e4… anonymous 1 """
5e4b8e4… anonymous 2 GraphStore — thin wrapper over FalkorDB (SQLite or Redis backend).
5e4b8e4… anonymous 3
5e4b8e4… anonymous 4 Usage:
5e4b8e4… anonymous 5 # SQLite (local, zero-infra)
5e4b8e4… anonymous 6 store = GraphStore.sqlite(".navegador/graph.db")
5e4b8e4… anonymous 7
5e4b8e4… anonymous 8 # Redis-backed FalkorDB (production)
5e4b8e4… anonymous 9 store = GraphStore.redis("redis://localhost:6379")
5e4b8e4… anonymous 10 """
5e4b8e4… anonymous 11
5e4b8e4… anonymous 12 import logging
5e4b8e4… anonymous 13 from pathlib import Path
5e4b8e4… anonymous 14 from typing import Any
5e4b8e4… anonymous 15
5e4b8e4… anonymous 16 logger = logging.getLogger(__name__)
5e4b8e4… anonymous 17
5e4b8e4… anonymous 18
5e4b8e4… anonymous 19 class GraphStore:
5e4b8e4… anonymous 20 """
5e4b8e4… anonymous 21 Wraps a FalkorDB graph, providing helpers for navegador node/edge operations.
5e4b8e4… anonymous 22
5e4b8e4… anonymous 23 The underlying graph is named "navegador" within the database.
5e4b8e4… anonymous 24 """
5e4b8e4… anonymous 25
5e4b8e4… anonymous 26 GRAPH_NAME = "navegador"
5e4b8e4… anonymous 27
5e4b8e4… anonymous 28 def __init__(self, client: Any) -> None:
5e4b8e4… anonymous 29 self._client = client
5e4b8e4… anonymous 30 self._graph = client.select_graph(self.GRAPH_NAME)
5e4b8e4… anonymous 31
5e4b8e4… anonymous 32 # ── Constructors ──────────────────────────────────────────────────────────
5e4b8e4… anonymous 33
5e4b8e4… anonymous 34 @classmethod
5e4b8e4… anonymous 35 def sqlite(cls, db_path: str | Path = ".navegador/graph.db") -> "GraphStore":
5e4b8e4… anonymous 36 """
5e4b8e4… anonymous 37 Open a SQLite-backed FalkorDB graph via falkordblite (zero-infra).
5e4b8e4… anonymous 38
5e4b8e4… anonymous 39 Requires: pip install FalkorDB falkordblite
5e4b8e4… anonymous 40 """
5e4b8e4… anonymous 41 try:
5e4b8e4… anonymous 42 from redislite import FalkorDB # type: ignore[import] # provided by falkordblite
5e4b8e4… anonymous 43 except ImportError as e:
5e4b8e4… anonymous 44 raise ImportError(
5e4b8e4… anonymous 45 "Install graph dependencies: pip install FalkorDB falkordblite"
5e4b8e4… anonymous 46 ) from e
5e4b8e4… anonymous 47
5e4b8e4… anonymous 48 db_path = Path(db_path)
5e4b8e4… anonymous 49 db_path.parent.mkdir(parents=True, exist_ok=True)
5e4b8e4… anonymous 50 client = FalkorDB(str(db_path))
5e4b8e4… anonymous 51 logger.info("GraphStore opened (SQLite/falkordblite): %s", db_path)
5e4b8e4… anonymous 52 return cls(client)
5e4b8e4… anonymous 53
5e4b8e4… anonymous 54 @classmethod
5e4b8e4… anonymous 55 def redis(cls, url: str = "redis://localhost:6379") -> "GraphStore":
5e4b8e4… anonymous 56 """
5e4b8e4… anonymous 57 Open a Redis-backed FalkorDB graph (production use).
5e4b8e4… anonymous 58
5e4b8e4… anonymous 59 Requires: pip install FalkorDB redis
5e4b8e4… anonymous 60 """
5e4b8e4… anonymous 61 try:
5e4b8e4… anonymous 62 import falkordb # type: ignore[import]
5e4b8e4… anonymous 63 except ImportError as e:
5e4b8e4… anonymous 64 raise ImportError("Install falkordb: pip install FalkorDB redis") from e
5e4b8e4… anonymous 65
5e4b8e4… anonymous 66 client = falkordb.FalkorDB.from_url(url)
5e4b8e4… anonymous 67 logger.info("GraphStore opened (Redis): %s", url)
5e4b8e4… anonymous 68 return cls(client)
5e4b8e4… anonymous 69
5e4b8e4… anonymous 70 # ── Core operations ───────────────────────────────────────────────────────
5e4b8e4… anonymous 71
5e4b8e4… anonymous 72 def query(self, cypher: str, params: dict[str, Any] | None = None) -> Any:
5e4b8e4… anonymous 73 """Execute a raw Cypher query and return the result."""
5e4b8e4… anonymous 74 return self._graph.query(cypher, params or {})
5e4b8e4… anonymous 75
5e4b8e4… anonymous 76 def create_node(self, label: str, props: dict[str, Any]) -> None:
04dabf9… lmata 77 """Upsert a node by (label, name[, file_path])."""
04dabf9… lmata 78 # Ensure merge key fields exist
04dabf9… lmata 79 props.setdefault("name", "")
04dabf9… lmata 80 props.setdefault("file_path", "")
04dabf9… lmata 81 # Filter out None values — FalkorDB rejects them as params
04dabf9… lmata 82 props = {k: ("" if v is None else v) for k, v in props.items()}
5e4b8e4… anonymous 83 prop_str = ", ".join(f"n.{k} = ${k}" for k in props)
758c6b7… lmata 84 cypher = f"MERGE (n:{label} {{name: $name, file_path: $file_path}}) SET {prop_str}"
5e4b8e4… anonymous 85 self.query(cypher, props)
5e4b8e4… anonymous 86
5e4b8e4… anonymous 87 def create_edge(
5e4b8e4… anonymous 88 self,
5e4b8e4… anonymous 89 from_label: str,
5e4b8e4… anonymous 90 from_key: dict[str, Any],
5e4b8e4… anonymous 91 edge_type: str,
5e4b8e4… anonymous 92 to_label: str,
5e4b8e4… anonymous 93 to_key: dict[str, Any],
5e4b8e4… anonymous 94 props: dict[str, Any] | None = None,
5e4b8e4… anonymous 95 ) -> None:
5e4b8e4… anonymous 96 """Create a directed edge between two nodes, merging if it already exists."""
04dabf9… lmata 97 from_match = ", ".join(f"{k}: $from_{k}" for k in from_key)
04dabf9… lmata 98 to_match = ", ".join(f"{k}: $to_{k}" for k in to_key)
5e4b8e4… anonymous 99 prop_set = ""
5e4b8e4… anonymous 100 if props:
5e4b8e4… anonymous 101 prop_set = " SET " + ", ".join(f"r.{k} = $p_{k}" for k in props)
5e4b8e4… anonymous 102
5e4b8e4… anonymous 103 cypher = (
5e4b8e4… anonymous 104 f"MATCH (a:{from_label} {{{from_match}}}), (b:{to_label} {{{to_match}}}) "
5e4b8e4… anonymous 105 f"MERGE (a)-[r:{edge_type}]->(b){prop_set}"
5e4b8e4… anonymous 106 )
5e4b8e4… anonymous 107 params = {f"from_{k}": v for k, v in from_key.items()}
5e4b8e4… anonymous 108 params.update({f"to_{k}": v for k, v in to_key.items()})
5e4b8e4… anonymous 109 if props:
5e4b8e4… anonymous 110 params.update({f"p_{k}": v for k, v in props.items()})
5e4b8e4… anonymous 111
5e4b8e4… anonymous 112 self.query(cypher, params)
5e4b8e4… anonymous 113
5e4b8e4… anonymous 114 def clear(self) -> None:
5e4b8e4… anonymous 115 """Delete all nodes and edges in the graph."""
5e4b8e4… anonymous 116 self.query("MATCH (n) DETACH DELETE n")
5e4b8e4… anonymous 117 logger.info("Graph cleared")
5e4b8e4… anonymous 118
5e4b8e4… anonymous 119 def node_count(self) -> int:
5e4b8e4… anonymous 120 result = self.query("MATCH (n) RETURN count(n) AS c")
5e4b8e4… anonymous 121 return result.result_set[0][0] if result.result_set else 0
5e4b8e4… anonymous 122
5e4b8e4… anonymous 123 def edge_count(self) -> int:
5e4b8e4… anonymous 124 result = self.query("MATCH ()-[r]->() RETURN count(r) AS c")
5e4b8e4… anonymous 125 return result.result_set[0][0] if result.result_set else 0

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button