Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(langchain): honor nested filters and index field selectors (#6404)

z1gond5022f57559f
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.md
index 1c47da27a..6e9b6ce97 100644
--- a/docs/en/agent-integrations/07-langchain-langgraph.md
+++ b/docs/en/agent-integrations/07-langchain-langgraph.md
@@ -271,6 +271,11 @@ errors propagate, and `put()` does not overwrite a record after a failed read.
`list_namespaces(prefix=("users", "*"))` matches one namespace label per `*`, including
when `root_uri` uses a peer home alias such as `viking://~/peers/support/memories/langgraph_store`.
+`search()` accepts nested JSON filters such as `filter={"metadata": {"color": "blue"}}`.
+Filter keys `eq`, `ne`, `gt`, `gte`, `lt`, `lte` and `in` are reserved operator aliases at every nesting level.
+Use `index=["items[*].text"]` to index selected array fields while retaining the complete
+stored value. Existing index projections are updated when the item is written again.
+
### LangGraph middleware
```python
diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.md
index 1cb7b089f..a2611530b 100644
--- a/docs/zh/agent-integrations/07-langchain-langgraph.md
+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md
@@ -258,6 +258,11 @@ store.put(("users", "ada"), "preferences", None) # 值为 None 表示删除该
`list_namespaces(prefix=("users", "*"))` 中的每个 `*` 匹配一层命名空间,
也适用于 `viking://~/peers/support/memories/langgraph_store` 这样的 peer 主目录别名。
+`search()` 支持 `filter={"metadata": {"color": "blue"}}` 这样的嵌套 JSON 筛选。
+筛选中的 `eq`、`ne`、`gt`、`gte`、`lt`、`lte` 和 `in` 在所有嵌套层级均为保留的运算符别名。
+使用 `index=["items[*].text"]` 可以只索引数组中的指定字段,同时保留完整的存储值。
+已有条目的索引会在再次写入该条目时更新。
+
### LangGraph middleware
```python
diff --git a/integrations/frameworks/langchain/src/langchain_openviking/store.py b/integrations/frameworks/langchain/src/langchain_openviking/store.py
index e1e4e5a3c..c977c2346 100644
--- a/integrations/frameworks/langchain/src/langchain_openviking/store.py
+++ b/integrations/frameworks/langchain/src/langchain_openviking/store.py
@@ -35,6 +35,7 @@ if TYPE_CHECKING:
PutOp,
SearchItem,
SearchOp,
+ get_text_at_path,
)
else:
try:
@@ -47,6 +48,7 @@ else:
PutOp,
SearchItem,
SearchOp,
+ get_text_at_path,
)
except ImportError: # pragma: no cover - exercised by optional import path
_LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")
@@ -559,7 +561,11 @@ def _extract_uris(value: Any) -> list[str]:
def _project_value(value: dict[str, Any], index: bool | list[str] | None) -> dict[str, Any]:
if isinstance(index, list):
- return {field: _nested_value(value, field) for field in index}
+ projected = {field: _nested_value(value, field) for field in index}
+ for field in index:
+ if projected[field] is None:
+ projected[field] = get_text_at_path(value, field) or None
+ return projected
return value
@@ -577,15 +583,32 @@ def _matches_filter(value: dict[str, Any], filter: dict[str, Any] | None) -> boo
return True
for path, expected in filter.items():
actual = _nested_value(value, path)
- if isinstance(expected, dict):
- for op, target in expected.items():
- if not _compare(actual, op, target):
- return False
- elif actual != expected:
+ if not _matches_value(actual, expected):
return False
return True
+def _matches_value(actual: Any, expected: Any) -> bool:
+ if isinstance(expected, dict):
+ if any(
+ key.startswith("$") or key in {"eq", "ne", "gt", "gte", "lt", "lte", "in"}
+ for key in expected
+ ):
+ return all(_compare(actual, op, target) for op, target in expected.items())
+ return isinstance(actual, dict) and all(
+ _matches_value(actual.get(key), target) for key, target in expected.items()
+ )
+ if isinstance(expected, (list, tuple)):
+ return (
+ isinstance(actual, (list, tuple))
+ and len(actual) == len(expected)
+ and all(
+ _matches_value(left, right) for left, right in zip(actual, expected, strict=False)
+ )
+ )
+ return actual == expected
+
+
def _compare(actual: Any, op: str, target: Any) -> bool:
if op in {"$eq", "eq"}:
return actual == target
diff --git a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py
index 063657047..a90e24fb2 100644
--- a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py
+++ b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py
@@ -24,7 +24,7 @@ from langchain_core.messages import (
convert_to_openai_messages,
)
from langchain_core.runnables import RunnableLambda
-from langgraph.store.base import InvalidNamespaceError, PutOp
+from langgraph.store.base import InvalidNamespaceError, PutOp, SearchOp
from openviking_sdk.errors import (
InvalidArgumentError,
NotFoundError,
@@ -1894,6 +1894,58 @@ def test_langgraph_store_removal_keeps_missing_targets_idempotent(missing_error)
assert store.search(namespace, query="azure") == []
[email protected]("query", [None, "doc"])
+ "filter, expected",
+ [
+ ({"metadata": {"color": "blue"}}, ["alpha"]),
+ ({"metadata": {"nested": {"owner": "ada"}}}, ["alpha"]),
+ ({"metadata": {"nested": {"rank": {"$gte": 2}}}}, ["alpha"]),
+ ({"metadata": {"detail.region": "eu"}}, ["alpha"]),
+ ({"tags": [{"role": "reviewer"}, "memory"]}, ["alpha"]),
+ ({"tags": [{"role": "reviewer"}]}, []),
+ ({"metadata": {}}, ["alpha", "beta"]),
+ ({"metadata": {"color": "black"}}, []),
+ ({"metadata.nested.rank": {"gte": 2}}, ["alpha"]),
+ ({"metadata.nested": {"$eq": {"rank": 3, "owner": "ada"}}}, ["alpha"]),
+ ({"metadata": {"eq": "blue", "label": "blue"}}, ["scalar"]),
+ ({"metadata": {"$unknown": "blue"}}, ["scalar"]),
+ ({"tags": ["reviewer", "memory"]}, ["scalar"]),
+ ({"kind": "doc"}, ["alpha", "beta", "scalar"]),
+ ],
+)
+async def test_langgraph_store_structured_filters(filter, expected, query):
+ store = OpenVikingStore(client=InMemoryOpenVikingClient())
+ for key, value in {
+ "alpha": {
+ "kind": "doc",
+ "metadata": {
+ "color": "blue",
+ "nested": {"rank": 3, "owner": "ada"},
+ "detail.region": "eu",
+ },
+ "tags": [{"role": "reviewer", "active": True}, "memory"],
+ },
+ "beta": {
+ "kind": "doc",
+ "metadata": {"color": "red", "nested": {"rank": 1, "owner": "bob"}},
+ "tags": [{"role": "reader", "active": True}, "memory"],
+ },
+ "scalar": {"kind": "doc", "metadata": "blue", "tags": ["reviewer", "memory"]},
+ }.items():
+ store.put(("users", "ada"), key, value)
+
+ op = SearchOp(("users",), filter=filter, query=query)
+ results = [
+ store.search(("users",), filter=filter, query=query),
+ await store.asearch(("users",), filter=filter, query=query),
+ store.batch([op])[0],
+ (await store.abatch([op]))[0],
+ ]
+ assert all(sorted(item.key for item in items) == expected for items in results)
+
+
def test_langgraph_store_semantic_search_keeps_peer_id_out_of_retrieval():
client = InMemoryOpenVikingClient()
store = OpenVikingStore(client=client, actor_peer_id="peer-store")
@@ -1911,6 +1963,71 @@ def test_langgraph_store_rejects_ttl_writes():
store.put(("users", "ada"), "temporary", {"note": "expires"}, ttl=60)
[email protected]("use_default", [False, True])
+ ("field", "query", "expected_match"),
+ [
+ ("$", "solstice", True),
+ ("", "solstice", True),
+ ("items[0].text", "pulsar", True),
+ ("items[-1].text", "galaxy", True),
+ ("items[*].text", "galaxy", True),
+ ("nested[*].parts[*].text", "aurora", True),
+ ("metadata.*", "quasar", True),
+ ("{text,metadata.title}", "nebula", True),
+ ("text", "nebula", True),
+ ("metadata.title", "quasar", True),
+ ("absent", "solstice", False),
+ ("literal[0]", "nova", True),
+ ],
+)
+async def test_langgraph_store_indexes_selected_field_paths(
+ field, query, expected_match, use_default
+):
+ value = {
+ "text": "nebula",
+ "metadata": {"title": "quasar"},
+ "items": [{"text": "pulsar"}, {"text": "galaxy"}],
+ "nested": [{"parts": [{"text": "aurora"}]}],
+ "literal[0]": "nova",
+ "ignored": "solstice",
+ }
+ original = deepcopy(value)
+ for mode in ("put", "aput", "batch", "abatch"):
+ client = InMemoryOpenVikingClient()
+ store = OpenVikingStore(client=client, index=[field] if use_default else None)
+ index = None if use_default else [field]
+ if mode == "put":
+ store.put(("documents",), "note", value, index=index)
+ elif mode == "aput":
+ await store.aput(("documents",), "note", value, index=index)
+ elif mode == "batch":
+ store.batch([PutOp(("documents",), "note", value, index=index)])
+ else:
+ await store.abatch([PutOp(("documents",), "note", value, index=index)])
+
+ assert store.get(("documents",), "note").value == value
+ assert value == original
+ expected_keys = ["note"] if expected_match else []
+ assert [item.key for item in store.search(("documents",), query=query)] == expected_keys
+ filter = {"metadata": {"title": "quasar"}}
+ op = SearchOp(("documents",), query=query, filter=filter)
+ results = [
+ store.search(("documents",), query=query, filter=filter),
+ await store.asearch(("documents",), query=query, filter=filter),
+ store.batch([op])[0],
+ (await store.abatch([op]))[0],
+ ]
+ assert all([item.key for item in items] == expected_keys for items in results)
+ assert (
+ store.search(("documents",), query=query, filter={"metadata": {"title": "absent"}})
+ == []
+ )
+ if field not in {"$", ""}:
+ assert store.search(("documents",), query="solstice") == []
+
+
def test_langgraph_store_batch_rejects_ttl_writes():
store = OpenVikingStore(client=InMemoryOpenVikingClient())