mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
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:
@@ -0,0 +1,70 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow::pyarrow::ToPyArrow;
|
||||
use lancedb::query::metadata_reader::QueryResultReader;
|
||||
use lancedb::query::{ExecutableQuery, MetadataRequest, TrackTotalHits};
|
||||
use pyo3::{Bound, PyAny, PyResult, Python, exceptions::PyRuntimeError, pyclass, pymethods};
|
||||
|
||||
use crate::{error::PythonErrorExt, runtime::future_into_py};
|
||||
|
||||
#[pyclass]
|
||||
pub struct NativeQueryResult(Arc<QueryResultReader>);
|
||||
|
||||
pub fn execute_with_metadata<Q: ExecutableQuery + Send + 'static>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
track: bool,
|
||||
cap: Option<NonZeroU64>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mode = match (track, cap) {
|
||||
(_, Some(cap)) => TrackTotalHits::UpTo(cap),
|
||||
(true, None) => TrackTotalHits::Exact,
|
||||
(false, None) => TrackTotalHits::Off,
|
||||
};
|
||||
let request = MetadataRequest::new().track_total_hits(mode);
|
||||
future_into_py(py, async move {
|
||||
let result = query
|
||||
.execute_with_metadata(crate::query::query_execution_options(None, None), request)
|
||||
.await
|
||||
.infer_error()?;
|
||||
Ok(NativeQueryResult(Arc::new(QueryResultReader::new(result))))
|
||||
})
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl NativeQueryResult {
|
||||
fn next_batch<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
|
||||
let reader = self.0.clone();
|
||||
future_into_py(py, async move {
|
||||
let batch = reader.next().await.infer_error()?;
|
||||
Python::attach(|py| {
|
||||
batch
|
||||
.map(|batch| batch.to_pyarrow(py).map(Bound::unbind))
|
||||
.transpose()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn total_hits(&self) -> PyResult<Option<(u64, &'static str)>> {
|
||||
let metadata = self
|
||||
.0
|
||||
.metadata()
|
||||
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
|
||||
Ok(metadata
|
||||
.total_hits
|
||||
.as_ref()
|
||||
.map(|hits| (hits.value, hits.relation.as_str())))
|
||||
}
|
||||
|
||||
fn close<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
|
||||
let reader = self.0.clone();
|
||||
future_into_py(py, async move {
|
||||
reader.close().await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user