mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation.
430 lines
19 KiB
Plaintext
430 lines
19 KiB
Plaintext
---
|
|
title: "Compaction and cleanup"
|
|
sidebarTitle: "Compaction"
|
|
description: "Merge small files, prune old versions, and fold new rows into existing indexes."
|
|
icon: broom
|
|
availability:
|
|
embedded: available
|
|
enterprise: available
|
|
---
|
|
|
|
import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompactionTuning } from '/snippets/doc_storage_examples.mdx';
|
|
|
|
Every write commits a new table version, and versions accumulate: small files
|
|
from frequent appends, superseded files from updates and deletes, and rows added
|
|
since an index was built. In the embedded library, `optimize()` addresses all
|
|
three. LanceDB Enterprise schedules maintenance in the background and also
|
|
supports explicit compaction jobs through the CLI, SQL, and compatible SDKs.
|
|
[Manual Enterprise compaction](#enterprise-manual-compaction) rewrites data files;
|
|
cleanup and index optimization remain separate operations.
|
|
|
|
Run optimization as regular table maintenance, particularly after many small
|
|
writes or a large ingest.
|
|
|
|
{/*
|
|
Draft for the LanceDB Embedded compaction SQ partition check release. Keep this section
|
|
unpublished until that behavior ships.
|
|
|
|
### Recover from an oversized SQ partition {#oversized-sq-partition}
|
|
|
|
Compacting a table with an IVF scalar-quantized (SQ) vector index can stop
|
|
before rewriting files if an affected partition is too large to remap. The
|
|
error identifies the index, segment, partition size, and vector dimension
|
|
instead of letting the remap fail at Arrow's fixed-size-list `u32`
|
|
child-array limit.
|
|
|
|
Rebuild the affected vector index with enough IVF partitions to keep each
|
|
partition at or below `floor(u32::MAX / dimension)` vectors, then retry the
|
|
optimize. Rebuilding with the default IVF partitioning can also choose enough
|
|
partitions.
|
|
*/}
|
|
|
|
## Optimize an Embedded table {#what-it-does}
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
table.optimize()
|
|
```
|
|
</CodeGroup>
|
|
|
|
Three operations, in one call:
|
|
|
|
| | |
|
|
| --- | --- |
|
|
| **Compaction** | merges small files into larger ones |
|
|
| **Prune** | removes versions older than the retention window (see [Garbage Collection](/maintenance/cleanup)) |
|
|
| **Index** | folds newly added rows into existing indexes (see [Incremental Indexing](/indexing/incremental-indexing)) |
|
|
|
|
Compaction itself is only the first of the three: merging small fragments back
|
|
into larger ones, which is what keeps a scan from opening more files than it
|
|
needs to.
|
|
|
|
<Note>
|
|
**Enterprise job type:** `compact`. Runs automatically as data accumulates,
|
|
separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs
|
|
even though `optimize()` bundles both in one LanceDB Embedded call.
|
|
</Note>
|
|
|
|
## Track on-demand Enterprise compaction {#compaction-jobs}
|
|
|
|
On compatible Enterprise deployments, `compact_async()` / `compactAsync()`
|
|
submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle.
|
|
The table handle supplies the namespace and branch. The existing remote
|
|
`optimize()` call keeps returning after submission with placeholder statistics;
|
|
use the job-returning API to wait for the actual rewrite and obtain its result.
|
|
|
|
<CodeGroup>
|
|
```python Python
|
|
from datetime import timedelta
|
|
|
|
job = table.compact_async(
|
|
compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128}
|
|
)
|
|
result = job.wait(timeout=timedelta(minutes=10))
|
|
print(result.rows_succeeded, result.fragments_removed, result.fragments_added)
|
|
|
|
# Resume from another process with the same connection settings.
|
|
result = db.open_job(job.id).wait()
|
|
```
|
|
```typescript TypeScript
|
|
import type { CompactionResult } from "@lancedb/lancedb";
|
|
|
|
const job = await table.compactAsync({
|
|
targetRowsPerFragment: 1000, batchSize: 128,
|
|
});
|
|
const result = await job.wait({ timeoutMs: 600_000 });
|
|
console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded);
|
|
|
|
if (job.id !== null) {
|
|
await (await db.openJob<CompactionResult>(job.id)).wait();
|
|
}
|
|
```
|
|
```rust Rust
|
|
use std::time::Duration;
|
|
use lancedb::job::JobWaitOptions;
|
|
use lancedb::table::{CompactionResult, optimize::CompactionOverrides};
|
|
|
|
let job = table.compact_async(CompactionOverrides {
|
|
target_rows_per_fragment: Some(1000),
|
|
batch_size: Some(128),
|
|
..Default::default()
|
|
}).await?;
|
|
let result = job.wait_with_options(
|
|
JobWaitOptions::new().timeout(Duration::from_secs(600)),
|
|
).await?;
|
|
println!("Committed {} rows", result.rows_succeeded);
|
|
|
|
if let Some(id) = job.id() {
|
|
db.open_job(id).await?.into_typed::<CompactionResult>()?.wait().await?;
|
|
}
|
|
```
|
|
</CodeGroup>
|
|
|
|
The result describes this job's committed rewrites, not a comparison of table
|
|
versions that could include concurrent writes. `partial_commit` identifies an
|
|
incomplete commit; `rows_failed` counts planned rows left uncommitted.
|
|
`more_work` means a bounded run left eligible work for another invocation.
|
|
A genuine no-op reports zero file/fragment counts; counts omitted by an older
|
|
worker are `None` in Python/Rust or `null` in TypeScript. A server that publishes
|
|
no compaction result raises an error when waiting, rather than fabricating zero
|
|
statistics.
|
|
|
|
Submission requires Flight SQL connectivity and, under Standard authorization,
|
|
table Ownership plus Usage on the database and namespace hierarchy. Status,
|
|
progress, events, and cancellation use the generic HTTP job APIs and their
|
|
existing permissions. A wait timeout or dropping the handle does not cancel
|
|
the job. Local tables and historical-version checkouts are unsupported by the
|
|
job-returning API; ordinary embedded `optimize()` remains available.
|
|
|
|
## Submit Enterprise compaction {#enterprise-manual-compaction}
|
|
|
|
Use an existing Enterprise table and a connection configured for its database.
|
|
The `lancedb admin ...` and `lancedb job ...` examples on this page require the
|
|
**Enterprise administrative CLI**, available from your deployment administrator.
|
|
Check that `lancedb --help` lists `admin` and `job`. It needs Flight SQL
|
|
connectivity to submit the job and REST connectivity to read table settings and
|
|
job progress.
|
|
|
|
The [public CLI installation](/tools/cli#install) supplies the client commands
|
|
`auth`, `profile`, and `sql`, without the administrative commands. You can use
|
|
that client for the SQL alternative below or submit through an SDK. Ask your
|
|
deployment administrator for the Enterprise CLI when you need the administrative
|
|
examples.
|
|
|
|
<Note>
|
|
Use versions of the SDK, query nodes, agents, and workers that support these
|
|
options.
|
|
Older agents or workers can silently discard new job fields and run without the
|
|
requested source-row cap. Older-server errors propagate through the SDK without
|
|
retrying after dropping the settings. Manual submission requires a deployment
|
|
with SQL job submission enabled. Targets are resolved through the service
|
|
catalog, including PostgreSQL-backed SaaS catalogs.
|
|
</Note>
|
|
|
|
Submit the same four invocation settings through any of these interfaces:
|
|
|
|
<CodeGroup>
|
|
```bash CLI icon="terminal"
|
|
lancedb admin table optimize --table events \
|
|
--target-rows-per-fragment 100000 \
|
|
--max-source-rows 1000000 \
|
|
--io-buffer-size 67108864 \
|
|
--batch-size 1024 \
|
|
--wait --wait-timeout-seconds 600 --poll-interval-seconds 5
|
|
```
|
|
```sql SQL icon="database"
|
|
OPTIMIZE events REWRITE DATA WITH (
|
|
target_rows_per_fragment = 100000,
|
|
max_source_rows = 1000000,
|
|
io_buffer_size = 67108864,
|
|
batch_size = 1024
|
|
);
|
|
```
|
|
</CodeGroup>
|
|
|
|
With the public CLI, execute SQL directly using a profile configured for the
|
|
same database and Flight SQL endpoint:
|
|
|
|
```bash
|
|
lancedb sql --profile production --command \
|
|
'OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);'
|
|
```
|
|
|
|
Add `--branch exp` to the Enterprise CLI's `admin table optimize` command or
|
|
`branch = 'exp'` to SQL's `WITH` clause to target a branch. SDK calls use the table handle's selected branch.
|
|
Without a branch, the job targets main. CLI and SQL validate the table and branch
|
|
through the service catalog before creating a job.
|
|
|
|
SQL and the CLI without `--wait` return after durable submission. The
|
|
job-returning SDK methods above preserve the ID and return committed statistics
|
|
when waiting completes. The CLI's `--wait` polls the same durable job and prints
|
|
its result. A timeout leaves the job running. Legacy remote `optimize()` still
|
|
returns after acceptance with placeholder statistics.
|
|
|
|
Find earlier submissions with a table-scoped list, replacing `DATABASE` with
|
|
the database name:
|
|
|
|
```bash
|
|
lancedb job list --db-name DATABASE --table-name events --job-type compact
|
|
```
|
|
|
|
For a namespaced table or branch, also pass `--namespace` or `--branch-name`.
|
|
Correlate the job's submission time and stored specification, then inspect
|
|
completion and worker events with a CLI profile for that deployment:
|
|
|
|
```bash
|
|
lancedb job describe --job-id JOB_ID
|
|
lancedb job events --job-id JOB_ID
|
|
```
|
|
|
|
Under Standard authorization, submission requires table Ownership. `job describe`
|
|
accepts system Usage or, for a table job, Usage on its database and every namespace
|
|
in its path. `job list` and `job events` require system Usage; `job cancel`
|
|
requires system Operate. An unauthorized describe request returns 404 to hide
|
|
the job's existence; denied list/events requests return 403. Submission does not
|
|
grant system-level access to job lists or events.
|
|
|
|
Manual compaction uses one worker with atomic execution and inline index
|
|
remapping. Remote `optimize` does not prune old versions or optimize indexes;
|
|
explicit pruning, index optimization, and unsupported non-default compaction
|
|
settings are rejected. Cleanup continues through the deployment's separate
|
|
[cleanup policy](/maintenance/cleanup).
|
|
|
|
### Preview and inspect a run
|
|
|
|
```sql
|
|
EXPLAIN OPTIMIZE events REWRITE DATA WITH (
|
|
target_rows_per_fragment = 100000,
|
|
max_source_rows = 1000000
|
|
);
|
|
|
|
DESCRIBE JOB '<job_id>' FORMAT JSON;
|
|
```
|
|
|
|
The preview uses the execution planner to report the source version, resolved
|
|
options, planned groups/fragments/rows, and whether more eligible work remains.
|
|
It creates no job. Submission plans against its own snapshot, so concurrent
|
|
writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported.
|
|
|
|
JSON job diagnostics include reported maintenance progress and the completed
|
|
operation result alongside the existing time profile. While a job runs, its
|
|
result is null. SDK progress callbacks and CLI `--wait` expose the same worker
|
|
observations: rewritten groups/rows are execution progress, not proof of a
|
|
successful commit. Repeated task reports are counted once within an execution.
|
|
Python's `job.wait(progress=True)` displays rewritten rows; read the completion
|
|
result for committed statistics.
|
|
|
|
### Choose invocation settings {#compaction-invocation-options}
|
|
|
|
| SQL / Python / Rust | TypeScript | Meaning |
|
|
| --- | --- | --- |
|
|
| `target_rows_per_fragment` | `targetRowsPerFragment` | Positive target rows per output fragment; also affects candidate selection. This is a target, not an exact output-size guarantee. |
|
|
| `max_source_rows` | `maxSourceRows` | Positive live-source-row budget across whole planned tasks. Selection stops before a task would exceed the remaining budget. If the first useful task exceeds the budget, worker planning fails with the required live rows and source fragment count. |
|
|
| `io_buffer_size` | `ioBufferSize` | Nonnegative I/O read-ahead budget in bytes. Zero disables byte-based I/O backpressure; a positive value limits read-ahead. It is not a total-memory limit. |
|
|
| `batch_size` | `batchSize` | Positive scanner input-batch size in rows. |
|
|
|
|
These settings do not impose a runtime limit. Values must be integers in the
|
|
interface's supported range. Python and TypeScript fragment targets and batch
|
|
sizes are limited to `u32::MAX`; TypeScript additionally requires safe integers.
|
|
|
|
### Set table defaults {#table-compaction-defaults}
|
|
|
|
Table tuning supports the same four fields under `job_types.compaction`:
|
|
|
|
```bash
|
|
lancedb admin table overrides get --table events
|
|
lancedb admin table overrides set --table events \
|
|
'{"job_types":{"compaction":{"enabled":false,"target_rows_per_fragment":100000,"max_source_rows":1000000,"io_buffer_size":67108864,"batch_size":1024}}}'
|
|
```
|
|
|
|
`set` replaces the whole overrides object. The example assumes no other settings
|
|
need preserving; read the current object and retain unrelated fields when
|
|
editing an existing policy. Use the same namespace and branch for policy reads,
|
|
writes, and compaction submission.
|
|
|
|
Each manual field resolves as **invocation option → table tuning →
|
|
deployment/built-in default**. Automatic jobs resolve **table tuning →
|
|
deployment/built-in default**. The fragment target has a shared deployment
|
|
default. Automatic atomic jobs also use the deployment
|
|
`agent.jobTypes.compaction.atomicMaxSourceRows` when the table has no source-row
|
|
override; manual and deferred-remap jobs do not inherit that agent-only fallback.
|
|
Otherwise, an omitted source-row budget is unbounded. Unset I/O and batch settings
|
|
use the existing Lance/scanner defaults.
|
|
|
|
The table's `enabled` flag controls automatic scheduling and admission. An
|
|
explicit manual job can run while table or deployment automatic compaction is
|
|
disabled. For example, inherit the table's target, source budget, and batch size
|
|
while overriding I/O backpressure for one run:
|
|
|
|
```bash
|
|
lancedb admin table optimize --table events --io-buffer-size 0
|
|
```
|
|
|
|
```sql
|
|
OPTIMIZE events REWRITE DATA WITH (io_buffer_size = 0);
|
|
```
|
|
|
|
Resolved tuning is stored with the durable job. A later table-policy change
|
|
affects future jobs and does not rewrite an existing job's settings. If the
|
|
budget cannot admit the first useful task, automatic preflight reports an error
|
|
without launching a compaction worker. A submitted manual job fails in worker
|
|
planning. Raise the budget to the reported requirement or review a smaller
|
|
fragment target; the target alone does not guarantee that a whole task fits.
|
|
Genuinely empty plans are still skipped by automatic preflight.
|
|
|
|
Successful bounded automatic atomic runs record whether work remains, allowing
|
|
later runs below the normal fragment-count threshold. Run intervals, index
|
|
readiness, refresh, and failure-backoff gates still apply. Failed or timed-out
|
|
attempts retain pending continuation; explicit cancellation clears it. Changing
|
|
the effective source-row budget re-arms automatic failures recorded under a
|
|
different budget; toggling automatic enablement alone does not reset backoff.
|
|
|
|
SDKs forward supplied fields and leave inheritance to the server. An explicitly
|
|
supplied SDK-default fragment target still overrides table tuning. Rust callers
|
|
should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy
|
|
`OptimizeAction::Compact` path treats its default-valued Lance fragment target
|
|
as unspecified because the options type has no presence bit.
|
|
|
|
## Retraining indexes {#retrain}
|
|
|
|
Folding new rows into an index preserves the structure the index was trained on.
|
|
When the data distribution has shifted enough that the index's clusters are a
|
|
poor fit, recreate the index with `replace=True` to train it on the current data.
|
|
The deprecated `retrain` argument to `optimize()` does not rebuild indexes.
|
|
|
|
This example assumes a populated table whose `vector` column has an IVF_FLAT
|
|
index configured for L2 distance and four partitions:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{PyStorageRebuildVectorIndex}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
Use your index's column, type, distance metric, and training settings when
|
|
rebuilding it. Recreating an index is more expensive than a normal optimize,
|
|
and can help after a large ingest that changed the data distribution.
|
|
|
|
## When to run it {#when}
|
|
|
|
In the embedded library there is no background compactor: `optimize()` runs
|
|
when you call it. A deployment compacts a table automatically once enough small
|
|
fragments accumulate, unless its operator turns this off.
|
|
|
|
Frequent small appends are what make it necessary, because each one commits
|
|
files. A table written in a few large batches needs it rarely; one taking
|
|
continuous small writes needs it on a schedule.
|
|
|
|
Opening a table in LanceDB Embedded logs a warning at most once per table per
|
|
process when at least 100 fragments have fewer than 100,000 rows each. Set
|
|
`LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default.
|
|
|
|
<Note>
|
|
Compaction rewrites files, which conflicts with a concurrent
|
|
[computed-column refresh](/feature-engineering/add-computed-column) or
|
|
[view refresh](/feature-engineering/refresh-materialized-view) planned against the
|
|
version it replaces. Sequence them rather than running both at once.
|
|
</Note>
|
|
|
|
See [Garbage Collection](/maintenance/cleanup) for pruning old versions, and
|
|
[Incremental Indexing](/indexing/incremental-indexing) for the index-folding half of
|
|
`optimize()`.
|
|
|
|
## Performance {#performance}
|
|
|
|
Two things accumulate on a long-lived table as more and more data gets added to it:
|
|
|
|
- **Many small fragments build up as you write**, slowing down queries that have to scan across more files. **Compaction** merges them back into larger fragments.
|
|
- **Old versions build up as the table changes**, growing disk usage beyond the live data size (LanceDB retains them for time-travel and rollback). **Cleanup** prunes versions older than a retention window.
|
|
|
|
In LanceDB Embedded, you run them yourself via `optimize()`, which bundles both into a single call:
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
from datetime import timedelta
|
|
table.optimize() # 7-day default retention
|
|
table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner
|
|
```
|
|
</CodeGroup>
|
|
|
|
The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/indexing/incremental-indexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches.
|
|
|
|
{/*
|
|
Draft for the Python compaction_options release. Keep this section unpublished
|
|
until the first supported release is confirmed.
|
|
|
|
### Tune compaction for wide rows {#tune-wide-rows}
|
|
|
|
For an existing LanceDB Embedded table, derive a fragment row target from the expected
|
|
row size. These examples use rows averaging 1 KiB and a 64 KiB fragment
|
|
target; choose sizes for your workload. Smaller scan batches and one compaction
|
|
task at a time can also reduce memory use.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{PyStorageCompactionTuning}
|
|
</CodeBlock>
|
|
<CodeBlock filename="Rust" language="Rust" icon="rust">
|
|
{RsStorageCompactionTuning}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
The Rust example runs compaction only. Run pruning and index optimization
|
|
separately when needed; Python's `optimize()` includes those steps.
|
|
|
|
TypeScript's `optimize()` exposes the fragment row target through
|
|
`compactionOptions.targetRowsPerFragment` and the scanner batch size through
|
|
`compactionOptions.batchSize`. Compaction thread count is not exposed. The tuning
|
|
examples above use Python and Rust tables in LanceDB Embedded.
|
|
|
|
Planning remains row based. The row target bounds later passes after existing
|
|
oversized fragments have been rewritten; the first pass rewrites those
|
|
fragments whole, so peak memory can exceed the target. `max_bytes_per_file`
|
|
limits output file size rather than compaction memory.
|
|
|
|
The `max_source_rows` and `max_source_bytes` budgets admit whole planned tasks.
|
|
If the first task exceeds a budget, that run performs no compaction. See the
|
|
[CompactionOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.CompactionOptions)
|
|
for all options and their limits.
|
|
*/}
|