feat: support IN subqueries in Embedded search filters (#5223)

Fixes #5222

## Summary

Embedded vector and full-text searches rejected `IN (SELECT ...)`
because Lance's scanner parsed the filter as a single-table expression.
A team-scoped search with `limit(1)` needs to rank eligible documents
using keys from the sharing table.

Resolve unqualified lookup tables through the originating database and
use DataFusion to evaluate the predicate on the search snapshot. Pass
the matching row IDs to Lance before ranking. The syntax applies to
base-table prefilters within one namespace. Literal filters use the
existing scanner path.

## Tests

Tests: `/bin/sh -c 'cd nodejs && corepack pnpm test --runInBand
__test__/query.test.ts -t '"'"'prefilters by keys from another
table'"'"''`.
Result: cd nodejs && corepack pnpm test --runInBand
__test__/query.test.ts on the exact-HEAD published native binary before
adding tests: 41 passed.
Result: cd nodejs && corepack pnpm test --runInBand
__test__/query.test.ts -t 'prefilters by keys from another table' on the
exact-HEAD published native binary: 2 failed with the reported
unsupported SQL expression, exit 1 (OSSCOUT_BASE.log).
Result: cd nodejs && corepack pnpm lint: passed after correcting new
fixture key style.
Result: cargo fmt --all && git diff --check: passed.
Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath
__test__/expr.test.ts __test__/remote.test.ts on the exact-HEAD
published native binary: 179 passed across 2 suites.
Result: cd nodejs && corepack pnpm tsc && corepack pnpm run docs with
the exact-HEAD native declarations: passed, with no generated
documentation changes.
Result: cd nodejs && corepack pnpm build:debug --profile ci && corepack
pnpm tsc: passed from the patched source.
Result: cd nodejs && corepack pnpm test --runInBand
__test__/query.test.ts -t 'prefilters by keys from another table' on the
source-built patch: 2 passed, exit 0 (OSSCOUT_PATCHED.log).
Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath
__test__/query.test.ts __test__/expr.test.ts __test__/remote.test.ts on
the source-built patch: 225 passed across 3 suites, exit 0
(OSSCOUT_PATCHED.log).
Result: cd nodejs && corepack pnpm run docs on the source-built patch:
passed, with no generated documentation changes.
Regression coverage: `nodejs/__test__/query.test.ts`.
<!-- oss-scout-job:job-2628acdb-66f3-4d91-8a6e-d5d15e92bde7 -->

---------

Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
This commit is contained in:
wangshun
2026-11-30 20:38:51 +08:00
committed by GitHub
parent 5db0513dd0
commit 04bf27af9d
14 changed files with 1464 additions and 18 deletions
+4
View File
@@ -46,6 +46,10 @@ _experimental_functions_enabled: bool
def _doc_url(campaign: str) -> str: ...
def _append_doc_url(message: str, campaign: str) -> str: ...
def _uses_sql_subquery_filter(sql: str) -> bool: ...
async def _share_hybrid_subquery_filter(
fts: FTSQuery, vector: VectorQuery
) -> tuple[FTSQuery, VectorQuery]: ...
def _parse_field_path(path: str) -> List[str]: ...
IvfHnswPq: type[HnswPq] = HnswPq
+46 -10
View File
@@ -32,7 +32,11 @@ import pydantic
from pydantic_core import PydanticUndefined
from typing_extensions import Annotated
from lancedb._lancedb import fts_query_to_json
from lancedb._lancedb import (
_share_hybrid_subquery_filter,
_uses_sql_subquery_filter,
fts_query_to_json,
)
from lancedb.background_loop import LOOP
from . import __version__
from .arrow import AsyncRecordBatchReader
@@ -3392,11 +3396,26 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
if self._pk_fusion is None:
fts_query = fts_query.with_row_id(True)
vector_query = vector_query.with_row_id(True)
with ThreadPoolExecutor() as executor:
fts_future = executor.submit(fts_query.to_arrow, timeout=timeout)
vector_future = executor.submit(vector_query.to_arrow, timeout=timeout)
fts_results = fts_future.result()
vector_results = vector_future.result()
if (
isinstance(self._where, str)
and _uses_sql_subquery_filter(self._where)
and not _is_remote_query_table(self._table)
):
# Keep the existing Python reranker, but prepare the two native
# legs together so they use the same snapshot and eligibility mask.
self._table._ensure_no_legacy_fts_index()
async_table = self._table._table
fts = async_table._sync_query_to_async(fts_query.to_query_object())
vec = async_table._sync_query_to_async(vector_query.to_query_object())
fts_results, vector_results = LOOP.run(
_execute_hybrid_subquery_legs(fts, vec, timeout)
)
else:
with ThreadPoolExecutor() as executor:
fts_future = executor.submit(fts_query.to_arrow, timeout=timeout)
vector_future = executor.submit(vector_query.to_arrow, timeout=timeout)
fts_results = fts_future.result()
vector_results = vector_future.result()
if self._pk_fusion is not None: # WAL-PK-FUSION: delete.
vector_results, fts_results = self._pk_fusion.stamp(
vector_results, fts_results
@@ -5738,6 +5757,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
async def _execute_hybrid_subquery_legs(
fts: AsyncFTSQuery, vector: AsyncVectorQuery, timeout: Optional[timedelta]
) -> tuple[pa.Table, pa.Table]:
fts._inner, vector._inner = await _share_hybrid_subquery_filter(
fts._inner, vector._inner
)
fts_results, vector_results = await asyncio.gather(
fts.to_arrow(timeout=timeout), vector.to_arrow(timeout=timeout)
)
return fts_results, vector_results
class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
"""
A query builder that performs hybrid vector and full text search.
@@ -5908,10 +5939,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
self._blob_auto_row_id = blob_auto_row_id
self._blob_paths = blob_paths
fts_results, vector_results = await asyncio.gather(
fts_query.to_arrow(timeout=timeout),
vec_query.to_arrow(timeout=timeout),
)
if isinstance(req.filter, str) and _uses_sql_subquery_filter(req.filter):
fts_results, vector_results = await _execute_hybrid_subquery_legs(
fts_query, vec_query, timeout
)
else:
fts_results, vector_results = await asyncio.gather(
fts_query.to_arrow(timeout=timeout),
vec_query.to_arrow(timeout=timeout),
)
if self._pk_fusion is not None: # WAL-PK-FUSION: delete.
vector_results, fts_results = self._pk_fusion.stamp(
vector_results, fts_results
+3 -2
View File
@@ -35,7 +35,7 @@ from urllib.parse import urlparse
from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
from . import __version__
from ._lancedb import FunctionColumnStatus, _parse_field_path
from ._lancedb import FunctionColumnStatus, _parse_field_path, _uses_sql_subquery_filter
from ._blob import (
BlobFile,
_normalize_blob_descriptor,
@@ -145,7 +145,8 @@ def _should_push_down_query_table(
def _requires_local_namespace_execution(query: Query) -> bool:
# The namespace QueryTable request does not support these query options.
return (
query.take_offsets is not None
(isinstance(query.filter, str) and _uses_sql_subquery_filter(query.filter))
or query.take_offsets is not None
or query.take_row_ids is not None
or query.search_effort is not None
or query.approx_mode is not None
+116
View File
@@ -2067,3 +2067,119 @@ def test_namespace_fts_count_fast_search(tmp_path):
query = pushed.search("gripper", query_type="fts").fast_search()
assert query.count_rows() == 15
assert len(query.limit(100).to_list()) == 15
@pytest.fixture
def subquery_namespace(tmp_path):
properties = {"root": str(tmp_path)}
db = lancedb.connect_namespace("dir", properties)
path = ["team"]
db.create_namespace(path)
schema = pa.schema(
[
("id", pa.int32()),
("text", pa.string()),
("vector", pa.list_(pa.float32(), 2)),
]
)
table = db.create_table(
"chunks",
[
{"id": 1, "text": "alpha alpha", "vector": [0.0, 0.0]},
{"id": 2, "text": "alpha", "vector": [1.0, 1.0]},
],
schema=schema,
namespace_path=path,
)
table.create_index("text", config=FTS())
db.create_table("acl", [{"id": 1}])
db.create_table("acl", [{"id": 2}], namespace_path=path)
return properties, path
@pytest.mark.parametrize("python_dispatch", [False, True])
def test_subquery_filter_query_table_pushdown(subquery_namespace, python_dispatch):
properties, path = subquery_namespace
filter_sql = "id IN (SELECT id FROM acl)"
for enabled in (False, True):
db = lancedb.connect_namespace(
"dir",
properties,
namespace_client_pushdown_operations=["QueryTable"] if enabled else [],
)
table = db.open_table("chunks", namespace_path=path)
client = _NamespaceClient()
if python_dispatch:
table._route_pushdown_to_rust = False
table._namespace_client = client
table._table._route_pushdown_to_rust = False
table._table._namespace_client = client
query = table.search([0.0, 0.0]).where(filter_sql).limit(1)
assert query.to_arrow()["id"].to_pylist() == [2]
assert query.to_batches().read_all()["id"].to_pylist() == [2]
assert table.search("alpha", query_type="fts").where(filter_sql).limit(
1
).to_arrow()["id"].to_pylist() == [2]
assert client.requests == []
def test_hybrid_subquery_filter_sync(subquery_namespace):
properties, path = subquery_namespace
table = lancedb.connect_namespace("dir", properties).open_table(
"chunks", namespace_path=path
)
result = (
table.search(query_type="hybrid")
.vector([0.0, 0.0])
.text("alpha")
.where("id IN (SELECT id FROM acl)")
.limit(1)
.to_arrow()
)
assert result["id"].to_pylist() == [2]
@pytest.mark.asyncio
async def test_hybrid_subquery_filter_async(subquery_namespace):
properties, path = subquery_namespace
db = lancedb.connect_namespace_async("dir", properties)
table = await db.open_table("chunks", namespace_path=path)
result = await (
table.vector_search([0.0, 0.0])
.nearest_to_text("alpha")
.where("id IN (SELECT id FROM acl)")
.limit(1)
.to_arrow()
)
assert result["id"].to_pylist() == [2]
def test_subquery_filter_rejects_wrapped_nullable_membership(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table(
"chunks",
pa.table(
{
"id": [1, 2, 3],
"key": [10, 20, None],
"vector": pa.array(
[[0, 0], [1, 1], [2, 2]], type=pa.list_(pa.float32(), 2)
),
}
),
)
db.create_table("acl", pa.table({"key": [20, None]}))
membership = "key IN (SELECT key FROM acl)"
assert (
table.search([0.0, 0.0])
.where(f"(id = 2 OR id = 3) AND ({membership})")
.to_arrow()["id"]
.to_pylist()
) == [2]
for predicate in [
f"({membership}) IS NULL",
"key NOT IN (SELECT key FROM acl) OR id = 3",
]:
with pytest.raises(NotImplementedError, match="positive IN"):
table.search([0.0, 0.0]).where(predicate).to_arrow()
+7
View File
@@ -76,6 +76,11 @@ fn _append_doc_url(message: &str, campaign: &str) -> PyResult<String> {
Ok(link.append_to(message))
}
#[pyfunction]
fn _uses_sql_subquery_filter(sql: &str) -> bool {
lancedb::table::query::uses_sql_subquery_filter(sql)
}
#[pymodule]
pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
lancedb::docs::set_sdk_ident("python", env!("CARGO_PKG_VERSION"));
@@ -110,6 +115,8 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<crate::sql::QueryDescription>()?;
m.add_class::<PyBlobFile>()?;
m.add_class::<IndexConfig>()?;
m.add_function(wrap_pyfunction!(_uses_sql_subquery_filter, m)?)?;
m.add_function(wrap_pyfunction!(query::_share_hybrid_subquery_filter, m)?)?;
m.add_class::<Query>()?;
m.add_class::<FTSQuery>()?;
m.add_class::<HybridQuery>()?;
+17
View File
@@ -1509,6 +1509,23 @@ impl HybridQuery {
}
}
/// Share a fresh eligibility plan without changing Python's reranking path.
#[pyfunction]
pub fn _share_hybrid_subquery_filter(
py: Python<'_>,
mut fts: FTSQuery,
mut vector: VectorQuery,
) -> PyResult<Bound<'_, PyAny>> {
future_into_py(py, async move {
vector
.inner
.share_subquery_filter_with(&mut fts.inner)
.await
.infer_error()?;
Ok((fts, vector))
})
}
/// Convert a Python FTS query to JSON string
#[pyfunction]
pub fn fts_query_to_json(query_obj: &Bound<'_, PyAny>) -> PyResult<String> {