-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathservice.py
More file actions
275 lines (237 loc) · 8.9 KB
/
Copy pathservice.py
File metadata and controls
275 lines (237 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""High-level Lance knowledge graph orchestration."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, Mapping, MutableMapping, Optional
from lance_graph import CypherQuery, DistanceMetric, GraphConfig, VectorSearch
from .config import KnowledgeGraphConfig, build_default_graph_config
from .store import LanceGraphStore
if TYPE_CHECKING:
import pyarrow as pa
from . import KnowledgeGraph
class LanceKnowledgeGraph:
"""Coordinate Lance datasets, configs, and query execution."""
def __init__(
self,
config: GraphConfig,
*,
storage: LanceGraphStore,
):
self._config = config
self._store = storage
@property
def config(self) -> GraphConfig:
"""Expose the active graph configuration."""
return self._config
@property
def store(self) -> LanceGraphStore:
"""Access the underlying Lance dataset store."""
return self._store
def dataset_names(self) -> Iterable[str]:
"""Return the known dataset identifiers."""
return self._store.list_datasets().keys()
def ensure_initialized(self) -> None:
"""Create any required on-disk structure."""
self._store.ensure_layout()
def materialize(self) -> KnowledgeGraph:
"""Materialize an in-memory ``KnowledgeGraph`` view of the datasets."""
from . import KnowledgeGraph # Avoid circular import at module load time
tables = self._store.load_tables()
return KnowledgeGraph(self._config, tables)
def has_dataset(self, name: str) -> bool:
"""Return ``True`` when a dataset has been persisted under ``name``."""
path = self._store.list_datasets().get(name)
return path is not None and path.exists()
def load_tables(
self,
names: Optional[Iterable[str]] = None,
) -> Mapping[str, "pa.Table"]:
"""Load persisted datasets as PyArrow tables."""
return self._store.load_tables(names)
def load_table(self, name: str) -> "pa.Table":
"""Load a single dataset by name."""
tables = self._store.load_tables([name])
return tables[name]
def write_tables(
self,
tables: Mapping[str, "pa.Table"],
) -> None:
"""Persist a batch of tables."""
self._store.write_tables(tables)
def upsert_table(
self,
name: str,
table: "pa.Table",
*,
merge: bool = True,
) -> None:
"""Insert or replace a dataset, merging with the existing table if requested."""
import pyarrow as pa
self.ensure_initialized()
new_rows = table.to_pylist()
if merge and name in self._store.list_datasets():
existing = self.load_table(name)
existing_rows = existing.to_pylist()
combined_rows = _normalize_rows(name, existing_rows + new_rows)
else:
combined_rows = _normalize_rows(name, new_rows)
if combined_rows:
table = pa.Table.from_pylist(combined_rows)
else:
table = pa.Table.from_arrays([], schema=table.schema)
self._store.write_tables({name: table})
def upsert_tables(
self,
tables: Mapping[str, "pa.Table"],
*,
merge: bool = True,
) -> None:
"""Insert multiple datasets, merging each with existing data when requested."""
for name, table in tables.items():
self.upsert_table(name, table, merge=merge)
def run(
self,
statement: str,
*,
datasets: Optional[Mapping[str, pa.Table]] = None,
) -> pa.Table:
"""Execute a Cypher statement against Lance datasets.
Only loads the datasets referenced in the query, avoiding expensive
enumeration of all datasets on cloud storage.
"""
query = CypherQuery(statement).with_config(self._config)
# Only load tables that are actually referenced in the query
referenced_tables = set(query.node_labels()) | set(query.relationship_types())
base_tables: MutableMapping[str, "pa.Table"] = dict(
self._store.load_tables(referenced_tables)
)
if datasets:
base_tables.update(datasets)
return query.execute(base_tables)
def query(
self,
statement: str,
*,
datasets: Optional[Mapping[str, "pa.Table"]] = None,
) -> "pa.Table":
"""Alias for :meth:`run` to match the semantic service naming."""
return self.run(statement, datasets=datasets)
def run_with_vector_rerank(
self,
statement: str,
vector_search: "VectorSearch",
*,
datasets: Optional[Mapping[str, "pa.Table"]] = None,
) -> "pa.Table":
"""Execute a Cypher statement and rerank results by vector similarity.
Parameters
----------
statement:
Cypher query string.
vector_search:
A configured ``VectorSearch`` instance (column, vector, metric, top_k).
datasets:
Optional override tables injected on top of persisted datasets.
"""
query = CypherQuery(statement).with_config(self._config)
referenced_tables = set(query.node_labels()) | set(query.relationship_types())
base_tables: MutableMapping[str, "pa.Table"] = dict(
self._store.load_tables(referenced_tables)
)
if datasets:
base_tables.update(datasets)
return query.execute_with_vector_rerank(base_tables, vector_search)
def query_by_text(
self,
statement: str,
query_text: str,
column: str,
*,
top_k: int = 10,
metric: str = "cosine",
include_distance: bool = True,
embedding_model: str = "text-embedding-3-small",
datasets: Optional[Mapping[str, "pa.Table"]] = None,
) -> "pa.Table":
"""Convenience method: embed ``query_text`` then call run_with_vector_rerank.
Parameters
----------
statement:
Cypher query string.
query_text:
Natural-language text to embed as the query vector.
column:
Name of the vector column in the dataset.
top_k:
Number of nearest neighbours to return.
metric:
Distance metric: "cosine", "l2", or "dot".
include_distance:
Whether to include the ``_distance`` column in results.
embedding_model:
OpenAI embedding model name.
datasets:
Optional override tables.
"""
from .embeddings import EmbeddingGenerator
_metric_map = {
"cosine": DistanceMetric.Cosine,
"l2": DistanceMetric.L2,
"dot": DistanceMetric.Dot,
}
rust_metric = _metric_map.get(metric.lower(), DistanceMetric.Cosine)
vector = EmbeddingGenerator(model=embedding_model).embed_one(query_text)
if vector is None:
raise RuntimeError(f"Failed to generate embedding for text: {query_text!r}")
vs = (
VectorSearch(column)
.query_vector(vector)
.metric(rust_metric)
.top_k(top_k)
.include_distance(include_distance)
)
return self.run_with_vector_rerank(statement, vs, datasets=datasets)
def create_default_service(
config: Optional[KnowledgeGraphConfig] = None,
*,
graph_config: Optional[GraphConfig] = None,
) -> LanceKnowledgeGraph:
"""Construct a knowledge graph service with default settings."""
config = config or KnowledgeGraphConfig.default()
storage = LanceGraphStore(config)
if graph_config is None:
graph_config = build_default_graph_config()
return LanceKnowledgeGraph(graph_config, storage=storage)
def _normalize_rows(name: str, rows: list[dict]) -> list[dict]:
normalized: list[dict] = []
upper = name.upper()
if upper == "ENTITY":
dedupe = {}
for row in rows:
entity_id = row.get("entity_id")
if not entity_id:
continue
row["name_lower"] = str(row.get("name", "")).lower()
row["entity_type"] = row.get("entity_type") or row.get("type") or "UNKNOWN"
dedupe[entity_id] = row
normalized = list(dedupe.values())
elif upper == "RELATIONSHIP":
dedupe = {}
for row in rows:
source = row.get("source_entity_id")
target = row.get("target_entity_id")
if not source or not target:
continue
relationship_type = (
row.get("relationship_type") or row.get("type") or "RELATED_TO"
)
key = (
source,
target,
relationship_type,
row.get("description"),
)
row["relationship_type"] = relationship_type
dedupe[key] = row
normalized = list(dedupe.values())
else:
normalized = rows
return normalized