-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharangodb_impl.py
More file actions
1863 lines (1585 loc) · 72.5 KB
/
Copy patharangodb_impl.py
File metadata and controls
1863 lines (1585 loc) · 72.5 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
ArangoDB implementation for LightRAG
"""
import os
import re
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from arango import ArangoClient
from arango.database import StandardDatabase
from sentence_transformers import SentenceTransformer
from ..base import BaseGraphStorage
from ..utils import logger
# ============================================================================
# WORKSPACE MANAGEMENT HELPER CLASS - NEW
# ============================================================================
class ArangoDBWorkspaceManager:
"""Helper class for managing workspaces (namespaces) across all storage types"""
def __init__(self, host: str, username: str, password: str, db_name: str):
self.host = host
self.username = username
self.password = password
self.db_name = db_name
self.client = ArangoClient(hosts=self.host)
self.db = self.client.db(self.db_name, username=self.username, password=self.password)
logger.info(f"Initialized Workspace Manager for {self.db_name}")
def list_workspaces(self) -> Dict[str, List[str]]:
"""
List all workspaces (namespaces) in the database.
Returns a dict mapping workspace names to their collection types.
"""
try:
collections = self.db.collections()
workspaces = {}
for coll in collections:
coll_name = coll['name']
# Skip system collections
if coll_name.startswith('_'):
continue
# Parse namespace from collection name
if '_nodes' in coll_name:
namespace = coll_name.replace('_nodes', '')
workspaces.setdefault(namespace, []).append('graph')
elif '_edges' in coll_name:
namespace = coll_name.replace('_edges', '')
workspaces.setdefault(namespace, []).append('graph')
elif '_kv_store' in coll_name:
namespace = coll_name.replace('_kv_store', '')
workspaces.setdefault(namespace, []).append('kv')
elif '_vectors' in coll_name:
namespace = coll_name.replace('_vectors', '')
workspaces.setdefault(namespace, []).append('vector')
elif '_doc_status' in coll_name:
namespace = coll_name.replace('_doc_status', '')
workspaces.setdefault(namespace, []).append('doc_status')
# Deduplicate collection types
for namespace in workspaces:
workspaces[namespace] = sorted(list(set(workspaces[namespace])))
logger.info(f"Found {len(workspaces)} workspaces")
return workspaces
except Exception as e:
logger.error(f"Error listing workspaces: {e}")
return {}
def get_workspace_stats(self, namespace: str) -> Dict[str, int]:
"""
Get statistics for a specific workspace.
Returns counts of documents in each collection type.
"""
try:
stats = {}
collection_suffixes = ['_nodes', '_edges', '_kv_store', '_vectors', '_doc_status']
for suffix in collection_suffixes:
coll_name = f"{namespace}{suffix}"
if self.db.has_collection(coll_name):
collection = self.db.collection(coll_name)
stats[suffix.lstrip('_')] = collection.count()
logger.debug(f"Workspace '{namespace}' stats: {stats}")
return stats
except Exception as e:
logger.error(f"Error getting workspace stats: {e}")
return {}
def delete_workspace(self, namespace: str, confirm: bool = False) -> bool:
"""
Delete all collections for a workspace.
Requires confirm=True for safety.
"""
if not confirm:
logger.warning(f"Workspace deletion requires confirm=True. Namespace: {namespace}")
return False
try:
deleted_collections = []
collection_suffixes = ['_nodes', '_edges', '_kv_store', '_vectors', '_doc_status']
for suffix in collection_suffixes:
coll_name = f"{namespace}{suffix}"
if self.db.has_collection(coll_name):
self.db.delete_collection(coll_name)
deleted_collections.append(coll_name)
logger.info(f"Deleted workspace '{namespace}': {deleted_collections}")
return True
except Exception as e:
logger.error(f"Error deleting workspace: {e}")
return False
@dataclass
class ArangoDBStorage(BaseGraphStorage):
"""ArangoDB storage backend"""
def __init__(self, namespace, global_config, embedding_func, workspace=None):
super().__init__(
namespace=namespace,
global_config=global_config,
embedding_func=embedding_func,
workspace=workspace,
)
self.host = os.environ.get("ARANGO_HOST", "http://localhost:8529")
self.username = os.environ.get("ARANGO_USERNAME", "root")
self.password = os.environ.get("ARANGO_PASSWORD", "")
self.db_name = os.environ.get("ARANGO_DATABASE", "_system")
logger.info(f"Initializing ArangoDB at {self.host}")
if embedding_func is None:
logger.info("Loading embedding model...")
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
else:
self.embedding_model = embedding_func
self.client = ArangoClient(hosts=self.host)
try:
self.db = self.client.db(
self.db_name,
username=self.username,
password=self.password
)
self.db.version()
logger.info("Connected to ArangoDB")
except Exception as e:
logger.error(f"Failed to connect: {e}")
raise
self._setup_collections()
def _setup_collections(self):
nodes_name = f"{self.namespace}_nodes"
edges_name = f"{self.namespace}_edges"
if not self.db.has_collection(nodes_name):
self.nodes_collection = self.db.create_collection(nodes_name)
logger.info(f"Created {nodes_name}")
else:
self.nodes_collection = self.db.collection(nodes_name)
if not self.db.has_collection(edges_name):
self.edges_collection = self.db.create_collection(edges_name, edge=True)
logger.info(f"Created {edges_name}")
else:
self.edges_collection = self.db.collection(edges_name)
self.nodes_name = nodes_name
self.edges_name = edges_name
try:
self.nodes_collection.add_hash_index(fields=["label"], unique=False)
except:
pass
def _node_key(self, node_id: str) -> str:
clean_id = re.sub(r'[^a-zA-Z0-9_]', '_', node_id.strip('"'))
if clean_id and not (clean_id[0].isalpha() or clean_id[0] == '_'):
clean_id = f"n_{clean_id}"
return clean_id
async def close(self):
pass
async def __aexit__(self, exc_type, exc, tb):
await self.close()
async def index_done_callback(self) -> None:
pass
async def has_node(self, node_id: str) -> bool:
try:
key = self._node_key(node_id)
return self.nodes_collection.has(key)
except:
return False
async def has_edge(self, source_node_id: str, target_node_id: str) -> bool:
try:
source_key = self._node_key(source_node_id)
target_key = self._node_key(target_node_id)
from_ref = f"{self.nodes_name}/{source_key}"
to_ref = f"{self.nodes_name}/{target_key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @from_ref AND edge._to == @to_ref
LIMIT 1
RETURN edge
"""
cursor = self.db.aql.execute(
aql,
bind_vars={"from_ref": from_ref, "to_ref": to_ref}
)
return cursor.count() > 0
except:
return False
async def get_node(self, node_id: str) -> Optional[Dict[str, Any]]:
try:
key = self._node_key(node_id)
if self.nodes_collection.has(key):
node = self.nodes_collection.get(key)
if node:
node.pop("_id", None)
node.pop("_key", None)
node.pop("_rev", None)
return node
return None
except:
return None
async def node_degree(self, node_id: str) -> int:
try:
key = self._node_key(node_id)
node_ref = f"{self.nodes_name}/{key}"
aql = f"""
LET outgoing = (FOR edge IN {self.edges_name} FILTER edge._from == @node RETURN 1)
LET incoming = (FOR edge IN {self.edges_name} FILTER edge._to == @node RETURN 1)
RETURN LENGTH(outgoing) + LENGTH(incoming)
"""
cursor = self.db.aql.execute(aql, bind_vars={"node": node_ref})
result = list(cursor)
return result[0] if result else 0
except:
return 0
async def edge_degree(self, src_id: str, tgt_id: str) -> int:
src_degree = await self.node_degree(src_id)
tgt_degree = await self.node_degree(tgt_id)
return src_degree + tgt_degree
async def get_edge(self, source_node_id: str, target_node_id: str) -> Optional[Dict[str, Any]]:
try:
source_key = self._node_key(source_node_id)
target_key = self._node_key(target_node_id)
from_ref = f"{self.nodes_name}/{source_key}"
to_ref = f"{self.nodes_name}/{target_key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @from_ref AND edge._to == @to_ref
LIMIT 1
RETURN edge
"""
cursor = self.db.aql.execute(
aql,
bind_vars={"from_ref": from_ref, "to_ref": to_ref}
)
edges = list(cursor)
if edges:
edge = edges[0]
edge.pop("_id", None)
edge.pop("_key", None)
edge.pop("_rev", None)
edge.pop("_from", None)
edge.pop("_to", None)
edge.setdefault("weight", 0.0)
edge.setdefault("source_id", source_node_id)
edge.setdefault("description", None)
edge.setdefault("keywords", None)
return edge
return {
"weight": 0.0,
"description": None,
"keywords": None,
"source_id": None,
}
except:
return {
"weight": 0.0,
"description": None,
"keywords": None,
"source_id": None,
}
async def get_node_edges(self, source_node_id: str) -> Optional[List[Tuple[str, str]]]:
try:
key = self._node_key(source_node_id)
node_ref = f"{self.nodes_name}/{key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @node OR edge._to == @node
LET from_node = DOCUMENT(edge._from)
LET to_node = DOCUMENT(edge._to)
RETURN {{from_label: from_node.label, to_label: to_node.label}}
"""
cursor = self.db.aql.execute(aql, bind_vars={"node": node_ref})
edges = []
for edge in cursor:
if edge["from_label"] and edge["to_label"]:
edges.append((edge["from_label"], edge["to_label"]))
return edges
except:
return []
async def upsert_node(self, node_id: str, node_data: Dict[str, Any]) -> None:
try:
key = self._node_key(node_id)
node_doc = {**node_data, "label": node_id}
self.nodes_collection.insert(
{"_key": key, **node_doc},
overwrite=True
)
logger.debug(f"Upserted node: {node_id}")
except Exception as e:
logger.error(f"Error upserting node: {e}")
raise
async def upsert_edge(self, source_node_id: str, target_node_id: str, edge_data: Dict[str, Any]) -> None:
try:
source_key = self._node_key(source_node_id)
target_key = self._node_key(target_node_id)
if not self.nodes_collection.has(source_key):
await self.upsert_node(source_node_id, {})
if not self.nodes_collection.has(target_key):
await self.upsert_node(target_node_id, {})
from_ref = f"{self.nodes_name}/{source_key}"
to_ref = f"{self.nodes_name}/{target_key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @from_ref AND edge._to == @to_ref
RETURN edge
"""
cursor = self.db.aql.execute(
aql,
bind_vars={"from_ref": from_ref, "to_ref": to_ref}
)
existing_edges = list(cursor)
edge_doc = {"_from": from_ref, "_to": to_ref, **edge_data}
if existing_edges:
edge_key = existing_edges[0]["_key"]
self.edges_collection.update({"_key": edge_key, **edge_doc})
else:
self.edges_collection.insert(edge_doc)
logger.debug(f"Upserted edge: {source_node_id} -> {target_node_id}")
except Exception as e:
logger.error(f"Error upserting edge: {e}")
raise
async def get_knowledge_graph(self, node_label: str, max_depth: int = 5):
try:
from ..types import KnowledgeGraph, KnowledgeGraphNode, KnowledgeGraphEdge
result = KnowledgeGraph()
if node_label == "*":
aql = f"""
LET nodes = (FOR node IN {self.nodes_name} LIMIT 1000 RETURN node)
LET edges = (FOR edge IN {self.edges_name} RETURN edge)
RETURN {{nodes: nodes, edges: edges}}
"""
cursor = self.db.aql.execute(aql)
else:
clean_label = node_label.strip('"')
aql = f"""
FOR start IN {self.nodes_name}
FILTER start.label LIKE @pattern
FOR v, e, p IN 0..@depth ANY start {self.edges_name}
RETURN DISTINCT {{node: v, edge: e}}
"""
cursor = self.db.aql.execute(
aql,
bind_vars={"pattern": f"%{clean_label}%", "depth": max_depth}
)
seen_nodes = set()
seen_edges = set()
for item in cursor:
if isinstance(item, dict) and "nodes" in item:
for node in item["nodes"]:
node_key = node["_key"]
if node_key not in seen_nodes:
result.nodes.append(
KnowledgeGraphNode(
id=node_key,
labels=[node.get("label", "")],
properties=dict(node)
)
)
seen_nodes.add(node_key)
for edge in item["edges"]:
edge_key = edge["_key"]
if edge_key not in seen_edges:
result.edges.append(
KnowledgeGraphEdge(
id=edge_key,
type=edge.get("relationship", "RELATED"),
source=edge["_from"].split("/")[1],
target=edge["_to"].split("/")[1],
properties=dict(edge)
)
)
seen_edges.add(edge_key)
else:
if item.get("node"):
node = item["node"]
node_key = node["_key"]
if node_key not in seen_nodes:
result.nodes.append(
KnowledgeGraphNode(
id=node_key,
labels=[node.get("label", "")],
properties=dict(node)
)
)
seen_nodes.add(node_key)
if item.get("edge") and item["edge"]:
edge = item["edge"]
edge_key = edge["_key"]
if edge_key not in seen_edges:
result.edges.append(
KnowledgeGraphEdge(
id=edge_key,
type=edge.get("relationship", "RELATED"),
source=edge["_from"].split("/")[1],
target=edge["_to"].split("/")[1],
properties=dict(edge)
)
)
seen_edges.add(edge_key)
logger.info(f"Retrieved graph: {len(result.nodes)} nodes, {len(result.edges)} edges")
return result
except:
from ..types import KnowledgeGraph
return KnowledgeGraph()
async def get_all_labels(self) -> List[str]:
try:
aql = f"""
FOR node IN {self.nodes_name}
RETURN DISTINCT node.label
"""
cursor = self.db.aql.execute(aql)
return sorted([label for label in cursor if label])
except:
return []
async def delete_node(self, node_id: str) -> None:
"""Delete a node by ID"""
try:
key = self._node_key(node_id)
if self.nodes_collection.has(key):
# Delete all edges connected to this node first
node_ref = f"{self.nodes_name}/{key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @node OR edge._to == @node
REMOVE edge IN {self.edges_name}
"""
self.db.aql.execute(aql, bind_vars={"node": node_ref})
# Delete the node
self.nodes_collection.delete(key)
logger.debug(f"Deleted node: {node_id}")
except Exception as e:
logger.error(f"Error deleting node {node_id}: {e}")
raise
async def drop(self) -> None:
"""Drop all collections"""
try:
for collection_name in [self.nodes_name, self.edges_name]:
if self.db.has_collection(collection_name):
self.db.delete_collection(collection_name)
logger.info(f"Dropped collection: {collection_name}")
except Exception as e:
logger.error(f"Error dropping collections: {e}")
raise
async def get_all_nodes(self) -> List[Dict[str, Any]]:
"""Get all nodes from the graph"""
try:
aql = f"FOR node IN {self.nodes_name} RETURN node"
cursor = self.db.aql.execute(aql)
nodes = []
for node in cursor:
node.pop("_id", None)
node.pop("_key", None)
node.pop("_rev", None)
nodes.append(node)
return nodes
except Exception as e:
logger.error(f"Error getting all nodes: {e}")
return []
async def get_all_edges(self) -> List[Dict[str, Any]]:
"""Get all edges from the graph"""
try:
aql = f"FOR edge IN {self.edges_name} RETURN edge"
cursor = self.db.aql.execute(aql)
edges = []
for edge in cursor:
edge.pop("_id", None)
edge.pop("_key", None)
edge.pop("_rev", None)
edges.append(edge)
return edges
except Exception as e:
logger.error(f"Error getting all edges: {e}")
return []
async def remove_nodes(self, node_ids: List[str]) -> None:
"""Remove multiple nodes by their IDs"""
try:
for node_id in node_ids:
await self.delete_node(node_id)
except Exception as e:
logger.error(f"Error removing nodes: {e}")
raise
async def remove_edges(self, edge_ids: List[Tuple[str, str]]) -> None:
"""Remove multiple edges by their source-target pairs"""
try:
for source_id, target_id in edge_ids:
source_key = self._node_key(source_id)
target_key = self._node_key(target_id)
from_ref = f"{self.nodes_name}/{source_key}"
to_ref = f"{self.nodes_name}/{target_key}"
aql = f"""
FOR edge IN {self.edges_name}
FILTER edge._from == @from_ref AND edge._to == @to_ref
REMOVE edge IN {self.edges_name}
"""
self.db.aql.execute(aql, bind_vars={"from_ref": from_ref, "to_ref": to_ref})
except Exception as e:
logger.error(f"Error removing edges: {e}")
raise
async def get_popular_labels(self, top_k: int = 10) -> List[Tuple[str, int]]:
"""Get the most popular node labels (most connected nodes)"""
try:
aql = f"""
FOR node IN {self.nodes_name}
LET inbound = LENGTH(FOR v IN 1..1 INBOUND node {self.edges_name} RETURN v)
LET outbound = LENGTH(FOR v IN 1..1 OUTBOUND node {self.edges_name} RETURN v)
LET total = inbound + outbound
SORT total DESC
LIMIT @top_k
RETURN {{label: node.label, count: total}}
"""
cursor = self.db.aql.execute(aql, bind_vars={"top_k": top_k})
return [(doc["label"], doc["count"]) for doc in cursor if doc.get("label")]
except Exception as e:
logger.error(f"Error getting popular labels: {e}")
return []
async def search_labels(self, query: str, top_k: int = 10) -> List[str]:
"""Search for node labels matching a query"""
try:
# Simple substring search on labels
aql = f"""
FOR node IN {self.nodes_name}
FILTER CONTAINS(LOWER(node.label), LOWER(@query))
LIMIT @top_k
RETURN DISTINCT node.label
"""
cursor = self.db.aql.execute(aql, bind_vars={"query": query, "top_k": top_k})
return [label for label in cursor if label]
except Exception as e:
logger.error(f"Error searching labels: {e}")
return []
# ========================================================================
# WORKSPACE MANAGEMENT METHODS - NEW
# ========================================================================
async def get_current_workspace(self) -> str:
"""Get the current workspace (namespace) name"""
return self.namespace
async def list_all_workspaces(self) -> Dict[str, List[str]]:
"""List all available workspaces in the database"""
try:
manager = ArangoDBWorkspaceManager(
self.host, self.username, self.password, self.db_name
)
return manager.list_workspaces()
except Exception as e:
logger.error(f"Error listing workspaces: {e}")
return {}
async def get_workspace_stats(self) -> Dict[str, int]:
"""Get statistics for the current workspace"""
try:
manager = ArangoDBWorkspaceManager(
self.host, self.username, self.password, self.db_name
)
return manager.get_workspace_stats(self.namespace)
except Exception as e:
logger.error(f"Error getting workspace stats: {e}")
return {}
# ============================================================================
# KV STORAGE IMPLEMENTATION
# ============================================================================
from ..base import BaseKVStorage
@dataclass
class ArangoDBKVStorage(BaseKVStorage):
"""ArangoDB Key-Value storage for document chunks and metadata"""
def __init__(self, namespace, global_config, embedding_func, workspace=None):
super().__init__(
namespace=namespace,
global_config=global_config,
embedding_func=embedding_func,
workspace=workspace,
)
self.host = os.environ.get("ARANGO_HOST", "http://localhost:8529")
self.username = os.environ.get("ARANGO_USERNAME", "root")
self.password = os.environ.get("ARANGO_PASSWORD", "")
self.db_name = os.environ.get("ARANGO_DATABASE", "_system")
logger.info(f"Initializing ArangoDB KV Storage at {self.host}")
self.client = ArangoClient(hosts=self.host)
try:
self.db = self.client.db(
self.db_name,
username=self.username,
password=self.password
)
logger.info("Connected to ArangoDB for KV Storage")
except Exception as e:
logger.error(f"Failed to connect: {e}")
raise
self._setup_kv_collection()
def _setup_kv_collection(self):
"""Setup KV collection for document storage"""
kv_name = f"{self.namespace}_kv_store"
if not self.db.has_collection(kv_name):
self.kv_collection = self.db.create_collection(kv_name)
logger.info(f"Created {kv_name}")
else:
self.kv_collection = self.db.collection(kv_name)
self.kv_name = kv_name
try:
self.kv_collection.add_hash_index(fields=["id"], unique=True)
except:
pass
def _sanitize_key(self, key: str) -> str:
"""Sanitize key to be ArangoDB-compatible"""
clean_key = re.sub(r'[^a-zA-Z0-9_\-:.]', '_', str(key))
if clean_key and not (clean_key[0].isalpha() or clean_key[0] == '_'):
clean_key = f"kv_{clean_key}"
return clean_key
async def get_by_id(self, id: str) -> Optional[Dict[str, Any]]:
"""Retrieve a document by ID"""
try:
key = self._sanitize_key(id)
if self.kv_collection.has(key):
doc = self.kv_collection.get(key)
if doc:
doc.pop("_id", None)
doc.pop("_key", None)
doc.pop("_rev", None)
return doc
return None
except Exception as e:
logger.error(f"Error getting document by id {id}: {e}")
return None
async def get_by_ids(self, ids: List[str]) -> List[Optional[Dict[str, Any]]]:
"""Retrieve multiple documents by IDs"""
results = []
for id in ids:
doc = await self.get_by_id(id)
results.append(doc)
return results
async def filter_keys(self, filter_func) -> List[str]:
"""Filter keys based on a filter function"""
try:
aql = f"""
FOR doc IN {self.kv_name}
RETURN doc
"""
cursor = self.db.aql.execute(aql)
filtered_keys = []
for doc in cursor:
if filter_func(doc.get("id", doc.get("_key"))):
filtered_keys.append(doc.get("id", doc.get("_key")))
return filtered_keys
except Exception as e:
logger.error(f"Error filtering keys: {e}")
return []
async def upsert(self, data: Dict[str, Any]) -> None:
"""Insert or update document(s)"""
try:
if "id" in data:
# Single document case
id = data["id"]
key = self._sanitize_key(id)
doc = {"_key": key, **data}
self.kv_collection.insert(doc, overwrite=True)
logger.debug(f"Upserted KV document: {id}")
else:
# Batch upsert case - data is dict of {id: {content, ...}}
for doc_id, doc_data in data.items():
key = self._sanitize_key(doc_id)
# Add the id field to the document data
doc = {"_key": key, "id": doc_id, **doc_data}
self.kv_collection.insert(doc, overwrite=True)
logger.debug(f"Upserted KV document: {doc_id}")
except Exception as e:
logger.error(f"Error upserting document: {e}")
raise
async def index_done_callback(self) -> None:
"""Callback after indexing is done"""
pass
async def drop(self) -> None:
"""Drop the KV collection"""
try:
if self.db.has_collection(self.kv_name):
self.db.delete_collection(self.kv_name)
logger.info(f"Dropped collection: {self.kv_name}")
except Exception as e:
logger.error(f"Error dropping collection: {e}")
raise
async def delete(self, key: str) -> None:
"""Delete a document by key"""
try:
doc_key = self._sanitize_key(key)
if self.kv_collection.has(doc_key):
self.kv_collection.delete(doc_key)
logger.debug(f"Deleted document: {key}")
except Exception as e:
logger.error(f"Error deleting document {key}: {e}")
raise
async def is_empty(self) -> bool:
"""Check if the collection is empty"""
try:
return self.kv_collection.count() == 0
except Exception as e:
logger.error(f"Error checking if collection is empty: {e}")
return True
# ========================================================================
# WORKSPACE MANAGEMENT METHODS - NEW
# ========================================================================
async def get_current_workspace(self) -> str:
"""Get the current workspace (namespace) name"""
return self.namespace
async def list_all_workspaces(self) -> Dict[str, List[str]]:
"""List all available workspaces in the database"""
try:
manager = ArangoDBWorkspaceManager(
self.host, self.username, self.password, self.db_name
)
return manager.list_workspaces()
except Exception as e:
logger.error(f"Error listing workspaces: {e}")
return {}
# ========================================================================
# METADATA FILTERING METHODS - NEW
# ========================================================================
async def filter_by_metadata(
self,
metadata_filters: Dict[str, Any],
return_fields: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
"""
Filter documents by metadata fields with support for:
- Exact match: {"user_id": "123", "department": "engineering"}
- List membership: {"authorized_users": ["user1", "user2"]} - checks if user is IN list
- Multiple conditions: Combined with AND logic
Args:
metadata_filters: Dict of field:value pairs to filter by
return_fields: Optional list of fields to return. If None, returns all fields.
Returns:
List of documents matching ALL filter criteria (AND logic)
"""
try:
if not metadata_filters:
logger.warning("No metadata filters provided")
return []
# Build AQL filter conditions
filter_conditions = []
bind_vars = {}
for idx, (field, value) in enumerate(metadata_filters.items()):
var_name = f"val_{idx}"
if isinstance(value, list):
filter_conditions.append(
f"("
f" (IS_ARRAY(doc.{field}) AND LENGTH(INTERSECTION(@{var_name}, doc.{field})) > 0) OR "
f" (NOT IS_ARRAY(doc.{field}) AND doc.{field} IN @{var_name}) OR "
f" (IS_ARRAY(doc.metadata.{field}) AND LENGTH(INTERSECTION(@{var_name}, doc.metadata.{field})) > 0) OR "
f" (NOT IS_ARRAY(doc.metadata.{field}) AND doc.metadata.{field} IN @{var_name})"
f")"
)
bind_vars[var_name] = value
else:
# Exact match - check both top-level and nested metadata
filter_conditions.append(f"(doc.{field} == @{var_name} OR doc.metadata.{field} == @{var_name})")
bind_vars[var_name] = value
# Combine conditions with AND
filter_clause = " AND ".join(filter_conditions)
# Build RETURN clause
if return_fields:
return_fields_str = ", ".join([f'"{f}":doc.{f}' for f in return_fields])
return_clause = f"{{ {return_fields_str} }}"
else:
return_clause = "doc"
# Execute query
aql = f"""
FOR doc IN {self.kv_name}
FILTER {filter_clause}
RETURN {return_clause}
"""
logger.debug(f"Metadata filter AQL: {aql}")
logger.debug(f"Bind vars: {bind_vars}")
cursor = self.db.aql.execute(aql, bind_vars=bind_vars)
results = []
for doc in cursor:
if not return_fields:
# Clean up system fields
doc.pop("_id", None)
doc.pop("_key", None)
doc.pop("_rev", None)
results.append(doc)
logger.info(f"Metadata filter returned {len(results)} documents")
return results
except Exception as e:
logger.error(f"Error filtering by metadata: {e}")
import traceback
logger.error(traceback.format_exc())
return []
async def get_with_metadata(self, ids: List[str]) -> List[Dict[str, Any]]:
"""
Get documents by IDs with ALL metadata preserved for citations.
Args:
ids: List of document IDs to retrieve
Returns:
List of documents with complete metadata
"""
try:
results = []
for doc_id in ids:
doc = await self.get_by_id(doc_id)
if doc:
results.append(doc)
logger.debug(f"Retrieved {len(results)} documents with metadata")
return results
except Exception as e:
logger.error(f"Error getting documents with metadata: {e}")
return []
async def drop(self) -> None:
"""Drop the entire KV collection"""
try:
if self.db.has_collection(self.kv_name):
self.db.delete_collection(self.kv_name)
logger.info(f"Dropped collection: {self.kv_name}")
except Exception as e:
logger.error(f"Error dropping collection: {e}")
raise
# ============================================================================
# VECTOR STORAGE IMPLEMENTATION
# ============================================================================
from ..base import BaseVectorStorage
@dataclass
class ArangoDBVectorStorage(BaseVectorStorage):
"""ArangoDB Vector storage for embeddings and similarity search"""
def __init__(self, namespace, global_config, embedding_func, meta_fields=None, workspace=None):
super().__init__(
namespace=namespace,
global_config=global_config,
embedding_func=embedding_func,
meta_fields=meta_fields or {},
workspace=workspace,
)
self.host = os.environ.get("ARANGO_HOST", "http://localhost:8529")
self.username = os.environ.get("ARANGO_USERNAME", "root")
self.password = os.environ.get("ARANGO_PASSWORD", "")
self.db_name = os.environ.get("ARANGO_DATABASE", "_system")
logger.info(f"Initializing ArangoDB Vector Storage at {self.host}")
if embedding_func is None:
logger.info("Loading embedding model for vector storage...")
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
else:
self.embedding_model = embedding_func
# Auto-detect embedding dimension from the model
self.embedding_dim = self._detect_embedding_dimension()
logger.info(f"Auto-detected embedding dimension: {self.embedding_dim}")
self.client = ArangoClient(hosts=self.host)
try: