Skip to main content
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 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.

Optimize an Embedded table

Three operations, in one call: 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.
Enterprise job type: compact. Runs automatically as data accumulates, separately from cleanup. The two are distinct jobs even though optimize() bundles both in one LanceDB Embedded call.

Track on-demand Enterprise compaction

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.
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

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 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.
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.
Submit the same four invocation settings through any of these interfaces:
With the public CLI, execute SQL directly using a profile configured for the same database and Flight SQL endpoint:
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:
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:
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.

Preview and inspect a run

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

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 tuning supports the same four fields under job_types.compaction:
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. The Python, TypeScript, and Rust SDKs can update selected fields while retaining unrelated overrides from the current read snapshot. For an existing Enterprise table handle:
Override keys use the server’s snake_case names in every SDK. These examples retain other compaction settings, such as enabled, and settings for other job types from the read snapshot. An empty update only reads the current overrides; use reset_table_overrides() / resetTableOverrides() to clear all overrides. SDK updates perform GET → recursive merge in the client → full PUT. This read–modify–write is not atomic: concurrent edits can be overwritten, even to unrelated fields. Coordinate override writers when concurrent edits must be preserved. CLI set and REST PUT replace the object without merging. These methods require a compatible Enterprise deployment. For namespaced tables, confirm that the deployment supports table-override reads and resets within namespaces before relying on these APIs. 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:
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

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:
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

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.
Compaction rewrites files, which conflicts with a concurrent computed-column refresh or view refresh planned against the version it replaces. Sequence them rather than running both at once.
See Garbage Collection for pruning old versions, and Incremental Indexing for the index-folding half of optimize().

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:
The best practice is to run optimize() after large writes or on a schedule. It also bundles incremental index updates. See 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.