LightRAG/lightrag/kg/json_kv_impl.py

55 lines
1.6 KiB
Python
Raw Normal View History

2025-01-27 09:07:52 +01:00
import asyncio
import os
from dataclasses import dataclass
2025-02-09 19:51:05 +01:00
from typing import Any, Union
2025-01-27 09:07:52 +01:00
2025-02-09 19:51:05 +01:00
from lightrag.base import (
BaseKVStorage,
)
2025-01-27 09:07:52 +01:00
from lightrag.utils import (
load_json,
2025-02-09 19:51:05 +01:00
logger,
2025-01-27 09:07:52 +01:00
write_json,
)
2025-02-08 23:58:15 +01:00
2025-01-27 09:07:52 +01:00
@dataclass
class JsonKVStorage(BaseKVStorage):
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")
2025-02-08 23:02:40 +01:00
self._data: dict[str, Any] = load_json(self._file_name) or {}
2025-01-27 09:07:52 +01:00
self._lock = asyncio.Lock()
logger.info(f"Load KV {self.namespace} with {len(self._data)} data")
2025-02-09 15:24:30 +01:00
2025-01-27 09:07:52 +01:00
async def index_done_callback(self):
write_json(self._data, self._file_name)
2025-02-09 19:51:05 +01:00
async def get_by_id(self, id: str) -> Union[dict[str, Any], None]:
return self._data.get(id)
2025-01-27 09:07:52 +01:00
2025-02-09 10:33:15 +01:00
async def get_by_ids(self, ids: list[str]) -> list[dict[str, Any]]:
2025-01-27 09:07:52 +01:00
return [
(
{k: v for k, v in self._data[id].items()}
2025-01-27 09:07:52 +01:00
if self._data.get(id, None)
else None
)
for id in ids
]
2025-02-09 19:21:49 +01:00
async def filter_keys(self, data: set[str]) -> set[str]:
2025-02-09 21:24:13 +01:00
return set(data) - set(self._data.keys())
2025-01-27 09:07:52 +01:00
async def upsert(self, data: dict[str, dict[str, Any]]) -> None:
2025-01-27 09:07:52 +01:00
left_data = {k: v for k, v in data.items() if k not in self._data}
self._data.update(left_data)
async def drop(self) -> None:
2025-02-09 15:24:30 +01:00
self._data = {}
async def delete(self, ids: list[str]) -> None:
for doc_id in ids:
self._data.pop(doc_id, None)
await self.index_done_callback()