Skip to content

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

Path filter (#92)

kkkwjx393a4c5878d8
diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.py
index 6b51fb929..102498dc4 100644
--- a/openviking/storage/collection_schemas.py
+++ b/openviking/storage/collection_schemas.py
@@ -44,15 +44,15 @@ class CollectionSchemas:
"Description": "Unified context collection",
"Fields": [
{"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
- {"FieldName": "uri", "FieldType": "string"},
+ {"FieldName": "uri", "FieldType": "path"},
{"FieldName": "type", "FieldType": "string"},
{"FieldName": "context_type", "FieldType": "string"},
{"FieldName": "vector", "FieldType": "vector", "Dim": vector_dim},
- {"FieldName": "sparse_vector", "FieldType": "sparse_vector"}, # Sparse vector field
- {"FieldName": "created_at", "FieldType": "string"},
- {"FieldName": "updated_at", "FieldType": "string"},
+ {"FieldName": "sparse_vector", "FieldType": "sparse_vector"},
+ {"FieldName": "created_at", "FieldType": "date_time"},
+ {"FieldName": "updated_at", "FieldType": "date_time"},
{"FieldName": "active_count", "FieldType": "int64"},
- {"FieldName": "parent_uri", "FieldType": "string"},
+ {"FieldName": "parent_uri", "FieldType": "path"},
{"FieldName": "is_leaf", "FieldType": "bool"},
{"FieldName": "name", "FieldType": "string"},
{"FieldName": "description", "FieldType": "string"},
diff --git a/openviking/storage/vectordb/README.md b/openviking/storage/vectordb/README.md
index 47703031d..3f5f26c66 100644
--- a/openviking/storage/vectordb/README.md
+++ b/openviking/storage/vectordb/README.md
@@ -723,293 +723,9 @@ for group in agg_result.groups:
print(f"{group['value']}: {group['count']}")
```
-### 7. 实际应用场景示例
+### 7. 高级特性
-#### 7.1 文档检索系统
-
-```python
-import random
-import hashlib
-
-# 创建文档集合
-doc_meta = {
- "CollectionName": "document_search",
- "Fields": [
- {"FieldName": "doc_id", "FieldType": "int64", "IsPrimaryKey": True},
- {"FieldName": "title", "FieldType": "text"},
- {"FieldName": "content", "FieldType": "text"},
- {"FieldName": "author", "FieldType": "text"},
- {"FieldName": "category", "FieldType": "text"},
- {"FieldName": "publish_date", "FieldType": "int64"},
- {"FieldName": "view_count", "FieldType": "int64"},
- {"FieldName": "embedding", "FieldType": "vector", "Dim": 256},
- ]
-}
-
-doc_collection = get_or_create_local_collection(meta_data=doc_meta)
-
-# 插入文档数据
-documents = [
- {
- "doc_id": 1,
- "title": "Introduction to Machine Learning",
- "content": "Machine learning is a subset of artificial intelligence...",
- "author": "John Doe",
- "category": "AI",
- "publish_date": 20240101,
- "view_count": 1250,
- "embedding": [random.random() for _ in range(256)]
- },
- {
- "doc_id": 2,
- "title": "Deep Learning Fundamentals",
- "content": "Deep learning uses neural networks with multiple layers...",
- "author": "Jane Smith",
- "category": "AI",
- "publish_date": 20240115,
- "view_count": 2340,
- "embedding": [random.random() for _ in range(256)]
- },
- {
- "doc_id": 3,
- "title": "Natural Language Processing",
- "content": "NLP enables computers to understand human language...",
- "author": "Bob Johnson",
- "category": "NLP",
- "publish_date": 20240120,
- "view_count": 890,
- "embedding": [random.random() for _ in range(256)]
- }
-]
-
-doc_collection.upsert_data(documents)
-
-# 创建索引
-doc_collection.create_index("doc_index", {
- "IndexName": "doc_index",
- "VectorIndex": {"IndexType": "flat", "Distance": "ip"},
- "ScalarIndex": ["category", "author", "view_count", "publish_date"]
-})
-
-# 场景1: 查找相似文档
-query_vec = [random.random() for _ in range(256)]
-similar_docs = doc_collection.search_by_vector(
- index_name="doc_index",
- dense_vector=query_vec,
- limit=3,
- output_fields=["title", "author", "category"]
-)
-
-print("=== Similar Documents ===")
-for doc in similar_docs.data:
- print(f"- {doc.fields['title']} by {doc.fields['author']} ({doc.fields['category']})")
-
-# 场景2: 查找特定作者的热门文档
-popular_docs = doc_collection.search_by_scalar(
- index_name="doc_index",
- field="view_count",
- order="desc",
- filters={"op": "must", "field": "category", "conds": ["AI"]},
- limit=5,
- output_fields=["title", "view_count"]
-)
-
-print("\n=== Popular AI Documents ===")
-for doc in popular_docs.data:
- print(f"- {doc.fields['title']}: {doc.fields['view_count']} views")
-
-# 场景3: 统计各类别的文档数量
-category_stats = doc_collection.aggregate_data(
- index_name="doc_index",
- op="count",
- field="category"
-)
-
-print("\n=== Documents by Category ===")
-for group in category_stats.groups:
- print(f"- {group['value']}: {group['count']} documents")
-
-# 清理
-doc_collection.close()
-```
-
-#### 7.2 推荐系统
-
-```python
-import random
-import time
-
-# 创建用户行为集合
-user_behavior_meta = {
- "CollectionName": "user_behaviors",
- "Fields": [
- {"FieldName": "behavior_id", "FieldType": "int64", "IsPrimaryKey": True},
- {"FieldName": "user_id", "FieldType": "int64"},
- {"FieldName": "item_id", "FieldType": "int64"},
- {"FieldName": "behavior_type", "FieldType": "text"}, # view, click, purchase
- {"FieldName": "timestamp", "FieldType": "int64"},
- {"FieldName": "user_embedding", "FieldType": "vector", "Dim": 64},
- ]
-}
-
-behavior_collection = get_or_create_local_collection(meta_data=user_behavior_meta)
-
-# 模拟用户行为数据
-behaviors = []
-behavior_types = ["view", "click", "purchase"]
-for i in range(1, 101):
- behaviors.append({
- "behavior_id": i,
- "user_id": (i % 10) + 1,
- "item_id": (i % 20) + 1,
- "behavior_type": behavior_types[i % 3],
- "timestamp": int(time.time()) - random.randint(0, 86400 * 30), # Last 30 days
- "user_embedding": [random.random() for _ in range(64)]
- })
-
-behavior_collection.upsert_data(behaviors)
-
-# 创建索引
-behavior_collection.create_index("behavior_index", {
- "IndexName": "behavior_index",
- "VectorIndex": {"IndexType": "flat", "Distance": "ip"},
- "ScalarIndex": ["user_id", "item_id", "behavior_type", "timestamp"]
-})
-
-# 场景1: 为用户推荐相似用户购买的商品
-user_vec = [random.random() for _ in range(64)]
-recommendations = behavior_collection.search_by_vector(
- index_name="behavior_index",
- dense_vector=user_vec,
- limit=10,
- filters={"op": "must", "field": "behavior_type", "conds": ["purchase"]},
- output_fields=["user_id", "item_id", "behavior_type"]
-)
-
-print("=== Recommended Items (from similar users' purchases) ===")
-recommended_items = set()
-for rec in recommendations.data:
- item_id = rec.fields['item_id']
- if item_id not in recommended_items:
- recommended_items.add(item_id)
- print(f"- Item {item_id} (purchased by user {rec.fields['user_id']})")
-
-# 场景2: 分析不同行为类型的分布
-behavior_stats = behavior_collection.aggregate_data(
- index_name="behavior_index",
- op="count",
- field="behavior_type"
-)
-
-print("\n=== Behavior Type Distribution ===")
-for group in behavior_stats.groups:
- print(f"- {group['value']}: {group['count']} actions")
-
-# 场景3: 查找某个用户的最近行为
-recent_timestamp = int(time.time()) - 86400 * 7 # Last 7 days
-user_recent = behavior_collection.search_by_scalar(
- index_name="behavior_index",
- field="timestamp",
- order="desc",
- filters={
- "op": "range",
- "field": "timestamp",
- "gte": recent_timestamp
- },
- limit=20,
- output_fields=["user_id", "item_id", "behavior_type", "timestamp"]
-)
-
-print("\n=== Recent User Behaviors (Last 7 Days) ===")
-for behavior in user_recent.data[:5]: # Show top 5
- print(f"- User {behavior.fields['user_id']}: {behavior.fields['behavior_type']} "
- f"item {behavior.fields['item_id']}")
-
-# 清理
-behavior_collection.close()
-```
-
-#### 7.3 语义搜索缓存系统
-
-```python
-import hashlib
-import random
-
-# 创建查询缓存集合
-cache_meta = {
- "CollectionName": "query_cache",
- "Fields": [
- {"FieldName": "query_hash", "FieldType": "text", "IsPrimaryKey": True},
- {"FieldName": "query_text", "FieldType": "text"},
- {"FieldName": "query_embedding", "FieldType": "vector", "Dim": 128},
- {"FieldName": "result_count", "FieldType": "int64"},
- {"FieldName": "cache_time", "FieldType": "int64"},
- ]
-}
-
-cache_collection = get_or_create_local_collection(meta_data=cache_meta)
-
-# 创建索引
-cache_collection.create_index("cache_index", {
- "IndexName": "cache_index",
- "VectorIndex": {"IndexType": "flat", "Distance": "ip"}
-})
-
-# 缓存查询函数
-def cache_query(query_text, query_embedding, result_count):
- query_hash = hashlib.md5(query_text.encode()).hexdigest()
- cache_data = [{
- "query_hash": query_hash,
- "query_text": query_text,
- "query_embedding": query_embedding,
- "result_count": result_count,
- "cache_time": int(time.time())
- }]
- cache_collection.upsert_data(cache_data, ttl=3600) # Cache for 1 hour
- return query_hash
-
-# 查找相似查询
-def find_similar_cached_queries(query_embedding, limit=5):
- result = cache_collection.search_by_vector(
- index_name="cache_index",
- dense_vector=query_embedding,
- limit=limit,
- output_fields=["query_text", "result_count", "cache_time"]
- )
- return result.data
-
-# 模拟使用
-queries = [
- "machine learning tutorial",
- "deep learning basics",
- "neural network introduction",
- "artificial intelligence overview",
- "ML algorithms explained"
-]
-
-print("=== Caching Queries ===")
-for query in queries:
- emb = [random.random() for _ in range(128)]
- count = random.randint(10, 100)
- query_hash = cache_query(query, emb, count)
- print(f"Cached: '{query}' (hash: {query_hash[:8]}...)")
-
-# 搜索相似的缓存查询
-print("\n=== Finding Similar Cached Queries ===")
-test_embedding = [random.random() for _ in range(128)]
-similar = find_similar_cached_queries(test_embedding, limit=3)
-
-for item in similar:
- print(f"- '{item.fields['query_text']}': {item.fields['result_count']} results "
- f"(similarity: {1-item.score:.4f})")
-
-# 清理
-cache_collection.close()
-```
-
-### 8. 高级特性
-
-#### 8.1 自动 ID 生成
+#### 7.1 自动 ID 生成
```python
# 不指定主键的集合(使用自动生成的 AUTO_ID)
@@ -1043,7 +759,7 @@ for item in fetch_result.items:
auto_collection.close()
```
-#### 8.2 向量归一化
+#### 7.2 向量归一化
```python
import math
@@ -1119,6 +835,45 @@ filters = {"op": "range", "field": "price", "gt": 100}
filters = {"op": "range", "field": "discount", "lt": 0.5}
```
+#### 3. `time_range` - 时间范围查询(date_time)
+
+`date_time` 字段使用 `datetime.isoformat()` 格式,例如 `2026-02-06T12:34:56.123456`。
+不带时区的时间会按**本地时区**解析。
+
+```python
+# 大于等于(ISO 时间字符串)
+filters = {
+ "op": "time_range",
+ "field": "created_at",
+ "gte": "2026-02-01T00:00:00"
+}
+
+# 时间范围(闭区间)
+filters = {
+ "op": "time_range",
+ "field": "created_at",
+ "gte": "2026-02-01T00:00:00",
+ "lte": "2026-02-07T23:59:59"
+}
+```
+
+#### 4. `geo_range` - 地理范围查询(geo_point)
+
+`geo_point` 字段写入格式为 `"longitude,latitude"`,其中:
+- `longitude` ∈ (-180, 180)
+- `latitude` ∈ (-90, 90)
+
+`radius` 支持 `m` 和 `km` 单位。
+
+```python
+filters = {
+ "op": "geo_range",
+ "field": "f_geo_point",
+ "center": "116.412138,39.914912",
+ "radius": "10km"
+}
+```
+
### 复杂过滤示例
```python
diff --git a/openviking/storage/vectordb/collection/local_collection.py b/openviking/storage/vectordb/collection/local_collection.py
index 43604f838..eaeea3c0b 100644
--- a/openviking/storage/vectordb/collection/local_collection.py
+++ b/openviking/storage/vectordb/collection/local_collection.py
@@ -38,6 +38,7 @@ from openviking.storage.vectordb.utils.constants import (
AggregateKeys,
SpecialFields,
)
+from openviking.storage.vectordb.utils.data_processor import DataProcessor
from openviking.storage.vectordb.utils.dict_utils import ThreadSafeDictManager
from openviking.storage.vectordb.utils.id_generator import generate_auto_id
from openviking.storage.vectordb.utils.str_to_uint64 import str_to_uint64
@@ -145,6 +146,9 @@ class LocalCollection(ICollection):
)
self.store_mgr: Optional[StoreManager] = store_mgr
+ self.data_processor = DataProcessor(
+ self.meta.fields_dict, collection_name=self.meta.collection_name
+ )
self.vectorizer_adapter = None
if meta.vectorize and vectorizer:
self.vectorizer_adapter = VectorizerAdapter(vectorizer, meta.vectorize)
@@ -166,6 +170,9 @@ class LocalCollection(ICollection):
if not meta_data:
return
self.meta.update(meta_data)
+ self.data_processor = DataProcessor(
+ self.meta.fields_dict, collection_name=self.meta.collection_name
+ )
def get_meta_data(self):
return self.meta.get_meta_data()
@@ -263,7 +270,7 @@ class LocalCollection(ICollection):
# Request more results to handle offset
actual_limit = limit + offset
label_list, scores_list = index.search(
- dense_vector or [], actual_limit, filters or {}, sparse_raw_terms, sparse_values
+ dense_vector or [], actual_limit, filters, sparse_raw_terms, sparse_values
)
# Apply offset by slicing the results
@@ -476,12 +483,20 @@ class LocalCollection(ICollection):
# data interface
def upsert_data(self, raw_data_list: List[Dict[str, Any]], ttl=0):
result = UpsertDataResult()
- for data in raw_data_list:
- if not validation.is_valid_fields_data(data, self.meta.fields_dict):
- return result
- data_list = [data.copy() for data in raw_data_list]
- for data in data_list:
- validation.fix_fields_data(data, self.meta.fields_dict)
+ data_list = []
+
+ for raw_data in raw_data_list:
+ if self.data_processor:
+ try:
+ data = self.data_processor.validate_and_process(raw_data)
+ except ValueError as e:
+ logger.error(f"Data validation failed: {e}, raw_data: {raw_data}")
+ return result
+ else:
+ # Should not happen given init logic, but for safety
+ data = raw_data
+ data_list.append(data)
+
dense_emb, sparse_emb = (
self.vectorizer_adapter.vectorize_raw_data(data_list)
if self.vectorizer_adapter
diff --git a/openviking/storage/vectordb/index/local_index.py b/openviking/storage/vectordb/index/local_index.py
index 4132b19ec..9b9c36f47 100644
--- a/openviking/storage/vectordb/index/local_index.py
+++ b/openviking/storage/vectordb/index/local_index.py
@@ -12,6 +12,7 @@ import openviking.storage.vectordb.engine as engine
from openviking.storage.vectordb.index.index import IIndex
from openviking.storage.vectordb.store.data import CandidateData, DeltaRecord
from openviking.storage.vectordb.utils.constants import IndexFileMarkers
+from openviking.storage.vectordb.utils.data_processor import DataProcessor
from openviking.utils.logger import default_logger as logger
@@ -211,6 +212,7 @@ class LocalIndex(IIndex):
index_path_or_json, normalize_vector_flag
)
self.meta = meta
+ self.field_type_converter = DataProcessor(self.meta.collection_meta.fields_dict)
pass
def update(
@@ -232,11 +234,11 @@ class LocalIndex(IIndex):
def upsert_data(self, delta_list: List[DeltaRecord]):
if self.engine_proxy:
- self.engine_proxy.upsert_data(delta_list)
+ self.engine_proxy.upsert_data(self._convert_delta_list_for_index(delta_list))
def delete_data(self, delta_list: List[DeltaRecord]):
if self.engine_proxy:
- self.engine_proxy.delete_data(delta_list)
+ self.engine_proxy.delete_data(self._convert_delta_list_for_index(delta_list))
def search(
self,
@@ -255,6 +257,8 @@ class LocalIndex(IIndex):
if sparse_values is None:
sparse_values = []
+ if self.field_type_converter and filters is not None:
+ filters = self.field_type_converter.convert_filter_for_index(filters)
return self.engine_proxy.search(
query_vector, limit, filters, sparse_raw_terms, sparse_values
)
@@ -274,6 +278,8 @@ class LocalIndex(IIndex):
req.topk = 1
if filters is None:
filters = {}
+ if self.field_type_converter and filters is not None:
+ filters = self.field_type_converter.convert_filter_for_index(filters)
req.dsl = json.dumps(filters)
logger.debug(f"aggregate DSL: {filters}")
@@ -326,6 +332,50 @@ class LocalIndex(IIndex):
return self.engine_proxy.get_data_count()
return 0
+ def _convert_delta_list_for_index(self, delta_list: List[DeltaRecord]) -> List[DeltaRecord]:
+ if not self.field_type_converter:
+ return delta_list
+ converted: List[DeltaRecord] = []
+ for data in delta_list:
+ item = DeltaRecord(type=data.type)
+ item.label = data.label
+ item.vector = list(data.vector) if data.vector else []
+ item.sparse_raw_terms = list(data.sparse_raw_terms) if data.sparse_raw_terms else []
+ item.sparse_values = list(data.sparse_values) if data.sparse_values else []
+ item.fields = (
+ self.field_type_converter.convert_fields_for_index(data.fields)
+ if data.fields
+ else data.fields
+ )
+ item.old_fields = (
+ self.field_type_converter.convert_fields_for_index(data.old_fields)
+ if data.old_fields
+ else data.old_fields
+ )
+ converted.append(item)
+ return converted
+
+ def _convert_candidate_list_for_index(
+ self, cands_list: List[CandidateData]
+ ) -> List[CandidateData]:
+ if not self.field_type_converter:
+ return cands_list
+ converted: List[CandidateData] = []
+ for data in cands_list:
+ item = CandidateData()
+ item.label = data.label
+ item.vector = list(data.vector) if data.vector else []
+ item.sparse_raw_terms = list(data.sparse_raw_terms) if data.sparse_raw_terms else []
+ item.sparse_values = list(data.sparse_values) if data.sparse_values else []
+ item.fields = (
+ self.field_type_converter.convert_fields_for_index(data.fields)
+ if data.fields
+ else data.fields
+ )
+ item.expire_ns_ts = data.expire_ns_ts
+ converted.append(item)
+ return converted
+
class VolatileIndex(LocalIndex):
"""In-memory index implementation without persistence.
@@ -379,7 +429,8 @@ class VolatileIndex(LocalIndex):
# Directly initialize engine_proxy without calling parent __init__
self.engine_proxy = IndexEngineProxy(index_config_json, normalize_vector_flag)
self.meta = meta
- self.engine_proxy.add_data(cands_list)
+ self.field_type_converter = DataProcessor(self.meta.collection_meta.fields_dict)
+ self.engine_proxy.add_data(self._convert_candidate_list_for_index(cands_list))
def need_rebuild(self) -> bool:
"""Determine if rebuild is needed.
@@ -498,6 +549,7 @@ class PersistentIndex(LocalIndex):
initial_timestamp: Optional[int] = None,
):
"""Create a new index from scratch."""
+ self.field_type_converter = DataProcessor(meta.collection_meta.fields_dict)
# Get the vector normalization flag from meta
normalize_vector_flag = meta.inner_meta.get("VectorIndex", {}).get("NormalizeVector", False)
@@ -511,7 +563,7 @@ class PersistentIndex(LocalIndex):
builder = IndexEngineProxy(index_config_json, normalize_vector_flag)
build_index_path = os.path.join(self.version_dir, version_str)
- builder.add_data(cands_list)
+ builder.add_data(self._convert_candidate_list_for_index(cands_list))
dump_version_int = builder.dump(build_index_path)
if dump_version_int > 0:
diff --git a/openviking/storage/vectordb/meta/index_meta.py b/openviking/storage/vectordb/meta/index_meta.py
index a7635e0f9..9e3762e13 100644
--- a/openviking/storage/vectordb/meta/index_meta.py
+++ b/openviking/storage/vectordb/meta/index_meta.py
@@ -7,6 +7,7 @@ from openviking.storage.vectordb.meta.collection_meta import CollectionMeta
from openviking.storage.vectordb.meta.dict import IDict
from openviking.storage.vectordb.meta.local_dict import PersistentDict, VolatileDict
from openviking.storage.vectordb.utils import validation
+from openviking.storage.vectordb.utils.data_processor import DataProcessor
def create_index_meta(
@@ -76,22 +77,8 @@ class IndexMeta:
fields_dict = collection_meta.fields_dict
scalar_index: List[Dict[str, str]] = []
if "ScalarIndex" in inner_meta:
- scalar_index = [
- {
- "FieldName": item,
- "FieldType": fields_dict[item]["FieldType"],
- }
- for item in inner_meta["ScalarIndex"]
- if item in fields_dict
- and fields_dict[item]["FieldType"]
- in [
- "int64",
- "float32",
- "string",
- "bool",
- "path",
- ]
- ]
+ converter = DataProcessor(fields_dict)
+ scalar_index = converter.build_scalar_index_meta(inner_meta["ScalarIndex"])
inner_meta["ScalarIndex"] = scalar_index
if "VectorIndex" in inner_meta:
vector_index = {
@@ -126,7 +113,9 @@ class IndexMeta:
return inner_meta
@staticmethod
- def _get_user_meta(inner_meta: Dict[str, Any]) -> Dict[str, Any]:
+ def _get_user_meta(
+ inner_meta: Dict[str, Any], collection_meta: CollectionMeta
+ ) -> Dict[str, Any]:
"""Convert internal metadata back to user facing metadata structure.
Args:
@@ -141,8 +130,10 @@ class IndexMeta:
if user_meta["VectorIndex"].pop("NormalizeVector", False):
user_meta["VectorIndex"]["Distance"] = "cosine"
if "ScalarIndex" in user_meta:
- scalar_index = [item["FieldName"] for item in user_meta["ScalarIndex"]]
- user_meta["ScalarIndex"] = scalar_index
+ converter = DataProcessor(collection_meta.fields_dict)
+ user_meta["ScalarIndex"] = converter.user_scalar_fields_from_engine(
+ user_meta["ScalarIndex"]
+ )
return user_meta
def update(self, additional_user_meta: Dict[str, Any]) -> bool:
@@ -158,7 +149,7 @@ class IndexMeta:
additional_user_meta, self.collection_meta.fields_dict
):
return False
- user_meta = IndexMeta._get_user_meta(self.inner_meta)
+ user_meta = IndexMeta._get_user_meta(self.inner_meta, self.collection_meta)
# Only update fields that are present in additional_user_meta
if "ScalarIndex" in additional_user_meta:
@@ -186,7 +177,7 @@ class IndexMeta:
Returns:
Dict[str, Any]: The user facing metadata.
"""
- return IndexMeta._get_user_meta(self.inner_meta)
+ return IndexMeta._get_user_meta(self.inner_meta, self.collection_meta)
def has_sparse(self) -> bool:
"""Check if sparse vector is enabled in the index.
diff --git a/openviking/storage/vectordb/utils/data_processor.py b/openviking/storage/vectordb/utils/data_processor.py
new file mode 100644
index 000000000..9896bc8f4
--- /dev/null
+++ b/openviking/storage/vectordb/utils/data_processor.py
@@ -0,0 +1,437 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Field type mapping and conversion helpers for scalar indexing."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+from typing import Annotated, Any, Dict, List, Optional, Tuple, Type
+
+from pydantic import (
+ AfterValidator,
+ BaseModel,
+ BeforeValidator,
+ Field,
+ create_model,
+)
+
+from openviking.storage.vectordb.utils.id_generator import generate_auto_id
+
+
+def get_pydantic_type(field_type: str) -> Type:
+ """Map internal field types to Pydantic/Python types."""
+ mapping = {
+ "int64": int,
+ "float32": float,
+ "string": str,
+ "bool": bool,
+ "list<string>": List[str],
+ "list<int64>": List[int],
+ "vector": List[float],
+ "sparse_vector": Dict[str, float],
+ "text": str,
+ "path": str,
+ "image": str,
+ "video": Dict[str, Any],
+ "date_time": str, # Input is string, parsed later
+ "geo_point": str, # Input is string "lon,lat"
+ }
+ return mapping.get(field_type, Any)
+
+
+def _split_str_list(v: Any) -> Any:
+ """Helper to split string input for list fields."""
+ if isinstance(v, str):
+ return v.split(";")
+ return v
+
+
+class DataProcessor:
+ ENGINE_SCALAR_TYPE_MAP: Dict[str, Optional[str]] = {
+ "int64": "int64",
+ "float32": "float32",
+ "string": "string",
+ "bool": "bool",
+ "list<string>": "string",
+ "list<int64>": "string",
+ "vector": None,
+ "sparse_vector": None,
+ "text": "string",
+ "path": "path",
+ "image": None,
+ "video": None,
+ "date_time": "int64",
+ "geo_point": "geo_point",
+ }
+
+ GEO_POINT_LON_SUFFIX = "_lon"
+ GEO_POINT_LAT_SUFFIX = "_lat"
+
+ def __init__(
+ self,
+ fields_dict: Optional[Dict[str, Any]] = None,
+ tz_policy: str = "local",
+ collection_name: str = "dynamic",
+ ):
+ self.fields_dict = fields_dict or {}
+ self.tz_policy = tz_policy
+ self.collection_name = collection_name
+ self._validator_model = self._build_validator_model()
+
+ def _build_validator_model(self) -> Type[BaseModel]:
+ """Dynamically build a Pydantic model based on fields_dict."""
+ field_definitions = {}
+
+ # Define sensible defaults for scalar types to handle missing fields
+ # This prevents validation errors when upstream doesn't provide all fields
+ TYPE_DEFAULTS = {
+ "int64": 0,
+ "float32": 0.0,
+ "string": "",
+ "bool": False,
+ "list<string>": [],
+ "list<int64>": [],
+ "text": "",
+ "path": "",
+ "date_time": "",
+ "geo_point": "",
+ }
+
+ # Define validators capturing self for configuration
+ def validate_dt(v: Optional[str]) -> Optional[str]:
+ if not v:
+ return v
+ self.parse_datetime_to_epoch_ms(v)
+ return v
+
+ def validate_gp(v: Optional[str]) -> Optional[str]:
+ if not v:
+ return v
+ self.parse_geo_point(v)
+ return v
+
+ for name, meta in self.fields_dict.items():
+ field_type_str = self.normalize_field_type(meta.get("FieldType"))
+ py_type = get_pydantic_type(field_type_str)
+ default_val = meta.get("DefaultValue")
+
+ # Apply specific validators
+ if field_type_str == "date_time":
+ py_type = Annotated[py_type, AfterValidator(validate_dt)]
+ elif field_type_str == "geo_point":
+ py_type = Annotated[py_type, AfterValidator(validate_gp)]
+ elif field_type_str in ("list<string>", "list<int64>"):
+ py_type = Annotated[py_type, BeforeValidator(_split_str_list)]
+
+ field_args = {}
+ if default_val is not None:
+ field_args["default"] = default_val
+ elif name == "AUTO_ID":
+ field_args["default_factory"] = generate_auto_id
+ else:
+ # Use type-based default if available, otherwise mark as required
+ if field_type_str in TYPE_DEFAULTS:
+ field_args["default"] = TYPE_DEFAULTS[field_type_str]
+ else:
+ field_args["default"] = ... # Required
+
+ # Add constraints
+ # if field_type_str == "string":
+ # field_args["max_length"] = 1024
+
+ field_definitions[name] = (py_type, Field(**field_args))
+
+ # extra='forbid' ensures no unknown fields are allowed
+ config = {"extra": "forbid"}
+
+ return create_model(
+ f"DynamicData_{self.collection_name}", __config__=config, **field_definitions
+ )
+
+ def validate_and_process(self, data: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Validate data against schema, fill defaults, and perform type conversion.
+ Returns the processed dictionary ready for storage.
+ """
+ # Pydantic Validation (Type check, Defaults, Unknown fields, Custom format checks)
+ # model_validate will raise ValidationError on failure
+ validated_obj = self._validator_model.model_validate(data)
+ processed_data = validated_obj.model_dump()
+
+ return processed_data
+
+ @classmethod
+ def normalize_field_type(cls, field_type: Any) -> str:
+ if hasattr(field_type, "value"):
+ return field_type.value
+ return str(field_type)
+
+ @classmethod
+ def get_engine_scalar_type(cls, field_type: Any) -> Optional[str]:
+ field_type_str = cls.normalize_field_type(field_type)
+ return cls.ENGINE_SCALAR_TYPE_MAP.get(field_type_str)
+
+ @classmethod
+ def get_geo_point_engine_fields(cls, field_name: str) -> Tuple[str, str]:
+ return f"{field_name}{cls.GEO_POINT_LON_SUFFIX}", f"{field_name}{cls.GEO_POINT_LAT_SUFFIX}"
+
+ def build_scalar_index_meta(self, user_scalar_fields: List[str]) -> List[Dict[str, str]]:
+ scalar_index: List[Dict[str, str]] = []
+ for field_name in user_scalar_fields:
+ meta = self.fields_dict.get(field_name)
+ if not meta:
+ continue
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ engine_type = self.get_engine_scalar_type(field_type)
+ if not engine_type:
+ continue
+ if engine_type == "geo_point":
+ lon_field, lat_field = self.get_geo_point_engine_fields(field_name)
+ if lon_field in self.fields_dict or lat_field in self.fields_dict:
+ raise ValueError(
+ f"geo_point index field name conflict: {lon_field} or {lat_field} already exists"
+ )
+ scalar_index.append({"FieldName": lon_field, "FieldType": "float32"})
+ scalar_index.append({"FieldName": lat_field, "FieldType": "float32"})
+ else:
+ scalar_index.append({"FieldName": field_name, "FieldType": engine_type})
+ return scalar_index
+
+ def user_scalar_fields_from_engine(self, engine_scalar_meta: List[Dict[str, str]]) -> List[str]:
+ engine_fields = {item.get("FieldName") for item in engine_scalar_meta}
+ scalar_fields: List[str] = []
+ for field_name, meta in self.fields_dict.items():
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ engine_type = self.get_engine_scalar_type(field_type)
+ if not engine_type:
+ continue
+ if engine_type == "geo_point":
+ lon_field, lat_field = self.get_geo_point_engine_fields(field_name)
+ if lon_field in engine_fields and lat_field in engine_fields:
+ scalar_fields.append(field_name)
+ else:
+ if field_name in engine_fields:
+ scalar_fields.append(field_name)
+ return scalar_fields
+
+ def parse_datetime_to_epoch_ms(self, value: Any) -> int:
+ if isinstance(value, (int, float)):
+ return int(value)
+ if not isinstance(value, str):
+ raise ValueError(
+ f"date_time value must be string or number, got {type(value).__name__}"
+ )
+ raw = value.strip()
+ if not raw:
+ raise ValueError("date_time value is empty")
+ if raw.endswith("Z"):
+ raw = raw[:-1] + "+00:00"
+ try:
+ dt = datetime.fromisoformat(raw)
+ except ValueError as exc:
+ raise ValueError(f"invalid date_time format: {value}") from exc
+ if dt.tzinfo is None:
+ if self.tz_policy == "local":
+ local_tz = datetime.now().astimezone().tzinfo
+ dt = dt.replace(tzinfo=local_tz)
+ elif self.tz_policy == "utc":
+ dt = dt.replace(tzinfo=timezone.utc)
+ else:
+ raise ValueError(f"unknown tz_policy: {self.tz_policy}")
+ return int(dt.timestamp() * 1000)
+
+ def parse_geo_point(self, value: str) -> Tuple[float, float]:
+ if not isinstance(value, str):
+ raise ValueError(f"geo_point value must be string, got {type(value).__name__}")
+ raw = value.strip()
+ if not raw:
+ raise ValueError("geo_point value is empty")
+ parts = raw.split(",")
+ if len(parts) != 2:
+ raise ValueError("geo_point must be in 'lon,lat' format")
+ try:
+ lon = float(parts[0].strip())
+ lat = float(parts[1].strip())
+ except ValueError as exc:
+ raise ValueError("geo_point lon/lat must be float") from exc
+ if not (-180.0 < lon < 180.0):
+ raise ValueError("geo_point longitude out of range (-180, 180)")
+ if not (-90.0 < lat < 90.0):
+ raise ValueError("geo_point latitude out of range (-90, 90)")
+ return lon, lat
+
+ def parse_radius(self, value: Any) -> float:
+ if isinstance(value, (int, float)):
+ # Assume meters if number is passed, convert to degrees approx
+ return float(value) / 111320.0
+ if not isinstance(value, str):
+ raise ValueError(f"radius must be string, got {type(value).__name__}")
+ raw = value.strip().lower()
+ meters = 0.0
+ if raw.endswith("km"):
+ num = raw[:-2].strip()
+ meters = float(num) * 1000.0
+ elif raw.endswith("m"):
+ num = raw[:-1].strip()
+ meters = float(num)
+ else:
+ try:
+ meters = float(raw)
+ except ValueError:
+ raise ValueError("radius must end with 'm' or 'km' or be a number")
+
+ # Convert meters to degrees (1 degree ~= 111.32 km at equator)
+ # This is a rough approximation for Euclidean engine on lon/lat
+ return meters / 111320.0
+
+ def convert_fields_dict_for_index(self, field_data_dict: Dict[str, Any]) -> Dict[str, Any]:
+ if not field_data_dict:
+ return field_data_dict
+ converted = dict(field_data_dict)
+ for field_name, value in field_data_dict.items():
+ meta = self.fields_dict.get(field_name)
+ if not meta:
+ continue
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ if field_type == "date_time":
+ if value in (None, ""):
+ converted.pop(field_name, None)
+ continue
+ converted[field_name] = self.parse_datetime_to_epoch_ms(value)
+ elif field_type == "geo_point":
+ if value in (None, ""):
+ converted.pop(field_name, None)
+ continue
+ lon, lat = self.parse_geo_point(value)
+ lon_field, lat_field = self.get_geo_point_engine_fields(field_name)
+ converted.pop(field_name, None)
+ converted[lon_field] = float(lon)
+ converted[lat_field] = float(lat)
+ elif field_type == "list<string>":
+ if value is None:
+ converted.pop(field_name, None)
+ continue
+ if isinstance(value, list):
+ converted[field_name] = value
+ elif isinstance(value, str):
+ converted[field_name] = value
+ else:
+ raise ValueError("list<string> must be list or ';' joined string")
+ elif field_type == "list<int64>":
+ if value is None:
+ converted.pop(field_name, None)
+ continue
+ if isinstance(value, list):
+ converted[field_name] = value
+ elif isinstance(value, str):
+ converted[field_name] = value
+ else:
+ raise ValueError("list<int64> must be list or ';' joined string")
+ return converted
+
+ def convert_fields_for_index(self, fields_json: str) -> str:
+ if not fields_json:
+ return fields_json
+ data = json.loads(fields_json)
+ converted = self.convert_fields_dict_for_index(data)
+ return json.dumps(converted, ensure_ascii=False)
+
+ def _convert_time_range_node(self, node: Dict[str, Any], field_type: str) -> Dict[str, Any]:
+ if field_type != "date_time":
+ return node
+ if node.get("op") == "time_range":
+ node["op"] = "range"
+ for key in ("gt", "gte", "lt", "lte"):
+ if key in node and node[key] is not None:
+ node[key] = self.parse_datetime_to_epoch_ms(node[key])
+ return node
+
+ def _convert_geo_range_node(self, node: Dict[str, Any]) -> Dict[str, Any]:
+ field = node.get("field")
+ if isinstance(field, str):
+ meta = self.fields_dict.get(field)
+ if meta:
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ if field_type != "geo_point":
+ raise ValueError("geo_range field must be geo_point")
+ if isinstance(field, list):
+ fields = field
+ else:
+ fields = []
+ if isinstance(field, str):
+ lon_field, lat_field = self.get_geo_point_engine_fields(field)
+ fields = [lon_field, lat_field]
+ if fields:
+ node["field"] = fields
+ center = node.get("center")
+ if isinstance(center, str):
+ lon, lat = self.parse_geo_point(center)
+ node["center"] = [lon, lat]
+ radius = node.get("radius")
+ if radius is not None:
+ node["radius"] = self.parse_radius(radius)
+ return node
+
+ def _convert_field_conds(self, node: Dict[str, Any]) -> Dict[str, Any]:
+ field = node.get("field")
+ if not isinstance(field, str):
+ return node
+ meta = self.fields_dict.get(field)
+ if not meta:
+ return node
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ if field_type != "date_time":
+ return node
+ conds = node.get("conds")
+ if not isinstance(conds, list):
+ return node
+ new_conds = []
+ for item in conds:
+ new_conds.append(self.parse_datetime_to_epoch_ms(item))
+ node["conds"] = new_conds
+ return node
+
+ def _convert_range_node(self, node: Dict[str, Any]) -> Dict[str, Any]:
+ field = node.get("field")
+ if isinstance(field, list):
+ return node
+ if not isinstance(field, str):
+ return node
+ meta = self.fields_dict.get(field)
+ if not meta:
+ return node
+ field_type = self.normalize_field_type(meta.get("FieldType"))
+ res = self._convert_time_range_node(node, field_type)
+ return res
+
+ def _convert_filter_node(self, node: Dict[str, Any]) -> Dict[str, Any]:
+ op = node.get("op")
+ if op in ("and", "or"):
+ conds = node.get("conds")
+ if isinstance(conds, list):
+ new_conds = []
+ for cond in conds:
+ if isinstance(cond, dict):
+ new_conds.append(self._convert_filter_node(dict(cond)))
+ else:
+ new_conds.append(cond)
+ node["conds"] = new_conds
+ return node
+ if op in ("must", "must_not", "prefix", "contains", "regex"):
+ return self._convert_field_conds(node)
+ if op in ("range", "range_out", "time_range"):
+ return self._convert_range_node(node)
+ if op == "geo_range":
+ return self._convert_geo_range_node(node)
+ return node
+
+ def convert_filter_for_index(self, filters: Dict[str, Any]) -> Dict[str, Any]:
+ if not filters:
+ return filters
+ if "filter" in filters or "sorter" in filters:
+ converted = dict(filters)
+ if "filter" in converted and isinstance(converted["filter"], dict):
+ converted["filter"] = self.convert_filter_for_index(converted["filter"])
+ return converted
+ return self._convert_filter_node(dict(filters))
diff --git a/openviking/storage/vectordb/utils/validation.py b/openviking/storage/vectordb/utils/validation.py
index b42029824..150d3638a 100644
--- a/openviking/storage/vectordb/utils/validation.py
+++ b/openviking/storage/vectordb/utils/validation.py
@@ -388,9 +388,6 @@ def is_valid_index_meta_data_for_update(meta_data: dict, field_meta_dict: dict)
def fix_collection_meta(meta_data: dict) -> dict:
- # This logic mutates the input dict to add AUTO_ID if missing, etc.
- # We can perform this on the dict directly or parse into model, modify, dump.
- # Direct dict modification is faster/closer to original behavior.
fields = meta_data.get("Fields", [])
has_pk = False
for item in fields:
@@ -418,7 +415,7 @@ def fix_collection_meta(meta_data: dict) -> dict:
return meta_data
-# Data validation logic - kept mostly manual or lightweight as creating models for dynamic data row is expensive
+# Data validation logic
REQUIRED_COLLECTION_FIELD_TYPE_CHECK = {
"int64": ([int], None, 0),
"float32": ([int, float], None, 0.0),
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 8f4aec680..439b61cfe 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -247,25 +247,23 @@ class VikingVectorIndexBackend(VikingDBInterface):
# Build scalar index fields list from Fields
scalar_index_fields = []
+ exclude_types = {"vector", "sparse_vector", "abstract"}
+
for field in collection_meta.get("Fields", []):
field_name = field.get("FieldName")
field_type = field.get("FieldType")
is_primary_key = field.get("IsPrimaryKey", False)
- # Index all non-vector, non-primary-key, and non-date_time fields by default
- # Volcengine VikingDB doesn't support indexing date_time fields
- if (
- field_name
- and field_type not in ("vector", "sparse_vector", "date_time")
- and not is_primary_key
- ):
+ # Index all non-vector and non-primary-key fields by default
+ if field_name and field_type not in exclude_types and not is_primary_key:
scalar_index_fields.append(field_name)
# Create default index for the collection
use_sparse = self.sparse_weight > 0.0
+ index_type = "flat_hybrid" if use_sparse else "flat"
index_meta = {
"IndexName": self.DEFAULT_INDEX_NAME,
"VectorIndex": {
- "IndexType": "flat_hybrid" if use_sparse else "flat",
+ "IndexType": index_type,
"Distance": distance,
"Quant": "int8",
},
diff --git a/src/index/detail/index_manager_impl.cpp b/src/index/detail/index_manager_impl.cpp
index a39762c6a..a87b68422 100644
--- a/src/index/detail/index_manager_impl.cpp
+++ b/src/index/detail/index_manager_impl.cpp
@@ -180,14 +180,13 @@ int IndexManagerImpl::search(const SearchRequest& req, SearchResult& result) {
"IndexManagerImpl::search calculate_filter_bitmap returned null");
return -1;
}
- ctx.filter_out = [bitmap](uint64_t id) { return bitmap->Isset(id); };
}
int ret = 0;
if (ctx.sorter_op) {
ret = handle_sorter_query(ctx, bitmap, result, dsl_filter_query_str);
} else if (!req.query.empty()) {
- ret = perform_vector_recall(req, ctx, result);
+ ret = perform_vector_recall(req, ctx, bitmap, result);
}
if (ret == 0) {
@@ -257,11 +256,12 @@ int IndexManagerImpl::handle_sorter_query(const SearchContext& ctx,
int IndexManagerImpl::perform_vector_recall(const SearchRequest& req,
SearchContext& ctx,
+ const BitmapPtr& bitmap,
SearchResult& result) {
VectorRecallRequest recall_request{
.dense_vector = req.query.data(),
.topk = req.topk,
- .filter = ctx.filter_out,
+ .bitmap = bitmap.get(),
.sparse_terms =
req.sparse_raw_terms.empty() ? nullptr : &req.sparse_raw_terms,
.sparse_values =
diff --git a/src/index/detail/index_manager_impl.h b/src/index/detail/index_manager_impl.h
index 6952e6f7c..bd31d7ef0 100644
--- a/src/index/detail/index_manager_impl.h
+++ b/src/index/detail/index_manager_impl.h
@@ -50,7 +50,7 @@ class IndexManagerImpl : public IndexManager {
SearchResult& result, const std::string& dsl);
int perform_vector_recall(const SearchRequest& req, SearchContext& ctx,
- SearchResult& result);
+ const BitmapPtr& bitmap, SearchResult& result);
void register_label_offset_converter_();
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap.cpp b/src/index/detail/scalar/bitmap_holder/bitmap.cpp
index bef201143..2b66f0739 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap.cpp
+++ b/src/index/detail/scalar/bitmap_holder/bitmap.cpp
@@ -206,4 +206,25 @@ void Bitmap::get_set_list(std::vector<uint32_t>& result) const {
}
}
+uint32_t Bitmap::get_range_list(std::vector<uint32_t>& result, uint32_t limit,
+ uint32_t offset) {
+ uint32_t max_num = get_cached_nbit();
+ uint32_t real_limit = std::min<uint32_t>(max_num - offset, limit);
+ if (max_num <= offset || real_limit <= 0) {
+ return 0;
+ }
+
+ if (result.size() != (size_t)real_limit) {
+ result.resize(real_limit, 0);
+ }
+ if (is_roaring_) {
+ roaring_.rangeUint32Array(result.data(), offset, real_limit);
+ } else {
+ auto iter = set_.begin();
+ std::advance(iter, offset);
+ std::copy_n(iter, real_limit, result.begin());
+ }
+ return static_cast<uint32_t>(result.size());
+}
+
} // namespace vectordb
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap.h b/src/index/detail/scalar/bitmap_holder/bitmap.h
index 173017eaf..734b2a54c 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap.h
+++ b/src/index/detail/scalar/bitmap_holder/bitmap.h
@@ -168,6 +168,9 @@ class Bitmap final {
// Access data
void get_set_list(std::vector<uint32_t>& result) const;
+ uint32_t get_range_list(std::vector<uint32_t>& result, uint32_t limit,
+ uint32_t offset = 0);
+
size_t get_estimate_bytes();
private:
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
index c2675ad23..3f9fc75bf 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
+++ b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
@@ -220,7 +220,9 @@ int FieldBitmapGroup::serialize_to_stream(std::ofstream& output) {
}
} else if (bitmap_type_id == kBitmapGroupRangedMap) {
- rangedmap_ptr_ = std::make_shared<RangedMap>();
+ if (!rangedmap_ptr_) {
+ rangedmap_ptr_ = std::make_shared<RangedMap>();
+ }
rangedmap_ptr_->SerializeToStream(output);
} else if (bitmap_type_id == kBitmapGroupBothBitmapsAndRange) {
for (auto& itr : bitmap_group_) {
@@ -519,7 +521,15 @@ BitmapPtr FieldBitmapGroupSet::make_field_prefix_copy(
if (itr == field_bitmap_groups_map_.end()) {
return nullptr;
}
- return itr->second->get_bitmap_by_prefix(prefix);
+
+ std::string search_prefix = prefix;
+ if (is_path_field_name(field)) {
+ if (!search_prefix.empty() && search_prefix[0] != '/') {
+ search_prefix = "/" + search_prefix;
+ }
+ }
+
+ return itr->second->get_bitmap_by_prefix(search_prefix);
}
BitmapPtr FieldBitmapGroupSet::make_field_contains_copy(
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
index c3acc103e..715a3c08e 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
+++ b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
@@ -135,25 +135,27 @@ class FieldBitmapGroup : public BitmapGroupBase {
std::vector<std::string> keys;
split(keys, field_str, ";");
for (auto& key_i : keys) {
- if (!exist_bitmap(key_i)) {
+ const std::string norm_key = dir_index_ ? normalize_path_key(key_i) : key_i;
+ if (!exist_bitmap(norm_key)) {
if (dir_index_) {
- dir_index_->add_key(key_i);
+ dir_index_->add_key(norm_key);
}
}
- Bitmap* temp_p = get_editable_bitmap(key_i);
+ Bitmap* temp_p = get_editable_bitmap(norm_key);
if (temp_p) {
temp_p->Set(offset);
}
}
} else {
- if (!exist_bitmap(field_str)) {
+ const std::string norm_key = dir_index_ ? normalize_path_key(field_str) : field_str;
+ if (!exist_bitmap(norm_key)) {
if (dir_index_) {
- dir_index_->add_key(field_str);
+ dir_index_->add_key(norm_key);
}
}
- Bitmap* temp_p = get_editable_bitmap(field_str);
+ Bitmap* temp_p = get_editable_bitmap(norm_key);
if (temp_p) {
temp_p->Set(offset);
}
@@ -207,13 +209,15 @@ class FieldBitmapGroup : public BitmapGroupBase {
std::vector<std::string> keys;
split(keys, field_str, ";");
for (auto& key_i : keys) {
- Bitmap* temp_p = get_editable_bitmap(key_i);
+ const std::string norm_key = dir_index_ ? normalize_path_key(key_i) : key_i;
+ Bitmap* temp_p = get_editable_bitmap(norm_key);
if (temp_p) {
temp_p->Unset(offset);
}
}
} else {
- Bitmap* temp_p = get_editable_bitmap(field_str);
+ const std::string norm_key = dir_index_ ? normalize_path_key(field_str) : field_str;
+ Bitmap* temp_p = get_editable_bitmap(norm_key);
if (temp_p) {
temp_p->Unset(offset);
}
@@ -269,6 +273,13 @@ class FieldBitmapGroup : public BitmapGroupBase {
}
private:
+ static std::string normalize_path_key(const std::string& key) {
+ if (key.empty() || key[0] == '/') {
+ return key;
+ }
+ return "/" + key;
+ }
+
size_t element_size_;
};
diff --git a/src/index/detail/scalar/bitmap_holder/ranged_map.cpp b/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
index ce6563810..5365251d6 100644
--- a/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
+++ b/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
@@ -500,7 +500,8 @@ BitmapPtr RangedMap2D::get_range2d_bitmap_with_slot_data(double x, double y,
temp_p->get_set_list(offsets);
const double dist_square_max = radius * radius;
for (uint32_t offset : offsets) {
- if (dist_square_to(x, y, offset) > dist_square_max) {
+ double d2 = dist_square_to(x, y, offset);
+ if (d2 > dist_square_max) {
temp_p->Unset(offset);
}
}
diff --git a/src/index/detail/scalar/filter/filter_ops.cpp b/src/index/detail/scalar/filter/filter_ops.cpp
index 6a3da1ccc..646824d7c 100644
--- a/src/index/detail/scalar/filter/filter_ops.cpp
+++ b/src/index/detail/scalar/filter/filter_ops.cpp
@@ -59,6 +59,7 @@ get_filter_op_registry() {
{"must", []() { return std::make_shared<MustOp>(); }},
{"must_not", []() { return std::make_shared<MustNotOp>(); }},
{"range", []() { return std::make_shared<RangeOp>(false); }},
+ {"geo_range", []() { return std::make_shared<RangeOp>(false); }},
{"range_out", []() { return std::make_shared<RangeOp>(true); }},
{"label_in", []() { return std::make_shared<LabelInOp>(); }},
{"prefix", []() { return std::make_shared<PrefixOp>(); }},
@@ -72,6 +73,7 @@ const std::unordered_map<std::string, FieldOpCreator>& get_field_op_registry() {
{"must", []() { return std::make_shared<MustOp>(); }},
{"must_not", []() { return std::make_shared<MustNotOp>(); }},
{"range", []() { return std::make_shared<RangeOp>(false); }},
+ {"geo_range", []() { return std::make_shared<RangeOp>(false); }},
{"range_out", []() { return std::make_shared<RangeOp>(true); }},
{"prefix", []() { return std::make_shared<PrefixOp>(); }},
{"contains", []() { return std::make_shared<ContainsOp>(); }},
@@ -94,7 +96,7 @@ FilterOpBasePtr make_filter_op_by_opname(const std::string& opname) {
return it->second();
}
SPDLOG_WARN(
- "Unsupported filter op '{}'. Supported ops: and, or, must, must_not, range, range_out, georange, label_in, prefix, contains, regex",
+ "Unsupported filter op '{}'. Supported ops: and, or, must, must_not, range, geo_range, range_out, label_in, prefix, contains, regex",
opname);
return nullptr;
}
@@ -106,7 +108,7 @@ FieldOpBasePtr make_field_op_by_opname(const std::string& opname) {
return it->second();
}
SPDLOG_WARN(
- "Unsupported field op '{}'. Supported ops: must, must_not, range, range_out, georange, prefix, contains, regex",
+ "Unsupported field op '{}'. Supported ops: must, must_not, range, geo_range, range_out, prefix, contains, regex",
opname);
return nullptr;
}
diff --git a/src/index/detail/scalar/filter/sort_ops.cpp b/src/index/detail/scalar/filter/sort_ops.cpp
index d2fad492c..e2a8e1eef 100644
--- a/src/index/detail/scalar/filter/sort_ops.cpp
+++ b/src/index/detail/scalar/filter/sort_ops.cpp
@@ -586,7 +586,7 @@ RecallResultPtr SorterOp::_calc_topk_result_with_small_bitmap(
return nullptr;
}
- SPDLOG_INFO("SorterOp::_calc_topk_result_with_small_bitmap topk {} in {}",
+ SPDLOG_DEBUG("SorterOp::_calc_topk_result_with_small_bitmap topk {} in {}",
search_k, all_valid_size);
return res_ptr;
}
diff --git a/src/index/detail/search_context.h b/src/index/detail/search_context.h
index 0aeec197a..53b0b803e 100644
--- a/src/index/detail/search_context.h
+++ b/src/index/detail/search_context.h
@@ -11,9 +11,6 @@ namespace vectordb {
struct SearchContext {
FilterOpBasePtr filter_op;
SorterOpBasePtr sorter_op;
- std::function<bool(uint64_t)> filter_out;
};
-using Filter = std::function<bool(uint64_t)>;
-
} // namespace vectordb
diff --git a/src/index/detail/vector/common/bruteforce.h b/src/index/detail/vector/common/bruteforce.h
index 2a065acfb..ba25de79b 100644
--- a/src/index/detail/vector/common/bruteforce.h
+++ b/src/index/detail/vector/common/bruteforce.h
@@ -20,6 +20,7 @@
#include "index/detail/vector/common/space_int8.h"
#include "index/detail/vector/common/space_l2.h"
#include "index/detail/vector/common/space_ip.h"
+#include "index/detail/scalar/bitmap_holder/bitmap.h"
#include "spdlog/spdlog.h"
namespace vectordb {
@@ -109,8 +110,8 @@ class BruteforceSearch {
index = current_count_;
label_map_[label] = index;
- uint32_t logical_offset = static_cast<uint32_t>(current_count_);
- offset_map_[logical_offset] = label;
+ uint32_t logical_offset = static_cast<uint32_t>(next_logical_offset_++);
+ offset_map_[logical_offset] = index;
std::memcpy(data_buffer_ + (index * element_byte_size_) +
vector_byte_size_ + sizeof(uint64_t),
@@ -153,6 +154,11 @@ class BruteforceSearch {
std::memcpy(&label_moved, dest + vector_byte_size_, sizeof(uint64_t));
label_map_[label_moved] = idx_to_remove;
+ uint32_t offset_moved;
+ std::memcpy(&offset_moved, dest + vector_byte_size_ + sizeof(uint64_t),
+ sizeof(uint32_t));
+ offset_map_[offset_moved] = idx_to_remove;
+
if (sparse_index_) {
// SPDLOG_INFO("remove_point: swapping sparse row {} with {}", idx_to_remove, idx_last);
auto last_row = sparse_index_->get_row(idx_last);
@@ -172,7 +178,7 @@ class BruteforceSearch {
current_count_--;
}
- void search_knn(const void* query_data, size_t k, Filter filter,
+ void search_knn(const void* query_data, size_t k, const Bitmap* filter_bitmap,
FloatValSparseDatapointLowLevel* sparse,
std::vector<uint64_t>& labels,
std::vector<float>& scores) const {
@@ -198,28 +204,52 @@ class BruteforceSearch {
auto dist_func = space_->get_metric_function();
void* dist_params = space_->get_metric_params();
- for (size_t i = 0; i < current_count_; ++i) {
- char* ptr = data_buffer_ + (i * element_byte_size_);
+ if (!filter_bitmap) {
+ for (size_t i = 0; i < current_count_; ++i) {
+ char* ptr = data_buffer_ + (i * element_byte_size_);
- uint32_t logical_offset;
- std::memcpy(&logical_offset, ptr + vector_byte_size_ + sizeof(uint64_t),
- sizeof(uint32_t));
+ float dist = compute_score(encoded_query.data(), ptr, query_sparse_view,
+ i, dist_func, dist_params);
+
+ uint64_t label;
+ std::memcpy(&label, ptr + vector_byte_size_, sizeof(uint64_t));
- if (filter && !filter(logical_offset)) {
- continue;
+ if (pq.size() < k) {
+ pq.emplace(dist, label);
+ } else if (dist > pq.top().first) {
+ pq.pop();
+ pq.emplace(dist, label);
+ }
+ }
+ } else {
+ if (filter_bitmap->empty()) {
+ labels.clear();
+ scores.clear();
+ return;
}
+ std::vector<uint32_t> offsets;
+ filter_bitmap->get_set_list(offsets);
+ for (uint32_t offset : offsets) {
+ auto it = offset_map_.find(offset);
+ if (it == offset_map_.end()) {
+ continue;
+ }
- float dist = compute_score(encoded_query.data(), ptr, query_sparse_view,
- i, dist_func, dist_params);
+ int idx = it->second;
+ char* ptr = data_buffer_ + (idx * element_byte_size_);
- uint64_t label;
- std::memcpy(&label, ptr + vector_byte_size_, sizeof(uint64_t));
+ float dist = compute_score(encoded_query.data(), ptr, query_sparse_view,
+ idx, dist_func, dist_params);
+
+ uint64_t label;
+ std::memcpy(&label, ptr + vector_byte_size_, sizeof(uint64_t));
- if (pq.size() < k) {
- pq.emplace(dist, label);
- } else if (dist > pq.top().first) {
- pq.pop();
- pq.emplace(dist, label);
+ if (pq.size() < k) {
+ pq.emplace(dist, label);
+ } else if (dist > pq.top().first) {
+ pq.pop();
+ pq.emplace(dist, label);
+ }
}
}
@@ -244,6 +274,7 @@ class BruteforceSearch {
write_binary(out, current_count_);
out.write(data_buffer_, capacity_ * element_byte_size_);
+ write_binary(out, next_logical_offset_);
if (sparse_index_) {
size_t dummy;
@@ -268,6 +299,12 @@ class BruteforceSearch {
resize_buffer(loaded_cap);
in.read(data_buffer_, loaded_cap * loaded_elem_size);
+
+ if (in.peek() != EOF) {
+ read_binary(in, next_logical_offset_);
+ } else {
+ next_logical_offset_ = 0; // Will be corrected in rebuild_maps
+ }
rebuild_maps();
@@ -296,8 +333,13 @@ class BruteforceSearch {
uint64_t get_label_by_offset(int offset) {
auto it = offset_map_.find(offset);
- if (it != offset_map_.end())
- return it->second;
+ if (it != offset_map_.end()) {
+ int idx = it->second;
+ char* ptr = data_buffer_ + (idx * element_byte_size_);
+ uint64_t label;
+ std::memcpy(&label, ptr + vector_byte_size_, sizeof(uint64_t));
+ return label;
+ }
return -1;
}
@@ -331,6 +373,7 @@ class BruteforceSearch {
void rebuild_maps() {
label_map_.clear();
offset_map_.clear();
+ uint32_t max_offset = 0;
for (size_t i = 0; i < current_count_; ++i) {
char* ptr = data_buffer_ + (i * element_byte_size_);
uint64_t lbl;
@@ -340,7 +383,13 @@ class BruteforceSearch {
sizeof(uint32_t));
label_map_[lbl] = i;
- offset_map_[off] = lbl;
+ offset_map_[off] = i;
+ if (off > max_offset) {
+ max_offset = off;
+ }
+ }
+ if (current_count_ > 0 && next_logical_offset_ <= max_offset) {
+ next_logical_offset_ = max_offset + 1;
}
}
@@ -382,12 +431,13 @@ class BruteforceSearch {
size_t element_byte_size_ = 0;
std::unordered_map<uint64_t, int> label_map_;
- std::unordered_map<int, uint64_t> offset_map_;
+ std::unordered_map<uint32_t, int> offset_map_;
std::unique_ptr<VectorSpace<float>> space_;
std::unique_ptr<VectorQuantizer> quantizer_;
std::unique_ptr<SparseDataHolder> sparse_index_;
bool reverse_query_score_ = false;
+ uint64_t next_logical_offset_ = 0;
};
} // namespace vectordb
diff --git a/src/index/detail/vector/vector_index_adapter.h b/src/index/detail/vector/vector_index_adapter.h
index 01dec080b..10118b86b 100644
--- a/src/index/detail/vector/vector_index_adapter.h
+++ b/src/index/detail/vector/vector_index_adapter.h
@@ -62,7 +62,7 @@ class BruteForceIndex : public VectorIndexAdapter {
FloatValSparseDatapointLowLevel* sparse_ptr =
(request.sparse_terms && request.sparse_values) ? &sparse_datapoint
: nullptr;
- index_->search_knn(request.dense_vector, request.topk, request.filter,
+ index_->search_knn(request.dense_vector, request.topk, request.bitmap,
sparse_ptr, result.labels, result.scores);
return 0;
}
diff --git a/src/index/detail/vector/vector_recall.h b/src/index/detail/vector/vector_recall.h
index 0082d8cfa..55ec79165 100644
--- a/src/index/detail/vector/vector_recall.h
+++ b/src/index/detail/vector/vector_recall.h
@@ -6,13 +6,14 @@
#include <string>
#include <cstdint>
#include "index/detail/search_context.h"
+#include "index/detail/scalar/bitmap_holder/bitmap.h"
namespace vectordb {
struct VectorRecallRequest {
const float* dense_vector = nullptr;
uint64_t topk = 0;
- Filter filter;
+ const Bitmap* bitmap = nullptr;
// Sparse vector data (optional)
const std::vector<std::string>* sparse_terms = nullptr;
diff --git a/tests/vectordb/test_data_processor.py b/tests/vectordb/test_data_processor.py
new file mode 100644
index 000000000..e52ba7a91
--- /dev/null
+++ b/tests/vectordb/test_data_processor.py
@@ -0,0 +1,111 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+import shutil
+import unittest
+from datetime import datetime, timezone
+
+from pydantic import ValidationError
+
+from openviking.storage.vectordb.utils.data_processor import DataProcessor
+
+DB_PATH = "./db_test_data_processor/"
+
+
+def clean_dir(path: str) -> None:
+ shutil.rmtree(path, ignore_errors=True)
+
+
+class TestDataProcessor(unittest.TestCase):
+ def setUp(self):
+ self.fields_dict = {
+ "created_at": {"FieldType": "date_time"},
+ "geo": {"FieldType": "geo_point"},
+ "uri": {"FieldType": "path"},
+ "tags": {"FieldType": "list<string>"},
+ }
+ self.processor = DataProcessor(self.fields_dict)
+
+ def test_scalar_index_meta_mapping(self):
+ scalar_meta = self.processor.build_scalar_index_meta(["created_at", "geo", "uri", "tags"])
+ mapped = {(item["FieldName"], item["FieldType"]) for item in scalar_meta}
+ self.assertIn(("created_at", "int64"), mapped)
+ self.assertIn(("geo_lon", "float32"), mapped)
+ self.assertIn(("geo_lat", "float32"), mapped)
+ self.assertIn(("uri", "path"), mapped)
+ self.assertIn(("tags", "string"), mapped)
+
+ def test_datetime_and_geo_point_conversion(self):
+ data = {
+ "created_at": "2026-02-06T12:34:56+00:00",
+ "geo": "116.412138,39.914912",
+ "tags": ["a", "b"],
+ }
+ converted = self.processor.convert_fields_dict_for_index(data)
+ self.assertIsInstance(converted["created_at"], int)
+ self.assertNotIn("geo", converted)
+ self.assertIn("geo_lon", converted)
+ self.assertIn("geo_lat", converted)
+ self.assertEqual(converted["tags"], ["a", "b"])
+
+ def test_filter_conversion_time_range(self):
+ filters = {
+ "op": "time_range",
+ "field": "created_at",
+ "gte": "2026-02-06T12:34:56+00:00",
+ }
+ converted = self.processor.convert_filter_for_index(filters)
+ expected = int(
+ datetime.fromisoformat("2026-02-06T12:34:56+00:00").astimezone(timezone.utc).timestamp()
+ * 1000
+ )
+ self.assertEqual(converted["gte"], expected)
+
+ def test_filter_conversion_geo_range(self):
+ filters = {
+ "op": "geo_range",
+ "field": "geo",
+ "center": "116.412138,39.914912",
+ "radius": "10km",
+ }
+ converted = self.processor.convert_filter_for_index(filters)
+ self.assertEqual(converted["field"], ["geo_lon", "geo_lat"])
+ # Radius is converted to degrees: 10000m / 111320.0
+ self.assertAlmostEqual(converted["radius"], 10000.0 / 111320.0, places=6)
+ self.assertAlmostEqual(converted["center"][0], 116.412138, places=6)
+ self.assertAlmostEqual(converted["center"][1], 39.914912, places=6)
+
+ def test_validate_and_process(self):
+ # Test basic validation
+ data = {
+ "created_at": "2026-02-06T12:34:56+00:00",
+ "geo": "116.412138,39.914912",
+ "tags": ["a", "b"],
+ "uri": "/tmp/test",
+ }
+ processed = self.processor.validate_and_process(data)
+ self.assertEqual(processed["tags"], ["a", "b"])
+
+ # Test string input for list (legacy support)
+ data_legacy = {
+ "created_at": "2026-02-06T12:34:56+00:00",
+ "geo": "116.412138,39.914912",
+ "tags": "a;b;c",
+ "uri": "/tmp/test",
+ }
+ processed_legacy = self.processor.validate_and_process(data_legacy)
+ self.assertEqual(processed_legacy["tags"], ["a", "b", "c"])
+
+ # Test invalid datetime
+ data_invalid_dt = {
+ "created_at": "invalid-date",
+ "geo": "116.412138,39.914912",
+ "tags": ["a"],
+ "uri": "/tmp/test",
+ }
+ with self.assertRaises(ValidationError):
+ self.processor.validate_and_process(data_invalid_dt)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/vectordb/test_filter_ops.py b/tests/vectordb/test_filter_ops.py
index b57f682e3..b84e46407 100644
--- a/tests/vectordb/test_filter_ops.py
+++ b/tests/vectordb/test_filter_ops.py
@@ -673,6 +673,42 @@ class TestFilterOpsPath(unittest.TestCase):
self._search({"op": "must_not", "field": "file_path", "conds": ["/a"]}), [4, 5]
)
+ def test_path_must_normalize_leading_slash(self):
+ """Test Must/MustNot when path values are missing leading '/'"""
+ data = [
+ {"id": 6, "embedding": [1.0, 0, 0, 0], "file_path": "a/b/c"},
+ {"id": 7, "embedding": [1.0, 0, 0, 0], "file_path": "f/h/i"},
+ {"id": 8, "embedding": [1.0, 0, 0, 0], "file_path": "a"},
+ {"id": 9, "embedding": [1.0, 0, 0, 0], "file_path": "viking://resources/tmp/x"},
+ ]
+ self.collection.upsert_data(data)
+
+ # Must /a -> /a/b/c, /a/b/d, /a/e, and /a
+ self.assertEqual(
+ self._search({"op": "must", "field": "file_path", "conds": ["/a"]}),
+ [1, 2, 3, 6, 8],
+ )
+ # Must /a/b -> /a/b/c, /a/b/d
+ self.assertEqual(
+ self._search({"op": "must", "field": "file_path", "conds": ["/a/b"]}),
+ [1, 2, 6],
+ )
+ # Must /f -> /f/g, /f/h/i
+ self.assertEqual(
+ self._search({"op": "must", "field": "file_path", "conds": ["/f"]}),
+ [4, 5, 7],
+ )
+ # MustNot /a/b -> exclude 1, 2, 6
+ self.assertEqual(
+ self._search({"op": "must_not", "field": "file_path", "conds": ["/a/b"]}),
+ [3, 4, 5, 7, 8, 9],
+ )
+ # Ensure scheme is preserved, only prefixed with '/'
+ self.assertEqual(
+ self._search({"op": "must", "field": "file_path", "conds": ["/viking://resources"]}),
+ [9],
+ )
+
def test_path_depth(self):
"""Test path type depth parameter"""
# Must /a with depth=1 (para="-d=1")
@@ -731,7 +767,7 @@ class TestFilterOpsScale(unittest.TestCase):
clean_dir(db_path_scale)
self.path = db_path_scale
self.collection = self._create_collection()
- self.data_count = 500000 # 50w
+ self.data_count = 50000 # Reduced from 500k to 50k to avoid timeout/OOM in test env
self._insert_large_data()
self._create_index()
@@ -833,7 +869,7 @@ class TestFilterOpsScale(unittest.TestCase):
# or verify standard limit behavior.
# Search with smaller result set for verification
- # Group A AND Score = 99 (1 per 100) -> 2500 expected
+ # Group A AND Score = 99 (1 per 100) -> 2500 expected (50k scale -> 250 expected)
filters = {
"op": "and",
"conds": [
@@ -843,34 +879,35 @@ class TestFilterOpsScale(unittest.TestCase):
}
ids = self._search(filters, limit=5000)
print(f"Filter 1 time: {time.time() - start_time:.4f}s")
- self.assertEqual(len(ids), 2500)
+ # 50k / 2 = 25k Group A. 25k / 100 = 250.
+ self.assertEqual(len(ids), 250)
for i in ids:
self.assertTrue(i < self.data_count / 2)
self.assertEqual(i % 100, 99)
# Filter 2: Complex Logic
# (Group A AND SubGroup X) OR (Group B AND Score < 5)
- # Group A (0-249999) AND X (Even) -> 125000 items
- # Group B (250000-499999) AND Score < 5 (0,1,2,3,4 -> 5 per 100) -> 2500 * 5 = 12500 items
- # Total = 137500 items. Too many to fetch all.
+ # Group A (0-24999) AND X (Even) -> 12500 items
+ # Group B (25000-49999) AND Score < 5 (0,1,2,3,4 -> 5 per 100) -> 250 * 5 = 1250 items
+ # Total = 13750 items. Too many to fetch all.
# Let's add more conditions to reduce result set.
# (Group A AND SubGroup X AND Tag="tag_0")
# Tag="tag_0" -> id % 1000 == 0.
- # Group A (0-249999): 250 items with tag_0.
- # SubGroup X (Even): tag_0 implies id%1000=0 which is even. So all 250 items match X.
- # Result: 250 items.
+ # Group A (0-24999): 25 items with tag_0.
+ # SubGroup X (Even): tag_0 implies id%1000=0 which is even. So all 25 items match X.
+ # Result: 25 items.
# OR
# (Group B AND Score=0 AND SubGroup Y)
- # Group B (250000-499999)
+ # Group B (25000-49999)
# Score=0 -> id % 100 == 0.
# SubGroup Y (Odd) -> id is Odd.
# id % 100 == 0 implies id is Even. So (Even AND Odd) -> Empty.
# Result: 0 items.
- # Total expected: 250 items.
+ # Total expected: 25 items.
print("Testing Filter 2: Complex Nested Logic")
filters = {
"op": "or",
@@ -896,7 +933,7 @@ class TestFilterOpsScale(unittest.TestCase):
start_time = time.time()
ids = self._search(filters, limit=1000)
print(f"Filter 2 time: {time.time() - start_time:.4f}s")
- self.assertEqual(len(ids), 250)
+ self.assertEqual(len(ids), 25)
for i in ids:
self.assertEqual(i % 1000, 0)
self.assertTrue(i < self.data_count / 2)
@@ -904,16 +941,352 @@ class TestFilterOpsScale(unittest.TestCase):
# Filter 3: Regex on Tag (Slow op check)
# Tag ends with "999" -> tag_999
# id % 1000 == 999.
- # Total 500,000 / 1000 = 500 items.
+ # Total 50000 / 1000 = 50 items.
print("Testing Filter 3: Regex")
filters = {"op": "regex", "field": "tag", "pattern": "999$"}
start_time = time.time()
ids = self._search(filters, limit=1000)
print(f"Filter 3 time: {time.time() - start_time:.4f}s")
- self.assertEqual(len(ids), 500)
+ self.assertEqual(len(ids), 50)
for i in ids:
self.assertEqual(i % 1000, 999)
+class TestFilterOpsTypes(unittest.TestCase):
+ """Comprehensive tests for various field types and operators"""
+
+ def setUp(self):
+ clean_dir("./db_test_filters_types/")
+ self.path = "./db_test_filters_types/"
+ self.collection = self._create_collection()
+ self._insert_data()
+ self._create_index()
+
+ def tearDown(self):
+ if self.collection:
+ self.collection.drop()
+ clean_dir(self.path)
+
+ def _create_collection(self):
+ collection_meta = {
+ "CollectionName": "test_filters_types",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
+ {"FieldName": "embedding", "FieldType": "vector", "Dim": 4},
+ {"FieldName": "f_int", "FieldType": "int64"},
+ {"FieldName": "f_float", "FieldType": "float32"},
+ {"FieldName": "f_bool", "FieldType": "bool"},
+ {"FieldName": "f_str", "FieldType": "string"},
+ {"FieldName": "f_list_str", "FieldType": "list<string>"},
+ {"FieldName": "f_list_int", "FieldType": "list<int64>"},
+ {"FieldName": "f_date", "FieldType": "date_time"},
+ {"FieldName": "f_geo", "FieldType": "geo_point"},
+ ],
+ }
+ return get_or_create_local_collection(meta_data=collection_meta, path=self.path)
+
+ def _insert_data(self):
+ self.data = [
+ {
+ "id": 1,
+ "embedding": [1.0, 0, 0, 0],
+ "f_int": 10,
+ "f_float": 1.1,
+ "f_bool": True,
+ "f_str": "apple",
+ "f_list_str": ["a", "b"],
+ "f_list_int": [1, 2],
+ "f_date": "2023-01-01T00:00:00+00:00",
+ "f_geo": "0,0",
+ },
+ {
+ "id": 2,
+ "embedding": [1.0, 0, 0, 0],
+ "f_int": 20,
+ "f_float": 2.2,
+ "f_bool": False,
+ "f_str": "banana",
+ "f_list_str": ["b", "c"],
+ "f_list_int": [2, 3],
+ "f_date": "2023-01-02T00:00:00+00:00",
+ "f_geo": "10,10",
+ },
+ {
+ "id": 3,
+ "embedding": [1.0, 0, 0, 0],
+ "f_int": 30,
+ "f_float": 3.3,
+ "f_bool": True,
+ "f_str": "cherry",
+ "f_list_str": ["c", "d"],
+ "f_list_int": [3, 4],
+ "f_date": "2023-01-03T00:00:00+00:00",
+ "f_geo": "20,20",
+ },
+ {
+ "id": 4,
+ "embedding": [1.0, 0, 0, 0],
+ "f_int": -10,
+ "f_float": -1.1,
+ "f_bool": False,
+ "f_str": "date",
+ "f_list_str": ["d", "e"],
+ "f_list_int": [4, 5],
+ "f_date": "2022-12-31T00:00:00+00:00",
+ "f_geo": "-10,-10",
+ },
+ {
+ "id": 5,
+ "embedding": [1.0, 0, 0, 0],
+ "f_int": 0,
+ "f_float": 0.0,
+ "f_bool": True,
+ "f_str": "elderberry",
+ "f_list_str": [],
+ "f_list_int": [],
+ "f_date": "2023-01-01T12:00:00+00:00",
+ "f_geo": "179,89",
+ },
+ ]
+ self.collection.upsert_data(self.data)
+
+ def _create_index(self):
+ index_meta = {
+ "IndexName": "idx_types",
+ "VectorIndex": {"IndexType": "flat"},
+ "ScalarIndex": [
+ "id",
+ "f_int",
+ "f_float",
+ "f_bool",
+ "f_str",
+ "f_list_str",
+ "f_list_int",
+ "f_date",
+ "f_geo",
+ ],
+ }
+ self.collection.create_index("idx_types", index_meta)
+
+ def _search(self, filters):
+ res = self.collection.search_by_vector(
+ "idx_types", dense_vector=[1.0, 0, 0, 0], limit=100, filters=filters
+ )
+ return sorted([item.id for item in res.data])
+
+ def test_debug_float(self):
+ # Check if data exists in storage
+ res = self.collection.search_by_vector("idx_types", dense_vector=[0] * 4, limit=10)
+ print("Stored Data:", [(item.id, item.fields.get("f_float")) for item in res.data])
+
+ def test_numeric_ops(self):
+ """Test numeric types (int64, float32)"""
+ # Int eq
+ self.assertEqual(self._search({"op": "must", "field": "f_int", "conds": [20]}), [2])
+ # Int gt
+ self.assertEqual(self._search({"op": "range", "field": "f_int", "gt": 0}), [1, 2, 3])
+ # Int lt
+ self.assertEqual(self._search({"op": "range", "field": "f_int", "lt": 0}), [4])
+ # Int range
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_int", "gte": 10, "lte": 20}), [1, 2]
+ )
+
+ # Float gt (approximate)
+ # FIXME: Float range query fails, possibly due to C++ implementation issue
+ self.assertEqual(self._search({"op": "range", "field": "f_float", "gt": 2.0}), [2, 3])
+ # Float range
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_float", "gte": -2.0, "lte": 0.0}), [4, 5]
+ )
+
+ def test_string_ops(self):
+ """Test string types"""
+ # Eq
+ self.assertEqual(self._search({"op": "must", "field": "f_str", "conds": ["banana"]}), [2])
+ # Prefix
+ self.assertEqual(self._search({"op": "prefix", "field": "f_str", "prefix": "c"}), [3])
+ # Contains
+ self.assertEqual(
+ self._search({"op": "contains", "field": "f_str", "substring": "erry"}), [3, 5]
+ )
+ # Regex (starts with 'a' or 'd')
+ self.assertEqual(
+ self._search({"op": "regex", "field": "f_str", "pattern": "^(a|d)"}), [1, 4]
+ )
+
+ def test_bool_ops(self):
+ """Test boolean types"""
+ # True
+ self.assertEqual(
+ self._search({"op": "must", "field": "f_bool", "conds": [True]}), [1, 3, 5]
+ )
+ # False
+ self.assertEqual(self._search({"op": "must", "field": "f_bool", "conds": [False]}), [2, 4])
+
+ def test_list_ops(self):
+ """Test list types"""
+ # List<String> contains
+ # "a" is in [a, b] (id 1)
+ self.assertEqual(self._search({"op": "must", "field": "f_list_str", "conds": ["a"]}), [1])
+ # "b" is in id 1, 2
+ self.assertEqual(
+ self._search({"op": "must", "field": "f_list_str", "conds": ["b"]}), [1, 2]
+ )
+
+ # List<Int64> contains
+ # 3 is in id 2, 3
+ self.assertEqual(self._search({"op": "must", "field": "f_list_int", "conds": [3]}), [2, 3])
+
+ def test_datetime_ops(self):
+ """Test date_time types"""
+ # Exact match (might be tricky due to ms conversion, use range preferred)
+ # 2023-01-01T00:00:00+00:00
+
+ # Range
+ # > 2023-01-01
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_date", "gt": "2023-01-01T10:00:00+00:00"}),
+ [2, 3, 5], # 2(Jan 2), 3(Jan 3), 5(Jan 1 12:00)
+ )
+
+ # Range with different format if supported (DataProcessor handles ISO)
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_date", "lt": "2023-01-01T00:00:00+00:00"}),
+ [4], # 4(Dec 31)
+ )
+
+ def test_geo_ops(self):
+ """Test geo_point types"""
+ # Geo Range (Circle)
+ # Center 0,0. Radius 100km.
+ # id 1 is 0,0 -> Match
+ # id 2 is 10,10 -> ~1500km away -> No match
+ self.assertEqual(
+ self._search({"op": "geo_range", "field": "f_geo", "center": "0,0", "radius": "100km"}),
+ [1],
+ )
+
+ # Center 10,10. Radius 2000km.
+ # id 1 (0,0) -> ~1500km -> Match
+ # id 2 (10,10) -> 0km -> Match
+ # id 3 (20,20) -> ~1500km from 10,10 -> Match
+ # id 4 (-10,-10) -> ~3000km -> No match
+ self.assertEqual(
+ self._search(
+ {"op": "geo_range", "field": "f_geo", "center": "10,10", "radius": "2000km"}
+ ),
+ [1, 2, 3],
+ )
+
+ def test_mixed_complex(self):
+ """Test mixed complex logic"""
+ # (f_bool=True AND f_int > 0) OR (f_str prefix "d")
+ # Part 1: True & >0 -> 1(10), 3(30). (5 is True but int=0, so not >0 if strictly gt)
+ # Part 2: prefix "d" -> 4("date")
+ # Union: 1, 3, 4
+
+ filters = {
+ "op": "or",
+ "conds": [
+ {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "f_bool", "conds": [True]},
+ {"op": "range", "field": "f_int", "gt": 0},
+ ],
+ },
+ {"op": "prefix", "field": "f_str", "prefix": "d"},
+ ],
+ }
+ self.assertEqual(self._search(filters), [1, 3, 4])
+
+ def test_persistence_queries(self):
+ """Test if filters work correctly after persistence and restart"""
+ # 1. Execute queries before close (verified by other tests, but good for baseline)
+
+ def _verify_all_ops():
+ # Int eq
+ self.assertEqual(self._search({"op": "must", "field": "f_int", "conds": [20]}), [2])
+ # Int range
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_int", "gte": 10, "lte": 20}), [1, 2]
+ )
+ # String prefix
+ self.assertEqual(self._search({"op": "prefix", "field": "f_str", "prefix": "c"}), [3])
+ # List contains
+ self.assertEqual(
+ self._search({"op": "must", "field": "f_list_str", "conds": ["a"]}), [1]
+ )
+ # Date range
+ self.assertEqual(
+ self._search({"op": "range", "field": "f_date", "gt": "2023-01-01T10:00:00+00:00"}),
+ [2, 3, 5],
+ )
+ # Mixed complex
+ filters = {
+ "op": "or",
+ "conds": [
+ {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "f_bool", "conds": [True]},
+ {"op": "range", "field": "f_int", "gt": 0},
+ ],
+ },
+ {"op": "prefix", "field": "f_str", "prefix": "d"},
+ ],
+ }
+ self.assertEqual(self._search(filters), [1, 3, 4])
+
+ print("Verifying before restart...")
+ _verify_all_ops()
+
+ # 2. Close and restart
+ print("Closing collection...")
+ self.collection.close()
+ del self.collection
+ self.collection = None
+ gc.collect()
+
+ print("Reopening collection...")
+ # Re-open using the same path
+ self.collection = get_or_create_local_collection(path=self.path)
+
+ # 3. Verify queries after restart
+ print("Verifying after restart...")
+ _verify_all_ops()
+
+
+class TestFilterOpsIP(TestFilterOpsBasic):
+ """Basic Filter operator tests with Inner Product distance"""
+
+ def setUp(self):
+ self.path = "./db_test_filters_ip/"
+ clean_dir(self.path)
+ self.collection = self._create_collection()
+ self._insert_data()
+ self._create_index()
+
+ def tearDown(self):
+ if self.collection:
+ self.collection.drop()
+ clean_dir(self.path)
+
+ def _create_index(self):
+ index_meta = {
+ "IndexName": "idx_basic_ip",
+ "VectorIndex": {"IndexType": "flat", "Distance": "ip"},
+ "ScalarIndex": ["id", "val_int", "val_float", "val_str"],
+ }
+ self.collection.create_index("idx_basic_ip", index_meta)
+
+ def _search(self, filters):
+ res = self.collection.search_by_vector(
+ "idx_basic_ip", dense_vector=[1.0, 0, 0, 0], limit=100, filters=filters
+ )
+ return sorted([item.id for item in res.data])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/vectordb/test_openviking_vectordb.py b/tests/vectordb/test_openviking_vectordb.py
new file mode 100644
index 000000000..e061673a8
--- /dev/null
+++ b/tests/vectordb/test_openviking_vectordb.py
@@ -0,0 +1,536 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+import shutil
+import unittest
+
+from openviking.storage.vectordb.collection.local_collection import get_or_create_local_collection
+
+TEST_DB_PATH = "./db_test_openviking_vectordb/"
+
+
+def clean_dir(path: str) -> None:
+ shutil.rmtree(path, ignore_errors=True)
+
+
+def make_vector(index: int, dim: int) -> list[float]:
+ vector = [0.0] * dim
+ pos = max(0, min(dim - 1, index - 1))
+ vector[pos] = 1.0
+ return vector
+
+
+def in_time_range(value: str, gte: str, lte: str) -> bool:
+ return (gte is None or value >= gte) and (lte is None or value <= lte)
+
+
+class TestOpenVikingVectorDB(unittest.TestCase):
+ def setUp(self):
+ clean_dir(TEST_DB_PATH)
+ self.collections = []
+ self.data = []
+ self.deleted_ids = set()
+
+ def tearDown(self):
+ for collection in self.collections:
+ try:
+ collection.drop()
+ except Exception:
+ pass
+ self.collections.clear()
+ clean_dir(TEST_DB_PATH)
+
+ def _register(self, collection):
+ self.collections.append(collection)
+ return collection
+
+ def _create_collection(self):
+ vector_dim = 1024
+ meta_data = {
+ "CollectionName": "test_openviking_vectordb",
+ "Description": "Unified context collection",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "uri", "FieldType": "path"},
+ {"FieldName": "type", "FieldType": "string"},
+ {"FieldName": "context_type", "FieldType": "string"},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": vector_dim},
+ {"FieldName": "sparse_vector", "FieldType": "sparse_vector"},
+ {"FieldName": "created_at", "FieldType": "date_time"},
+ {"FieldName": "updated_at", "FieldType": "date_time"},
+ {"FieldName": "active_count", "FieldType": "int64"},
+ {"FieldName": "parent_uri", "FieldType": "path"},
+ {"FieldName": "is_leaf", "FieldType": "bool"},
+ {"FieldName": "name", "FieldType": "string"},
+ {"FieldName": "description", "FieldType": "string"},
+ {"FieldName": "tags", "FieldType": "string"},
+ {"FieldName": "abstract", "FieldType": "string"},
+ ],
+ }
+ collection = get_or_create_local_collection(meta_data=meta_data, path=TEST_DB_PATH)
+ return self._register(collection)
+
+ def _generate_data(self, dim: int):
+ groups = [
+ {
+ "type": "file",
+ "context_type": "markdown",
+ "parent_uri": "viking://resources/demo/",
+ "ext": ".md",
+ "tags": "tag_a;tag_b",
+ "abstract": "quick brown",
+ "desc_word": "hello",
+ },
+ {
+ "type": "file",
+ "context_type": "text",
+ "parent_uri": "viking://resources/docs/",
+ "ext": ".txt",
+ "tags": "tag_b",
+ "abstract": "lazy dog",
+ "desc_word": "beta",
+ },
+ {
+ "type": "image",
+ "context_type": "image",
+ "parent_uri": "viking://resources/images/",
+ "ext": ".png",
+ "tags": "tag_c",
+ "abstract": "fox",
+ "desc_word": "keyword",
+ },
+ ]
+
+ data = []
+ idx = 1
+ month_by_group = ["01", "02", "03"]
+ for group_idx, group in enumerate(groups):
+ for j in range(10):
+ day = 1 + j
+ month = month_by_group[group_idx]
+ created_at = f"2026-{month}-{day:02d}T10:00:00.{j + 1:06d}"
+ updated_at = f"2026-{month}-{day:02d}T12:00:00.{j + 2:06d}"
+ name = f"{group['context_type']}_{j}{group['ext']}"
+ uri = f"{group['parent_uri']}{name}"
+ data.append(
+ {
+ "id": f"res_{idx}",
+ "uri": uri,
+ "type": group["type"],
+ "context_type": group["context_type"],
+ "vector": make_vector(idx, dim),
+ "sparse_vector": {},
+ "created_at": created_at,
+ "updated_at": updated_at,
+ "active_count": idx * 3,
+ "parent_uri": group["parent_uri"],
+ "is_leaf": j % 2 == 0,
+ "name": name,
+ "description": f"{group['desc_word']} desc {j}",
+ "tags": group["tags"],
+ "abstract": group["abstract"],
+ }
+ )
+ idx += 1
+ return data
+
+ def _insert_data(self, collection):
+ self.data = self._generate_data(1024)
+ result = collection.upsert_data(self.data)
+ self.assertEqual(len(result.ids), len(self.data))
+
+ def _create_index(self, collection):
+ index_meta = {
+ "IndexName": "idx_filters",
+ "VectorIndex": {"IndexType": "flat", "Distance": "l2"},
+ "ScalarIndex": [
+ "uri",
+ "type",
+ "context_type",
+ "created_at",
+ "updated_at",
+ "active_count",
+ "parent_uri",
+ "is_leaf",
+ "name",
+ "description",
+ "tags",
+ "abstract",
+ ],
+ }
+ collection.create_index("idx_filters", index_meta)
+
+ def _search_ids(self, collection, filters, limit=100):
+ result = collection.search_by_vector(
+ "idx_filters", dense_vector=make_vector(1, 1024), limit=limit, filters=filters
+ )
+ return sorted([item.id for item in result.data])
+
+ def _expected_ids(self, predicate):
+ return sorted(
+ [
+ item["id"]
+ for item in self.data
+ if item["id"] not in self.deleted_ids and predicate(item)
+ ]
+ )
+
+ def test_filters_update_delete_recall(self):
+ collection = self._create_collection()
+ self._insert_data(collection)
+ self._create_index(collection)
+
+ index_meta = collection.get_index_meta_data("idx_filters") or {}
+ self.assertIn("type", index_meta.get("ScalarIndex", []))
+ fetched = collection.fetch_data(["res_1"])
+ self.assertEqual(fetched.items[0].fields.get("type"), "file")
+
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "must", "field": "context_type", "conds": ["markdown"]}
+ ),
+ self._expected_ids(lambda item: item["context_type"] == "markdown"),
+ )
+ self.assertEqual(
+ self._search_ids(collection, {"op": "must", "field": "type", "conds": ["file"]}),
+ self._expected_ids(lambda item: item["type"] == "file"),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "must_not", "field": "context_type", "conds": ["markdown"]}
+ ),
+ self._expected_ids(lambda item: item["context_type"] != "markdown"),
+ )
+ self.assertEqual(
+ self._search_ids(collection, {"op": "must", "field": "tags", "conds": ["tag_b"]}),
+ self._expected_ids(lambda item: "tag_b" in item["tags"]),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {"op": "prefix", "field": "uri", "prefix": "viking://resources/demo/"},
+ ),
+ self._expected_ids(lambda item: item["uri"].startswith("viking://resources/demo/")),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {"op": "prefix", "field": "parent_uri", "prefix": "viking://resources/docs/"},
+ ),
+ self._expected_ids(
+ lambda item: item["parent_uri"].startswith("viking://resources/docs/")
+ ),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "contains", "field": "description", "substring": "keyword"}
+ ),
+ self._expected_ids(lambda item: "keyword" in item["description"]),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "contains", "field": "abstract", "substring": "quick"}
+ ),
+ self._expected_ids(lambda item: "quick" in item["abstract"]),
+ )
+ self.assertEqual(
+ self._search_ids(collection, {"op": "regex", "field": "name", "pattern": r".*\.txt$"}),
+ self._expected_ids(lambda item: item["name"].endswith(".txt")),
+ )
+ self.assertEqual(
+ self._search_ids(collection, {"op": "range", "field": "active_count", "gt": 60}),
+ self._expected_ids(lambda item: item["active_count"] > 60),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "range_out", "field": "active_count", "gte": 10, "lte": 20}
+ ),
+ self._expected_ids(lambda item: item["active_count"] < 10 or item["active_count"] > 20),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {
+ "op": "time_range",
+ "field": "created_at",
+ "gte": "2026-02-03T00:00:00",
+ "lte": "2026-02-08T23:59:59",
+ },
+ ),
+ self._expected_ids(
+ lambda item: in_time_range(
+ item["created_at"], "2026-02-03T00:00:00", "2026-02-08T23:59:59"
+ )
+ ),
+ )
+ target_updated_at = self.data[0]["updated_at"]
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {"op": "must", "field": "updated_at", "conds": [target_updated_at]},
+ ),
+ self._expected_ids(lambda item: item["updated_at"] == target_updated_at),
+ )
+ self.assertEqual(
+ self._search_ids(collection, {"op": "must", "field": "is_leaf", "conds": [True]}),
+ self._expected_ids(lambda item: item["is_leaf"] is True),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "context_type", "conds": ["text"]},
+ {"op": "must", "field": "tags", "conds": ["tag_b"]},
+ {"op": "must", "field": "is_leaf", "conds": [False]},
+ ],
+ },
+ ),
+ self._expected_ids(
+ lambda item: item["context_type"] == "text"
+ and "tag_b" in item["tags"]
+ and item["is_leaf"] is False
+ ),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {
+ "op": "or",
+ "conds": [
+ {"op": "must", "field": "context_type", "conds": ["markdown"]},
+ {"op": "must", "field": "context_type", "conds": ["image"]},
+ ],
+ },
+ ),
+ self._expected_ids(lambda item: item["context_type"] in ("markdown", "image")),
+ )
+
+ # Update: change active_count + name + updated_at for res_12
+ target_id = "res_12"
+ updated_payload = None
+ for item in self.data:
+ if item["id"] == target_id:
+ item["active_count"] = 999
+ item["name"] = "text_99.txt"
+ item["updated_at"] = "2026-02-28T12:00:00.000000"
+ updated_payload = dict(item)
+ break
+ self.assertIsNotNone(updated_payload)
+ collection.upsert_data([updated_payload])
+
+ self.assertEqual(
+ self._search_ids(collection, {"op": "range", "field": "active_count", "gt": 900}),
+ self._expected_ids(lambda item: item["active_count"] > 900),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection, {"op": "regex", "field": "name", "pattern": r"text_99\.txt"}
+ ),
+ self._expected_ids(lambda item: item["name"] == "text_99.txt"),
+ )
+ self.assertEqual(
+ self._search_ids(
+ collection,
+ {
+ "op": "time_range",
+ "field": "updated_at",
+ "gte": "2026-02-28T00:00:00",
+ "lte": "2026-02-28T23:59:59",
+ },
+ ),
+ self._expected_ids(
+ lambda item: in_time_range(
+ item["updated_at"], "2026-02-28T00:00:00", "2026-02-28T23:59:59"
+ )
+ ),
+ )
+
+ # Delete: remove res_30
+ self.deleted_ids.add("res_30")
+ collection.delete_data(["res_30"])
+ self.assertEqual(
+ self._search_ids(collection, {"op": "must", "field": "tags", "conds": ["tag_c"]}),
+ self._expected_ids(lambda item: item["tags"] == "tag_c"),
+ )
+
+ # Recall: exact vector should return res_1 at top-1
+ recall = collection.search_by_vector(
+ "idx_filters", dense_vector=make_vector(1, 1024), limit=1
+ )
+ self.assertEqual([item.id for item in recall.data], ["res_1"])
+
+ def test_offset_collision_after_delete(self):
+ """Test for regression of logical offset collision.
+
+ Scenario:
+ 1. Insert A, B. (A=0, B=1)
+ 2. Delete A. (Count=1)
+ 3. Insert C. (Count=2, New Offset should not be 1 if B is still at 1)
+ 4. Search for B and C with filters to ensure no collision.
+ """
+ collection = self._create_collection()
+ dim = 1024
+
+ # 1. Insert A and B
+ data_init = [
+ {
+ "id": "A",
+ "vector": make_vector(1, dim),
+ "sparse_vector": {},
+ "type": "file",
+ "context_type": "text",
+ "tags": "tag_A",
+ "created_at": "2026-01-01T00:00:00.000000",
+ "updated_at": "2026-01-01T00:00:00.000000",
+ "active_count": 10,
+ "is_leaf": True,
+ "name": "A.txt",
+ "description": "desc A",
+ "abstract": "abs A",
+ },
+ {
+ "id": "B",
+ "vector": make_vector(2, dim),
+ "sparse_vector": {},
+ "type": "file",
+ "context_type": "text",
+ "tags": "tag_B",
+ "created_at": "2026-01-02T00:00:00.000000",
+ "updated_at": "2026-01-02T00:00:00.000000",
+ "active_count": 20,
+ "is_leaf": True,
+ "name": "B.txt",
+ "description": "desc B",
+ "abstract": "abs B",
+ },
+ ]
+ collection.upsert_data(data_init)
+ self._create_index(collection)
+
+ # Verify initial state
+ res_a = collection.search_by_vector(
+ "idx_filters",
+ make_vector(1, dim),
+ limit=1,
+ filters={"op": "must", "field": "tags", "conds": ["tag_A"]},
+ )
+ self.assertEqual(res_a.data[0].id, "A")
+
+ res_b = collection.search_by_vector(
+ "idx_filters",
+ make_vector(2, dim),
+ limit=1,
+ filters={"op": "must", "field": "tags", "conds": ["tag_B"]},
+ )
+ self.assertEqual(res_b.data[0].id, "B")
+
+ # 2. Delete A
+ collection.delete_data(["A"])
+
+ # 3. Insert C
+ data_c = [
+ {
+ "id": "C",
+ "vector": make_vector(3, dim),
+ "sparse_vector": {},
+ "type": "file",
+ "context_type": "text",
+ "tags": "tag_C",
+ "created_at": "2026-01-03T00:00:00.000000",
+ "updated_at": "2026-01-03T00:00:00.000000",
+ "active_count": 30,
+ "is_leaf": True,
+ "name": "C.txt",
+ "description": "desc C",
+ "abstract": "abs C",
+ }
+ ]
+ collection.upsert_data(data_c)
+
+ # 4. Search for B (should still be found correctly)
+ # If collision happens, searching for tag_B (offset 1) might point to C's vector or vice versa
+ res_b_final = collection.search_by_vector(
+ "idx_filters",
+ make_vector(2, dim),
+ limit=1,
+ filters={"op": "must", "field": "tags", "conds": ["tag_B"]},
+ )
+ self.assertEqual(len(res_b_final.data), 1, "Should find B")
+ self.assertEqual(res_b_final.data[0].id, "B", "Should match ID B")
+
+ # 5. Search for C
+ res_c_final = collection.search_by_vector(
+ "idx_filters",
+ make_vector(3, dim),
+ limit=1,
+ filters={"op": "must", "field": "tags", "conds": ["tag_C"]},
+ )
+ self.assertEqual(len(res_c_final.data), 1, "Should find C")
+ self.assertEqual(res_c_final.data[0].id, "C", "Should match ID C")
+
+
+class TestOpenVikingVectorDBIP(TestOpenVikingVectorDB):
+ def setUp(self):
+ super().setUp()
+ global TEST_DB_PATH
+ TEST_DB_PATH = "./db_test_openviking_vectordb_ip/"
+ clean_dir(TEST_DB_PATH)
+
+ def tearDown(self):
+ super().tearDown()
+ global TEST_DB_PATH
+ clean_dir(TEST_DB_PATH)
+ TEST_DB_PATH = "./db_test_openviking_vectordb/" # Reset
+
+ def _create_collection(self):
+ vector_dim = 1024
+ meta_data = {
+ "CollectionName": "test_openviking_vectordb_ip",
+ "Description": "Unified context collection IP",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "uri", "FieldType": "path"},
+ {"FieldName": "type", "FieldType": "string"},
+ {"FieldName": "context_type", "FieldType": "string"},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": vector_dim},
+ {"FieldName": "sparse_vector", "FieldType": "sparse_vector"},
+ {"FieldName": "created_at", "FieldType": "date_time"},
+ {"FieldName": "updated_at", "FieldType": "date_time"},
+ {"FieldName": "active_count", "FieldType": "int64"},
+ {"FieldName": "parent_uri", "FieldType": "path"},
+ {"FieldName": "is_leaf", "FieldType": "bool"},
+ {"FieldName": "name", "FieldType": "string"},
+ {"FieldName": "description", "FieldType": "string"},
+ {"FieldName": "tags", "FieldType": "string"},
+ {"FieldName": "abstract", "FieldType": "string"},
+ ],
+ }
+ collection = get_or_create_local_collection(meta_data=meta_data, path=TEST_DB_PATH)
+ return self._register(collection)
+
+ def _create_index(self, collection):
+ index_meta = {
+ "IndexName": "idx_filters",
+ "VectorIndex": {"IndexType": "flat", "Distance": "ip"},
+ "ScalarIndex": [
+ "uri",
+ "type",
+ "context_type",
+ "created_at",
+ "updated_at",
+ "active_count",
+ "parent_uri",
+ "is_leaf",
+ "name",
+ "description",
+ "tags",
+ "abstract",
+ ],
+ }
+ collection.create_index("idx_filters", index_meta)
+
+
+if __name__ == "__main__":
+ unittest.main()