forked from HKUDS/LightRAG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_impl.py
1511 lines (1339 loc) · 57.2 KB
/
postgres_impl.py
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
import asyncio
import inspect
import json
import os
import time
from dataclasses import dataclass
from typing import Union, List, Dict, Set, Any, Tuple, Optional, Callable
import numpy as np
import pipmaster as pm
if not pm.is_installed("asyncpg"):
pm.install("asyncpg")
import asyncpg
import sys
from tqdm.asyncio import tqdm as tqdm_async
from tenacity import (
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
from ..utils import logger
from ..base import (
BaseKVStorage,
BaseVectorStorage,
DocStatusStorage,
DocStatus,
DocProcessingStatus,
BaseGraphStorage,
T,
)
if sys.platform.startswith("win"):
import asyncio.windows_events
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class PostgreSQLDB:
def __init__(self, config, **kwargs):
self.pool = None
self.host = config.get("host", "localhost")
self.port = config.get("port", 5432)
self.user = config.get("user", "postgres")
self.password = config.get("password", None)
self.database = config.get("database", "postgres")
self.workspace = config.get("workspace", "default")
self.max = 12
self.increment = 1
logger.info(f"Using the label {self.workspace} for PostgreSQL as identifier")
if self.user is None or self.password is None or self.database is None:
raise ValueError(
"Missing database user, password, or database in addon_params"
)
async def initdb(self):
try:
self.pool = await asyncpg.create_pool(
user=self.user,
password=self.password,
database=self.database,
host=self.host,
port=self.port,
min_size=1,
max_size=self.max,
)
logger.info(
f"Connected to PostgreSQL database at {self.host}:{self.port}/{self.database}"
)
except Exception as e:
logger.error(
f"Failed to connect to PostgreSQL database at {self.host}:{self.port}/{self.database}"
)
logger.error(f"PostgreSQL database error: {e}")
raise
async def check_tables(self):
for k, v in TABLES.items():
try:
logger.info(f"Checking if table {k} exists...")
await self.query("SELECT 1 FROM {k} LIMIT 1".format(k=k))
logger.info(f"Table {k} exists")
except Exception as e:
logger.error(f"Failed to check table {k} in PostgreSQL database")
logger.error(f"PostgreSQL database error: {e}")
try:
logger.info(f"Attempting to create table {k}")
await self.execute(v['ddl'])
# Verify the table was actually created
await self.query("SELECT 1 FROM {k} LIMIT 1".format(k=k))
logger.info(f"Successfully created and verified table {k}")
except Exception as e:
logger.error(f"Failed to create table {k} in PostgreSQL database")
logger.error(f"PostgreSQL database error: {e}")
raise # Re-raise the exception to fail fast
logger.info("Finished checking all tables in PostgreSQL database")
async def query(
self,
sql: str,
params: dict = None,
multirows: bool = False,
for_age: bool = False,
graph_name: str = None,
) -> Union[dict, None, list[dict]]:
async with self.pool.acquire() as connection:
try:
if for_age:
await PostgreSQLDB._prerequisite(connection, graph_name)
if params:
rows = await connection.fetch(sql, *params.values())
else:
rows = await connection.fetch(sql)
if multirows:
if rows:
columns = [col for col in rows[0].keys()]
data = [dict(zip(columns, row)) for row in rows]
else:
data = []
else:
if rows:
columns = rows[0].keys()
data = dict(zip(columns, rows[0]))
else:
data = None
return data
except Exception as e:
logger.error(f"PostgreSQL database error: {e}")
print(sql)
print(params)
raise
async def execute(
self,
sql: str,
data: Union[list, dict] = None,
for_age: bool = False,
graph_name: str = None,
upsert: bool = False,
):
try:
async with self.pool.acquire() as connection:
if for_age:
await PostgreSQLDB._prerequisite(connection, graph_name)
if data is None:
await connection.execute(sql)
else:
await connection.execute(sql, *data.values())
except (
asyncpg.exceptions.UniqueViolationError,
asyncpg.exceptions.DuplicateTableError,
) as e:
if upsert:
print("Key value duplicate, but upsert succeeded.")
else:
logger.error(f"Upsert error: {e}")
except Exception as e:
logger.error(f"PostgreSQL database error: {e.__class__} - {e}")
print(sql)
print(data)
raise
@staticmethod
async def _prerequisite(conn: asyncpg.Connection, graph_name: str):
try:
await conn.execute('SET search_path = ag_catalog, "$user", public')
await conn.execute(f"""select create_graph('{graph_name}')""")
except (
asyncpg.exceptions.InvalidSchemaNameError,
asyncpg.exceptions.UniqueViolationError,
):
pass
@dataclass
class PGKVStorage(BaseKVStorage):
db: PostgreSQLDB = None
def __post_init__(self):
self._max_batch_size = self.global_config["embedding_batch_num"]
################ QUERY METHODS ################
async def get_by_id(self, id: str) -> Union[dict, None]:
"""Get doc_full data by id."""
sql = SQL_TEMPLATES["get_by_id_" + self.namespace]
params = {"workspace": self.db.workspace, "id": id}
if "llm_response_cache" == self.namespace:
array_res = await self.db.query(sql, params, multirows=True)
res = {}
for row in array_res:
res[row["id"]] = row
else:
res = await self.db.query(sql, params)
if res:
return res
else:
return None
async def get_by_mode_and_id(self, mode: str, id: str) -> Union[dict, None]:
"""Specifically for llm_response_cache."""
sql = SQL_TEMPLATES["get_by_mode_id_" + self.namespace]
params = {"workspace": self.db.workspace, mode: mode, "id": id}
if "llm_response_cache" == self.namespace:
array_res = await self.db.query(sql, params, multirows=True)
res = {}
for row in array_res:
res[row["id"]] = row
return res
else:
return None
# Query by id
async def get_by_ids(self, ids: List[str], fields=None) -> Union[List[dict], None]:
"""Get doc_chunks data by id"""
sql = SQL_TEMPLATES["get_by_ids_" + self.namespace].format(
ids=",".join([f"'{id}'" for id in ids])
)
params = {"workspace": self.db.workspace}
if "llm_response_cache" == self.namespace:
array_res = await self.db.query(sql, params, multirows=True)
modes = set()
dict_res: dict[str, dict] = {}
for row in array_res:
modes.add(row["mode"])
for mode in modes:
if mode not in dict_res:
dict_res[mode] = {}
for row in array_res:
dict_res[row["mode"]][row["id"]] = row
res = [{k: v} for k, v in dict_res.items()]
else:
res = await self.db.query(sql, params, multirows=True)
if res:
return res
else:
return None
async def get_all_docs(self) -> List[Dict[str, Any]]:
"""Get all documents from storage.
Returns:
List of document dictionaries containing id and doc_name
"""
try:
if self.namespace == "full_docs":
sql = """
SELECT id, doc_name
FROM LIGHTRAG_DOC_FULL
WHERE workspace = $1
ORDER BY id
"""
results = await self.db.query(sql, {"workspace": self.db.workspace}, multirows=True)
return results if results else []
return [] # Return empty list for other namespaces
except Exception as e:
logger.error(f"Error getting all documents from {self.namespace}: {e}")
raise
async def get_all(self) -> dict:
"""Get all entries from the cache
Returns:
dict: All cache entries organized by mode and id
"""
if self.namespace == "llm_response_cache":
sql = f"""
SELECT id, original_prompt, return_value as "return", mode
FROM {NAMESPACE_TABLE_MAP[self.namespace]}
WHERE workspace = $1
"""
results = await self.db.query(sql, {"workspace": self.db.workspace}, multirows=True)
# Organize results by mode
cache_data = {}
if results:
for row in results:
mode = row.pop("mode") # Remove mode from row data
if mode not in cache_data:
cache_data[mode] = {}
cache_data[mode][row["id"]] = row
return cache_data
else:
logger.warning(f"get_all() not implemented for namespace {self.namespace}")
return {}
async def all_keys(self) -> list[dict]:
if "llm_response_cache" == self.namespace:
sql = "select workspace,mode,id from lightrag_llm_cache"
res = await self.db.query(sql, multirows=True)
return res
else:
logger.error(
f"all_keys is only implemented for llm_response_cache, not for {self.namespace}"
)
async def filter(self, filter_func):
"""Filter key-value pairs based on a filter function
Args:
filter_func: The filter function, which takes a value as an argument and returns a boolean value
Returns:
Dict: Key-value pairs that meet the condition
"""
if self.namespace == "text_chunks":
sql = """SELECT c.id, c.tokens, COALESCE(c.content, '') as content,
c.chunk_order_index, c.full_doc_id, f.doc_name
FROM LIGHTRAG_DOC_CHUNKS c
JOIN lightrag_doc_full f ON f.id = c.full_doc_id
WHERE c.workspace=$1 AND f.workspace=$1"""
params = {"workspace": self.db.workspace}
results = await self.db.query(sql, params, multirows=True)
filtered_results = {}
if results:
for row in results:
if filter_func(row):
filtered_results[row['id']] = row
return filtered_results
else:
logger.warning(f"Filter operation not implemented for namespace {self.namespace}")
return {}
async def filter_keys(self, keys: List[str]) -> Set[str]:
"""Filter out duplicated content"""
sql = SQL_TEMPLATES["filter_keys"].format(
table_name=NAMESPACE_TABLE_MAP[self.namespace],
ids=",".join([f"'{id}'" for id in keys]),
)
params = {"workspace": self.db.workspace}
try:
res = await self.db.query(sql, params, multirows=True)
if res:
exist_keys = [key["id"] for key in res]
else:
exist_keys = []
data = set([s for s in keys if s not in exist_keys])
return data
except Exception as e:
logger.error(f"PostgreSQL database error: {e}")
print(sql)
print(params)
################ INSERT METHODS ################
async def upsert(self, data: Dict[str, dict]):
if self.namespace == "text_chunks":
pass
elif self.namespace == "full_docs":
for k, v in data.items():
_data = {
"id": k,
"content": v["content"],
"workspace": self.db.workspace,
}
if "doc_name" in v:
upsert_sql = SQL_TEMPLATES["upsert_doc_full_with_doc_name"]
_data["doc_name"] = v["doc_name"]
else:
upsert_sql = SQL_TEMPLATES["upsert_doc_full"]
await self.db.execute(upsert_sql, _data)
elif self.namespace == "llm_response_cache":
for mode, items in data.items():
for k, v in items.items():
upsert_sql = SQL_TEMPLATES["upsert_llm_response_cache"]
_data = {
"workspace": self.db.workspace,
"id": k,
"original_prompt": v["original_prompt"],
"return_value": v["return"],
"mode": mode,
}
await self.db.execute(upsert_sql, _data)
async def index_done_callback(self):
if self.namespace in ["full_docs", "text_chunks"]:
logger.info("full doc and chunk data had been saved into postgresql db!")
async def delete(self, ids: list[str]):
"""Delete records with specified IDs
Args:
ids: List of IDs to be deleted
"""
try:
if not ids:
return
# Map namespace to table name
table_name = {
"full_docs": "LIGHTRAG_DOC_FULL",
"text_chunks": "LIGHTRAG_DOC_CHUNKS",
"llm_response_cache": "LIGHTRAG_LLM_CACHE",
"doc_status": "LIGHTRAG_DOC_STATUS"
}.get(self.namespace)
if not table_name:
raise ValueError(f"Unknown namespace: {self.namespace}")
# Create parameterized query
placeholders = ','.join([f"'{id}'" for id in ids])
sql = f"""
DELETE FROM {table_name}
WHERE workspace = $1 AND id IN ({placeholders})
"""
await self.db.execute(sql, {"workspace": self.db.workspace})
logger.info(f"Successfully deleted {len(ids)} records from {self.namespace}")
except Exception as e:
logger.error(f"Error while deleting records from {self.namespace}: {e}")
raise
@dataclass
class PGVectorStorage(BaseVectorStorage):
cosine_better_than_threshold: float = float(os.getenv("COSINE_THRESHOLD", "0.2"))
db: PostgreSQLDB = None
def __post_init__(self):
self._max_batch_size = self.global_config["embedding_batch_num"]
# Use global config value if specified, otherwise use default
config = self.global_config.get("vector_db_storage_cls_kwargs", {})
self.cosine_better_than_threshold = config.get(
"cosine_better_than_threshold", self.cosine_better_than_threshold
)
@property
async def client_storage(self):
"""Return data structure needed for debugging and entity/relationship checks"""
if self.namespace == "entities":
sql = """SELECT id, entity_name, content FROM LIGHTRAG_VDB_ENTITY
WHERE workspace=$1"""
elif self.namespace == "relationships":
sql = """SELECT id, source_id, target_id, content FROM LIGHTRAG_VDB_RELATION
WHERE workspace=$1"""
else:
return {"data": []}
params = {"workspace": self.db.workspace}
result = await self.db.query(sql, params, multirows=True)
return {"data": result if result else []}
def _upsert_chunks(self, item: dict):
try:
upsert_sql = SQL_TEMPLATES["upsert_chunk"]
data = {
"workspace": self.db.workspace,
"id": item["__id__"],
"tokens": item["tokens"],
"chunk_order_index": item["chunk_order_index"],
"full_doc_id": item["full_doc_id"],
"content": item["content"],
"content_vector": json.dumps(item["__vector__"].tolist()),
}
except Exception as e:
logger.error(f"Error to prepare upsert sql: {e}")
print(item)
raise e
return upsert_sql, data
def _upsert_entities(self, item: dict):
upsert_sql = SQL_TEMPLATES["upsert_entity"]
data = {
"workspace": self.db.workspace,
"id": item["__id__"],
"entity_name": item["entity_name"],
"content": item["content"],
"content_vector": json.dumps(item["__vector__"].tolist()),
}
return upsert_sql, data
def _upsert_relationships(self, item: dict):
upsert_sql = SQL_TEMPLATES["upsert_relationship"]
data = {
"workspace": self.db.workspace,
"id": item["__id__"],
"source_id": item["src_id"],
"target_id": item["tgt_id"],
"content": item["content"],
"content_vector": json.dumps(item["__vector__"].tolist()),
}
return upsert_sql, data
async def upsert(self, data: Dict[str, dict]):
logger.info(f"Inserting {len(data)} vectors to {self.namespace}")
if not len(data):
logger.warning("You insert an empty data to vector DB")
return []
current_time = time.time()
list_data = [
{
"__id__": k,
"__created_at__": current_time,
**{k1: v1 for k1, v1 in v.items()},
}
for k, v in data.items()
]
contents = [v["content"] for v in data.values()]
batches = [
contents[i : i + self._max_batch_size]
for i in range(0, len(contents), self._max_batch_size)
]
async def wrapped_task(batch):
result = await self.embedding_func(batch)
pbar.update(1)
return result
embedding_tasks = [wrapped_task(batch) for batch in batches]
pbar = tqdm_async(
total=len(embedding_tasks), desc="Generating embeddings", unit="batch"
)
embeddings_list = await asyncio.gather(*embedding_tasks)
embeddings = np.concatenate(embeddings_list)
for i, d in enumerate(list_data):
d["__vector__"] = embeddings[i]
for item in list_data:
if self.namespace == "chunks":
upsert_sql, data = self._upsert_chunks(item)
elif self.namespace == "entities":
upsert_sql, data = self._upsert_entities(item)
elif self.namespace == "relationships":
upsert_sql, data = self._upsert_relationships(item)
else:
raise ValueError(f"{self.namespace} is not supported")
await self.db.execute(upsert_sql, data)
async def index_done_callback(self):
logger.info("vector data had been saved into postgresql db!")
#################### query method ###############
async def query(
self,
query_text: str,
top_k: int = 5,
filter_func: Optional[Callable] = None
) -> List[Dict]:
# Generate embedding for query
embedding = await self.embedding_func([query_text])
embedding = embedding[0] if isinstance(embedding, np.ndarray) else embedding
embedding_string = ','.join(map(str, embedding.tolist()))
# Optimized query that joins tables and gets all necessary data in one go
base_sql = f"""
SELECT
c.id,
COALESCE(c.content, '') as content,
c.tokens,
c.chunk_order_index,
c.full_doc_id,
f.doc_name,
1 - (c.content_vector <=> '[{embedding_string}]'::vector) as similarity
FROM {NAMESPACE_TABLE_MAP[self.namespace]} c
JOIN LIGHTRAG_DOC_FULL f ON f.id = c.full_doc_id
WHERE c.workspace = $1 AND f.workspace = $1
"""
if filter_func:
# If filter is provided, get all results and filter in Python
results = await self.db.query(
base_sql + " ORDER BY similarity DESC",
{"workspace": self.db.workspace},
multirows=True
)
filtered_results = [r for r in results if filter_func(r)]
return filtered_results[:top_k]
else:
# Standard top-k query
results = await self.db.query(
base_sql + f" ORDER BY similarity DESC LIMIT {top_k}",
{"workspace": self.db.workspace},
multirows=True
)
return results if results else []
async def delete(self, ids: list[str]):
"""Delete vectors with specified IDs
Args:
ids: List of vector IDs to be deleted
"""
try:
if not ids:
return
# Different tables for different namespaces
table_name = {
"chunks": "LIGHTRAG_DOC_CHUNKS",
"entities": "LIGHTRAG_VDB_ENTITY",
"relationships": "LIGHTRAG_VDB_RELATION"
}.get(self.namespace)
if not table_name:
raise ValueError(f"Unknown namespace: {self.namespace}")
# Create SQL with parameterized query
placeholders = ','.join([f"'{id}'" for id in ids])
sql = f"""
DELETE FROM {table_name}
WHERE workspace = $1 AND id IN ({placeholders})
"""
await self.db.execute(sql, {"workspace": self.db.workspace})
logger.info(f"Successfully deleted {len(ids)} vectors from {self.namespace}")
except Exception as e:
logger.error(f"Error while deleting vectors from {self.namespace}: {e}")
raise
async def get_all_docs(self) -> List[Dict]:
"""Get all documents from the vector storage.
Returns:
List[Dict]: List of all documents with their metadata
"""
try:
# SQL to get all documents based on namespace
if self.namespace == "chunks":
sql = """SELECT id, content_vector, full_doc_id as source_id
FROM LIGHTRAG_DOC_CHUNKS
WHERE workspace=$1"""
elif self.namespace == "entities":
sql = """SELECT id, content_vector, entity_name as source_id
FROM LIGHTRAG_VDB_ENTITY
WHERE workspace=$1"""
elif self.namespace == "relationships":
sql = """SELECT id, content_vector, source_id, target_id
FROM LIGHTRAG_VDB_RELATION
WHERE workspace=$1"""
else:
logger.warning(f"Unsupported namespace for get_all_docs: {self.namespace}")
return []
params = {"workspace": self.db.workspace}
results = await self.db.query(sql, params, multirows=True)
return results if results else []
except Exception as e:
logger.error(f"Error getting all docs from {self.namespace}: {e}")
return []
@dataclass
class PGDocStatusStorage(DocStatusStorage):
"""PostgreSQL implementation of document status storage"""
db: PostgreSQLDB = None
def __post_init__(self):
pass
async def filter_keys(self, data: list[str]) -> set[str]:
"""Return keys that don't exist in storage"""
keys = ",".join([f"'{_id}'" for _id in data])
sql = (
f"SELECT id FROM LIGHTRAG_DOC_STATUS WHERE workspace=$1 AND id IN ({keys})"
)
result = await self.db.query(sql, {"workspace": self.db.workspace}, True)
# The result is like [{'id': 'id1'}, {'id': 'id2'}, ...].
if result is None:
return set(data)
else:
existed = set([element["id"] for element in result])
return set(data) - existed
async def get(self, doc_id: str) -> Union[DocProcessingStatus, None]:
"""Get document status by ID"""
result = await self.get_by_id(doc_id)
if result is None:
return None
return DocProcessingStatus(
content_length=result["content_length"],
content_summary=result["content_summary"],
status=result["status"],
chunks_count=result["chunks_count"],
created_at=result["created_at"],
updated_at=result["updated_at"]
)
async def get_by_id(self, id: str) -> Union[T, None]:
sql = "select * from LIGHTRAG_DOC_STATUS where workspace=$1 and id=$2"
params = {"workspace": self.db.workspace, "id": id}
result = await self.db.query(sql, params, True)
if result is None or len(result) == 0:
return None
else:
return DocProcessingStatus(
content_length=result[0]["content_length"],
content_summary=result[0]["content_summary"],
status=result[0]["status"],
chunks_count=result[0]["chunks_count"],
created_at=result[0]["created_at"],
updated_at=result[0]["updated_at"],
)
async def get_status_counts(self) -> Dict[str, int]:
"""Get counts of documents in each status"""
sql = """SELECT status as "status", COUNT(1) as "count"
FROM LIGHTRAG_DOC_STATUS
where workspace=$1 GROUP BY STATUS
"""
result = await self.db.query(sql, {"workspace": self.db.workspace}, True)
# Result is like [{'status': 'PENDING', 'count': 1}, {'status': 'PROCESSING', 'count': 2}, ...]
counts = {}
for doc in result:
counts[doc["status"]] = doc["count"]
return counts
async def get_docs_by_status(
self, status: DocStatus
) -> Dict[str, DocProcessingStatus]:
"""Get all documents by status"""
sql = "select * from LIGHTRAG_DOC_STATUS where workspace=$1 and status=$1"
params = {"workspace": self.db.workspace, "status": status}
result = await self.db.query(sql, params, True)
# Result is like [{'id': 'id1', 'status': 'PENDING', 'updated_at': '2023-07-01 00:00:00'}, {'id': 'id2', 'status': 'PENDING', 'updated_at': '2023-07-01 00:00:00'}, ...]
# Converting to be a dict
return {
element["id"]: DocProcessingStatus(
content_summary=element["content_summary"],
content_length=element["content_length"],
status=element["status"],
created_at=element["created_at"],
updated_at=element["updated_at"],
chunks_count=element["chunks_count"],
)
for element in result
}
async def get_all_docs(self) -> List[Dict[str, Any]]:
"""Get all document statuses from storage.
Returns:
List of document status dictionaries
"""
try:
sql = """
SELECT id, doc_name, status, created_at, updated_at
FROM LIGHTRAG_DOC_STATUS
WHERE workspace = $1
ORDER BY created_at DESC
"""
results = await self.db.query(sql, {"workspace": self.db.workspace}, multirows=True)
return results if results else []
except Exception as e:
logger.error(f"Error getting all documents from doc_status: {e}")
raise
async def get_failed_docs(self) -> Dict[str, DocProcessingStatus]:
"""Get all failed documents"""
return await self.get_docs_by_status(DocStatus.FAILED)
async def get_pending_docs(self) -> Dict[str, DocProcessingStatus]:
"""Get all pending documents"""
return await self.get_docs_by_status(DocStatus.PENDING)
async def index_done_callback(self):
"""Save data after indexing, but for PostgreSQL, we already saved them during the upsert stage, so no action to take here"""
logger.info("Doc status had been saved into postgresql db!")
async def upsert(self, data: dict[str, dict]):
"""Update or insert document status
Args:
data: Dictionary of document IDs and their status data
"""
sql = """insert into LIGHTRAG_DOC_STATUS(workspace,id,content_summary,content_length,chunks_count,status)
values($1,$2,$3,$4,$5,$6)
on conflict(id,workspace) do update set
content_summary = EXCLUDED.content_summary,
content_length = EXCLUDED.content_length,
chunks_count = EXCLUDED.chunks_count,
status = EXCLUDED.status,
updated_at = CURRENT_TIMESTAMP"""
for k, v in data.items():
# chunks_count is optional
await self.db.execute(
sql,
{
"workspace": self.db.workspace,
"id": k,
"content_summary": v["content_summary"],
"content_length": v["content_length"],
"chunks_count": v["chunks_count"] if "chunks_count" in v else -1,
"status": v["status"],
},
)
return data
async def delete(self, ids: list[str]):
"""Delete document status records with specified IDs
Args:
ids: List of document IDs to be deleted
"""
try:
if not ids:
return
# Create parameterized query
placeholders = ','.join([f"'{id}'" for id in ids])
sql = f"""
DELETE FROM LIGHTRAG_DOC_STATUS
WHERE workspace = $1 AND id IN ({placeholders})
"""
await self.db.execute(sql, {"workspace": self.db.workspace})
logger.info(f"Successfully deleted {len(ids)} records from doc_status")
except Exception as e:
logger.error(f"Error while deleting records from doc_status: {e}")
raise
class PGGraphQueryException(Exception):
"""Exception for the AGE queries."""
def __init__(self, exception: Union[str, Dict]) -> None:
if isinstance(exception, dict):
self.message = exception["message"] if "message" in exception else "unknown"
self.details = exception["details"] if "details" in exception else "unknown"
else:
self.message = exception
self.details = "unknown"
def get_message(self) -> str:
return self.message
def get_details(self) -> Any:
return self.details
@dataclass
class PGGraphStorage(BaseGraphStorage):
db: PostgreSQLDB = None
@staticmethod
def load_nx_graph(file_name):
print("no preloading of graph with AGE in production")
def __init__(self, namespace, global_config, embedding_func):
super().__init__(
namespace=namespace,
global_config=global_config,
embedding_func=embedding_func,
)
self.graph_name = os.environ["AGE_GRAPH_NAME"]
self._node_embed_algorithms = {
"node2vec": self._node2vec_embed,
}
async def index_done_callback(self):
print("KG successfully indexed.")
@staticmethod
def _record_to_dict(record: asyncpg.Record) -> Dict[str, Any]:
"""
Convert a record returned from an age query to a dictionary
Args:
record (): a record from an age query result
Returns:
Dict[str, Any]: a dictionary representation of the record where
the dictionary key is the field name and the value is the
value converted to a python type
"""
# result holder
d = {}
# prebuild a mapping of vertex_id to vertex mappings to be used
# later to build edges
vertices = {}
for k in record.keys():
v = record[k]
# agtype comes back '{key: value}::type' which must be parsed
if isinstance(v, str) and "::" in v:
dtype = v.split("::")[-1]
v = v.split("::")[0]
if dtype == "vertex":
vertex = json.loads(v)
vertices[vertex["id"]] = vertex.get("properties")
# iterate returned fields and parse appropriately
for k in record.keys():
v = record[k]
if isinstance(v, str) and "::" in v:
dtype = v.split("::")[-1]
v = v.split("::")[0]
else:
dtype = ""
if dtype == "vertex":
vertex = json.loads(v)
field = vertex.get("properties")
if not field:
field = {}
field["label"] = PGGraphStorage._decode_graph_label(field["node_id"])
d[k] = field
# convert edge from id-label->id by replacing id with node information
# we only do this if the vertex was also returned in the query
# this is an attempt to be consistent with neo4j implementation
elif dtype == "edge":
edge = json.loads(v)
d[k] = (
vertices.get(edge["start_id"], {}),
edge[
"label"
], # we don't use decode_graph_label(), since edge label is always "DIRECTED"
vertices.get(edge["end_id"], {}),
)
else:
d[k] = json.loads(v) if isinstance(v, str) else v
return d
@staticmethod
def _format_properties(
properties: Dict[str, Any], _id: Union[str, None] = None
) -> str:
"""
Convert a dictionary of properties to a string representation that
can be used in a cypher query insert/merge statement.
Args:
properties (Dict[str,str]): a dictionary containing node/edge properties
_id (Union[str, None]): the id of the node or None if none exists
Returns:
str: the properties dictionary as a properly formatted string
"""
props = []
# wrap property key in backticks to escape
for k, v in properties.items():
prop = f"`{k}`: {json.dumps(v)}"
props.append(prop)
if _id is not None and "id" not in properties:
props.append(
f"id: {json.dumps(_id)}" if isinstance(_id, str) else f"id: {_id}"
)
return "{" + ", ".join(props) + "}"
@staticmethod
def _encode_graph_label(label: str) -> str:
"""
Since AGE supports only alphanumerical labels, we will encode generic label as HEX string
Args:
label (str): the original label
Returns:
str: the encoded label
"""
return "x" + label.encode().hex()
@staticmethod
def _decode_graph_label(encoded_label: str) -> str:
"""
Since AGE supports only alphanumerical labels, we will encode generic label as HEX string
Args:
encoded_label (str): the encoded label
Returns:
str: the decoded label
"""
return bytes.fromhex(encoded_label.removeprefix("x")).decode()
@staticmethod
def _get_col_name(field: str, idx: int) -> str:
"""
Convert a cypher return field to a pgsql select field
If possible keep the cypher column name, but create a generic name if necessary
Args:
field (str): a return field from a cypher query to be formatted for pgsql
idx (int): the position of the field in the return statement
Returns:
str: the field to be used in the pgsql select statement
"""
# remove white space
field = field.strip()