diff --git a/docs/web-tests/py/test_search_examples.py b/docs/web-tests/py/test_search_examples.py index eccf50bfb..670704847 100644 --- a/docs/web-tests/py/test_search_examples.py +++ b/docs/web-tests/py/test_search_examples.py @@ -187,6 +187,27 @@ def test_filter_search(): assert all(row["category"] == "animals" for row in rows) +def test_scan_batches(): + import lancedb + + db = lancedb.connect("memory://") + table = db.create_table( + "documents", + [ + {"text": "A puppy playing in the park", "category": "animals"}, + {"text": "A dog resting at home", "category": "animals"}, + {"text": "A guide to growing tomatoes", "category": "gardening"}, + ], + ) + # --8<-- [start:scan_batches] + query = table.search().select(["text", "category"]).with_row_id(True) + rows_read = 0 + for batch in query.to_batches(batch_size=1024): + rows_read += batch.num_rows + # --8<-- [end:scan_batches] + assert rows_read == 3 + + def test_query_plan(): from tempfile import TemporaryDirectory diff --git a/docs/web-tests/rs/search_filter_search.rs b/docs/web-tests/rs/search_filter_search.rs index 0417b5b15..f493f4ad1 100644 --- a/docs/web-tests/rs/search_filter_search.rs +++ b/docs/web-tests/rs/search_filter_search.rs @@ -86,7 +86,29 @@ async fn main() -> Result<(), Box> { .iter() .all(|v| v == Some("animals")) })); + assert_eq!(scan_batches(&table).await?, 3); // --8<-- [start:example_tail] Ok(()) } // --8<-- [end:example_tail] + +// --8<-- [start:scan_batches] +async fn scan_batches(table: &lancedb::Table) -> lancedb::Result { + use futures::TryStreamExt; + use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions, Select}; + + let query = table + .query() + .select(Select::columns(&["text", "category"])) + .with_row_id(); + let mut options = QueryExecutionOptions::default(); + options.max_batch_length = 1024; + + let mut batches = query.execute_with_options(options).await?; + let mut rows_read = 0; + while let Some(batch) = batches.try_next().await? { + rows_read += batch.num_rows(); + } + Ok(rows_read) +} +// --8<-- [end:scan_batches] diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index 3503954e6..1297c155e 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -8,7 +8,8 @@ availability: enterprise: available --- -import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; +import { PyScanBatches, PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; +import { RsScanBatches } from '/snippets/search_filter_search.mdx'; import { RsExampleBody as RsVectorSearchBody, RsExampleTail as RsVectorSearchTail } from '/snippets/search_vector_search.mdx'; LanceDB supports vector, full-text and hybrid search. Use vector search to find @@ -98,15 +99,43 @@ never returned. ## Read large result sets in batches {#avoid-materializing-the-whole-table} -Materializing all rows at once can exhaust application memory. For exports and -training reads, use bounded queries or the batch-reading interfaces described -in [Data loading](/training/data-loading). The SDK buffers Enterprise -query responses before exposing batches. Set a query limit rather than relying -on batch iteration alone to bound memory. +For an export or a full table scan, build a query without a search term or +vector and read the results one batch at a time. LanceDB Enterprise runs one +query, so the scan needs no key column, index or pagination. The examples +read the `text` and `category` columns from an open table. -Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB -Embedded interface. Use the SDK query builders for reads that need to work with -both LanceDB Embedded and LanceDB Enterprise. + + +{PyScanBatches} + + +{RsScanBatches} + + + +The row ID option includes `_rowid` in each batch. To restrict the scan, add a +predicate with `where()` in Python or `only_if()` in Rust. Omit `limit()` to read +every matching row. Use `limit(n)` to cap the total number of rows. + +Python's `batch_size` and Rust's `max_batch_length` cap the rows per batch +delivered to the application. The SDK decodes each server batch at its original +size before slicing it. In TypeScript, `for await (const batch of table.query())` +uses the default batch sizing. TypeScript's `maxBatchLength` option is available +on `toArrow()` and `toArray()`, which collect the full result. + +Use a current SDK with LanceDB Enterprise 1.16.0 or later for this workflow. SDK +0.42.0 introduced streaming Arrow IPC query responses. Python and Rust SDKs +through 0.42.1 may return Enterprise batches larger than the requested cap. +Older deployments can return buffered Arrow IPC files or reject scans without +`limit()` if they enforce a query row cap. + +To pin a retained version, call `table.checkout(version)` in Python or +`table.checkout(version).await?` in Rust before building the query. If the +stream is interrupted, the batches already read are a partial result. Python +raises `ResponseInterruptedError` and Rust returns `Error::ResponseInterrupted`. + +For training, see [Data loading](/training/data-loading). Python's +`table.to_lance()` gives direct Lance dataset access in LanceDB Embedded. ## Investigate a slow query {#diagnostics} diff --git a/docs/web/snippets/search_examples.mdx b/docs/web/snippets/search_examples.mdx index 806f129d0..8a6cf01ca 100644 --- a/docs/web/snippets/search_examples.mdx +++ b/docs/web/snippets/search_examples.mdx @@ -6,6 +6,8 @@ export const PyHybridSearch = "table = db.create_table(\n \"documents\",\n export const PyQueryPlan = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nquery = table.search([1.0, 0.0]).select([\"id\", \"text\", \"_distance\"]).limit(2)\nprint(\"Plan:\", query.explain_plan())\nprint(\"Measured execution:\", query.analyze_plan())\nrows = query.to_list()\nprint(rows)\n"; +export const PyScanBatches = "query = table.search().select([\"text\", \"category\"]).with_row_id(True)\nrows_read = 0\nfor batch in query.to_batches(batch_size=1024):\n rows_read += batch.num_rows\n"; + export const PyTextSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n },\n ],\n)\ntable.create_index(\"text\", config=FTS())\nrows = (\n table.search(\"puppy\", query_type=\"fts\", fts_columns=\"text\")\n .select([\"id\", \"text\", \"_score\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; export const PyVectorSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nrows = (\n table.search([1.0, 0.0])\n .distance_type(\"l2\")\n .select([\"id\", \"text\", \"_distance\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; diff --git a/docs/web/snippets/search_filter_search.mdx b/docs/web/snippets/search_filter_search.mdx index efe325aae..05544b49a 100644 --- a/docs/web/snippets/search_filter_search.mdx +++ b/docs/web/snippets/search_filter_search.mdx @@ -4,3 +4,5 @@ export const RsExampleBody = "use arrow_array::types::Float32Type;\nuse arrow_ar export const RsExampleTail = " Ok(())\n}\n"; +export const RsScanBatches = "async fn scan_batches(table: &lancedb::Table) -> lancedb::Result {\n use futures::TryStreamExt;\n use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions, Select};\n\n let query = table\n .query()\n .select(Select::columns(&[\"text\", \"category\"]))\n .with_row_id();\n let mut options = QueryExecutionOptions::default();\n options.max_batch_length = 1024;\n\n let mut batches = query.execute_with_options(options).await?;\n let mut rows_read = 0;\n while let Some(batch) = batches.try_next().await? {\n rows_read += batch.num_rows();\n }\n Ok(rows_read)\n}\n"; + diff --git a/nodejs/src/query.rs b/nodejs/src/query.rs index 9e134880e..7b32f4f32 100644 --- a/nodejs/src/query.rs +++ b/nodejs/src/query.rs @@ -203,10 +203,8 @@ impl Query { timeout_ms: Option, with_row_id: Option, ) -> napi::Result { - let mut execution_opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - execution_opts.max_batch_length = max_batch_length; - } + let mut execution_opts = + QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length); if let Some(timeout_ms) = timeout_ms { execution_opts.timeout = Some(std::time::Duration::from_millis(timeout_ms as u64)) } @@ -446,10 +444,8 @@ impl VectorQuery { timeout_ms: Option, with_row_id: Option, ) -> napi::Result { - let mut execution_opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - execution_opts.max_batch_length = max_batch_length; - } + let mut execution_opts = + QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length); if let Some(timeout_ms) = timeout_ms { execution_opts.timeout = Some(std::time::Duration::from_millis(timeout_ms as u64)) } diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py index ee92ddf53..86958c572 100644 --- a/python/python/lancedb/remote/errors.py +++ b/python/python/lancedb/remote/errors.py @@ -297,7 +297,7 @@ class ResponseInterruptedError(HttpError): Attributes ---------- batches: int - The number of batches returned before the interruption. + The number of Arrow batches decoded from the server before the interruption. rows: int The number of rows in those batches. table_version: int or None diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 72cf1f124..e46795adf 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -307,7 +307,8 @@ class RemoteTable(Table): validate_blob_mode(blob_mode) raise NotImplementedError( "to_arrow() is not supported in LanceDB Enterprise. " - "Use table.search().to_arrow() instead." + "Use table.search().to_batches() to stream results or " + "table.search().to_arrow() to materialize them." ) def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 853e7ab20..033f81714 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -3888,12 +3888,18 @@ def test_remote_python_only_messages(): with pytest.raises(NotImplementedError, match=next(iter(options))): db.open_table("test", **options) table = db.open_table("test") - for method in ["to_arrow", "to_pandas", "to_polars"]: + for method, guidance in { + "to_arrow": ( + "Use table.search().to_batches() to stream results or " + "table.search().to_arrow() to materialize them." + ), + "to_pandas": "Use table.search().to_pandas() instead.", + "to_polars": "Use table.search().to_polars() instead.", + }.items(): with pytest.raises(NotImplementedError) as error: getattr(table, method)() assert str(error.value) == ( - f"{method}() is not supported in LanceDB Enterprise. " - f"Use table.search().{method}() instead." + f"{method}() is not supported in LanceDB Enterprise. {guidance}" ) for method, expected in { "compact_files": "compact_files() is a no-op in LanceDB Enterprise.", @@ -4710,10 +4716,24 @@ def streamed_query_table(write_body): yield db.open_table("test"), queries -def test_query_sync_to_batches_yields_before_the_body_is_complete(): - batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] +@pytest.mark.parametrize("batch_size", [None, 0, 37, 1024]) +def test_query_sync_to_batches_yields_before_the_body_is_complete(batch_size): + server_batch_sizes = [1063, 81] + values = list(range(sum(server_batch_sizes))) + row_ids = [(1 << 32) + 2 * value for value in values] + results = pa.record_batch( + { + "id": pa.array(values, pa.int32()), + "_rowid": pa.array(row_ids, pa.uint64()), + } + ) + first_server_size = server_batch_sizes[0] + batches = [ + results.slice(0, first_server_size), + results.slice(first_server_size), + ] body = _arrow_stream(batches) - # The schema and first batch, without the 8-byte end-of-stream marker. + # Send the schema and first server batch without the end-of-stream marker. head = _arrow_stream(batches[:1])[:-8] first_batch_read = threading.Event() waited_for_client = [] @@ -4725,13 +4745,24 @@ def test_query_sync_to_batches_yields_before_the_body_is_complete(): request.wfile.write(body[len(head) :]) with streamed_query_table(write_body) as (table, queries): - reader = table.search().to_batches() - assert reader.read_next_batch()["id"].to_pylist() == [0] + query = table.search().select(["id"]).with_row_id(True) + reader = query.to_batches(batch_size=batch_size) + first_batch = reader.read_next_batch() first_batch_read.set() - assert reader.read_all()["id"].to_pylist() == [1, 2] + received = [first_batch, *reader] + + sizes = [batch.num_rows for batch in received] + if batch_size: + assert all(0 < size <= batch_size for size in sizes) + else: + assert sizes == server_batch_sizes + result = pa.Table.from_batches(received) + assert result["id"].to_pylist() == values + assert result["_rowid"].to_pylist() == row_ids # The wait times out if the client needs the whole body for the first batch. assert waited_for_client == [True] + assert len(queries) == 1 assert queries[0]["Accept"] == ( "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9" ) @@ -4739,8 +4770,9 @@ def test_query_sync_to_batches_yields_before_the_body_is_complete(): @pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"]) def test_query_sync_interrupted_response_raises(abort): - batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] - head = _arrow_stream(batches[:1])[:-8] + values = list(range(45)) + batch = pa.record_batch({"id": pa.array(values, pa.int32())}) + head = _arrow_stream([batch])[:-8] def write_body(request): if abort: @@ -4751,14 +4783,16 @@ def test_query_sync_interrupted_response_raises(abort): request.wfile.write(head) with streamed_query_table(write_body) as (table, queries): - reader = table.search().to_batches() - assert reader.read_next_batch()["id"].to_pylist() == [0] + reader = table.search().to_batches(batch_size=37) + received = [] with pytest.raises(ResponseInterruptedError) as exc_info: - reader.read_next_batch() + for batch in reader: + received.extend(batch["id"].to_pylist()) + assert received == values error = exc_info.value assert isinstance(error, HttpError) - assert (error.batches, error.rows, error.table_version) == (1, 1, 7) + assert (error.batches, error.rows, error.table_version) == (1, len(values), 7) assert error.request_id == queries[0]["x-request-id"] assert error.is_transport_error is abort assert len(queries) == 1 diff --git a/python/src/query.rs b/python/src/query.rs index a755b38fe..f72de6613 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -102,13 +102,9 @@ fn query_execution_options( max_batch_length: Option, timeout: Option, ) -> QueryExecutionOptions { - let mut options = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - options.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - options.timeout = Some(timeout); - } + let mut options = + QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length); + options.timeout = timeout; options } @@ -1060,13 +1056,7 @@ impl FTSQuery { .full_text_search(self_.fts_query_for_execution()); future_into_py(self_.py(), async move { - let mut opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - opts.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - opts.timeout = Some(timeout); - } + let opts = query_execution_options(max_batch_length, timeout); let inner_stream = inner.execute_with_options(opts).await.infer_error()?; Ok(RecordBatchStream::new(inner_stream)) }) @@ -1351,13 +1341,7 @@ impl VectorQuery { ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let mut opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - opts.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - opts.timeout = Some(timeout); - } + let opts = query_execution_options(max_batch_length, timeout); let inner_stream = inner.execute_with_options(opts).await.infer_error()?; Ok(RecordBatchStream::new(inner_stream)) }) diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index a6a88cac4..f22384eb8 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -513,7 +513,7 @@ pub enum Error { ))] ResponseInterrupted { request_id: String, - /// Batches returned before the interruption. + /// Arrow batches decoded from the server before the interruption. batches: u64, /// Rows in those batches. rows: u64, diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index c761f75a9..ce476866d 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -703,7 +703,7 @@ pub struct QueryExecutionOptions { /// and so the performance penalty of reading smaller batches /// is typically very small. /// - /// By default, this is 1024 + /// The default value is 1024. Zero leaves the batch size to the engine. pub max_batch_length: u32, /// Max duration to wait for the query to execute before timing out. /// @@ -717,6 +717,9 @@ pub struct QueryExecutionOptions { /// This only affects remote distributed query plans. Local query execution /// ignores this option. pub analyze_plan_distributed_metrics: AnalyzePlanDistributedMetrics, + // An omitted batch length keeps the server's batch sizes for Enterprise + // queries. Embedded queries and takes still use the numeric default. + pub(crate) use_server_batch_length: bool, } impl Default for QueryExecutionOptions { @@ -725,11 +728,20 @@ impl Default for QueryExecutionOptions { max_batch_length: 1024, timeout: None, analyze_plan_distributed_metrics: AnalyzePlanDistributedMetrics::Aggregate, + use_server_batch_length: false, } } } impl QueryExecutionOptions { + /// Preserve the execution path's default when the caller omits a batch length. + #[doc(hidden)] + pub fn with_optional_max_batch_length(mut self, max_batch_length: Option) -> Self { + self.use_server_batch_length = max_batch_length.is_none(); + self.max_batch_length = max_batch_length.unwrap_or(Self::default().max_batch_length); + self + } + fn without_output_batch_length_limit(&self) -> Self { let mut options = self.clone(); options.max_batch_length = 0; @@ -775,11 +787,15 @@ pub trait ExecutableQuery { options: QueryExecutionOptions, ) -> impl Future>> + Send; - /// Execute the query with default options and return results + /// Execute the query with default options and return results. /// - /// See [`ExecutableQuery::execute_with_options`] for more details. + /// Embedded queries and takes use the default maximum batch length. + /// To cap batches from an Enterprise query response, pass a positive + /// `max_batch_length` to [`ExecutableQuery::execute_with_options`]. fn execute(&self) -> impl Future> + Send { - self.execute_with_options(QueryExecutionOptions::default()) + self.execute_with_options( + QueryExecutionOptions::default().with_optional_max_batch_length(None), + ) } /// Execute the query and return results diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 7a5ba8505..3a2625e7b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1959,7 +1959,10 @@ impl RemoteTable { &self, query: &AnyQuery, options: &QueryExecutionOptions, - ) -> Result>>> { + ) -> Result<( + Vec, + Option<(tokio::time::Instant, Duration)>, + )> { if let AnyQuery::VectorQuery(query) = query && query.query_vector.len() > 1 && query.base.reranker.is_some() @@ -2039,7 +2042,7 @@ impl RemoteTable { == first.schema().metadata().get("lancedb:query_snapshot") }) }); - Ok(streams + let streams = streams .into_iter() .map(|stream| { // Ordinary descriptor queries remain usable during an upgrade. @@ -2060,7 +2063,8 @@ impl RemoteTable { None => stream, } }) - .collect()) + .collect(); + Ok((streams, deadline)) } fn prepare_query_bodies( @@ -3725,7 +3729,7 @@ impl BaseTable for RemoteTable { .await; } - let streams = self.execute_query(query, &options).await?; + let (streams, _) = self.execute_query(query, &options).await?; if streams.len() == 1 { let stream = streams.into_iter().next().unwrap(); Ok(Arc::new(OneShotExec::new(stream))) @@ -3763,24 +3767,31 @@ impl BaseTable for RemoteTable { return Ok(DatasetRecordBatchStream::new(inner)); } - let streams = self.execute_query(query, &options).await?; - - if streams.len() == 1 { - Ok(DatasetRecordBatchStream::new( - streams.into_iter().next().unwrap(), - )) + let (streams, deadline) = self.execute_query(query, &options).await?; + let stream = if streams.len() == 1 { + streams.into_iter().next().unwrap() } else { let stream_execs = streams .into_iter() .map(|stream| Arc::new(OneShotExec::new(stream)) as Arc) .collect(); let plan = create_multi_vector_plan(stream_execs)?; + execute_plan(plan, Default::default())? + }; - Ok(DatasetRecordBatchStream::new(execute_plan( - plan, - Default::default(), - )?)) + if options.use_server_batch_length || options.max_batch_length == 0 { + return Ok(DatasetRecordBatchStream::new(stream)); } + + // A multi-vector plan can coalesce batches, so cap the final output. + let stream = MaxBatchLengthStream::new_boxed(stream, options.max_batch_length as usize); + // Keep the original deadline when the consumer reads buffered slices. + let stream: SendableRecordBatchStream = if let Some((deadline, timeout)) = deadline { + Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline)) + } else { + stream + }; + Ok(DatasetRecordBatchStream::new(stream)) } async fn blob_columns(&self) -> Result> {