Route native schema export and Arrow IPC decode failures through the same terminal cleanup as polling, without reopening the reader or repeating release. Add the Table.delta stream example and focused lifecycle tests.
51 KiB
@lancedb/lancedb • Docs
@lancedb/lancedb / Table
Class: abstract Table
A Table is a collection of Records in a LanceDB Database.
A Table object is expected to be long lived and reused for multiple operations.
Table objects will cache a certain amount of index data in memory. This cache
will be freed when the Table is garbage collected. To eagerly free the cache you
can call the close method. Once the Table is closed, it cannot be used for any
further operations.
Tables are created using the methods Connection#createTable and Connection#createEmptyTable. Existing tables are opened using Connection#openTable.
Closing a table is optional. It not closed, it will be closed when it is garbage collected.
Accessors
name
get abstract name(): string
Returns the name of the table
Returns
string
Methods
add()
abstract add(data, options?): Promise<AddResult>
Insert records into this Table.
Parameters
-
data:
DataRecords to be inserted into the Table -
options?:
Partial<AddDataOptions>
Returns
Promise<AddResult>
A promise that resolves to an object containing the new version number of the table
addColumns()
abstract addColumns(newColumnTransforms): Promise<AddColumnsResult>
Add new columns with defined values.
LanceDB Embedded computed-column declaration and refresh require a source
build with the experimental-functions Cargo feature. Published packages
disable it; LanceDB Enterprise operations remain available.
The { computed } form stores the expression rather than evaluating it
now: the column is committed with no values, and rows get them from
Table#refreshColumn. Declaring one therefore costs the same on a
large table as on an empty one.
A refresh also recomputes the rows whose inputs changed since they were computed, so a mutated input is reflected by the next refresh. While a declaration reads a column, that column cannot be renamed, retyped or dropped.
In LanceDB Enterprise the expression is planned by the server, and the refresh runs as a server job -- see Table#refreshColumnAsync.
Parameters
- newColumnTransforms:
|
Field<any> |Field<any>[] |Schema<any> |AddColumnsSql[] |objectEither:- An array of objects with column names and SQL expressions to calculate values
- A single Arrow Field defining one column with its data type (column will be initialized with null values)
- An array of Arrow Fields defining columns with their data types (columns will be initialized with null values)
- An Arrow Schema defining columns with their data types (columns will be initialized with null values)
{ computed }, declaring columns defined by a SQL expression whose type and inputs are derived from it
Returns
Promise<AddColumnsResult>
A promise that resolves to an object containing the new version number of the table after adding the columns.
Example
await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }] });
const { rowsFilled } = await table.refreshColumn("doubled");
alterColumns()
abstract alterColumns(columnAlterations): Promise<AlterColumnsResult>
Alter the name or nullability of columns.
Local tables reject renaming source or vector columns referenced by
embedding_functions schema metadata, preserving the embedding binding.
Parameters
- columnAlterations:
ColumnAlteration[] One or more alterations to apply to columns.
Returns
Promise<AlterColumnsResult>
A promise that resolves to an object containing the new version number of the table after altering the columns.
blobColumns()
abstract blobColumns(): Promise<string[]>
Blob v2 columns addressable by row ID, including struct-nested dotted paths. Blobs inside lists are omitted because a row ID does not identify an element.
Returns
Promise<string[]>
branches()
abstract branches(): Promise<Branches>
Get the branch manager for this table.
Branches are isolated, writable lines of history forked from another
branch (or version). Writes on a branch do not affect main.
Returns
Promise<Branches>
checkout()
abstract checkout(version): Promise<void>
Checks out a specific version of the table This is an in-place operation.
This allows viewing previous versions of the table. If you wish to
keep writing to the dataset starting from an old version, then use
the restore function.
Calling this method will set the table into time-travel mode. If you
wish to return to standard mode, call checkoutLatest.
Parameters
- version:
string|numberThe version to checkout, could be version number or tag
Returns
Promise<void>
Example
import * as lancedb from "@lancedb/lancedb"
const db = await lancedb.connect("./.lancedb");
const table = await db.createTable("my_table", [
{ vector: [1.1, 0.9], type: "vector" },
]);
console.log(await table.version()); // 1
console.log(table.display());
await table.add([{ vector: [0.5, 0.2], type: "vector" }]);
await table.checkout(1);
console.log(await table.version()); // 2
checkoutLatest()
abstract checkoutLatest(): Promise<void>
Checkout the latest version of the table. This is an in-place operation.
The table will be set back into standard mode, and will track the latest version of the table.
Returns
Promise<void>
checkpointRTE()
abstract checkpointRTE(): Promise<void>
Converge this table's RTE write path into its base table.
Freezes once, then triggers compaction and polls until the SSTables that existed at the start is gone. The target set is fixed at the start, so SSTables created during the checkpoint are ignored — that is what lets it terminate under write load, and what makes it best-effort: it converges the fresh tier as of some instant. Idempotent, abandonable at any point, and safe to run on a cadence.
There is no liveness bound — the compactor pool is shared across tables, so a checkpoint queued behind unrelated work looks exactly like one that is merging. The caller owns the deadline.
Returns
Promise<void>
Example
const before = await table.getRTEStats();
await table.checkpointRTE();
const after = await table.getRTEStats();
cleanupAsync()
cleanupAsync(_options?): Promise<Job<CleanupResult>>
Submit durable remote cleanup through SQL VACUUM and return after acceptance. Requires table Ownership and parent Usage. Retention inherits from the table then deployment when omitted. Local/historical handles are unsupported. Before submission, disable/drain automatic cleanup and prevent other cleanup, tag/branch publication and restore until completion, including direct clients. Coordination is not enforced by the server. Cancellation cannot undo deletion or prove storage I/O stopped. Preview is available without deletion. Wait timeout leaves work running; save the ID and reopen with db.openJob().
Parameters
- _options?:
CleanupOptions
Returns
Promise<Job<CleanupResult>>
Example
const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
const result = await job.wait({ timeoutMs: 600000 });
close()
abstract close(): void
Close the table, releasing any underlying resources.
It is safe to call this method multiple times.
Any attempt to use the table after it is closed will result in an error.
Returns
void
closeRTEWriters()
abstract closeRTEWriters(): Promise<void>
Drain and close any cached RTE shard writers held for this table.
When an RTEWriteSpec is installed, mergeInsert opens RTE
shard writers and caches them for reuse across calls. This closes them,
flushing pending data; writers reopen lazily on the next mergeInsert.
It is a no-op when no writers are cached.
Returns
Promise<void>
compactAsync()
compactAsync(_options?): Promise<Job<CompactionResult>>
Submit remote compaction and return its durable job after acceptance.
Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires a compatible remote server and table Ownership plus parent Usage. Local and historical-version handles are unsupported. Existing optimize() behavior is unchanged. Waiting tracks the rewrite itself and returns actual row/file statistics. Missing result payloads are errors; older workers can omit file counts. Status, progress, events and cancellation reuse the generic HTTP job APIs. Reopen with db.openJob(job.id!). A wait timeout does not cancel work.
Parameters
- _options?:
CompactionOptions
Returns
Promise<Job<CompactionResult>>
Example
const job = await table.compactAsync({ targetRowsPerFragment: 1000 });
const result = await job.wait();
console.log(result.rowsSucceeded, result.fragmentsRemoved);
compactRTE()
abstract compactRTE(): Promise<void>
Trigger a background SSTable compaction pass per table shard.
Returns once the passes are dispatched, not once they finish — watch Table#getRTEStats for progress, or use Table#checkpointRTE to wait for convergence.
Returns
Promise<void>
countRows()
abstract countRows(filter?): Promise<number>
Count the total number of rows in the dataset.
Parameters
- filter?:
string
Returns
Promise<number>
createIndex()
abstract createIndex(column, options?): Promise<void>
Create an index to speed up queries.
Indices can be created on vector columns or scalar columns. Indices on vector columns will speed up vector searches. Indices on scalar columns will speed up filtering (in both vector and non-vector searches)
We currently don't support custom named indexes.
The index name will always be ${column}_idx.
On LanceDB Embedded tables the index is built before the returned promise resolves. On LanceDB Enterprise tables it resolves once the build is scheduled. Until the build finishes, a vector index may be missing from Table.listIndices, a scalar or FTS index may be listed with 0 indexed rows, and queries won't use the index. To wait until the index is ready, set IndexOptions.waitTimeoutSeconds, call Table.waitForIndex, or use Table.createIndexAsync and wait on its job when the server returned a job ID.
waitTimeoutSeconds waits for the submitted build when the server returns
a job ID. On older servers that don't return one, it falls back to polling
the index by name. Table.waitForIndex always waits by name. When
replacing an existing index, those name-based waits may return before the
new build finishes because the old index can still match.
createIndexAsync can track a specific build only when the server returned
a job ID; otherwise it returns an already-complete job and callers must
use Table.waitForIndex for that build.
Parameters
-
column:
string -
options?:
Partial<IndexOptions>
Returns
Promise<void>
Examples
// If the column has a vector (fixed size list) data type then
// an IvfPq vector index will be created.
const table = await conn.openTable("my_table");
await table.createIndex("vector");
// For advanced control over vector index creation you can specify
// the index type and options.
const table = await conn.openTable("my_table");
await table.createIndex("vector", {
config: lancedb.Index.ivfPq({
numPartitions: 128,
numSubVectors: 16,
}),
});
// Or size the partitions by row count instead of choosing how many.
await table.createIndex("vector", {
config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }),
});
// Or create a Scalar index
await table.createIndex("my_float_col");
createIndexAsync()
abstract createIndexAsync(column, options?): Promise<Job<void>>
Create an index, returning a handle to the indexing job.
The job may already be complete when returned; callers must not assume the index exists until Job.wait resolves.
In LanceDB Enterprise, the returned job tracks this submission only if the server returns a job ID. If it does not, the job is already complete and does not wait for the background build; use Table.waitForIndex and account for the replacement caveat described in Table.createIndex.
Parameters
-
column:
string -
options?:
Partial<IndexOptions>
Returns
Promise<Job<void>>
currentBranch()
abstract currentBranch(): null | string
The branch this table handle is scoped to, or null for the main branch.
A handle returned by Branches.create or Branches.checkout
reports the branch it targets; a handle opened normally reports null.
Returns
null | string
delete()
abstract delete(predicate): Promise<DeleteResult>
Delete the rows that satisfy the predicate.
Parameters
- predicate:
string
Returns
Promise<DeleteResult>
A promise that resolves to an object containing the new version number of the table
delta()
delta(fromVersion, toVersion?): Promise<TableDelta>
Compare two persisted versions or same-branch tags on an Embedded table.
fromVersion is exclusive and toVersion is inclusive. Omitting
toVersion uses the version currently visible through this handle,
including a checked-out version. The endpoints are fixed when the delta is
created.
Row readers require stable row IDs at both endpoints. Create the table with
storageOptions: { new_table_enable_stable_row_ids: "true" } to enable
them. listTransactions() works without stable row IDs.
Row readers reject ranges containing a Restore, or ranges whose transaction history cannot prove they are restore-free. Recompute the checkpoint with a full rescan and reinitialize it at the range end version.
LanceDB Enterprise tables reject this operation.
Parameters
-
fromVersion:
DeltaVersion -
toVersion?:
DeltaVersion
Returns
Promise<TableDelta>
Example
const delta = await table.delta("baseline");
const reader = delta.insertedRows();
console.log((await reader.schema()).fields.map((field) => field.name));
for await (const batch of reader) {
console.log(batch.getChild("id")?.toJSON());
}
console.log(await delta.listTransactions());
disableRTE()
abstract disableRTE(): Promise<void>
Remove the RTEWriteSpec from this table, reverting to the standard
mergeInsert write path.
Errors if no spec is currently set.
Returns
Promise<void>
display()
abstract display(): string
Return a brief description of the table
Returns
string
dropColumns()
abstract dropColumns(columnNames): Promise<DropColumnsResult>
Drop one or more columns from the dataset
This is a metadata-only operation and does not remove the data from the
underlying storage. In order to remove the data, you must subsequently
call compact_files to rewrite the data without the removed columns and
then call cleanup_files to remove the old files.
Local tables reject dropping source or vector columns referenced by
embedding_functions schema metadata, preserving the embedding binding.
Parameters
- columnNames:
string[] The names of the columns to drop. These can be nested column references (e.g. "a.b.c") or top-level column names (e.g. "a").
Returns
Promise<DropColumnsResult>
A promise that resolves to an object containing the new version number of the table after dropping the columns.
dropIndex()
abstract dropIndex(name): Promise<void>
Drop an index from the table.
Parameters
- name:
stringThe name of the index. This does not delete the index from disk, it just removes it from the table. To delete the index, run Table#optimize after dropping the index. Use Table.listIndices to find the names of the indices.
Returns
Promise<void>
enableRTE()
abstract enableRTE(spec): Promise<void>
Install an RTEWriteSpec on this table, selecting Lance's MemWAL
LSM-style write path for future mergeInsert calls.
RTEWriteSpec chooses one of three sharding strategies via specType:
"bucket"— hash-bucket writes by the single-column unenforced primary key (columnandnumBucketsrequired)."identity"— shard by the raw value of a scalarcolumn."unsharded"— route every write to a single shard.
All variants require the table to have an unenforced primary key (Table#setUnenforcedPrimaryKey); bucket sharding additionally requires it to be the single column being bucketed.
Omitting maintainedIndexes maintains every index the table has,
including ones created later, and skips a kind the RTE cannot maintain.
Naming them pins an exact set, and a still-building index is rejected
rather than quietly omitted.
Parameters
- spec:
RTEWriteSpecThe sharding spec to install.
Returns
Promise<void>
Example
await table.setUnenforcedPrimaryKey("id");
await table.enableRTE({
specType: "bucket",
column: "id",
numBuckets: 16,
maintainedIndexes: ["id_idx"],
});
explainCleanup()
explainCleanup(_options?): Promise<CleanupPlan>
Preview version deletion without creating a job. Execution re-evaluates current state.
Parameters
- _options?:
CleanupOptions
Returns
Promise<CleanupPlan>
explainPrewarmData()
explainPrewarmData(_options?): Promise<PrewarmDataPlan>
Preview prewarm with the same options as prewarmDataAsync, without submitting a warming job. Requires LanceDB Enterprise with structured SQL previews, table Select and database/namespace Usage. Reads metadata and returns the source version, readable plan, and conservative pruning summary. A later submission plans its own snapshot. Historical and Embedded handles are unsupported. Unknown measurements remain null. Custom table implementations can override this method; its default rejects with an unsupported-operation error.
Parameters
- _options?:
PrewarmDataOptions
Returns
Promise<PrewarmDataPlan>
Example
const plan = await table.explainPrewarmData({
columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7},
});
console.log(plan.pruning.selectedFragments);
fetchBlobFiles()
abstract fetchBlobFiles(
column,
rowIds,
options?): Promise<(null | BlobFile)[]>
Opens lazy blob handles for column at the given row IDs using the
table's current checkout.
Preserves input order, duplicates, and nulls. Use this for large payloads. See Table.fetchBlobs for row-ID validity across versions. One missing or deleted row ID rejects the entire batch, including on remote tables; no partial handles are returned.
Parameters
-
column:
string -
rowIds: readonly (
number|bigint)[] -
options?:
BlobReadOptions
Returns
Promise<(null | BlobFile)[]>
fetchBlobRanges()
abstract fetchBlobRanges(
column,
requests,
options?): Promise<(null | Buffer)[]>
Materializes row-specific byte ranges at the table's current checkout. Preserves request order, duplicates, and nulls. Zero length returns an empty buffer for a non-null blob. Invalid ranges or missing rows reject the entire call. See Table.fetchBlobs for row-ID validity across versions.
Remote tables use the batched endpoint when the server advertises support, splitting at 1024 ranges and 64 MiB, including individual larger ranges. Older servers use descriptor queries and BlobFile range reads. Both protocols use one exact branch and version. Errors from an advertised endpoint propagate without switching protocols. All output bytes occupy memory.
Parameters
-
column:
string -
requests: readonly
BlobRangeRequest[] -
options?:
BlobReadOptions
Returns
Promise<(null | Buffer)[]>
Example
const bytes = await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1024n },
]);
fetchBlobs()
abstract fetchBlobs(
column,
rowIds,
options?): Promise<(null | Buffer)[]>
Bytes for column at row IDs from Query.withRowId.
Reads the table's current checkout. IDs from another version can fail after
compaction unless stable row ids are enabled. Results keep input order and
duplicates. Null blobs are null. Empty blobs are empty buffers.
One missing or deleted row ID rejects the entire batch, including on remote
tables; no partial results are returned.
Blobs inside lists cannot be fetched by row ID.
Remote servers limit each request to 1024 row IDs and 64 MiB of blob bytes. The client splits requests automatically and reads an individual larger blob through the Range route. This method still materializes all bytes in memory; use Table.fetchBlobFiles for large values.
Parameters
-
column:
string -
rowIds: readonly (
number|bigint)[] -
options?:
BlobReadOptions
Returns
Promise<(null | Buffer)[]>
flushRTE()
abstract flushRTE(): Promise<void>
Freeze every table shard's active memtable into a new SSTable.
Returns once the freeze is committed. Freezing an empty memtable is a no-op, so this is safe to call repeatedly.
Returns
Promise<void>
functionColumnStatus()
abstract functionColumnStatus(column): Promise<FunctionColumnStatus>
Return exact freshness status for one Function-backed output column.
Parameters
- column:
string
Returns
Promise<FunctionColumnStatus>
functionColumnStatuses()
abstract functionColumnStatuses(column?): Promise<FunctionColumnStatus[]>
Return exact freshness status for Function-backed output columns.
All results describe one server table version. Omit column for every
Function output. Rows already failed remain visible and do not prevent
waitFresh from completing. A handle pinned to an exact version requests
that version; a latest handle retains normal read-freshness behavior.
Parameters
- column?:
string
Returns
Promise<FunctionColumnStatus[]>
functionErrors()
abstract functionErrors(options?): Promise<FunctionErrors>
The per-row errors Function refreshes recorded on this table.
A refresh running under a skip policy records each row it skipped with the input that failed and the error. This lists those records, newest job first, plus a summary for any fragment whose per-row detail was capped. LanceDB Enterprise only; reading errors needs read access to the table, since a message carries the value that failed.
Parameters
- options?:
FunctionErrorsOptionsOptional filters:jobId,column, andlimit(server default 10000, cap 100000).
Returns
Promise<FunctionErrors>
The records, the capped fragments, and whether the listing stopped at its limit.
Example
const { records, truncated } = await table.functionErrors({ column: "embedding" });
getRTESpec()
abstract getRTESpec(): Promise<undefined | RTEWriteSpec>
Read the RTEWriteSpec currently installed on this table.
Resolves to undefined when the RTE write path is not enabled (no
spec has been set, or it was removed with Table#disableRTE).
The spec is the one installed, including its maintained-index selection:
an absent maintainedIndexes for every index the table has, an empty
array for none.
Returns
Promise<undefined | RTEWriteSpec>
getRTEStats()
abstract getRTEStats(includeSstableRows?): Promise<undefined | RTEStats>
Read live per-table-shard RTE state.
Answers "how far behind is my fresh tier", "which table shard is hot", and "why is my fresh-tier vector search brute-force". Mutates no table state.
Resolves to undefined only when the RTE write path is not enabled.
Parameters
- includeSstableRows?:
booleanAlso count rows per SSTable. Off by default because each count opens an uncached Lance dataset.
Returns
Promise<undefined | RTEStats>
getTableOverrides()
getTableOverrides(): Promise<Record<string, unknown>>
Read the stored overrides for a remote Enterprise table.
Overrides configure background behavior such as automatic compaction, cleanup, and reindex execution. Keys use the server's snake_case names. Returns an empty object when no overrides are set. Local tables are unsupported. Custom table implementations inherit a default rejection unless they override this method.
Returns
Promise<Record<string, unknown>>
indexStats()
abstract indexStats(name): Promise<undefined | IndexStatistics>
List all the stats of a specified index
Parameters
- name:
stringThe name of the index.
Returns
Promise<undefined | IndexStatistics>
The stats of the index. If the index does not exist, it will return undefined
Use Table.listIndices to find the names of the indices.
initialStorageOptions()
abstract initialStorageOptions(): Promise<undefined | null | Record<string, string>>
Get the initial storage options that were passed in when opening this table.
For dynamically refreshed options (e.g., credential vending), use Table.latestStorageOptions.
Warning: This is an internal API and the return value is subject to change.
Returns
Promise<undefined | null | Record<string, string>>
The storage options, or undefined if no storage options were configured.
isOpen()
abstract isOpen(): boolean
Return true if the table has not been closed
Returns
boolean
latestStorageOptions()
abstract latestStorageOptions(): Promise<undefined | null | Record<string, string>>
Get the latest storage options, refreshing from provider if configured.
This method is useful for credential vending scenarios where storage options may be refreshed dynamically. If no dynamic provider is configured, this returns the initial static options.
Warning: This is an internal API and the return value is subject to change.
Returns
Promise<undefined | null | Record<string, string>>
The storage options, or undefined if no storage options were configured.
listIndices()
abstract listIndices(): Promise<IndexConfig[]>
List all indices that have been created with Table.createIndex
On LanceDB Enterprise tables, an index whose build hasn't finished may be
missing (vector indices) or listed with 0 indexed rows (scalar and FTS
indices), and numUnindexedRows may be undefined. Use
Table.waitForIndex to wait until an index is ready.
Returns
Promise<IndexConfig[]>
listVersions()
abstract listVersions(): Promise<Version[]>
List all the versions of the table
Returns
Promise<Version[]>
mergeInsert()
abstract mergeInsert(on): MergeInsertBuilder
Create a MergeInsertBuilder, which combines new data with the existing table in a single transaction — inserting, updating and deleting rows depending on how they match.
Parameters
- on:
string|string[] The column, or columns, to match source rows against target rows on. Typically a key or id column. Several columns match on the composite key: a source row updates a target row only when it agrees on every one of them.
Returns
optimize()
abstract optimize(options?): Promise<OptimizeStats>
Optimize the on-disk data and indices for better performance.
Modeled after VACUUM in PostgreSQL.
Optimization covers three operations:
- Compaction: Merges small files into larger ones
- Prune: Removes old versions of the dataset
- Index: Optimizes the indices, adding new data to existing indices
The frequency an application should call optimize is based on the frequency of data modifications. If data is frequently added, deleted, or updated then optimize should be run frequently. A good rule of thumb is to run optimize if you have added or modified 100,000 or more records or run more than 20 data modification operations.
On a LanceDB Enterprise (remote) table, only compaction is currently
supported. Pruning old versions and index optimization are silently
skipped there instead of being attempted, so this call resolves
successfully, with zeroed pruning statistics, once the compaction job
has been submitted; it does not wait for that job to finish.
compactionOptions can tune the four per-job settings documented in
CompactionOptions. Older-server errors are propagated without
retrying with the settings removed.
Parameters
- options?:
Partial<OptimizeOptions>
Returns
Promise<OptimizeStats>
prewarmData()
prewarmData(options)
abstract prewarmData(options?): Promise<void>
Prewarm one or more columns of data in the table.
This will load the column data into the page cache so that future queries that read those columns avoid the initial cold-start latency. This call initiates prewarming and returns once the request is accepted; the warming itself may continue in the background. Submission uses SQL PREWARM and needs Flight SQL connectivity. Use prewarmDataAsync to retain the job handle.
Prewarming is generally useful for columns used in filters or projections. Large columns (e.g. high-dimensional vectors or binary data) may not be practical to prewarm.
This feature is currently only supported in LanceDB Enterprise.
Parameters
- options?:
PrewarmDataOptionsColumns, a metadata-pruning filter, and per-executor concurrency. Omitted or empty columns warm every column.
Returns
Promise<void>
Example
await table.prewarmData({
columns: ["payload"], filter: "quality > 0.7", concurrency: 4,
});
prewarmData(columns)
abstract prewarmData(columns?): Promise<void>
Submit data prewarm using the columns-array form and return after acceptance.
Parameters
- columns?:
string[] Columns to warm; omitted or empty means every column.
Returns
Promise<void>
prewarmDataAsync()
abstract prewarmDataAsync(options?): Promise<Job<PrewarmDataResult>>
Submit data prewarm through SQL and return its durable warming-job handle.
The table handle supplies the branch and namespace. Requires a compatible
SQL PREWARM server and Flight SQL connectivity. Standard authorization
requires table Select and database/namespace Usage. Status/wait use generic
HTTP job APIs; events and cancellation retain their own privileges.
No REST fallback or option-dropping retry is performed. Historical-version
handles are unsupported; call checkoutLatest() first.
Submission returns after acceptance. Use job.wait() for completion, or
save job.id and reopen it with db.openJob(id). A timeout does not cancel
the job. After job.refresh(), job.spec.table_version is the pinned version.
Parameters
- options?:
PrewarmDataOptions
Returns
Promise<Job<PrewarmDataResult>>
Example
const job = await table.prewarmDataAsync({
columns: ["video"], filter: "quality > $minimum",
parameters: { minimum: 0.7 }, concurrency: 4,
});
await job.wait();
prewarmIndex()
abstract prewarmIndex(name): Promise<void>
Prewarm an index in the table.
Parameters
- name:
stringThe name of the index. This will load the index into memory. This may reduce the cold-start time for future queries. If the index does not fit in the cache then this call may be wasteful.
Returns
Promise<void>
query()
abstract query(): Query
Create a Query Builder.
Queries allow you to search your existing data. By default the query will return all the data in the table in no particular order. The builder returned by this method can be used to control the query using filtering, vector similarity, sorting, and more.
Note: By default, all columns are returned. For best performance, you should only fetch the columns you need.
When appropriate, various indices and statistics based pruning will be used to accelerate the query.
Returns
A builder that can be used to parameterize the query
Examples
// SQL-style filtering
//
// This query will return up to 1000 rows whose value in the `id` column
// is greater than 5. LanceDb supports a broad set of filtering functions.
for await (const batch of table
.query()
.where("id > 1")
.select(["id"])
.limit(20)) {
console.log(batch);
}
// Vector Similarity Search
//
// This example will find the 10 rows whose value in the "vector" column are
// closest to the query vector [1.0, 2.0, 3.0]. If an index has been created
// on the "vector" column then this will perform an ANN search.
//
// The `refineFactor` and `nprobes` methods are used to control the recall /
// latency tradeoff of the search.
for await (const batch of table
.query()
.where("id > 1")
.select(["id"])
.limit(20)) {
console.log(batch);
}
// Scan the full dataset
//
// This query will return everything in the table in no particular order.
for await (const batch of table.query()) {
console.log(batch);
}
refreshColumn()
abstract refreshColumn(column, options?): Promise<RefreshColumnResult>
Fill the rows of a computed column that hold no value yet.
Local refresh requires a source build with experimental-functions.
Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. LanceDB Embedded only: in LanceDB Enterprise a refresh runs as a server job, through Table#refreshColumnAsync.
Parameters
-
column:
stringThe name of the computed column to fill. -
options?:
RefreshColumnOptionsRefresh options, all LanceDB Enterprise only; see Table#refreshColumnAsync.
Returns
Promise<RefreshColumnResult>
A promise that resolves to the number of rows filled and the new version number of the table.
refreshColumnAsync()
abstract refreshColumnAsync(column, options?): Promise<Job<void>>
Like Table#refreshColumn, but returns a handle to the refresh
job instead of blocking until it completes.
LanceDB Embedded refresh requires a source build with
experimental-functions. LanceDB Enterprise jobs do not require this
feature.
The job may already be complete when returned; callers must not assume the column is filled until Job.wait resolves. Invalid input -- an unknown column, or one that is not computed -- rejects here rather than failing the job. In LanceDB Embedded the job runs in-process; in LanceDB Enterprise it is the server's backfill job.
Parameters
-
column:
stringThe name of the computed column to fill. -
options?:
RefreshColumnOptionsRefresh options, mirroring the SQLREFRESH COLUMN ... WHERE ... WITH (...)form:wherenarrows the rows,errorPolicy,maxFailedFraction,maxFailedRows,rowTimeoutSecondsandinitTimeoutSecondsgovern failing rows.batchSize,gpuClass,maxConcurrency,resourceBudget,supervisorResources,planningWorkersandmaxExecutorProcessesPerWorkersize registered Function refreshes.retryPolicyoverrides user-code retries only when repeating partial work is safe; setmaxAttempts: 1to disable retries.maxConcurrencyoverrides the registered default for this logical execution only and is a positive integer; it is not an account-wide quota. AresourceBudgetrequirescpuMillisandmemoryBytes; itsgpuCountdefaults to zero for a CPU-only Function.supervisorResourcesand eachplanningWorkers.resourcesentry require positivecpuMillis,memoryBytesandephemeralStorageBytes.planningWorkersalso requires positivemaxWorkers,rowsPerWorkerandfragmentsPerWorker. The budget applies only to this explicit refresh and does not configure a later automatic refresh.gpuCountat the top level is the shorthand that preserves the deployment defaults for CPU and memory, and cannot be combined withresourceBudget.numWorkersapplies only to expression columns; useresourceBudgetfor registered Functions. All are LanceDB Enterprise only; a LanceDB Embedded refresh rejects every option other thanbatchSize,gpuClassandgpuCount.publicationIntervalRowsopts into publishing completed Function split ranges once their accumulated unpublished rows reach the threshold. It must be a positive safe integer and requires non-Blob Function outputs. Omit it for whole-fragment publication. Publications can exceed the threshold, and remaining rows publish at completion.
Returns
Promise<Job<void>>
Example
const job = await table.refreshColumnAsync("embedding", {
where: "published_at > '2026-01-01'",
resourceBudget: {
cpuMillis: 8000,
memoryBytes: 16 * 1024 ** 3,
},
maxConcurrency: 4,
publicationIntervalRows: 10000,
errorPolicy: "skip",
maxFailedFraction: 0.01,
rowTimeoutSeconds: 30,
});
await job.wait();
console.log(await job.status()); // "finished"
resetTableOverrides()
resetTableOverrides(): Promise<Record<string, unknown>>
Clear a remote Enterprise table's overrides and return an empty object. Local tables and custom table implementations without override support reject this operation.
Returns
Promise<Record<string, unknown>>
restore()
abstract restore(): Promise<void>
Restore the table to the currently checked out version
This operation will fail if checkout has not been called previously
This operation will overwrite the latest version of the table with a previous version. Any changes made since the checked out version will no longer be visible.
Once the operation concludes the table will no longer be in a checked out state and the read_consistency_interval, if any, will apply.
Returns
Promise<void>
schema()
abstract schema(): Promise<Schema<any>>
Get the schema of the table.
Returns
Promise<Schema<any>>
search()
abstract search(
query,
queryType?,
ftsColumns?): Query | VectorQuery | AutoQuery
Create a search query to find the nearest neighbors of the given query
Parameters
-
query:
string|IntoVector|MultiVector|FullTextQuerythe query, a vector or string -
queryType?:
stringthe type of the query, "vector", "fts", or "auto" -
ftsColumns?:
string|string[] the columns to search in for full text search for now, only one column can be searched at a time. when "auto" is used, if the query is a string and an embedding function is defined, it will be treated as a vector query if the query is a string and no embedding function is defined, it will be treated as a full text search query
Returns
Query | VectorQuery | AutoQuery
setUnenforcedPrimaryKey()
abstract setUnenforcedPrimaryKey(columns): Promise<void>
Set the unenforced primary key for this table to a single column.
"Unenforced" means LanceDB does not check uniqueness on writes; the
column is recorded in the schema as the primary key for use by features
such as merge_insert. Only single-column primary keys are supported,
and the key cannot be changed once set.
Parameters
- columns:
string|string[] The primary key column. A one-element array is also accepted; passing more than one column is rejected.
Returns
Promise<void>
stats()
abstract stats(): Promise<TableStatistics>
Returns table and fragment statistics
Returns
Promise<TableStatistics>
The table and fragment statistics
tags()
abstract tags(): Promise<Tags>
Get a tags manager for this table.
Tags allow you to label specific versions of a table with a human-readable name. The returned tags manager can be used to list, create, update, or delete tags.
Returns
Promise<Tags>
A tags manager for this table
Example
const tagsManager = await table.tags();
await tagsManager.create("v1", 1);
const tags = await tagsManager.list();
console.log(tags); // { "v1": { version: 1, manifestSize: ... } }
takeOffsets()
abstract takeOffsets(offsets): TakeQuery
Create a query that returns a subset of the rows in the table.
Parameters
- offsets:
number[] The offsets of the rows to return.
Returns
A builder that can be used to parameterize the query.
takeRowIds()
abstract takeRowIds(rowIds): TakeQuery
Create a query that returns a subset of the rows in the table.
Parameters
- rowIds: readonly (
number|bigint)[] The row ids of the rows to return. Row ids returned bywithRowId()arebigint, sobigint[]is supported. For convenience / backwards compatibility,number[]is also accepted (for small row ids that fit in a safe integer).
Returns
A builder that can be used to parameterize the query.
toArrow()
abstract toArrow(): Promise<Table<any>>
Return the table as an arrow table
Returns
Promise<Table<any>>
tokenize()
abstract tokenize(query, options): Promise<FtsToken[]>
Tokenize a full-text search query using the tokenizer configured on an FTS index.
Specify exactly one of column or indexName.
Model-backed tokenizers such as jieba/* and lindera/* are rebuilt in
the client process from index metadata. In LanceDB Enterprise, this means the
same tokenizer model files must also exist locally (under
LANCE_LANGUAGE_MODEL_HOME) and must match the files the server uses. A
mismatch cannot be detected: the returned tokens may differ from what the
server's index produces. If the model files are missing, an error naming
the tokenizer is raised.
Parameters
-
query:
string -
options:
TokenizeTableOptions
Returns
Promise<FtsToken[]>
update()
update(opts)
abstract update(opts): Promise<UpdateResult>
Update existing records in the Table
Parameters
- opts:
object&Partial<UpdateOptions>
Returns
Promise<UpdateResult>
A promise that resolves to an object containing the number of rows updated and the new version number
Example
table.update({where:"x = 2", values:{"vector": [10, 10]}})
update(opts)
abstract update(opts): Promise<UpdateResult>
Update existing records in the Table
Parameters
- opts:
object&Partial<UpdateOptions>
Returns
Promise<UpdateResult>
A promise that resolves to an object containing the number of rows updated and the new version number
Example
table.update({where:"x = 2", valuesSql:{"x": "x + 1"}})
update(updates, options)
abstract update(updates, options?): Promise<UpdateResult>
Update existing records in the Table
An update operation can be used to adjust existing values. Use the returned builder to specify which columns to update. The new value can be a literal value (e.g. replacing nulls with some default value) or an expression applied to the old value (e.g. incrementing a value)
An optional condition can be specified (e.g. "only update if the old value is 0")
Note: if your condition is something like "some_id_column == 7" and
you are updating many rows (with different ids) then you will get
better performance with a single [merge_insert] call instead of
repeatedly calling this method.
Parameters
-
updates:
Map<string,string> |Record<string,string> the columns to update -
options?:
Partial<UpdateOptions> additional options to control the update behavior
Returns
Promise<UpdateResult>
A promise that resolves to an object containing the number of rows updated and the new version number
Keys in the map should specify the name of the column to update. Values in the map provide the new value of the column. These can be SQL literal strings (e.g. "7" or "'foo'") or they can be expressions based on the row being updated (e.g. "my_col + 1")
updateFieldMetadata()
abstract updateFieldMetadata(updates): Promise<UpdateFieldMetadataResult>
Update per-field (column) metadata.
The following keys are treated specially, by convention, and should be used when appropriate:
lancedb:description: for a human-readable description of a field.lancedb:tag:<name>: for a user-defined key-value tag, where the suffix names the tag category; e.g.lancedb:tag:model: "clip".lancedb:status: for status options (production,candidate,deprecated,archived) to designate the current life cycle state of this column.
Parameters
- updates:
FieldMetadataUpdate[] One or more per-field updates. Each update's metadata is merged into the field's existing metadata by default; a value ofnulldeletes that key, andreplace: trueswaps the whole map.
Returns
Promise<UpdateFieldMetadataResult>
resolves to the new table version.
updateTableOverrides()
updateTableOverrides(overrides): Promise<Record<string, unknown>>
Recursively merge overrides into a remote Enterprise table's stored overrides.
Fetches the current overrides, merges nested objects locally, then sends the complete replacement using REST PUT. Other values replace existing values; unrelated fields from the read snapshot are preserved. This read-modify-write is not atomic: concurrent edits can be overwritten, even to unrelated fields. Coordinate writers when concurrent edits must be preserved. An empty update only reads and returns the current overrides.
Unlike this SDK method, CLI set and REST PUT replace the overrides object
without merging. Use Table.resetTableOverrides to clear all overrides.
Local tables and custom table implementations without override support reject
this operation.
Parameters
- overrides:
Record<string,unknown>
Returns
Promise<Record<string, unknown>>
Example
await table.updateTableOverrides({
job_types: { compaction: { enabled: false } },
});
vectorSearch()
abstract vectorSearch(vector): VectorQuery
Search the table with a given query vector.
This is a convenience method for preparing a vector query and
is the same thing as calling nearestTo on the builder returned
by query.
Parameters
- vector:
IntoVector|MultiVector
Returns
See
Query#nearestTo for more details.
version()
abstract version(): Promise<number>
Retrieve the version of the table
Returns
Promise<number>
waitForIndex()
abstract waitForIndex(indexNames, timeoutSeconds): Promise<void>
Waits for asynchronous indexing to complete on the table.
Parameters
-
indexNames:
string[] The name of the indices to wait for -
timeoutSeconds:
numberThe number of seconds to wait before timing out This will raise an error if the indices are not created and fully indexed within the timeout.
Returns
Promise<void>
waitFresh()
abstract waitFresh(column, timeoutSeconds?): Promise<FunctionColumnStatus>
Poll until no stale or never-computed rows remain.
Only HTTP 503 with the exact finalization-pending error code is retried; every other error propagates. Failed rows do not block completion.
Parameters
-
column:
string -
timeoutSeconds?:
number
Returns
Promise<FunctionColumnStatus>