LightRAG/lightrag/kg/json_doc_status_impl.py

113 lines
3.9 KiB
Python
Raw Normal View History

2025-01-27 09:08:14 +01:00
from dataclasses import dataclass
2025-02-09 21:24:13 +01:00
import os
from typing import Any, Union, final
2025-01-27 09:08:14 +01:00
from lightrag.base import (
DocProcessingStatus,
2025-02-09 19:21:49 +01:00
DocStatus,
2025-01-27 09:08:14 +01:00
DocStatusStorage,
)
2025-02-09 19:21:49 +01:00
from lightrag.utils import (
load_json,
logger,
write_json,
)
from .shared_storage import (
get_namespace_data,
get_storage_lock,
try_initialize_namespace,
)
2025-01-27 09:08:14 +01:00
@final
2025-01-27 09:08:14 +01:00
@dataclass
class JsonDocStatusStorage(DocStatusStorage):
"""JSON implementation of document status storage"""
def __post_init__(self):
working_dir = self.global_config["working_dir"]
self._file_name = os.path.join(working_dir, f"kv_store_{self.namespace}.json")
self._storage_lock = get_storage_lock()
# check need_init must before get_namespace_data
need_init = try_initialize_namespace(self.namespace)
self._data = get_namespace_data(self.namespace)
if need_init:
loaded_data = load_json(self._file_name) or {}
with self._storage_lock:
self._data.update(loaded_data)
logger.info(
f"Loaded document status storage with {len(loaded_data)} records"
)
2025-01-27 09:08:14 +01:00
async def filter_keys(self, keys: set[str]) -> set[str]:
2025-01-27 09:08:14 +01:00
"""Return keys that should be processed (not in storage or not successfully processed)"""
with self._storage_lock:
return set(keys) - set(self._data.keys())
2025-02-09 19:21:49 +01:00
async def get_by_ids(self, ids: list[str]) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
with self._storage_lock:
for id in ids:
data = self._data.get(id, None)
if data:
result.append(data)
2025-02-09 19:21:49 +01:00
return result
2025-01-27 09:08:14 +01:00
2025-02-09 15:24:30 +01:00
async def get_status_counts(self) -> dict[str, int]:
2025-01-27 09:08:14 +01:00
"""Get counts of documents in each status"""
2025-02-16 14:51:24 +01:00
counts = {status.value: 0 for status in DocStatus}
with self._storage_lock:
for doc in self._data.values():
counts[doc["status"]] += 1
2025-01-27 09:08:14 +01:00
return counts
2025-02-16 15:52:59 +01:00
async def get_docs_by_status(
self, status: DocStatus
) -> dict[str, DocProcessingStatus]:
"""Get all documents with a specific status"""
result = {}
with self._storage_lock:
for k, v in self._data.items():
if v["status"] == status.value:
try:
# Make a copy of the data to avoid modifying the original
data = v.copy()
# If content is missing, use content_summary as content
if "content" not in data and "content_summary" in data:
data["content"] = data["content_summary"]
result[k] = DocProcessingStatus(**data)
except KeyError as e:
logger.error(f"Missing required field for document {k}: {e}")
continue
return result
2025-02-11 13:28:18 +08:00
async def index_done_callback(self) -> None:
with self._storage_lock:
data_dict = dict(self._data) if hasattr(self._data, "_getvalue") else self._data
write_json(data_dict, self._file_name)
2025-01-27 09:08:14 +01:00
2025-02-16 14:50:04 +01:00
async def upsert(self, data: dict[str, dict[str, Any]]) -> None:
2025-02-19 22:22:41 +01:00
logger.info(f"Inserting {len(data)} to {self.namespace}")
if not data:
return
with self._storage_lock:
self._data.update(data)
2025-01-27 09:08:14 +01:00
await self.index_done_callback()
2025-02-09 21:12:39 +01:00
async def get_by_id(self, id: str) -> Union[dict[str, Any], None]:
with self._storage_lock:
return self._data.get(id)
2025-01-27 09:08:14 +01:00
async def delete(self, doc_ids: list[str]):
with self._storage_lock:
for doc_id in doc_ids:
self._data.pop(doc_id, None)
2025-02-17 23:20:10 +01:00
await self.index_done_callback()
2025-02-18 10:24:54 +01:00
2025-02-18 10:22:16 +01:00
async def drop(self) -> None:
"""Drop the storage"""
with self._storage_lock:
self._data.clear()