mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 15:55:19 +00:00
A coordinator can publish batches staged by multiple ingest workers in a single table version. This adds staged append and overwrite in LanceDB Embedded and Enterprise across Rust, synchronous and asynchronous Python, and TypeScript. Ordinary `table.add()` continues to commit immediately. A coordinator selects the mode with `begin_write(mode)` (`beginWrite` in TypeScript) and shares the opaque write ID. Workers open the same writable table and branch and resume with `open_write(id)` (`openWrite` in TypeScript). They can retry the same input with the same idempotency key. Staging returns no version. Explicit `commit()` publishes one version and returns `AddResult`. Explicit `abort()` discards the staged write and can be repeated. Dropping a handle performs no I/O. Enterprise uses the existing multipart endpoints on servers with multipart write support. A non-empty staged overwrite input carrying top-level Arrow schema metadata fails before the SDK sends any part insert. The SDK enforces this in Rust `StagedWrite::add(...).execute()`, Python `StagedWrite.add` and `AsyncStagedWrite.add`, and TypeScript `StagedWrite.add` on every supported Enterprise server version. Empty input is a no-op. Staged append and overwrite with an empty top-level map are supported, including field and nested field metadata on overwrite. [OSS-2859](https://linear.app/lancedb/issue/OSS-2859) · [Distributed reads in OSS-441](https://linear.app/lancedb/issue/OSS-441) The separate Sophon fix preserves top-level schema metadata in the server’s multipart overwrite path. The SDK follow-up verifies a route that sends every part, retry, and completion to fixed instances before lifting the guard. [ENT-4970](https://linear.app/lancedb/issue/ENT-4970/multipart-overwrite-drops-top-level-schema-metadata-in-sophon) · [Sophon #11472](https://github.com/lancedb/sophon/pull/11472) · [OSS-3312](https://linear.app/lancedb/issue/OSS-3312/enable-schema-metadata-in-enterprise-staged-overwrite-after-verifying) Embedded staged overwrites keep top-level, field, and nested-field metadata from the replacement schema. Commit rejects overwrite parts whose restored schemas differ. The Insert data guide shows staged writes in Python, TypeScript, and Rust. The Distributed Write guide describes both SDK-coordinated staging and server-coordinated CTAS. ## Validation Final head `cf6737cece7b17f33a13556ba13f1460a0d4cfc8` adds the guard in `a02beb97084cb9d5d70b0bfdbbf31ce7bb4b1067` and a documentation-only commit. - **Rust.** All 14 `--lib staged_write` tests and all 15 `--lib multipart_write` tests passed with the locked `ci` profile and Enterprise support. `explicit_enterprise_overwrite_rejects_schema_metadata_before_upload` covers rejection before insert, known and streaming empty inputs, and a subsequent field-metadata part in the same session. - **Python and Sophon 1.16.0.** The Python extension was rebuilt with the final Rust inputs. The staged-write and permutation suites passed 133 tests with 2 skipped. On the isolated released-service fixture, sync and async staged overwrite rejected top-level metadata with zero insert requests. A materialized zero-row table and a streaming zero-row batch both succeeded without an insert. A fresh read verified the original version, row, and schema. Two independent workers then staged parts with field and nested field metadata, and an independent coordinator published one version with exactly the replacement rows. The reopened SDK table and Lance manifest preserved that metadata. Ordinary overwrite and staged append also succeeded. - **TypeScript and docs.** TypeScript compilation, lint, TypeDoc, strict MkDocs, and Vale passed. The final TypeScript changes are documentation. The earlier Node native build and staged-write test below cover the binding. The Rust tests and rebuilt Python extension exercised the final shared guard. At `ab9f49fba5055a5f731fe013a820515aa5cfa12c`, all 11 Rust staged-write integration tests and 13 staged-write unit tests passed. The new tests exercise independent reopen, reject differences at each metadata level, and verify one publication with the complete schema after replacing the mismatched part. Rust formatting and Vale passed for the follow-up. On the initial validation head `68e950d24a1418890f80eb04102de49388012318`: - Rust passed the library check with Enterprise support and 15 existing multipart tests. - Python passed both staged-write tests covering synchronous multiprocessing and asynchronous overwrite and abort. The separate fail-loud fragment constraint regression passed all 39 cases. [#5120](https://github.com/lancedb/lancedb/pull/5120) - Node.js passed the native build, TypeScript compilation, lint, and the staged-write Jest test. TypeDoc generation and strict MkDocs also passed. The initial Python and Node.js native extensions were built at `47ea43533f103744e84a7cdbe83d8e4a8ddf093e` with the repository’s `ci` profile, the default SDK features, and locked Lance 16.0.0-beta.7 and `object_store` 0.14.2. The initial validation head differs from that build commit only in two generated TypeDoc pages. The Python and Node.js tests ran again at that head using the same native artifacts. The candidate Python SDK passed multipart create, cross-process staging, commit, and abort against released LanceDB Enterprise (Sophon) 1.16.0 on an isolated loopback gateway and S3-compatible store. After an ordinary append published version 2, a separate coordinator committed the staged batches once to version 3, with exactly the three expected rows. The probe also verified overwrite conflict handling, schema refresh after a successful overwrite, and branch and pinned-handle behavior. Both abort modes removed the upload marker and staged transaction records, rejected subsequent staging and commit, and left the table at version 3 with the same rows. Append abort removed its staged payload. Overwrite abort left one unreferenced data file in object storage for storage cleanup. A separate Sophon 1.16.0 probe confirmed that multipart overwrite loses top-level schema metadata, including `embedding_functions` and `lancedb::column_definitions`. Field and nested-field metadata survived, and a single-request overwrite preserved the full metadata on the same input. ## Local security comparison Compared head `ab9f49fba5055a5f731fe013a820515aa5cfa12c` with its merge base `c85647526c90647d9b5d6a701afeacca3f47b34d`. - **Dependencies.** OSV-Scanner 2.7.1 used one offline crates.io advisory snapshot for both Cargo locks. Each scan read 1,098 package entries and reported the same 48 advisory matches across 24 package versions. The change makes the already-locked `prost` 0.14.4 a direct dependency for Embedded, where Lance already pulls it in. OSV and the GitHub Advisory Database returned no advisory for that version. The Cargo, Python, and Node lockfiles are byte-identical. The latter two therefore did not require a dependency audit. - **Source.** Semgrep Community Edition 1.187.0 ran 658 security and secret rules on 16 baseline files and 24 candidate files across Rust, Python, and TypeScript. Both results contained the same 31 matches on unchanged code, with zero skipped targets or parse errors. These were existing Rust `unsafe` blocks in tests and N-API branch metadata, a Python serialization check, and a TypeScript iterator call through `Symbol.asyncIterator`. [Rule snapshot](https://github.com/semgrep/semgrep-rules/tree/a5ad1714f00c9f7fde980cab0ea1d6dc6d414fd2) The OSV results cover lockfile package versions in the local database. Semgrep covers the changed source files with file-local analysis. Rule-level Aikido results were unavailable for comparison.
429 lines
19 KiB
Plaintext
429 lines
19 KiB
Plaintext
---
|
|
title: "Insert data"
|
|
sidebarTitle: "Insert"
|
|
description: "Append records, load file-backed data or batches, and verify ingestion."
|
|
icon: plus
|
|
availability:
|
|
embedded: available
|
|
enterprise: available
|
|
---
|
|
|
|
import {
|
|
TsCreateTableFromIterator as TsCreateTableFromIterator,
|
|
RsCreateTableFromIterator as RsCreateTableFromIterator,
|
|
} from '/snippets/tables.mdx';
|
|
import {
|
|
PyAddFromDataset as AddFromDataset,
|
|
PyAddFromRecordBatchReader,
|
|
PyAddFromRecordBatchReaderAsync,
|
|
PyCreateTableFromIterator as CreateTableFromIterator,
|
|
} from '/snippets/ingestion_examples.mdx';
|
|
|
|
import { RsExample as RsAddProgress } from '/snippets/ingestion_progress.mdx';
|
|
import { PyAddProgress, TsAddProgressBody, TsAddProgressTail } from '/snippets/ingestion_examples.mdx';
|
|
import { PyAppendRows } from '/snippets/ingestion_examples.mdx';
|
|
import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx';
|
|
|
|
Use `add()` to append records to an existing table. It does not compare incoming
|
|
keys with stored keys. Choose [merge insert](/ingestion/merge-insert) when the
|
|
same record may arrive again and should update an existing row.
|
|
|
|
## Append a first batch {#append}
|
|
|
|
Install the Python SDK with `pip install lancedb`. This complete example starts
|
|
with Alice, appends Bob and Charlie, and prints all three records.
|
|
|
|
<CodeBlock filename="append_rows.py" language="python" icon="python">
|
|
{PyAppendRows}
|
|
</CodeBlock>
|
|
|
|
The program uses temporary local storage. For a complete TypeScript or Rust
|
|
example, see [Complete write workflow](#complete-example).
|
|
Enterprise SQL offers [`INSERT`](/sql/dml/insert), including `INSERT ... SELECT`.
|
|
|
|
## Prepare the input {#prepare}
|
|
|
|
Match the table's schema, including required fields and vector dimensions.
|
|
Supported input formats differ by SDK; see
|
|
[Create a table](/ingestion/create-table). Inspect conversion errors before
|
|
retrying, and verify the final row count and representative values.
|
|
|
|
## Choose input for a large load {#large-datasets}
|
|
|
|
Avoid building one large in-memory list when records already live in files
|
|
or arrive as batches. Create a table with the intended schema, then append
|
|
through the appropriate input path.
|
|
|
|
<span id="bulk-ingestion-for-data-you-already-have"></span>
|
|
### Read from files {#from-files-parquet-csv-etc}
|
|
|
|
Python accepts a `pyarrow.dataset.Dataset`. This example writes a small Parquet
|
|
file locally, creates an empty table with its schema, and appends the two records.
|
|
For your own data, point the dataset reader at the input files instead.
|
|
|
|
<CodeBlock filename="load_parquet.py" language="python" icon="python">
|
|
{AddFromDataset}
|
|
</CodeBlock>
|
|
|
|
A file-backed source can be scanned without first loading the whole dataset
|
|
into application memory. This Python input API is distinct from converting
|
|
files to Arrow batches yourself in another language.
|
|
|
|
<span id="iterator-ingestion-for-data-you-transform-on-the-fly"></span>
|
|
### Produce batches during ingestion {#from-iterators-custom-batch-generation}
|
|
|
|
Use batches when processing the input as it arrives. The Python example creates
|
|
an empty table and appends ten records produced by a batch iterator.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="python" icon="python">
|
|
{CreateTableFromIterator}
|
|
</CodeBlock>
|
|
<CodeBlock filename="TypeScript" language="typescript" icon="square-js">
|
|
{TsCreateTableFromIterator}
|
|
</CodeBlock>
|
|
<CodeBlock filename="Rust" language="rust" icon="rust">
|
|
{RsCreateTableFromIterator}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
The language APIs differ: the TypeScript example appends each constructed Arrow
|
|
batch, while the Rust example supplies an Arrow reader when creating the table.
|
|
These are input-format examples, not equivalent parallel-write benchmarks.
|
|
|
|
### Append an Arrow batch reader {#from-record-batch-reader}
|
|
|
|
Pass a `pyarrow.RecordBatchReader` to append multiple batches in one Python
|
|
`add()` call. A successful append commits the reader's batches together as one
|
|
table version. If each flush needs its own commit acknowledgment, call `add()`
|
|
separately for each flush and wait for it to succeed.
|
|
|
|
Each example uses an open table and an iterable of `pyarrow.RecordBatch` objects
|
|
that match the table's schema. For LanceDB Enterprise, check the
|
|
[multipart upload requirements](#bulk-ingests-into-a-remote-table).
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python (sync)" language="python" icon="python">
|
|
{PyAddFromRecordBatchReader}
|
|
</CodeBlock>
|
|
<CodeBlock filename="Python (async)" language="python" icon="python">
|
|
{PyAddFromRecordBatchReaderAsync}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
### Control write parallelism {#write-parallelism}
|
|
|
|
Python's `add()` can estimate parallelism for materialized inputs. A streaming
|
|
reader may not expose its total size or support replay. Use `write_parallelism`
|
|
when controlling the number of concurrent partitions; increasing it can also
|
|
increase memory use. TypeScript does not expose that manual option.
|
|
|
|
Measure with realistic row sizes and storage. Avoid one write per row when a
|
|
batch will do, and avoid a large worker count for a small input.
|
|
|
|
## Stage a write across processes {#staged-writes}
|
|
|
|
Use a staged write when several workers need to publish their batches as one
|
|
table version. A coordinator opens the write in `append` or `overwrite` mode
|
|
and shares its opaque ID. Workers connect to the same writable table and
|
|
branch, reopen the write by ID, and stage their batches. `add()` on a staged
|
|
write returns no version. Once all workers finish, a coordinator reopens the
|
|
write and calls `commit()` to publish one version and receive its number.
|
|
|
|
The examples assume that the coordinator and worker have separate connections
|
|
to the same database and that the `items` table has an integer `id` column.
|
|
Pass the ID and a task-specific key to each worker through your job runner.
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
# Coordinator
|
|
items = coordinator_db.open_table("items")
|
|
write_id = items.begin_write(mode="append").id
|
|
|
|
# Worker
|
|
worker = worker_db.open_table("items").open_write(write_id)
|
|
worker.add([{"id": 42}], idempotency_key="batch-1")
|
|
|
|
# Coordinator, after every worker finishes
|
|
result = items.open_write(write_id).commit()
|
|
print(result.version)
|
|
```
|
|
|
|
```typescript TypeScript icon="square-js"
|
|
// Coordinator
|
|
const items = await coordinatorDb.openTable("items");
|
|
const { id: writeId } = await items.beginWrite("append");
|
|
|
|
// Worker
|
|
const workerTable = await workerDb.openTable("items");
|
|
const worker = await workerTable.openWrite(writeId);
|
|
await worker.add([{ id: 42 }], { idempotencyKey: "batch-1" });
|
|
|
|
// Coordinator, after every worker finishes
|
|
const write = await items.openWrite(writeId);
|
|
const { version } = await write.commit();
|
|
console.log(version);
|
|
```
|
|
|
|
```rust Rust icon="rust"
|
|
use lancedb::table::AddDataMode;
|
|
|
|
// Coordinator
|
|
let items = coordinator_db.open_table("items").execute().await?;
|
|
let write_id = items.begin_write(AddDataMode::Append).await?.id().to_owned();
|
|
|
|
// Worker
|
|
let worker_table = worker_db.open_table("items").execute().await?;
|
|
let worker = worker_table.open_write(&write_id).await?;
|
|
let batch = arrow_array::record_batch!(("id", Int32, [42]))?;
|
|
worker.add(batch).idempotency_key("batch-1").execute().await?;
|
|
|
|
// Coordinator, after every worker finishes
|
|
let result = items.open_write(&write_id).await?.commit().await?;
|
|
println!("{}", result.version);
|
|
```
|
|
</CodeGroup>
|
|
|
|
Reuse a task's idempotency key with the same data, order, and batching when
|
|
retrying. Use a different key for each task. Enterprise stages parts by byte
|
|
size, so keep the [request byte limit](#bulk-ingests-into-a-remote-table)
|
|
consistent across workers. If changed input produces fewer parts under the same
|
|
key, the original trailing parts remain staged.
|
|
|
|
Empty batches have no effect. If every worker produces zero rows, `commit()`
|
|
returns an error. To discard a write, reopen it by ID and call `abort()`.
|
|
Repeating `abort()` is safe. Dropping a handle leaves the session open.
|
|
|
|
Keep the write's base version and staged data available until you commit or
|
|
abort. Append can rebase over concurrent appends. An overwrite requires
|
|
matching replacement schemas and fails if another write advances the table.
|
|
Embedded compares schema and field metadata across overwrite parts. On
|
|
Enterprise, a non-empty overwrite input must have an empty top-level schema
|
|
metadata map. The SDK rejects input with top-level schema metadata before
|
|
uploading any parts. Field and nested field metadata are supported.
|
|
|
|
If a completion error reports an unknown outcome, inspect the table before
|
|
retrying or aborting. Enterprise staging requires server and catalog support
|
|
for [multipart writes](#bulk-ingests-into-a-remote-table). Enterprise can retain
|
|
unreferenced data files after an overwrite abort for storage cleanup.
|
|
|
|
## Track completion and progress {#tracking-ingestion-progress}
|
|
|
|
Python, TypeScript and Rust support progress callbacks when adding data.
|
|
These examples start with Alice, append Bob and Charlie, and print the number
|
|
of rows written as progress updates arrive. After the write succeeds, they
|
|
query the table to show all three records.
|
|
|
|
Each program uses a temporary local database and removes it when finished.
|
|
|
|
- **Python:** install `lancedb`, save the code as `insert_progress.py`, and run
|
|
`python insert_progress.py`.
|
|
- **TypeScript:** install `@lancedb/lancedb`, save the code as `insert_progress.mts`,
|
|
and run `node insert_progress.mts` with Node.js 22.18 or later.
|
|
- **Rust:** download the [Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-feedback-rust.zip),
|
|
extract the project, and run `cargo run --locked --bin progress`.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="python" icon="python">
|
|
{PyAddProgress}
|
|
</CodeBlock>
|
|
<CodeBlock filename="TypeScript" language="typescript" icon="square-js">
|
|
{TsAddProgressBody}
|
|
{TsAddProgressTail}
|
|
</CodeBlock>
|
|
<CodeBlock filename="Rust" language="rust" icon="rust">
|
|
{RsAddProgress}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
For a progress bar in Python, install `tqdm` and pass `progress=True` instead
|
|
of a callback.
|
|
|
|
### Read progress updates
|
|
|
|
Updates include row and byte counts, elapsed time, and parallel write activity.
|
|
The field names differ by language:
|
|
|
|
| Meaning | Python dictionary key | TypeScript property | Rust method |
|
|
|:--------|:----------------------|:--------------------|:------------|
|
|
| Rows written so far | `output_rows` | `outputRows` | `output_rows()` |
|
|
| Bytes written so far | `output_bytes` | `outputBytes` | `output_bytes()` |
|
|
| Expected row count, when known | `total_rows` | `totalRows` | `total_rows()` |
|
|
| Elapsed time | `elapsed_seconds` | `elapsedSeconds` | `elapsed()` |
|
|
| Active write tasks | `active_tasks` | `activeTasks` | `active_tasks()` |
|
|
| Total write tasks | `total_tasks` | `totalTasks` | `total_tasks()` |
|
|
| Final update | `done` | `done` | `done()` |
|
|
|
|
Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`.
|
|
The expected row count may be unknown for streaming input. On the final update,
|
|
it falls back to the number of rows written.
|
|
|
|
For remote multipart writes, both rows and IPC bytes count acknowledged parts.
|
|
Both start at zero; a retried part is counted once, after acknowledgement.
|
|
Scanning input or sending a rejected part does not advance these counts.
|
|
Acknowledged parts are staged and do not imply a successful commit.
|
|
|
|
Keep callbacks short and use the write operation's result to determine success.
|
|
The final `done` update means progress reporting has ended; it can also occur
|
|
after a write fails or is cancelled. Input errors before writing starts may
|
|
produce no updates.
|
|
|
|
TypeScript delivers callbacks asynchronously. Slow callbacks can queue up,
|
|
and the `add()` promise may resolve before every callback has run. Exceptions
|
|
from a TypeScript callback are logged and do not abort the write.
|
|
|
|
## Verify writes and handle retries {#performance}
|
|
|
|
Wait for the write operation's result, then check the expected records.
|
|
Progress callbacks describe activity; they do not establish that a write
|
|
succeeded. If a request fails after the server may have committed it, blindly
|
|
repeating an append can duplicate rows. Current clients do not automatically
|
|
replay non-idempotent writes after `500`, `502`, `503`, or `504`, or after a
|
|
response is lost. A plain `503` does not prove that a write was rejected before
|
|
commit. Connection failures before sending, `409` transaction conflicts, and
|
|
explicit `429` rate-limit rejections may be retried within `RetryConfig` limits. Idempotent multipart
|
|
parts have a separate retry policy described below.
|
|
|
|
If multipart completion times out, loses its response, or receives a `5xx`, the
|
|
error reports **commit outcome unknown**. The client neither aborts the upload
|
|
nor resends completion or the input under
|
|
a new upload ID: aborting at this point could delete already committed data.
|
|
Check the table using your record IDs before retrying the operation.
|
|
|
|
Configure connection-wide limits with `client_config.retry_config` in Python
|
|
(`lancedb.remote.RetryConfig`) or `clientConfig.retryConfig` in TypeScript.
|
|
Override the budget for one `add()` with Python `table.add(data, retries=0)`
|
|
or TypeScript `table.add(data, { retries: 0 })`. The value must be an integer
|
|
between 0 and 255. Rust write builders also provide a per-call override, for
|
|
example `table.add(data).retries(0).execute().await?`,
|
|
`table.update().retries(0)`, and `table.merge_insert(&["id"]).retries(0)`.
|
|
This disables transport retries for that operation, including multipart part
|
|
retries; it does not change local transaction conflict handling. Increasing a
|
|
retry budget never makes ambiguous commits safe to replay.
|
|
|
|
## Configure large uploads {#bulk-ingests-into-a-remote-table}
|
|
|
|
<Badge color="red">Enterprise</Badge>
|
|
|
|
This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected.
|
|
|
|
With server protocol `0.4.0` or later, the client uses multipart writes for large
|
|
measured inputs, unknown-length streams such as a non-empty Python
|
|
`RecordBatchReader`, and explicit parallel uploads. Multipart writes require a
|
|
supporting catalog, such as a native directory or manifest catalog. Federated
|
|
catalogs reject multipart writes. With an older protocol, the client sends the
|
|
append in a single insert request, subject to the server's request limits.
|
|
|
|
The client slices large batches before IPC encoding and buffers each part for
|
|
replay. On a disconnected request, read timeout, or configured retryable staging
|
|
status, the client retries the part with the same upload ID, part ID, and IPC
|
|
bytes. `RetryConfig.statuses` controls status retries. An empty list disables
|
|
them. The default includes `500`, `502`, `503`, and `504`.
|
|
The server replaces that part's staged transaction, so losing
|
|
its response does not append the rows twice.
|
|
|
|
For multipart uploads managed by an ordinary table `add()`, exhausting the part
|
|
retry budget aborts the uncommitted upload. A complete request rejected with a
|
|
transaction conflict (`409`) or rate limit (`429`) also triggers best-effort
|
|
cleanup. Cleanup uses the call's retry budget and preserves the original error.
|
|
With [explicit staging](#staged-writes), the coordinator controls abort and a
|
|
failed worker can retry its own part. Ambiguous completion outcomes never
|
|
trigger cleanup or replay.
|
|
|
|
Part size still affects memory and HTTP timeouts. A single blob row cannot be
|
|
split across Arrow batches; a very large row may require a larger timeout and
|
|
more memory. No connection-pool or keepalive setting guarantees that a write
|
|
response will arrive.
|
|
|
|
Two environment variables control how a multipart write's parts are cut. Both are picked up automatically by the Python and TypeScript clients, for clients that support these settings:
|
|
|
|
| Variable | Default | What it controls |
|
|
|----------|---------|------------------|
|
|
| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. |
|
|
| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. |
|
|
|
|
For ordinary table `add()`, a part is cut after an encoding slice reaches either
|
|
limit. Explicit staged writes use the byte limit. Input batches are sliced to
|
|
approximately 8 MiB before encoding, preserving row order. Peak additional
|
|
memory scales with active writers and the part budget. Lower `write_parallelism`
|
|
or the byte budget to reduce memory use.
|
|
|
|
<CodeGroup>
|
|
```bash Bash icon="terminal"
|
|
export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=33554432 # 32 MiB
|
|
export LANCE_CLIENT_MAX_REQUEST_DURATION=30 # payload preparation budget
|
|
```
|
|
</CodeGroup>
|
|
|
|
Splitting into more parts does not change the final table. The server stages the parts under their shared upload ID before committing
|
|
the write. This upload protocol is separate from repeating an application-level
|
|
`add()` after a timeout.
|
|
|
|
Remote `create_table(name, data)` remains one atomic request, including overwrite
|
|
and `exist_ok` modes. The client encodes into an automatically removed temporary
|
|
file before sending, rejects payloads larger than 256 MiB of compressed IPC, and
|
|
never silently creates an empty table as a fallback. Encoding and input failures
|
|
therefore issue no create request. Temporary disk usage is bounded by this budget;
|
|
individual oversized rows can still need substantial encoding memory.
|
|
|
|
For larger imports, create the schema first and upload with progress reporting.
|
|
The empty table becomes visible immediately; `add()` commits its rows atomically.
|
|
The following examples use an existing connection `db`, an Arrow `schema`, and
|
|
input `data` matching that schema (an Arrow reader in Rust):
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
table = db.create_table("items", schema=schema)
|
|
table.add(data, progress=True)
|
|
```
|
|
|
|
```typescript TypeScript icon="square-js"
|
|
const table = await db.createEmptyTable("items", schema);
|
|
await table.add(data, {
|
|
progress: (p) => console.log(`Rows written: ${p.outputRows}`),
|
|
});
|
|
```
|
|
|
|
```rust Rust icon="rust"
|
|
let table = db.create_empty_table("items", schema).execute().await?;
|
|
table
|
|
.add(data)
|
|
.progress(|p| println!("Rows written: {}", p.output_rows()))
|
|
.execute()
|
|
.await?;
|
|
```
|
|
</CodeGroup>
|
|
|
|
## Complete write workflow {#complete-example}
|
|
|
|
<Accordion title="Complete examples: create, append, update, upsert and delete">
|
|
|
|
Each program creates a temporary local database, performs the five operations,
|
|
prints the result, and removes its temporary data when finished.
|
|
|
|
- **Python:** install `lancedb`, save the code as `ingestion.py`, and run
|
|
`python ingestion.py`.
|
|
- **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`,
|
|
and run `node ingestion.mts` with Node.js 22.18 or later.
|
|
- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip),
|
|
extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo
|
|
manifest and a lockfile for the example's dependencies. The code is shown below.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="ingestion.py" language="python" icon="python">
|
|
{PyWriteWorkflow}
|
|
</CodeBlock>
|
|
<CodeBlock filename="ingestion.mts" language="typescript" icon="square-js">
|
|
{TsWriteWorkflowBody}
|
|
{TsWriteWorkflowTail}
|
|
</CodeBlock>
|
|
<CodeBlock filename="src/main.rs" language="rust" icon="rust">
|
|
{RsWriteWorkflow}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
After the operations, Alice has 10 logins, Bobby has 21, and Charlie has 6.
|
|
Dana is selected for deletion and is absent from the final result.
|
|
|
|
</Accordion>
|