mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(fts): add WAND factor support for FTS and hybrid search (#4894)
Fixes #4754 Add wand_factor support across synchronous and asynchronous FTS and hybrid query APIs, with finite non-negative value validation, PyO3 propagation, query serialization support, and namespace execution fallback when a custom factor is configured. Add tests covering default behavior, custom values, validation, clearing the factor, sync/async execution, serialization round-trips, and namespace routing. --------- Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -1143,6 +1143,8 @@ class FTSQuery:
|
||||
def postfilter(self): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
def get_query(self) -> str: ...
|
||||
def wand_factor(self, wand_factor: Optional[float]): ...
|
||||
def get_wand_factor(self) -> Optional[float]: ...
|
||||
def add_query_vector(self, query_vec: pa.Array) -> None: ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
@@ -1222,6 +1224,8 @@ class HybridQuery:
|
||||
def to_fts_query(self) -> FTSQuery: ...
|
||||
def get_limit(self) -> int: ...
|
||||
def get_with_row_id(self) -> bool: ...
|
||||
def wand_factor(self, wand_factor: Optional[float]): ...
|
||||
def get_wand_factor(self) -> Optional[float]: ...
|
||||
def to_query_request(self) -> PyQueryRequest: ...
|
||||
|
||||
class FullTextQuery:
|
||||
@@ -1235,6 +1239,7 @@ class PyQueryRequest:
|
||||
preserve_order: Optional[bool]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
wand_factor: Optional[float]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
select_source_columns: Optional[Dict[str, str]]
|
||||
fast_search: Optional[bool]
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
from abc import ABC, abstractmethod
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
@@ -1004,6 +1005,18 @@ class BooleanQuery(FullTextQuery):
|
||||
return FullTextQueryType.BOOLEAN
|
||||
|
||||
|
||||
def _validate_wand_factor(wand_factor: Optional[float]) -> Optional[float]:
|
||||
if wand_factor is not None:
|
||||
if wand_factor < 0 or not math.isfinite(wand_factor):
|
||||
raise ValueError("wand_factor must be finite and non-negative")
|
||||
if wand_factor != 1.0:
|
||||
raise ValueError(
|
||||
f"wand_factor must be None or 1.0 (got {wand_factor}); "
|
||||
"non-default factors are currently unsupported "
|
||||
)
|
||||
return wand_factor
|
||||
|
||||
|
||||
class FullTextSearchQuery(pydantic.BaseModel):
|
||||
"""A LanceDB Full Text Search Query
|
||||
|
||||
@@ -1016,15 +1029,28 @@ class FullTextSearchQuery(pydantic.BaseModel):
|
||||
query: str | FullTextQuery
|
||||
If a string, it is treated as a MatchQuery.
|
||||
If a FullTextQuery object, it is used directly.
|
||||
wand_factor: Optional[float]
|
||||
Factor for dynamic pruning in WAND (Weak AND) search.
|
||||
operator: FullTextOperator, optional
|
||||
Combine terms in a string query using AND or OR (the default).
|
||||
Quoted strings keep phrase semantics regardless of the operator.
|
||||
"""
|
||||
|
||||
model_config = pydantic.ConfigDict(
|
||||
arbitrary_types_allowed=True,
|
||||
validate_assignment=True,
|
||||
)
|
||||
|
||||
columns: Optional[List[str]] = None
|
||||
query: Union[str, FullTextQuery]
|
||||
wand_factor: Optional[float] = None
|
||||
operator: Optional[FullTextOperator] = None
|
||||
|
||||
@pydantic.field_validator("wand_factor")
|
||||
@classmethod
|
||||
def _validate_wand_factor_field(cls, v: Optional[float]) -> Optional[float]:
|
||||
return _validate_wand_factor(v)
|
||||
|
||||
@pydantic.model_validator(mode="after")
|
||||
def _validate_operator(self) -> Self:
|
||||
if self.operator is not None and not isinstance(self.query, str):
|
||||
@@ -1156,6 +1182,10 @@ class Query(pydantic.BaseModel):
|
||||
# Internal: the sync query layer already prepared blob row ids.
|
||||
_blob_row_id_prepared: bool = pydantic.PrivateAttr(default=False)
|
||||
|
||||
# Internal: forces namespace-backed queries to execute against the local
|
||||
# embedded table instead of using QueryTable pushdown.
|
||||
_force_local_namespace: bool = pydantic.PrivateAttr(default=False)
|
||||
|
||||
# The name of the vector column to use for vector search.
|
||||
vector_column: Optional[str] = None
|
||||
|
||||
@@ -1298,6 +1328,7 @@ class Query(pydantic.BaseModel):
|
||||
query.full_text_query = FullTextSearchQuery(
|
||||
columns=None,
|
||||
query=req.full_text_search,
|
||||
wand_factor=getattr(req, "wand_factor", None),
|
||||
)
|
||||
return query
|
||||
|
||||
@@ -2442,6 +2473,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
self._reranker = None
|
||||
self._str_query = str_query
|
||||
self._fast_search = fast_search
|
||||
self._force_local_namespace = False
|
||||
|
||||
def metric(self, metric: Literal["l2", "cosine", "dot"]) -> LanceVectorQueryBuilder:
|
||||
"""Set the distance metric to use.
|
||||
@@ -2461,6 +2493,21 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
"""
|
||||
return self.distance_type(metric)
|
||||
|
||||
def _force_local_namespace_execution(self) -> "LanceVectorQueryBuilder":
|
||||
"""Mark this vector query to always execute locally (never namespace pushdown).
|
||||
|
||||
This is an internal method used by LanceHybridQueryBuilder to ensure the
|
||||
vector leg and the FTS leg of a hybrid query share the same local embedded
|
||||
table snapshot when an explicit wand_factor is configured.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceVectorQueryBuilder
|
||||
self
|
||||
"""
|
||||
self._force_local_namespace = True
|
||||
return self
|
||||
|
||||
def distance_type(
|
||||
self, distance_type: Literal["l2", "cosine", "dot"]
|
||||
) -> "LanceVectorQueryBuilder":
|
||||
@@ -2741,7 +2788,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
vector = self._query if isinstance(self._query, list) else self._query.tolist()
|
||||
if isinstance(vector[0], np.ndarray):
|
||||
vector = [v.tolist() for v in vector]
|
||||
return Query(
|
||||
query = Query(
|
||||
vector=vector,
|
||||
filter=self._where,
|
||||
postfilter=self._postfilter,
|
||||
@@ -2768,6 +2815,10 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
bypass_vector_index=self._bypass_vector_index,
|
||||
order_by=self._order_by,
|
||||
)
|
||||
# Preserve the local-execution requirement when converting to a Query.
|
||||
if self._force_local_namespace:
|
||||
query._force_local_namespace = True
|
||||
return query
|
||||
|
||||
def _to_batches_prepared(
|
||||
self,
|
||||
@@ -2954,6 +3005,27 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
if isinstance(fts_columns, str):
|
||||
fts_columns = [fts_columns]
|
||||
self._fts_columns = fts_columns
|
||||
self._wand_factor = None
|
||||
|
||||
def wand_factor(self, wand_factor: Optional[float]) -> LanceFtsQueryBuilder:
|
||||
"""Set the WAND factor for full text search.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
wand_factor: Optional[float]
|
||||
The WAND factor to use, or ``None`` to restore the default.
|
||||
|
||||
.. note::
|
||||
Only ``None`` and ``1.0`` are currently accepted. Non-default
|
||||
values raise ``ValueError`` pending engine support.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceFtsQueryBuilder
|
||||
The LanceFtsQueryBuilder object.
|
||||
"""
|
||||
self._wand_factor = _validate_wand_factor(wand_factor)
|
||||
return self
|
||||
|
||||
def operator(
|
||||
self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]]
|
||||
@@ -3044,6 +3116,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query=self._query_with_phrase_semantics(),
|
||||
columns=self._fts_columns,
|
||||
wand_factor=self._wand_factor,
|
||||
operator=self._operator,
|
||||
),
|
||||
offset=self._offset,
|
||||
@@ -3295,6 +3368,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
self._refine_factor = None
|
||||
self._distance_type = None
|
||||
self._phrase_query = None
|
||||
self._wand_factor = None
|
||||
self._lower_bound = None
|
||||
self._upper_bound = None
|
||||
# WAL-PK-FUSION: delete both, and the `with_row_id` override below.
|
||||
@@ -3382,6 +3456,26 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
self._phrase_query = phrase_query
|
||||
return self
|
||||
|
||||
def wand_factor(self, wand_factor: Optional[float]) -> LanceHybridQueryBuilder:
|
||||
"""Set the WAND factor for the full text search component.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
wand_factor: Optional[float]
|
||||
The WAND factor to use, or ``None`` to restore the default.
|
||||
|
||||
.. note::
|
||||
Only ``None`` and ``1.0`` are currently accepted. Non-default
|
||||
values raise ``ValueError`` pending engine support.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceHybridQueryBuilder
|
||||
The LanceHybridQueryBuilder object.
|
||||
"""
|
||||
self._wand_factor = _validate_wand_factor(wand_factor)
|
||||
return self
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
raise NotImplementedError("to_query_object not yet supported on a hybrid query")
|
||||
|
||||
@@ -4074,6 +4168,13 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
self._fts_query.use_rte(self._use_rte)
|
||||
if self._phrase_query:
|
||||
self._fts_query.phrase_query(True)
|
||||
if self._wand_factor is not None:
|
||||
self._fts_query.wand_factor(self._wand_factor)
|
||||
# For non-default WAND factors, keep both hybrid legs on the same
|
||||
# local snapshot. The default factor (1.0) is normalized to None
|
||||
# for execution, so both legs can use standard namespace routing.
|
||||
if self._wand_factor != 1.0:
|
||||
self._vector_query._force_local_namespace_execution()
|
||||
if self._distance_type:
|
||||
self._vector_query.metric(self._distance_type)
|
||||
if self._nprobes is not None:
|
||||
@@ -5269,6 +5370,30 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
def get_query(self) -> str:
|
||||
return self._inner.get_query()
|
||||
|
||||
def wand_factor(self, wand_factor: Optional[float]) -> AsyncFTSQuery:
|
||||
"""Set the WAND factor for full text search.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
wand_factor: Optional[float]
|
||||
The WAND factor to use, or ``None`` to restore the default.
|
||||
|
||||
.. note::
|
||||
Only ``None`` and ``1.0`` are currently accepted. Non-default
|
||||
values raise ``ValueError`` pending engine support.
|
||||
|
||||
Returns
|
||||
-------
|
||||
AsyncFTSQuery
|
||||
The AsyncFTSQuery object.
|
||||
"""
|
||||
_validate_wand_factor(wand_factor)
|
||||
self._inner.wand_factor(wand_factor)
|
||||
return self
|
||||
|
||||
def get_wand_factor(self) -> Optional[float]:
|
||||
return self._inner.get_wand_factor()
|
||||
|
||||
def rerank(
|
||||
self,
|
||||
reranker: Reranker = RRFReranker(),
|
||||
@@ -5667,6 +5792,22 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
self._inner = inner
|
||||
self._reranker = None
|
||||
self._query_string = None
|
||||
self._force_local_namespace: bool = False
|
||||
|
||||
def _force_local_namespace_execution(self) -> "AsyncVectorQuery":
|
||||
"""Mark this vector query to always execute locally (never namespace pushdown).
|
||||
|
||||
Internal method used by AsyncHybridQuery to ensure the vector leg and the FTS
|
||||
leg share the same local embedded table snapshot when an explicit wand_factor is
|
||||
configured. Mirrors LanceVectorQueryBuilder._force_local_namespace_execution().
|
||||
|
||||
Returns
|
||||
-------
|
||||
AsyncVectorQuery
|
||||
self
|
||||
"""
|
||||
self._force_local_namespace = True
|
||||
return self
|
||||
|
||||
def rerank(
|
||||
self, reranker: Reranker = RRFReranker(), query_string: Optional[str] = None
|
||||
@@ -5745,7 +5886,14 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
results = await super()._execute_eager(timeout=timeout)
|
||||
if self._force_local_namespace and self._table is not None:
|
||||
# Preserve local execution for the vector leg so it uses the same
|
||||
# embedded table snapshot as the FTS leg.
|
||||
query = self.to_query_object()
|
||||
query._force_local_namespace = True
|
||||
results = await self._table._execute_arrow(query, timeout=timeout)
|
||||
else:
|
||||
results = await super()._execute_eager(timeout=timeout)
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_vector(self._query_string, results)
|
||||
@@ -5849,6 +5997,30 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
|
||||
return self
|
||||
|
||||
def wand_factor(self, wand_factor: Optional[float]) -> AsyncHybridQuery:
|
||||
"""Set the WAND factor for the full text search component.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
wand_factor: Optional[float]
|
||||
The WAND factor to use, or ``None`` to restore the default.
|
||||
|
||||
.. note::
|
||||
Only ``None`` and ``1.0`` are currently accepted. Non-default
|
||||
values raise ``ValueError`` pending engine support.
|
||||
|
||||
Returns
|
||||
-------
|
||||
AsyncHybridQuery
|
||||
The AsyncHybridQuery object.
|
||||
"""
|
||||
_validate_wand_factor(wand_factor)
|
||||
self._inner.wand_factor(wand_factor)
|
||||
return self
|
||||
|
||||
def get_wand_factor(self) -> Optional[float]:
|
||||
return self._inner.get_wand_factor()
|
||||
|
||||
def _reject_explicit_zero_limit(self) -> None:
|
||||
"""Reject an explicit zero limit before any work runs for this query.
|
||||
|
||||
@@ -5892,6 +6064,13 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table)
|
||||
vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table)
|
||||
|
||||
# A non-default wand_factor forces the FTS leg to execute locally.
|
||||
# Force the vector leg local as well so both legs use the same
|
||||
# embedded table handle and snapshot. The default factor (1.0)
|
||||
# does not require local execution.
|
||||
if self.get_wand_factor() is not None and self.get_wand_factor() != 1.0:
|
||||
vec_query._force_local_namespace_execution()
|
||||
|
||||
fts_req = fts_query._inner.to_query_request()
|
||||
vec_req = vec_query._inner.to_query_request()
|
||||
|
||||
|
||||
@@ -144,6 +144,10 @@ def _should_push_down_query_table(
|
||||
|
||||
def _requires_local_namespace_execution(query: Query) -> bool:
|
||||
# The namespace QueryTable request does not support these query options.
|
||||
_fts_wand = (
|
||||
query.full_text_query.wand_factor if query.full_text_query is not None else None
|
||||
)
|
||||
_fts_forces_local = _fts_wand is not None and _fts_wand != 1.0
|
||||
return (
|
||||
(isinstance(query.filter, str) and _uses_sql_subquery_filter(query.filter))
|
||||
or query.take_offsets is not None
|
||||
@@ -161,6 +165,12 @@ def _requires_local_namespace_execution(query: Query) -> bool:
|
||||
and query.fast_search is True
|
||||
and query.vector is None
|
||||
)
|
||||
# Namespace QueryTable cannot represent non-default wand_factor values.
|
||||
# wand_factor=1.0 is equivalent to None and remains eligible for pushdown.
|
||||
or _fts_forces_local
|
||||
# A hybrid vector subquery carries this sentinel when its FTS sibling
|
||||
# requires local execution, ensuring both legs use the same snapshot.
|
||||
or query._force_local_namespace
|
||||
)
|
||||
|
||||
|
||||
@@ -9032,6 +9042,11 @@ class AsyncTable:
|
||||
query.full_text_query.columns,
|
||||
operator=query.full_text_query.operator,
|
||||
)
|
||||
if getattr(query.full_text_query, "wand_factor", None) is not None:
|
||||
async_query = async_query.wand_factor(query.full_text_query.wand_factor)
|
||||
|
||||
if getattr(query, "_force_local_namespace", False):
|
||||
async_query._force_local_namespace = True
|
||||
|
||||
return async_query
|
||||
|
||||
|
||||
@@ -0,0 +1,966 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from lancedb.query import (
|
||||
AsyncFTSQuery,
|
||||
AsyncHybridQuery,
|
||||
FullTextSearchQuery,
|
||||
LanceFtsQueryBuilder,
|
||||
LanceHybridQueryBuilder,
|
||||
Query,
|
||||
)
|
||||
from lancedb.table import _requires_local_namespace_execution
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(tmp_path):
|
||||
return lancedb.connect(str(tmp_path))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fts_table(db):
|
||||
"""Small table with an FTS index."""
|
||||
data = pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"text": [
|
||||
"machine learning is great",
|
||||
"deep learning rocks",
|
||||
"python rocks",
|
||||
],
|
||||
"vector": [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
],
|
||||
}
|
||||
)
|
||||
tbl = db.create_table("fts_table", data=data)
|
||||
tbl.create_fts_index("text", replace=True)
|
||||
return tbl
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def async_db(tmp_path):
|
||||
return await lancedb.connect_async(str(tmp_path))
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def async_fts_table(async_db):
|
||||
"""Small table with an FTS index (async connection)."""
|
||||
data = pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"text": [
|
||||
"machine learning is great",
|
||||
"deep learning rocks",
|
||||
"python rocks",
|
||||
],
|
||||
"vector": [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
],
|
||||
}
|
||||
)
|
||||
tbl = await async_db.create_table("async_fts_table", data=data)
|
||||
await tbl.create_index("text", config=lancedb.index.FTS(with_position=False))
|
||||
return tbl
|
||||
|
||||
|
||||
def test_default_wand_factor_is_none():
|
||||
"""wand_factor must default to None in FullTextSearchQuery."""
|
||||
q = FullTextSearchQuery(query="hello")
|
||||
assert q.wand_factor is None
|
||||
|
||||
|
||||
def test_fts_builder_default_wand_factor(fts_table):
|
||||
"""LanceFtsQueryBuilder must not set wand_factor by default."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
query_obj = builder.to_query_object()
|
||||
assert query_obj.full_text_query is not None
|
||||
assert query_obj.full_text_query.wand_factor is None
|
||||
|
||||
|
||||
def test_fts_builder_set_wand_factor_1_0(fts_table):
|
||||
"""wand_factor=1.0 set on LanceFtsQueryBuilder is stored in the Query object."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning").wand_factor(1.0)
|
||||
query_obj = builder.to_query_object()
|
||||
assert query_obj.full_text_query is not None
|
||||
assert query_obj.full_text_query.wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_fts_builder_wand_factor_negative_raises(fts_table):
|
||||
"""Negative wand_factor must raise ValueError."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
builder.wand_factor(-1.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
|
||||
def test_fts_builder_wand_factor_non_finite_raises(fts_table, value):
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
builder.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [0.0, 0.8, 1.5, 2.0])
|
||||
def test_fts_builder_unsupported_factor_raises(fts_table, value):
|
||||
"""Non-default factors other than 1.0 must be rejected."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
builder.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [0.0, 0.8, 1.5, 2.0])
|
||||
def test_full_text_search_query_unsupported_factor_raises(value):
|
||||
"""FullTextSearchQuery must reject non-default factors other than 1.0."""
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
FullTextSearchQuery(query="hello", wand_factor=value)
|
||||
|
||||
|
||||
def test_full_text_search_query_valid_factors():
|
||||
"""FullTextSearchQuery must accept None and 1.0."""
|
||||
q_none = FullTextSearchQuery(query="hello", wand_factor=None)
|
||||
assert q_none.wand_factor is None
|
||||
q_one = FullTextSearchQuery(query="hello", wand_factor=1.0)
|
||||
assert q_one.wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_fts_builder_wand_factor_returns_self(fts_table):
|
||||
"""wand_factor() must be fluent (returns the builder)."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
result = builder.wand_factor(1.0)
|
||||
assert result is builder
|
||||
|
||||
|
||||
def test_fts_builder_wand_factor_none_clears(fts_table):
|
||||
"""Calling wand_factor(None) should clear the value."""
|
||||
builder = (
|
||||
LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
.wand_factor(1.0)
|
||||
.wand_factor(None)
|
||||
)
|
||||
query_obj = builder.to_query_object()
|
||||
assert query_obj.full_text_query.wand_factor is None
|
||||
|
||||
|
||||
def test_pyo3_fts_query_wand_factor(fts_table):
|
||||
"""FTSQuery (PyO3) getter/setter round-trip works correctly."""
|
||||
sync_q = (
|
||||
LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
.wand_factor(1.0)
|
||||
.to_query_object()
|
||||
)
|
||||
async_tbl = fts_table._table
|
||||
async_q = async_tbl._sync_query_to_async(sync_q)
|
||||
assert isinstance(async_q, AsyncFTSQuery)
|
||||
assert async_q.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_pyo3_fts_query_wand_factor_roundtrip(fts_table):
|
||||
"""wand_factor survives PyO3 FTSQuery getter/setter round-trip."""
|
||||
sync_q = (
|
||||
LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
.wand_factor(1.0)
|
||||
.to_query_object()
|
||||
)
|
||||
async_tbl = fts_table._table
|
||||
async_q = async_tbl._sync_query_to_async(sync_q)
|
||||
assert isinstance(async_q, AsyncFTSQuery)
|
||||
|
||||
req = async_q._inner.to_query_request()
|
||||
assert hasattr(req, "wand_factor"), "PyQueryRequest is missing wand_factor field"
|
||||
assert req.wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_pyo3_hybrid_query_wand_factor(fts_table):
|
||||
"""HybridQuery (PyO3) delegates wand_factor to its inner FTSQuery."""
|
||||
builder = (
|
||||
fts_table.search(query_type="hybrid")
|
||||
.vector([0.1, 0.2, 0.3, 0.4])
|
||||
.text("machine learning")
|
||||
)
|
||||
assert isinstance(builder, LanceHybridQueryBuilder)
|
||||
builder.wand_factor(1.0)
|
||||
assert builder._wand_factor == pytest.approx(1.0)
|
||||
builder._create_query_builders()
|
||||
fts_child = builder._fts_query
|
||||
assert isinstance(fts_child, LanceFtsQueryBuilder)
|
||||
assert fts_child._wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_wand_factor_roundtrip_via_query_request(fts_table):
|
||||
"""wand_factor must survive a PyQueryRequest -> Query.from_inner() roundtrip."""
|
||||
sync_q = (
|
||||
LanceFtsQueryBuilder(fts_table, "machine learning")
|
||||
.wand_factor(1.0)
|
||||
.to_query_object()
|
||||
)
|
||||
async_tbl = fts_table._table
|
||||
async_q = async_tbl._sync_query_to_async(sync_q)
|
||||
|
||||
req = async_q._inner.to_query_request()
|
||||
assert hasattr(req, "wand_factor"), "PyQueryRequest is missing wand_factor field"
|
||||
assert req.wand_factor == pytest.approx(1.0)
|
||||
|
||||
reconstructed = Query.from_inner(req)
|
||||
assert reconstructed.full_text_query is not None
|
||||
assert reconstructed.full_text_query.wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_wand_factor_absent_in_roundtrip(fts_table):
|
||||
"""When wand_factor is not set, roundtrip must not introduce it."""
|
||||
sync_q = LanceFtsQueryBuilder(fts_table, "machine learning").to_query_object()
|
||||
async_tbl = fts_table._table
|
||||
async_q = async_tbl._sync_query_to_async(sync_q)
|
||||
|
||||
req = async_q._inner.to_query_request()
|
||||
assert getattr(req, "wand_factor", None) is None
|
||||
|
||||
reconstructed = Query.from_inner(req)
|
||||
assert reconstructed.full_text_query is not None
|
||||
assert reconstructed.full_text_query.wand_factor is None
|
||||
|
||||
|
||||
def test_sync_fts_execution_with_wand_factor(fts_table):
|
||||
"""Sync FTS query with wand_factor=1.0 must execute and return results."""
|
||||
results = (
|
||||
fts_table.search("machine learning", query_type="fts")
|
||||
.wand_factor(1.0)
|
||||
.limit(10)
|
||||
.to_list()
|
||||
)
|
||||
assert len(results) > 0
|
||||
texts = [r["text"] for r in results]
|
||||
assert any("machine" in t for t in texts)
|
||||
|
||||
|
||||
def test_sync_fts_default_behavior_unchanged(fts_table):
|
||||
"""Existing FTS behavior without wand_factor must be unaffected."""
|
||||
results_default = (
|
||||
fts_table.search("machine learning", query_type="fts").limit(10).to_list()
|
||||
)
|
||||
results_with_wand = (
|
||||
fts_table.search("machine learning", query_type="fts")
|
||||
.wand_factor(1.0)
|
||||
.limit(10)
|
||||
.to_list()
|
||||
)
|
||||
assert len(results_default) > 0
|
||||
assert len(results_with_wand) > 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fts_execution_with_wand_factor(async_fts_table):
|
||||
"""Async FTS query with wand_factor=1.0 must execute and return results."""
|
||||
q = await async_fts_table.search("machine learning", query_type="fts")
|
||||
results = await q.wand_factor(1.0).limit(10).to_arrow()
|
||||
assert results.num_rows > 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fts_wand_factor_stored(async_fts_table):
|
||||
"""AsyncFTSQuery.wand_factor() must be stored and retrievable."""
|
||||
q = await async_fts_table.search("machine learning", query_type="fts")
|
||||
assert isinstance(q, AsyncFTSQuery)
|
||||
q.wand_factor(1.0)
|
||||
assert q.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fts_default_wand_factor_is_none(async_fts_table):
|
||||
"""AsyncFTSQuery must not have wand_factor set by default."""
|
||||
q = await async_fts_table.search("machine learning", query_type="fts")
|
||||
assert isinstance(q, AsyncFTSQuery)
|
||||
assert q.get_wand_factor() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value", [-1.0, float("nan"), float("inf"), float("-inf")])
|
||||
async def test_async_fts_wand_factor_validation_non_finite(async_fts_table, value):
|
||||
q = await async_fts_table.search("machine learning", query_type="fts")
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
q.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value", [0.0, 0.8, 1.5, 2.0])
|
||||
async def test_async_fts_wand_factor_unsupported_raises(async_fts_table, value):
|
||||
q = await async_fts_table.search("machine learning", query_type="fts")
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
q.wand_factor(value)
|
||||
|
||||
|
||||
def test_hybrid_builder_wand_factor_stored(fts_table):
|
||||
"""LanceHybridQueryBuilder.wand_factor() must be stored in the builder."""
|
||||
builder = LanceHybridQueryBuilder(fts_table, "machine learning")
|
||||
builder.wand_factor(1.0)
|
||||
assert builder._wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_hybrid_builder_wand_factor_negative_raises(fts_table):
|
||||
"""Negative wand_factor must raise ValueError on the hybrid builder."""
|
||||
builder = LanceHybridQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
builder.wand_factor(-0.5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
|
||||
def test_hybrid_builder_wand_factor_non_finite_raises(fts_table, value):
|
||||
builder = LanceHybridQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
builder.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [0.0, 0.8, 1.5, 2.0])
|
||||
def test_hybrid_builder_wand_factor_unsupported_raises(fts_table, value):
|
||||
builder = LanceHybridQueryBuilder(fts_table, "machine learning")
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
builder.wand_factor(value)
|
||||
|
||||
|
||||
def test_hybrid_builder_wand_factor_returns_self(fts_table):
|
||||
"""wand_factor() must be fluent on LanceHybridQueryBuilder."""
|
||||
builder = LanceHybridQueryBuilder(fts_table, "machine learning")
|
||||
result = builder.wand_factor(1.0)
|
||||
assert result is builder
|
||||
|
||||
|
||||
def test_hybrid_builder_wand_factor_applied_to_fts_child(fts_table):
|
||||
"""wand_factor must be propagated to the FTS child builder."""
|
||||
builder = (
|
||||
fts_table.search(query_type="hybrid")
|
||||
.vector([0.1, 0.2, 0.3, 0.4])
|
||||
.text("machine learning")
|
||||
.wand_factor(1.0)
|
||||
)
|
||||
assert isinstance(builder, LanceHybridQueryBuilder)
|
||||
builder._create_query_builders()
|
||||
assert builder._fts_query._wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_wand_factor_stored(async_fts_table):
|
||||
"""AsyncHybridQuery.wand_factor() must be stored and retrievable."""
|
||||
q = (
|
||||
async_fts_table.query()
|
||||
.nearest_to(np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32))
|
||||
.nearest_to_text("machine learning")
|
||||
)
|
||||
assert isinstance(q, AsyncHybridQuery)
|
||||
q.wand_factor(1.0)
|
||||
assert q.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_default_wand_factor_is_none(async_fts_table):
|
||||
"""AsyncHybridQuery must not have wand_factor set by default."""
|
||||
q = (
|
||||
async_fts_table.query()
|
||||
.nearest_to(np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32))
|
||||
.nearest_to_text("machine learning")
|
||||
)
|
||||
assert isinstance(q, AsyncHybridQuery)
|
||||
assert q.get_wand_factor() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value", [0.0, 0.8, 1.5, 2.0])
|
||||
async def test_async_hybrid_wand_factor_unsupported_raises(async_fts_table, value):
|
||||
q = (
|
||||
async_fts_table.query()
|
||||
.nearest_to(np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32))
|
||||
.nearest_to_text("machine learning")
|
||||
)
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
q.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_wand_factor_conversion_and_clear(async_fts_table):
|
||||
q = (
|
||||
async_fts_table.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("machine learning")
|
||||
)
|
||||
q.wand_factor(1.0)
|
||||
assert q._inner.to_query_request().wand_factor == pytest.approx(1.0)
|
||||
assert q._inner.to_fts_query().get_wand_factor() == pytest.approx(1.0)
|
||||
q.wand_factor(None)
|
||||
assert q.get_wand_factor() is None
|
||||
assert q._inner.to_query_request().wand_factor is None
|
||||
|
||||
|
||||
def test_sync_hybrid_execution_with_wand_factor(fts_table):
|
||||
results = (
|
||||
fts_table.search(query_type="hybrid")
|
||||
.vector([1.0, 0.0, 0.0, 0.0])
|
||||
.text("machine learning")
|
||||
.wand_factor(1.0)
|
||||
.limit(2)
|
||||
.to_list()
|
||||
)
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_execution_with_wand_factor(async_fts_table):
|
||||
q = (
|
||||
async_fts_table.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("machine learning")
|
||||
.wand_factor(1.0)
|
||||
.limit(2)
|
||||
)
|
||||
results = await q.to_arrow()
|
||||
assert results.num_rows > 0
|
||||
|
||||
|
||||
def test_requires_local_namespace_execution_with_wand_factor():
|
||||
"""_requires_local_namespace_execution returns False for None and 1.0."""
|
||||
q_no_wand = Query(
|
||||
full_text_query=FullTextSearchQuery(query="hello", wand_factor=None)
|
||||
)
|
||||
assert not _requires_local_namespace_execution(q_no_wand)
|
||||
|
||||
q_with_wand = Query(
|
||||
full_text_query=FullTextSearchQuery(query="hello", wand_factor=1.0)
|
||||
)
|
||||
assert not _requires_local_namespace_execution(q_with_wand)
|
||||
|
||||
q_non_default = Query(
|
||||
full_text_query=FullTextSearchQuery.model_construct(
|
||||
query="hello", wand_factor=1.5
|
||||
)
|
||||
)
|
||||
assert _requires_local_namespace_execution(q_non_default)
|
||||
|
||||
|
||||
def test_requires_local_namespace_execution_wand_factor_1_0():
|
||||
"""wand_factor=1.0 is the WAND identity and must NOT force local execution."""
|
||||
q = Query(full_text_query=FullTextSearchQuery(query="hello", wand_factor=1.0))
|
||||
assert not _requires_local_namespace_execution(q)
|
||||
|
||||
|
||||
def test_requires_local_namespace_execution_default_query():
|
||||
"""Plain query without FTS must not force local execution."""
|
||||
q = Query()
|
||||
assert not _requires_local_namespace_execution(q)
|
||||
|
||||
|
||||
def test_requires_local_namespace_execution_fts_no_wand():
|
||||
"""FTS query without wand_factor must not force local execution."""
|
||||
q = Query(full_text_query=FullTextSearchQuery(query="hello"))
|
||||
assert not _requires_local_namespace_execution(q)
|
||||
|
||||
|
||||
def test_requires_local_namespace_execution_force_local_flag():
|
||||
"""_force_local_namespace private attr routes any query locally."""
|
||||
q = Query(vector=[1.0, 0.0, 0.0, 0.0])
|
||||
assert not _requires_local_namespace_execution(q)
|
||||
q._force_local_namespace = True
|
||||
assert _requires_local_namespace_execution(q)
|
||||
|
||||
|
||||
def test_hybrid_wand_vector_leg_compatible_routing(fts_table):
|
||||
"""When a hybrid query has wand_factor=1.0, both legs must follow
|
||||
pushdown-compatible routing without forcing local execution, while
|
||||
preserving wand_factor on the builder and query."""
|
||||
builder = (
|
||||
fts_table.search(query_type="hybrid")
|
||||
.vector([0.1, 0.2, 0.3, 0.4])
|
||||
.text("machine learning")
|
||||
.wand_factor(1.0)
|
||||
)
|
||||
assert isinstance(builder, LanceHybridQueryBuilder)
|
||||
assert builder._wand_factor == pytest.approx(1.0)
|
||||
builder._create_query_builders()
|
||||
|
||||
fts_q_obj = builder._fts_query.to_query_object()
|
||||
assert fts_q_obj.full_text_query.wand_factor == pytest.approx(1.0)
|
||||
assert not _requires_local_namespace_execution(fts_q_obj)
|
||||
|
||||
vec_q_obj = builder._vector_query.to_query_object()
|
||||
assert vec_q_obj._force_local_namespace is False
|
||||
assert not _requires_local_namespace_execution(vec_q_obj)
|
||||
|
||||
|
||||
def test_hybrid_no_wand_vector_leg_not_forced_local(fts_table):
|
||||
"""Without wand_factor the vector sub-query must NOT carry the local flag."""
|
||||
builder = (
|
||||
fts_table.search(query_type="hybrid")
|
||||
.vector([0.1, 0.2, 0.3, 0.4])
|
||||
.text("machine learning")
|
||||
)
|
||||
builder._create_query_builders()
|
||||
|
||||
vec_q_obj = builder._vector_query.to_query_object()
|
||||
assert vec_q_obj._force_local_namespace is False
|
||||
assert not _requires_local_namespace_execution(vec_q_obj)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_wand_vector_leg_compatible_routing(tmp_path):
|
||||
"""Async: when a hybrid query has wand_factor=1.0, both legs follow
|
||||
pushdown-compatible routing without forcing local execution."""
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace_async("dir", properties)
|
||||
tbl = await db.create_table(
|
||||
"async_leg_test",
|
||||
data=pa.table(
|
||||
{
|
||||
"id": [1],
|
||||
"vector": [[1.0, 0.0, 0.0, 0.0]],
|
||||
"text": ["hello world"],
|
||||
}
|
||||
),
|
||||
)
|
||||
await tbl.create_index("text", config=lancedb.index.FTS())
|
||||
await tbl.create_index("vector")
|
||||
|
||||
q_wand = (
|
||||
tbl.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("hello")
|
||||
.wand_factor(1.0)
|
||||
)
|
||||
_, vec_child, _, _ = await q_wand._create_child_queries()
|
||||
assert vec_child._force_local_namespace is False
|
||||
assert q_wand.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
q_default = (
|
||||
tbl.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("hello")
|
||||
)
|
||||
_, vec_child_default, _, _ = await q_default._create_child_queries()
|
||||
assert vec_child_default._force_local_namespace is False
|
||||
assert q_default.get_wand_factor() is None
|
||||
|
||||
|
||||
def test_namespace_hybrid_deleted_row_snapshot_consistency(tmp_path):
|
||||
"""Integration test: deleting a row on a namespace table with QueryTable
|
||||
pushdown must return identical results for hybrid queries with or without
|
||||
wand_factor(1.0), both legs follow equivalent routing, and neither query
|
||||
returns the deleted row."""
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
properties,
|
||||
read_consistency_interval=timedelta(0),
|
||||
namespace_client_pushdown_operations=["QueryTable"],
|
||||
)
|
||||
data = pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"text": ["apple fruit", "banana fruit", "apple pie"],
|
||||
"vector": [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.5, 0.5, 0.0, 0.0],
|
||||
],
|
||||
}
|
||||
)
|
||||
tbl1 = db.create_table("ns_hybrid_tbl", data=data)
|
||||
tbl1.create_index("text", config=lancedb.index.FTS())
|
||||
tbl1.create_index("vector")
|
||||
|
||||
tbl2 = db.open_table("ns_hybrid_tbl")
|
||||
tbl2.delete("id = 1")
|
||||
|
||||
builder_default = (
|
||||
tbl1.search(query_type="hybrid")
|
||||
.vector([1.0, 0.0, 0.0, 0.0])
|
||||
.text("apple")
|
||||
.limit(10)
|
||||
)
|
||||
builder_default._create_query_builders()
|
||||
vec_def = builder_default._vector_query.to_query_object()
|
||||
fts_def = builder_default._fts_query.to_query_object()
|
||||
assert not _requires_local_namespace_execution(vec_def)
|
||||
assert not _requires_local_namespace_execution(fts_def)
|
||||
|
||||
res_default = builder_default.to_list()
|
||||
ids_default = [r["id"] for r in res_default]
|
||||
|
||||
builder_wand = (
|
||||
tbl1.search(query_type="hybrid")
|
||||
.vector([1.0, 0.0, 0.0, 0.0])
|
||||
.text("apple")
|
||||
.wand_factor(1.0)
|
||||
.limit(10)
|
||||
)
|
||||
assert builder_wand._wand_factor == pytest.approx(1.0)
|
||||
builder_wand._create_query_builders()
|
||||
vec_wand = builder_wand._vector_query.to_query_object()
|
||||
fts_wand = builder_wand._fts_query.to_query_object()
|
||||
assert not _requires_local_namespace_execution(vec_wand)
|
||||
assert not _requires_local_namespace_execution(fts_wand)
|
||||
|
||||
res_wand = builder_wand.to_list()
|
||||
ids_wand = [r["id"] for r in res_wand]
|
||||
|
||||
assert builder_wand._wand_factor == pytest.approx(1.0)
|
||||
assert 1 not in ids_default, "Deleted row returned in default hybrid query"
|
||||
assert 1 not in ids_wand, "Deleted row returned in wand_factor(1.0) hybrid query"
|
||||
assert ids_default == ids_wand, (
|
||||
f"Hybrid results diverged: default={ids_default}, wand={ids_wand}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_namespace_hybrid_deleted_row_snapshot_consistency(tmp_path):
|
||||
"""Async integration test: deleting a row on a namespace table with
|
||||
QueryTable pushdown must return identical results for hybrid queries with
|
||||
or without wand_factor(1.0), both legs follow equivalent routing, and
|
||||
neither query returns the deleted row."""
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace_async(
|
||||
"dir",
|
||||
properties,
|
||||
read_consistency_interval=timedelta(0),
|
||||
namespace_client_pushdown_operations=["QueryTable"],
|
||||
)
|
||||
data = pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"text": ["apple fruit", "banana fruit", "apple pie"],
|
||||
"vector": [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.5, 0.5, 0.0, 0.0],
|
||||
],
|
||||
}
|
||||
)
|
||||
tbl1 = await db.create_table("async_ns_hybrid_tbl", data=data)
|
||||
assert "QueryTable" in tbl1._pushdown_operations
|
||||
await tbl1.create_index("text", config=lancedb.index.FTS())
|
||||
await tbl1.create_index("vector")
|
||||
|
||||
tbl2 = await db.open_table("async_ns_hybrid_tbl")
|
||||
await tbl2.delete("id = 1")
|
||||
|
||||
executed_queries = []
|
||||
original_execute_arrow = tbl1._execute_arrow
|
||||
|
||||
async def instrumented_execute_arrow(query, timeout=None):
|
||||
executed_queries.append(query)
|
||||
return await original_execute_arrow(query, timeout=timeout)
|
||||
|
||||
tbl1._execute_arrow = instrumented_execute_arrow
|
||||
|
||||
q_default = (
|
||||
tbl1.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("apple")
|
||||
.limit(10)
|
||||
)
|
||||
fts_def, vec_def, _, _ = await q_default._create_child_queries()
|
||||
assert vec_def._force_local_namespace is False
|
||||
assert q_default.get_wand_factor() is None
|
||||
|
||||
res_default = (await q_default.to_arrow()).to_pydict()["id"]
|
||||
calls_default = len(executed_queries)
|
||||
assert calls_default == 0
|
||||
|
||||
q_wand = (
|
||||
tbl1.query()
|
||||
.nearest_to(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
|
||||
.nearest_to_text("apple")
|
||||
.wand_factor(1.0)
|
||||
.limit(10)
|
||||
)
|
||||
fts_wand, vec_wand, _, _ = await q_wand._create_child_queries()
|
||||
assert vec_wand._force_local_namespace is False
|
||||
assert q_wand.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
res_wand = (await q_wand.to_arrow()).to_pydict()["id"]
|
||||
calls_wand = len(executed_queries) - calls_default
|
||||
assert calls_wand == 0
|
||||
assert q_wand.get_wand_factor() == pytest.approx(1.0)
|
||||
assert 1 not in res_default, "Deleted row returned in async default hybrid query"
|
||||
assert 1 not in res_wand, (
|
||||
"Deleted row returned in async wand_factor(1.0) hybrid query"
|
||||
)
|
||||
assert res_default == res_wand, (
|
||||
f"Async hybrid results diverged: default={res_default}, wand={res_wand}"
|
||||
)
|
||||
|
||||
|
||||
def test_sync_query_to_async_preserves_force_local_namespace(fts_table):
|
||||
"""_sync_query_to_async preserves _force_local_namespace flag."""
|
||||
q = Query(vector=[1.0, 0.0, 0.0, 0.0])
|
||||
q._force_local_namespace = True
|
||||
async_q = fts_table._table._sync_query_to_async(q)
|
||||
assert async_q._force_local_namespace is True
|
||||
|
||||
|
||||
def test_fts_wand_factor_preserved_after_execution(fts_table):
|
||||
"""Sync FTS query preserves wand_factor=1.0 on builder after execution."""
|
||||
builder = fts_table.search("machine learning", query_type="fts").wand_factor(1.0)
|
||||
assert builder._wand_factor == pytest.approx(1.0)
|
||||
results = builder.limit(5).to_list()
|
||||
assert len(results) > 0
|
||||
assert builder._wand_factor == pytest.approx(1.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fts_wand_factor_preserved_after_execution(async_fts_table):
|
||||
"""Async FTS query preserves wand_factor=1.0 on query after execution."""
|
||||
q = async_fts_table.query().nearest_to_text("machine learning").wand_factor(1.0)
|
||||
assert q.get_wand_factor() == pytest.approx(1.0)
|
||||
results = await q.limit(5).to_arrow()
|
||||
assert results.num_rows > 0
|
||||
assert q.get_wand_factor() == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_regression_fts_basic(fts_table):
|
||||
"""Basic FTS query without wand_factor must still work correctly."""
|
||||
results = fts_table.search("deep learning", query_type="fts").limit(5).to_list()
|
||||
assert len(results) > 0
|
||||
texts = [r["text"] for r in results]
|
||||
assert any("deep" in t or "learning" in t for t in texts)
|
||||
|
||||
|
||||
def test_regression_fts_query_object_unchanged(fts_table):
|
||||
"""to_query_object() must not break existing code path (no wand_factor)."""
|
||||
builder = LanceFtsQueryBuilder(fts_table, "python")
|
||||
q = builder.to_query_object()
|
||||
assert q.full_text_query is not None
|
||||
assert q.full_text_query.columns is None
|
||||
assert q.full_text_query.wand_factor is None
|
||||
|
||||
|
||||
def test_regression_fulltext_search_query_fields():
|
||||
"""FullTextSearchQuery must still accept and expose existing fields."""
|
||||
q = FullTextSearchQuery(query="hello", columns=["text"])
|
||||
assert q.query == "hello"
|
||||
assert q.columns == ["text"]
|
||||
assert q.wand_factor is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[-1.0, float("nan"), float("inf"), float("-inf")],
|
||||
)
|
||||
def test_pyo3_fts_wand_factor_validation_non_finite(fts_table, value):
|
||||
sync_q = LanceFtsQueryBuilder(fts_table, "machine learning").to_query_object()
|
||||
async_q = fts_table._table._sync_query_to_async(sync_q)
|
||||
|
||||
with pytest.raises(ValueError, match="finite and non-negative"):
|
||||
async_q._inner.wand_factor(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[0.0, 0.8, 1.5, 2.0],
|
||||
)
|
||||
def test_pyo3_fts_wand_factor_validation_unsupported(fts_table, value):
|
||||
"""PyO3 direct setter must reject unsupported non-default factors."""
|
||||
sync_q = LanceFtsQueryBuilder(fts_table, "machine learning").to_query_object()
|
||||
async_q = fts_table._table._sync_query_to_async(sync_q)
|
||||
|
||||
with pytest.raises(ValueError, match="must be None or 1.0"):
|
||||
async_q._inner.wand_factor(value)
|
||||
|
||||
|
||||
def test_fulltext_search_query_validate_assignment():
|
||||
"""validate_assignment=True must enforce wand_factor constraints on mutation."""
|
||||
q = FullTextSearchQuery(query="test", wand_factor=1.0)
|
||||
assert q.wand_factor == 1.0
|
||||
|
||||
q.wand_factor = None
|
||||
assert q.wand_factor is None
|
||||
|
||||
q.wand_factor = 1.0
|
||||
assert q.wand_factor == 1.0
|
||||
|
||||
with pytest.raises(ValueError, match="wand_factor must be None or 1.0"):
|
||||
q.wand_factor = 1.5
|
||||
|
||||
with pytest.raises(ValueError, match="wand_factor must be None or 1.0"):
|
||||
q.wand_factor = 0.8
|
||||
|
||||
with pytest.raises(ValueError, match="wand_factor must be finite and non-negative"):
|
||||
q.wand_factor = -1.0
|
||||
|
||||
|
||||
def test_fts_count_rows_preserves_wand_factor_sync(fts_table):
|
||||
"""An FTS query configured with wand_factor(1.0) must retain that value
|
||||
|
||||
on the original query after count_rows() is called, and count results must
|
||||
be unaffected by limit and offset.
|
||||
"""
|
||||
builder = (
|
||||
fts_table.search("machine learning", query_type="fts")
|
||||
.wand_factor(1.0)
|
||||
.limit(1)
|
||||
.offset(1)
|
||||
)
|
||||
assert builder._wand_factor == 1.0
|
||||
query_obj_before = builder.to_query_object()
|
||||
assert query_obj_before.full_text_query.wand_factor == 1.0
|
||||
|
||||
count = builder.count_rows()
|
||||
assert count == 2
|
||||
|
||||
assert builder._wand_factor == 1.0
|
||||
query_obj_after = builder.to_query_object()
|
||||
assert query_obj_after.full_text_query.wand_factor == 1.0
|
||||
|
||||
results = builder.to_list()
|
||||
assert len(results) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_count_rows_preserves_wand_factor_async(async_fts_table):
|
||||
"""Async FTS query configured with wand_factor(1.0) must retain that value
|
||||
|
||||
on the original query and PyO3 inner handle after count_rows() is called.
|
||||
"""
|
||||
query = await async_fts_table.search("machine learning", query_type="fts")
|
||||
query.wand_factor(1.0).limit(1).offset(1)
|
||||
|
||||
assert query.get_wand_factor() == 1.0
|
||||
assert query._inner.get_wand_factor() == 1.0
|
||||
|
||||
count = await query.count_rows()
|
||||
assert count == 2
|
||||
|
||||
assert query.get_wand_factor() == 1.0
|
||||
assert query._inner.get_wand_factor() == 1.0
|
||||
|
||||
results = await query.to_list()
|
||||
assert len(results) == 1
|
||||
|
||||
direct = (
|
||||
async_fts_table.query()
|
||||
.nearest_to_text("machine learning")
|
||||
.wand_factor(1.0)
|
||||
.limit(1)
|
||||
.offset(1)
|
||||
)
|
||||
assert direct.get_wand_factor() == 1.0
|
||||
assert direct._inner.get_wand_factor() == 1.0
|
||||
|
||||
direct_count = await direct.count_rows()
|
||||
assert direct_count == 2
|
||||
assert direct.get_wand_factor() == 1.0
|
||||
assert direct._inner.get_wand_factor() == 1.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_count_rows_internal_count_uses_wand_factor_none(
|
||||
fts_table, async_fts_table
|
||||
):
|
||||
"""The internal count query must use wand_factor=None independently of
|
||||
|
||||
the original retrieval query, returning identical exact counts whether
|
||||
wand_factor is None or explicitly set to 1.0.
|
||||
"""
|
||||
sync_default = fts_table.search("machine learning", query_type="fts")
|
||||
sync_wand = fts_table.search("machine learning", query_type="fts").wand_factor(1.0)
|
||||
|
||||
count_default = sync_default.count_rows()
|
||||
count_wand = sync_wand.count_rows()
|
||||
assert count_default == 2
|
||||
assert count_wand == count_default
|
||||
|
||||
sync_q = sync_wand.to_query_object()
|
||||
async_q = fts_table._table._sync_query_to_async(sync_q)
|
||||
assert async_q._inner.get_wand_factor() == 1.0
|
||||
inner_count = await async_q._inner.count_rows()
|
||||
assert inner_count == 2
|
||||
assert async_q._inner.get_wand_factor() == 1.0
|
||||
|
||||
async_default = await async_fts_table.search("machine learning", query_type="fts")
|
||||
async_wand = await async_fts_table.search("machine learning", query_type="fts")
|
||||
async_wand.wand_factor(1.0)
|
||||
|
||||
assert await async_default.count_rows() == 2
|
||||
assert await async_wand.count_rows() == 2
|
||||
|
||||
|
||||
def test_fts_count_rows_unaffected_by_limit_and_offset(fts_table):
|
||||
"""Count results must be unaffected by the original query's limit and offset;
|
||||
|
||||
counting must cover all matching rows.
|
||||
"""
|
||||
base_builder = fts_table.search("rocks", query_type="fts")
|
||||
total_matching = base_builder.count_rows()
|
||||
assert total_matching == 2
|
||||
|
||||
combinations = [
|
||||
{"limit": 0},
|
||||
{"limit": 1},
|
||||
{"offset": 1},
|
||||
{"limit": 1, "offset": 1},
|
||||
{"limit": 1, "offset": 10},
|
||||
]
|
||||
|
||||
for params in combinations:
|
||||
b = fts_table.search("rocks", query_type="fts")
|
||||
if "limit" in params:
|
||||
b.limit(params["limit"])
|
||||
if "offset" in params:
|
||||
b.offset(params["offset"])
|
||||
assert b.count_rows() == total_matching
|
||||
|
||||
b_wand = fts_table.search("rocks", query_type="fts").wand_factor(1.0)
|
||||
if "limit" in params:
|
||||
b_wand.limit(params["limit"])
|
||||
if "offset" in params:
|
||||
b_wand.offset(params["offset"])
|
||||
assert b_wand.count_rows() == total_matching
|
||||
|
||||
filtered = (
|
||||
fts_table.search("rocks", query_type="fts")
|
||||
.wand_factor(1.0)
|
||||
.where("id = 2")
|
||||
.limit(1)
|
||||
.offset(5)
|
||||
)
|
||||
assert filtered.count_rows() == 1
|
||||
|
||||
absent = (
|
||||
fts_table.search("nonexistent_term_xyz", query_type="fts")
|
||||
.wand_factor(1.0)
|
||||
.limit(1)
|
||||
)
|
||||
assert absent.count_rows() == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_count_rows_ordinary_query_exact_count(fts_table, async_fts_table):
|
||||
"""Existing exact-count behavior remains correct for ordinary FTS queries
|
||||
|
||||
without an explicit WAND factor across sync and async APIs.
|
||||
"""
|
||||
sync_q = fts_table.search("rocks", query_type="fts")
|
||||
assert sync_q._wand_factor is None
|
||||
assert sync_q.to_query_object().full_text_query.wand_factor is None
|
||||
assert sync_q.count_rows() == 2
|
||||
|
||||
sync_q.limit(1).offset(1).where("id >= 2")
|
||||
before_obj = sync_q.to_query_object()
|
||||
assert sync_q.count_rows() == 2
|
||||
assert sync_q.to_query_object() == before_obj
|
||||
assert len(sync_q.to_list()) == 1
|
||||
|
||||
async_q = await async_fts_table.search("rocks", query_type="fts")
|
||||
assert async_q.get_wand_factor() is None
|
||||
assert async_q._inner.get_wand_factor() is None
|
||||
assert await async_q.count_rows() == 2
|
||||
|
||||
async_q.limit(1).offset(1).where("id >= 2")
|
||||
assert await async_q.count_rows() == 2
|
||||
assert len(await async_q.to_list()) == 1
|
||||
+102
-12
@@ -67,6 +67,23 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult<QueryExec
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn validate_wand_factor(wand_factor: Option<f32>) -> PyResult<Option<f32>> {
|
||||
if let Some(value) = wand_factor {
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(PyValueError::new_err(
|
||||
"wand_factor must be finite and non-negative",
|
||||
));
|
||||
}
|
||||
if value != 1.0 {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"wand_factor must be None or 1.0 (got {value}); non-default factors are currently unsupported",
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(wand_factor)
|
||||
}
|
||||
|
||||
fn execute_to_reader_sync<Q>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
@@ -390,6 +407,7 @@ pub struct PyQueryRequest {
|
||||
pub preserve_order: Option<bool>,
|
||||
pub filter: Option<PyQueryFilter>,
|
||||
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
|
||||
pub wand_factor: Option<f32>,
|
||||
pub select: PySelect,
|
||||
pub select_source_columns: Option<HashMap<String, String>>,
|
||||
pub fast_search: Option<bool>,
|
||||
@@ -426,7 +444,12 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
filter: query_request.filter.map(PyQueryFilter),
|
||||
full_text_search: query_request
|
||||
.full_text_search
|
||||
.map(|fts| PyLanceDB(fts.query)),
|
||||
.as_ref()
|
||||
.map(|fts| PyLanceDB(fts.query.clone())),
|
||||
wand_factor: query_request
|
||||
.full_text_search
|
||||
.as_ref()
|
||||
.and_then(|fts| fts.wand_factor),
|
||||
select_source_columns: PySelect::source_columns(&query_request.select),
|
||||
select: PySelect(query_request.select),
|
||||
fast_search: Some(query_request.fast_search),
|
||||
@@ -459,7 +482,16 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
take_row_ids: vector_query.base.take_row_ids,
|
||||
preserve_order: vector_query.base.preserve_order.then_some(true),
|
||||
filter: vector_query.base.filter.map(PyQueryFilter),
|
||||
full_text_search: None,
|
||||
full_text_search: vector_query
|
||||
.base
|
||||
.full_text_search
|
||||
.as_ref()
|
||||
.map(|fts| PyLanceDB(fts.query.clone())),
|
||||
wand_factor: vector_query
|
||||
.base
|
||||
.full_text_search
|
||||
.as_ref()
|
||||
.and_then(|fts| fts.wand_factor),
|
||||
select_source_columns: PySelect::source_columns(&vector_query.base.select),
|
||||
select: PySelect(vector_query.base.select),
|
||||
fast_search: Some(vector_query.base.fast_search),
|
||||
@@ -637,7 +669,12 @@ impl Query {
|
||||
"Query text is required for nearest_to_text",
|
||||
))?;
|
||||
|
||||
let query = if let Ok(query_text) = fts_query.cast::<PyString>() {
|
||||
let wand_factor = query
|
||||
.get_item("wand_factor")?
|
||||
.map(|wf| wf.extract::<f32>())
|
||||
.transpose()?;
|
||||
|
||||
let mut query = if let Ok(query_text) = fts_query.cast::<PyString>() {
|
||||
let mut query_text = query_text.to_string();
|
||||
let columns = query
|
||||
.get_item("columns")?
|
||||
@@ -690,6 +727,10 @@ impl Query {
|
||||
FullTextSearchQuery::new_query(query.0)
|
||||
};
|
||||
|
||||
if let Some(wf) = validate_wand_factor(wand_factor)? {
|
||||
query.wand_factor = Some(wf);
|
||||
}
|
||||
|
||||
Ok(FTSQuery {
|
||||
inner: self.inner.clone(),
|
||||
fts_query: query,
|
||||
@@ -919,6 +960,19 @@ pub struct FTSQuery {
|
||||
fts_query: FullTextSearchQuery,
|
||||
}
|
||||
|
||||
impl FTSQuery {
|
||||
fn fts_query_for_execution(&self) -> FullTextSearchQuery {
|
||||
let mut fts_query = self.fts_query.clone();
|
||||
// Normalize the default WAND factor for execution so explicit 1.0
|
||||
// follows the same execution path as None, without mutating the
|
||||
// original query configuration.
|
||||
if fts_query.wand_factor == Some(1.0) {
|
||||
fts_query.wand_factor = None;
|
||||
}
|
||||
fts_query
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl FTSQuery {
|
||||
pub fn r#where(&mut self, predicate: String) {
|
||||
@@ -992,7 +1046,7 @@ impl FTSQuery {
|
||||
let inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
.full_text_search(self_.fts_query_for_execution());
|
||||
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut opts = QueryExecutionOptions::default();
|
||||
@@ -1023,7 +1077,7 @@ impl FTSQuery {
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
.full_text_search(self_.fts_query_for_execution()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
@@ -1040,17 +1094,17 @@ impl FTSQuery {
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
.full_text_search(self_.fts_query_for_execution()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
let mut fts_query = self_.fts_query.clone();
|
||||
fts_query.wand_factor = None;
|
||||
|
||||
let mut inner = self_.inner.clone().full_text_search(fts_query);
|
||||
let request = inner.mut_query();
|
||||
request.limit = None;
|
||||
request.offset = None;
|
||||
@@ -1080,7 +1134,7 @@ impl FTSQuery {
|
||||
let inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
.full_text_search(self_.fts_query_for_execution());
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.explain_plan(verbose)
|
||||
@@ -1097,7 +1151,7 @@ impl FTSQuery {
|
||||
let inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
.full_text_search(self_.fts_query_for_execution());
|
||||
let options = analyze_plan_options(distributed_metrics.as_deref())?;
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
@@ -1111,6 +1165,15 @@ impl FTSQuery {
|
||||
self.fts_query.query.query().clone()
|
||||
}
|
||||
|
||||
pub fn wand_factor(&mut self, wand_factor: Option<f32>) -> PyResult<()> {
|
||||
self.fts_query.wand_factor = validate_wand_factor(wand_factor)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_wand_factor(&self) -> Option<f32> {
|
||||
self.fts_query.wand_factor
|
||||
}
|
||||
|
||||
pub fn to_query_request(&self) -> PyQueryRequest {
|
||||
let mut req = self.inner.clone().into_request();
|
||||
req.full_text_search = Some(self.fts_query.clone());
|
||||
@@ -1490,6 +1553,16 @@ impl HybridQuery {
|
||||
self.inner_fts.inner.current_request().with_row_id
|
||||
}
|
||||
|
||||
pub fn wand_factor(&mut self, wand_factor: Option<f32>) -> PyResult<()> {
|
||||
let validated = validate_wand_factor(wand_factor)?;
|
||||
self.inner_fts.wand_factor(validated)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_wand_factor(&self) -> Option<f32> {
|
||||
self.inner_fts.get_wand_factor()
|
||||
}
|
||||
|
||||
pub fn to_query_request(&self) -> PyQueryRequest {
|
||||
let mut req = self.inner_fts.to_query_request();
|
||||
let vec_req = self.inner_vec.to_query_request();
|
||||
@@ -1537,3 +1610,20 @@ pub fn fts_query_to_json(query_obj: &Bound<'_, PyAny>) -> PyResult<String> {
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_count_rows_cloned_fts_query_clears_wand_factor() {
|
||||
let mut original_fts_query = FullTextSearchQuery::new("machine learning".to_string());
|
||||
original_fts_query.wand_factor = Some(0.8);
|
||||
|
||||
let mut count_fts_query = original_fts_query.clone();
|
||||
count_fts_query.wand_factor = None;
|
||||
|
||||
assert_eq!(original_fts_query.wand_factor, Some(0.8));
|
||||
assert_eq!(count_fts_query.wand_factor, None);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user