From 04bf27af9d44c152c9310b597935c2b7c70ee98e Mon Sep 17 00:00:00 2001
From: wangshun <96341168+xixi-box@users.noreply.github.com>
Date: Mon, 30 Nov 2026 20:38:51 +0800
Subject: [PATCH] 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`.
---------
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
---
docs/web/search/filtering.mdx | 51 +
nodejs/__test__/query.test.ts | 95 ++
python/python/lancedb/_lancedb.pyi | 4 +
python/python/lancedb/query.py | 56 +-
python/python/lancedb/table.py | 5 +-
python/python/tests/test_namespace.py | 116 +++
python/src/lib.rs | 7 +
python/src/query.rs | 17 +
rust/lancedb/src/expr.rs | 2 +-
rust/lancedb/src/expr/sql.rs | 6 +-
rust/lancedb/src/query.rs | 56 +
rust/lancedb/src/table.rs | 2 +-
rust/lancedb/src/table/query.rs | 80 +-
.../src/table/query/subquery_filter.rs | 985 ++++++++++++++++++
14 files changed, 1464 insertions(+), 18 deletions(-)
create mode 100644 rust/lancedb/src/table/query/subquery_filter.rs
diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx
index 58c974614..a1721a6ad 100644
--- a/docs/web/search/filtering.mdx
+++ b/docs/web/search/filtering.mdx
@@ -59,6 +59,57 @@ vector and full-text searches.
SDK filters use SQL expressions without requiring a SQL connection. For
Enterprise SQL queries, see [SELECT](/sql/dql/select#filtering).
+## Prefilter with keys from another table {#prefilter-with-subquery}
+
+In LanceDB Embedded, use `IN (SELECT ...)` to restrict vector or full-text
+search to keys in another table in the same namespace. Use unqualified table
+names in the subquery. LanceDB computes the matching row IDs before ranking
+candidates, so `limit(1)` returns the best eligible row. When namespace query
+pushdown is enabled, this filter requires the client to have access to the
+table storage.
+
+Use a positive `IN (SELECT ...)` predicate on its own or join it to other
+conditions with `AND`. `OR` is allowed in a separate condition, such as
+`(status = 'draft' OR status = 'published') AND document_id IN (SELECT document_id FROM team_documents)`.
+A membership subquery wrapped in `OR`, `NOT`, or `IS NULL`, a `NOT IN (SELECT ...)`
+predicate, or a nested membership subquery returns an error. Literal `IN`
+and `NOT IN` lists keep their usual behavior.
+
+
+```python Python icon="python"
+matches = (
+ chunks.search(query_vector)
+ .where(
+ "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')"
+ )
+ .limit(1)
+ .to_arrow()
+)
+```
+
+```typescript TypeScript icon="square-js"
+const matches = await chunks
+ .vectorSearch(queryVector)
+ .where(
+ "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')",
+ )
+ .limit(1)
+ .toArray();
+```
+
+```rust Rust icon="rust"
+use lancedb::query::{ExecutableQuery, QueryBase};
+
+let matches = chunks
+ .query()
+ .nearest_to(query_vector)?
+ .only_if("document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')")
+ .limit(1)
+ .execute()
+ .await?;
+```
+
+
## Filtering examples by language {#example-metadata-filtering}
The following excerpts use a connected `db` handle. Create this sample table
diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts
index a911372ec..dd2424d67 100644
--- a/nodejs/__test__/query.test.ts
+++ b/nodejs/__test__/query.test.ts
@@ -15,6 +15,101 @@ import {
} from "../lancedb/arrow";
import { Index } from "../lancedb/indices";
+describe("Search subquery filters", () => {
+ const documentIdColumn = "document_id";
+ const teamIdColumn = "team_id";
+ let tmpDir: tmp.DirResult;
+ let chunks: Table;
+ let teamDocuments: Table;
+
+ beforeEach(async () => {
+ tmpDir = tmp.dirSync({ unsafeCleanup: true });
+ const db = await connect(tmpDir.name);
+ chunks = await db.createTable("chunks", [
+ { [documentIdColumn]: "AAA", text: "cat cat cat cat", vector: [0, 0] },
+ { [documentIdColumn]: "BBB", text: "cat dog dog dog", vector: [1, 1] },
+ ]);
+ await chunks.createIndex("text", { config: Index.fts() });
+ teamDocuments = await db.createTable("team_documents", [
+ { [teamIdColumn]: "Team 1", [documentIdColumn]: "BBB" },
+ { [teamIdColumn]: "Team 1", [documentIdColumn]: "BBB" },
+ { [teamIdColumn]: "Team 2", [documentIdColumn]: "AAA" },
+ ]);
+ });
+
+ afterEach(() => {
+ tmpDir.removeCallback();
+ });
+
+ it.each(["vector", "fts"])(
+ "%s search prefilters by keys from another table",
+ async (kind) => {
+ const search = () =>
+ (kind === "vector"
+ ? chunks.vectorSearch([0, 0])
+ : chunks.search("cat", "fts")
+ ).limit(1);
+ const ids = async (query: ReturnType) =>
+ (await query.toArray()).map((row) => row[documentIdColumn]);
+
+ expect(await ids(search())).toEqual(["AAA"]);
+ expect(await ids(search().where("document_id IN ('BBB')"))).toEqual([
+ "BBB",
+ ]);
+
+ const predicate = (team: string) =>
+ `document_id IN (SELECT "document_id" FROM team_documents WHERE team_id = '${team}')`;
+ expect(
+ await ids(
+ search().where("document_id IS NOT NULL").where(predicate("Team 1")),
+ ),
+ ).toEqual(["BBB"]);
+ expect(
+ await ids(
+ search().where("document_id = 'AAA'").where(predicate("Team 1")),
+ ),
+ ).toEqual([]);
+ expect(await ids(search().where(predicate("Missing team")))).toEqual([]);
+ },
+ );
+
+ it.each(["flat", "indexed"])(
+ "%s vector search reads current keys on repeated execution",
+ async (kind) => {
+ if (kind === "indexed") {
+ await chunks.createIndex("vector", {
+ config: Index.ivfFlat({ numPartitions: 1 }),
+ });
+ }
+ const query = chunks
+ .vectorSearch([0, 0])
+ .where(
+ "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')",
+ )
+ .limit(1);
+ expect(
+ (await query.toArray()).map((row) => row[documentIdColumn]),
+ ).toEqual(["BBB"]);
+ await teamDocuments.add([
+ { [teamIdColumn]: "Team 1", [documentIdColumn]: "AAA" },
+ ]);
+ expect(
+ (await query.toArray()).map((row) => row[documentIdColumn]),
+ ).toEqual(["AAA"]);
+ },
+ );
+
+ it("rejects a missing lookup table and explicit postfiltering", async () => {
+ const filter = "document_id IN (SELECT document_id FROM missing_table)";
+ await expect(
+ chunks.vectorSearch([0, 0]).where(filter).toArray(),
+ ).rejects.toThrow(/missing_table/);
+ await expect(
+ chunks.vectorSearch([0, 0]).postfilter().where(filter).toArray(),
+ ).rejects.toThrow("SQL subquery filters require prefiltering");
+ });
+});
+
describe("Query outputSchema", () => {
let tmpDir: tmp.DirResult;
let table: Table;
diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
index be19b1210..0468d9033 100644
--- a/python/python/lancedb/_lancedb.pyi
+++ b/python/python/lancedb/_lancedb.pyi
@@ -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
diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py
index 1809775c5..e2b1f475c 100644
--- a/python/python/lancedb/query.py
+++ b/python/python/lancedb/query.py
@@ -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
diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
index 299243b45..5dc627eb3 100644
--- a/python/python/lancedb/table.py
+++ b/python/python/lancedb/table.py
@@ -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
diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py
index 2c999d1b0..d04da4568 100644
--- a/python/python/tests/test_namespace.py
+++ b/python/python/tests/test_namespace.py
@@ -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()
diff --git a/python/src/lib.rs b/python/src/lib.rs
index 4680aab4c..c9f382090 100644
--- a/python/src/lib.rs
+++ b/python/src/lib.rs
@@ -76,6 +76,11 @@ fn _append_doc_url(message: &str, campaign: &str) -> PyResult {
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::()?;
m.add_class::()?;
m.add_class::()?;
+ m.add_function(wrap_pyfunction!(_uses_sql_subquery_filter, m)?)?;
+ m.add_function(wrap_pyfunction!(query::_share_hybrid_subquery_filter, m)?)?;
m.add_class::()?;
m.add_class::()?;
m.add_class::()?;
diff --git a/python/src/query.rs b/python/src/query.rs
index f14276d74..5e30546ae 100644
--- a/python/src/query.rs
+++ b/python/src/query.rs
@@ -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> {
+ 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 {
diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs
index 04d1b0e9e..1682dcab5 100644
--- a/rust/lancedb/src/expr.rs
+++ b/rust/lancedb/src/expr.rs
@@ -19,8 +19,8 @@
mod sql;
-pub(crate) use sql::canonicalize_sql_predicate;
pub use sql::expr_to_sql_string;
+pub(crate) use sql::{PredicateDialect, canonicalize_sql_predicate};
use std::sync::Arc;
diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs
index 96bb5b60c..64ed7cf23 100644
--- a/rust/lancedb/src/expr/sql.rs
+++ b/rust/lancedb/src/expr/sql.rs
@@ -55,7 +55,7 @@ impl UnparserDialect for LanceSqlDialect {
/// delegates only identifier recognition, leaving every other dialect option at
/// its default. In particular, `/*! ... */` remains an ordinary block comment.
#[derive(Debug, Default)]
-struct PredicateDialect(GenericDialect);
+pub(crate) struct PredicateDialect(GenericDialect);
impl SqlParserDialect for PredicateDialect {
fn dialect(&self) -> TypeId {
@@ -73,6 +73,10 @@ impl SqlParserDialect for PredicateDialect {
fn is_delimited_identifier_start(&self, ch: char) -> bool {
ch == '"' || ch == '`'
}
+
+ fn supports_lambda_functions(&self) -> bool {
+ true
+ }
}
/// Canonicalize a raw SQL predicate for Lance's parser.
diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs
index bc460dc35..93a026a04 100644
--- a/rust/lancedb/src/query.rs
+++ b/rust/lancedb/src/query.rs
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::collections::{HashMap, HashSet};
+use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use std::{future::Future, time::Duration};
@@ -39,6 +40,7 @@ use lance_index::scalar::FullTextSearchQuery;
use lance_index::scalar::inverted::SCORE_COL;
use lance_index::vector::DIST_COL;
+use crate::database::Database;
use crate::error::{Error, Result};
use crate::rerankers::rrf::RRFReranker;
use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result};
@@ -422,6 +424,10 @@ pub trait QueryBase {
/// Identifiers may be delimited with SQL-standard double quotes or
/// backticks. String literals must use single quotes.
///
+ /// Embedded prefilters support positive `IN (SELECT ...)` predicates
+ /// alone or combined with other conditions using `AND`. Use unqualified
+ /// table names in the same namespace inside the subquery.
+ ///
/// Filtering performance can often be improved by creating a scalar index
/// on the filter column(s).
///
@@ -613,6 +619,7 @@ impl QueryBase for T {
}
fn postfilter(mut self) -> Self {
+ self.mut_query().prepared_subquery = None;
self.mut_query().prefilter = false;
self
}
@@ -890,6 +897,12 @@ pub struct QueryRequest {
/// `Result`.
pub(crate) filter_error: Option,
+ /// Resolves tables referenced by Embedded SQL query filters.
+ pub(crate) database: Option,
+
+ /// Per-execution eligibility plan and snapshot shared by the two hybrid legs.
+ pub(crate) prepared_subquery: Option>,
+
/// Perform a full text search on the table.
pub full_text_search: Option,
@@ -948,6 +961,16 @@ pub struct QueryRequest {
pub use_rte: Option,
}
+#[derive(Clone)]
+pub(crate) struct QueryDatabase(pub(crate) Arc);
+
+impl fmt::Debug for QueryDatabase {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // Connection options may contain credentials.
+ f.debug_struct("QueryDatabase").finish_non_exhaustive()
+ }
+}
+
impl Default for QueryRequest {
fn default() -> Self {
Self {
@@ -958,6 +981,8 @@ impl Default for QueryRequest {
preserve_order: false,
filter: None,
filter_error: None,
+ database: None,
+ prepared_subquery: None,
full_text_search: None,
select: Select::All,
fast_search: false,
@@ -984,6 +1009,7 @@ impl QueryRequest {
/// use different representations) the error is recorded and surfaced later
/// by [`Self::check_filter`].
pub(crate) fn add_filter(&mut self, new: QueryFilter) {
+ self.prepared_subquery = None;
let new = match new {
QueryFilter::Sql(filter) => match crate::expr::canonicalize_sql_predicate(&filter) {
Ok(filter) => QueryFilter::Sql(filter),
@@ -1049,6 +1075,11 @@ impl Query {
}
}
+ pub(crate) fn with_database(mut self, database: Option>) -> Self {
+ self.request.database = database.map(QueryDatabase);
+ self
+ }
+
/// Helper method to convert the query to a VectorQuery with a `query_vector`
/// of None. This retrofits to some existing inner paths that work with a
/// single query object for both vector and plain queries.
@@ -1601,6 +1632,28 @@ impl VectorQuery {
self
}
+ /// Share one eligibility plan when a binding executes its hybrid legs separately.
+ #[doc(hidden)]
+ pub async fn share_subquery_filter_with(&mut self, fts_query: &mut Query) -> Result<()> {
+ let Some(table) = self.parent.as_native() else {
+ return Ok(());
+ };
+ let base = &self.request.base;
+ let fts = &fts_query.request;
+ if !Arc::ptr_eq(&self.parent, &fts_query.parent)
+ || base.use_rte != fts.use_rte
+ || base.prefilter != fts.prefilter
+ || !matches!((&base.filter, &fts.filter), (Some(QueryFilter::Sql(a)), Some(QueryFilter::Sql(b))) if a == b)
+ {
+ return Ok(());
+ }
+ fts.check_filter()?;
+ let prepared = crate::table::query::prepare_hybrid_subquery(table, base).await?;
+ fts_query.request.prepared_subquery = prepared.clone();
+ self.request.base.prepared_subquery = prepared;
+ Ok(())
+ }
+
pub async fn execute_hybrid(
&self,
options: QueryExecutionOptions,
@@ -1637,6 +1690,9 @@ impl VectorQuery {
}
vector_query.request.base.full_text_search = None;
+ vector_query
+ .share_subquery_filter_with(&mut fts_query)
+ .await?;
let (fts_results, vec_results) = try_join!(
fts_query.execute_with_options(internal_options.clone()),
vector_query.inner_execute_with_options(internal_options)
diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs
index b34d4a55b..280e9a5c4 100644
--- a/rust/lancedb/src/table.rs
+++ b/rust/lancedb/src/table.rs
@@ -2062,7 +2062,7 @@ impl Table {
/// # });
/// ```
pub fn query(&self) -> Query {
- Query::new(self.inner.clone())
+ Query::new(self.inner.clone()).with_database(self.database.clone())
}
/// Extract rows from the dataset using dataset offsets.
diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs
index f63bf50bf..8e001e220 100644
--- a/rust/lancedb/src/table/query.rs
+++ b/rust/lancedb/src/table/query.rs
@@ -7,6 +7,9 @@ use std::{
};
mod lsm;
+mod subquery_filter;
+
+pub(crate) use subquery_filter::PreparedSubquery;
use super::NativeTable;
use crate::connection::NamespaceClientPushdownOperation;
@@ -123,7 +126,8 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool {
// RTE read routing lives only in `create_plan`, so a pushed-down query would return
// stale base-only data. A dropped order_by would return the wrong top-K rows, and a
// dropped ordered scan would silently stop guaranteeing manifest order.
- if query.base().use_rte.is_some()
+ if subquery_filter::predicate(query.base().filter.as_ref()).is_some()
+ || query.base().use_rte.is_some()
|| query.base().has_take()
|| query.base().scan_in_order == Some(true)
|| query
@@ -145,6 +149,32 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool {
)
}
+/// Returns whether an Embedded SQL filter needs cross-table eligibility resolution.
+#[doc(hidden)]
+pub fn uses_sql_subquery_filter(sql: &str) -> bool {
+ subquery_filter::parse_predicate(sql).is_some()
+}
+
+pub(crate) async fn prepare_hybrid_subquery(
+ table: &NativeTable,
+ query: &QueryRequest,
+) -> Result