fix: honor Enterprise query batch size limits (#5350)

Enterprise queries could return Arrow batches larger than the size
explicitly requested by the caller. The SDK now slices oversized batches
in the final query stream and keeps server-selected batch sizes when the
caller omits the limit or passes zero.

The search guide shows how to stream a full table or filtered scan in
one query using Python's `search().to_batches()`. It covers older
deployments that return buffered Arrow IPC files or enforce a query row
cap.

A local Enterprise 1.16.0 probe streamed all 131,073 rows from a pinned
snapshot in one query, with batches of at most 37 rows and the first
batch available before the Arrow end-of-stream marker. The probe ran
with Plan Executor enabled and disabled.

Related to OSS-3133.
This commit is contained in:
Xuanwo
2026-12-02 09:42:17 +00:00
committed by GitHub
parent 53a8c6973c
commit b5f35d5c56
13 changed files with 192 additions and 74 deletions
+21
View File
@@ -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
+22
View File
@@ -86,7 +86,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.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<usize> {
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]
+38 -9
View File
@@ -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.
<CodeGroup>
<CodeBlock filename="Python" language="python" icon="python">
{PyScanBatches}
</CodeBlock>
<CodeBlock filename="Rust" language="rust" icon="rust">
{RsScanBatches}
</CodeBlock>
</CodeGroup>
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}
+2
View File
@@ -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";
@@ -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<usize> {\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";