feat(query): stream query results with optional total hits (#5354)

## Summary

An Embedded query can stream one page of results and report how many
visible rows matched before offset and limit. This adds Rust
`execute_with_metadata`, Python sync and async `to_result`, and
TypeScript `toResult`. The existing query terminals continue to use
their existing execution paths.

Tracking defaults to Off. An exact count returns `eq(N)`. A positive cap
C returns `eq(N)` below C and `gte(C)` as soon as C matches are proven,
including equality. TypeScript exposes counts as bigint. Counts use the
same snapshot as the result batches. The accessor reports pending until
the stream reaches successful EOF. Explicit counts can add work after
the last batch, especially when full-text counting needs to scan visible
text. Closing an unfinished result cancels execution. Stream and
metadata failures retain interruption details, including the request ID.

Embedded supports scalar and row-level lexical counts. Unordered FTS
retains its existing top-k and scoring policy. Enterprise and
unsupported query shapes return a typed error when a count is requested.

## Dependency

#5352 merged Lance v16.0.0-beta.7 into main, including [Lance
#11680](https://github.com/lance-format/lance/pull/11680). This PR uses
that dependency and its lockfiles.

## Validation

The Linux-tested revision `bc39ad7ac` and rebased revision `24f4e90c2`
have the same Git tree. The only change in `6932b3082` is the Python
namespace regression fixture, which now resolves the local table without
the optional pylance package. The revised test passed on managed Linux
with CPython 3.11.18 both with pylance and pandas installed and after
removing both packages. Managed Linux runs used the unmodified manifests
and lockfiles from #5352 and the published `pylance 16.0.0b7` wheel.

- The Rust metadata suite passed 57 tests, with two existing ignores.
Coverage includes unordered FTS plans, top-k scores, physical row
addresses under pagination, pending-read cancellation, and interruption
after the last batch.
- Python query, remote and namespace suites passed 1,163 tests. One
optional slow test requires PyTorch, which was unavailable on this VM.
The Node query, remote, table and error suites passed 913 tests, with
three experimental cases skipped.
- Regression tests reproduced the failures on the previous revision and
verified the fixes. Python sync reranking and namespace FTS preserve an
explicit empty page. Python sync and async scans expose `_rowaddr`
alongside the pre-pagination count. Explicit counts are rejected before
TypeScript auto-search issues an Enterprise request or invokes a vector
embedding provider. Python and Node retain the server's 1,063-row first
batch in Off mode.
- A custom Python namespace opened through the public API receives the
same computed projection in Off mode as with `to_batches()`. A Node
result interrupted after another SDK load retains its original error
class and request ID. Both regressions were reproduced on the prior
revision.
- Workspace Clippy, formatting, Ruff, Biome, TypeScript checks, TypeDoc
and strict MkDocs passed. All 287 generated TypeDoc files matched the
committed files byte for byte.
This commit is contained in:
Yang Cen
2026-12-02 22:47:37 +08:00
committed by GitHub
parent 623777389e
commit feff86a08d
43 changed files with 3540 additions and 103 deletions
+42
View File
@@ -910,6 +910,37 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and
::: lancedb.query.Query
Use `query.to_result(track_total_hits=True)` to stream a page and read its exact
pre-pagination count after EOF. A positive integer up to `2**64 - 1` requests a
capped count. At the cap, `relation` is `"gte"`. Call `result.close()` or use a
context manager to cancel an unfinished read.
Embedded scalar queries and supported row-level lexical queries can request counts.
A requested count on an unsupported plan raises
`lancedb.exceptions.UnsupportedMetadata` before yielding batches. The rich terminal
supports `with_row_address()` on plain Embedded scans. Each returned row's
`_rowaddr` identifies its physical fragment and offset in the query snapshot.
`with_fragments()` and `fragment_ids()` raise `UnsupportedMetadata`.
Before EOF, `metadata()` raises `MetadataPending`.
An early close raises `MetadataCancelled` on subsequent access. Stream failures
retain the underlying exception, including its request ID when supplied. An
explicit count can still take time or fail after the final data batch. For
example, a full-text query may scan visible text to establish the count.
```python
with table.search().where("year >= 2020").limit(10).to_result(track_total_hits=100) as result:
for batch in result.batches:
print(batch.num_rows)
hits = result.metadata().total_hits
print(hits.relation, hits.value) # "gte", 100 if at least 100 rows match
```
::: lancedb.query_result.QueryResult
::: lancedb.query_result.QueryMetadata
::: lancedb.query_result.TotalHits
::: lancedb.query.ColumnOrdering
::: lancedb.query.LanceQueryBuilder
@@ -1469,6 +1500,17 @@ to return the entire (typically filtered) table. Vector searches return the
rows nearest to a query vector and can be created with the
[AsyncTable.vector_search][lancedb.table.AsyncTable.vector_search] method.
Use an async context manager to release an unfinished query when leaving the
loop early. Read the count after the iterator reaches EOF.
```python
async with await table.query().limit(10).to_result(track_total_hits=True) as result:
async for batch in result.batches:
print(batch.num_rows)
print(result.metadata().total_hits.value)
```
::: lancedb.query_result.AsyncQueryResult
::: lancedb.query.AsyncQuery
options: