# About this version Source: https://docs.lancedb.com/enterprise/v1-12-0/about-this-version The release and sources of the LanceDB Enterprise 1.12.0 documentation. These pages document LanceDB Enterprise 1.12.0. They were saved from the sources below when this edition was prepared. * **Release:** LanceDB Enterprise 1.12.0, a qualified release * **REST API specification:** `lance-format/lance-namespace` `v0.13.0` An Enterprise release bundles a particular LanceDB, which can be older than the newest LanceDB Embedded release. The pages it shares with LanceDB Embedded can then differ from the newest LanceDB Embedded documentation. # Agentic skills Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/agentic-skills Give a coding agent a current, maintained reference for the LanceDB APIs. A coding agent writing LanceDB code from memory writes whatever was in its training data: often an older API, sometimes one that never existed. The LanceDB agent plugin fixes that by supplying the current reference at the point the agent needs it. ## The plugin It ships as the `lancedb` plugin in the [lancedb-agent-plugins](https://github.com/lancedb/lancedb-agent-plugins) repository, which is also a plugin marketplace. Install it with your agent's plugin manager: ```text Claude Code theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} /plugin marketplace add lancedb/lancedb-agent-plugins /plugin install lancedb@lancedb ``` ```bash Codex icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} codex plugin marketplace add lancedb/lancedb-agent-plugins codex plugin add lancedb@lancedb ``` ```bash Other agents icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx plugins add lancedb/lancedb-agent-plugins ``` The [`plugins`](https://www.npmjs.com/package/plugins) installer shown under **Other agents** is a cross-tool option. It detects which agent CLIs are on your `PATH` (Cursor, GitHub Copilot CLI, VS Code, Grok Build, and Kimi Code, as well as Claude Code and Codex) and installs through each one's native plugin system. The plugin supplements the agent's training data with current LanceDB instructions. To pick up later revisions, refresh the marketplace: ```text Claude Code theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} /plugin marketplace update lancedb ``` ```bash Codex icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} codex plugin marketplace upgrade ``` ```bash Other agents icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx plugins add lancedb/lancedb-agent-plugins ``` > [accordion] Where the plugin gets installed > > Each plugin manager clones the repository, reads its marketplace manifest to find > the `lancedb` plugin, and hands the plugin to the agent's own plugin store rather > than copying files into your project. Claude Code and Codex keep it under > `~/.claude/plugins` and `~/.codex/plugins` respectively, so the plugin is available > in every project on the machine. > > The `npx plugins` installer defaults to the same user-wide scope. Pass > `--scope project` to record the plugin in the current repository instead, so that > everyone working in it gets the same plugin, or `-t ` to install for a > single agent rather than every one it detects: > > ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > npx plugins add lancedb/lancedb-agent-plugins --scope project -t cursor > ``` > > Not every agent supports project scope; `npx plugins targets` lists what it > found and what each target supports. ## Automated prompt catalog Explore the prompts covered by automated agent evaluations. Each prompt uses example data and may require existing tables, indexes, metadata, branches, version history, or running jobs. Replace the test fixtures and connection details with your own before using a prompt. The evaluations run against a LanceDB Enterprise test database, with and without the agent plugin. Evaluation coverage does not guarantee success for every agent or model. Prompts are reproduced verbatim, including the answer formats used by automated grading. Table names, local files, and placeholders in these prompts refer to test fixtures. Supply your own data, database connection, and timestamps when adapting them. 66 prompts. ### Tables and schema design > [accordion] 101: list tables by prefix > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Some tables in this database came from a legacy load and are named with the prefix `eval_lt_`. Find every table whose name starts with `eval_lt_` and report them. This is a read-only check. End your answer with one line per table, each of exactly this form: > > TABLE: > ``` > [accordion] 102: describe table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Give me an overview of the `eval_describe` table: its columns with their types, and how many rows it holds. This is a read-only check — do not modify anything. End your answer with one line per column, then two final lines, of exactly these forms. Write each `` exactly as the API reports it, not as a synonym; for a nested type, write the outer type name with its element type and length in angle brackets (a 4-element vector of 8-bit ints would read `fixed_size_list`): > > COLUMN: = > ROWS: > COLUMNS: > ``` > [accordion] 103: table storage stats > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How is the `eval_table_stats` table laid out in storage? Report its total size on disk and its fragment layout. This is a read-only check. End your answer with two lines of exactly this form: > > BYTES: > FRAGMENTS: > ``` > [accordion] 104: create table with data > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a new table called `eval_created_products` in this database with three columns: `sku` (string), `name` (string), and `price` (float64). Populate it with exactly these 4 rows: > > | sku | name | price | > |---------|------------------|--------| > | SKU-001 | Espresso Machine | 249.99 | > | SKU-002 | Milk Frother | 39.5 | > | SKU-003 | Coffee Grinder | 89.0 | > | SKU-004 | Digital Scale | 24.95 | > ``` > [accordion] 105: create empty table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a new, empty table called `eval_empty_events` in this database, ready for an event-logging pipeline to start writing into later. It needs three columns: `event_name` (string), `severity` (int64), and `payload` (string) — and no rows yet. > ``` > [accordion] 107: drop table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_drop_me` table was created by a test run and is no longer needed. Drop it from the database — and nothing else. > ``` > [accordion] 108: design tables from joined schema > > ````text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > My current DB has these 5 tables that join; how should I set up my tables in LanceDB? > > ``` > products (product_id BIGINT PK, name TEXT, description TEXT, price NUMERIC(10,2), category_id BIGINT FK, brand_id BIGINT FK) > categories (category_id BIGINT PK, name TEXT) > brands (brand_id BIGINT PK, name TEXT, country TEXT) > reviews (review_id BIGINT PK, product_id BIGINT FK, rating SMALLINT, body TEXT) > order_items (order_id BIGINT, product_id BIGINT FK, quantity INT, unit_price NUMERIC(10,2)) > ``` > > In LanceDB the app will run one query: semantic search over product descriptions, filtered by category name and brand name, where every hit shows the product's name, price, category name, brand name, and average review rating. Order analytics stays in our warehouse. Description embeddings are 384-dimensional float32 vectors. > > Set the tables up in this database as you recommend: create them empty (schema only, no rows). Name the table the product search runs against `eval_schema_search`, and give any other table you create the `eval_schema_` prefix. Explain your design in your answer. > ```` ### Data ingestion and updates > [accordion] 201: insert rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Append these 5 new products to the `eval_insert_rows` table (the embedding columns can be left null): > > | id | title | category | price_usd | relevance_score | > |-----|--------------|-----------|-----------|-----------------| > | 100 | Clearance A | clearance | 9.99 | 0.1 | > | 101 | Clearance B | clearance | 10.99 | 0.1 | > | 102 | Clearance C | clearance | 11.99 | 0.1 | > | 103 | Clearance D | clearance | 12.99 | 0.1 | > | 104 | Clearance E | clearance | 13.99 | 0.1 | > ``` > [accordion] 202: delete rows by filter > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > All 'toys' products have been discontinued. Delete every row in category `toys` from the `eval_delete_rows` table — and nothing else. > ``` > [accordion] 203: delete all rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_purge` table was loaded from a corrupted export and every row in it is suspect. Clear out all of its rows — but keep the table itself (and its schema) in place so it can be reloaded. > ``` > [accordion] 204: update rows by filter > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Editorial flagged every 'books' product in the `eval_update_rows` table for re-review: set `relevance_score` to 0 for all rows in category `books`. Don't touch any other rows. > ``` > [accordion] 205: update with expression > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Run a flash sale on the `eval_discount` table: cut the price of every product in category `electronics` by 10% — each one's `price_usd` becomes 90% of its current value. Leave every other category's prices alone. > ``` > [accordion] 206: upsert rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Sync the `eval_upsert` table with this batch of refurbished products, matching on `id`: update the row if the id already exists, insert it if not — as one upsert operation, not separate update and insert passes. The embedding columns can be left null. > > | id | title | category | price_usd | relevance_score | > |-----|-----------------------|----------|-----------|-----------------| > | 2 | Refurbished Product 2 | refurb | 19.99 | 0.5 | > | 6 | Refurbished Product 6 | refurb | 29.99 | 0.5 | > | 200 | Refurb Special A | refurb | 15.0 | 0.5 | > | 201 | Refurb Special B | refurb | 18.0 | 0.5 | > ``` > [accordion] 207: add column backfill > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Analytics needs integer cents. Add a `price_cents` integer column to the `eval_add_column` table, backfilled for every existing row as the price in cents (`price_usd` × 100, rounded to the nearest integer). > ``` > [accordion] 208: rename column > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Rename the `price_usd` column of the `eval_rename_column` table to `price`, in place, keeping the data — do not rebuild or rewrite the table. > ``` > [accordion] 209: drop column > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The legacy `image_clip_v1` embedding column of the `eval_drop_column` table is superseded and wasting storage. Remove that column — keep everything else. > ``` > [accordion] 210: cast column type > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Downstream tooling needs 64-bit floats: change the type of the `relevance_score` column in the `eval_cast_column` table from float32 to float64, in place, keeping the values. > ``` > [accordion] 211: performant batch ingest > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Make sure my ingest pattern will be performant. My ingest script is `ingest.py` in your working directory; it creates the table `eval_ingest_events` in this database and loads the day's 1,000 events into it. Fix whatever would make the ingest slow or hurt the table, keeping the same table name, schema, and rows, then run it against this database so the table ends up holding exactly those 1,000 events. > ``` ### Queries and search > [accordion] 301: filtered count > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How many products in the `eval_filter_count` table are in category `books` with a price above $100? This is a read-only check. End your answer with a line of exactly this form: > > COUNT: > ``` > [accordion] 302: filtered ids > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Which products in the `eval_filter_ids` table are in category `electronics` and priced under $50? This is a read-only check. End your answer with one line per matching product, each of exactly this form: > > ID: > ``` > [accordion] 303: lookup row by id > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Look up the product with id 12 in the `eval_lookup_row` table and report its title. This is a read-only check. End your answer with a line of exactly this form: > > TITLE: > ``` > [accordion] 304: top k cheapest > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What are the 3 cheapest products in the `eval_cheapest` table? This is a read-only check. End your answer with a line of exactly this form, ids ordered from cheapest up: > > CHEAPEST: <id>,<id>,<id> > ``` > [accordion] 305: paginated read > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our storefront lists the `eval_pagination` table's products cheapest-first, 3 to a page. A customer is looking at page 2 — which products do they see? This is a read-only check. End your answer with a line of exactly this form, the three ids in display (price-ascending) order: > > PAGE2: <id>,<id>,<id> > ``` > [accordion] 306: pick column for image search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > I have a LanceDB table called `eval_pick_column`. I want to let users upload a photo and find visually similar products. Which column should the similarity search run against? If there's more than one candidate, tell me which one to use and why. This is a read-only check — do not modify the table, its rows, or its metadata. End your answer with a line of exactly this form, naming the single column to use: > > RECOMMENDATION: <column_name> > ``` > [accordion] 307: vector search similar > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A shopper is viewing product 5 in the `eval_vector_search` table and we want a 'similar items' shelf. Using product 5's `image_clip_v2` embedding as the query, find the single most visually similar OTHER product. This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 308: vector search filtered > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Same 'similar items' feature, but constrained to a department: using product 8's `image_clip_v2` embedding as the query on the `eval_vector_filtered` table, find the single most similar product in category `books` (product 8 itself is not in that category). This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 309: full text search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A customer remembers a product description mentioning 'waterproof'. Using full-text search on the `eval_fts_search` table, find which product that is. This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 310: fts multi match > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Marketing wants a list of every product in the `eval_fts_multi` table whose description mentions 'wireless'. Use full-text search to find them all. This is a read-only check. End your answer with one line per matching product, each of exactly this form: > > ID: <id> > ``` > [accordion] 311: hybrid search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Find the product in the `eval_hybrid_search` table most relevant to a shopper who typed the keyword 'solar' and whose taste profile is product 4's `image_clip_v2` embedding — i.e. combine keyword relevance and vector similarity (a hybrid search). This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 312: explain query plan > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Before we ship a price filter on the `eval_explain_plan` table, confirm from the server's query plan whether a filter on `price_usd` (for example `price_usd < 50`) is served by an index or by scanning the table. This is a read-only check — do not build or drop anything. End your answer with exactly one of these lines: > > PLAN: index > PLAN: scan > ``` ### Index management > [accordion] 401: build index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Queries that filter the `eval_build_index` table by `category` are slow. Build the appropriate index to speed them up. > ``` > [accordion] 402: create vector index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Vector similarity queries against the `image_clip_v2` column of the `eval_vector_index` table are running as brute-force scans. Build an ANN index on that column using cosine distance, and make sure it finishes building. > ``` > [accordion] 403: create fts index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Enable keyword (full-text) search over the `body_text` column of the `eval_fts_index` table, and make sure the index finishes building. > ``` > [accordion] 404: inspect indexes > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Audit the indexes on the `eval_index_report` table: what indexes exist, and how many rows does the index on `category` cover? This is a read-only check. End your answer with one line per index plus one final line, of exactly these forms: > > INDEX: <index_name> > INDEXED_ROWS: <rows covered by the category index> > ``` > [accordion] 405: index coverage > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The scalar index on `price_usd` of the `eval_index_coverage` table was built a while ago, and data has landed in the table since. Check the index's coverage: how many rows does it currently cover, and how many rows are not yet indexed? This is a read-only check — do not rebuild or modify anything. End your answer with two lines of exactly this form: > > INDEXED: <rows covered by the index> > UNINDEXED: <rows not yet covered> > ``` > [accordion] 406: drop index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The index on `price_usd` in the `eval_drop_index` table was an experiment and is slowing down writes. Drop that index. > ``` ### Version history and tags > [accordion] 501: version history > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How many versions does the `eval_versions` table have? This is a read-only check — do not create new versions. End your answer with a line of exactly this form: > > VERSIONS: <n> > ``` > [accordion] 502: time travel read > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Without modifying the `eval_timetravel` table, compare it to its past: how many rows did it have at version 1, and how many does it have now? End your answer with two lines of exactly this form: > > THEN: <rows at version 1> > NOW: <rows now> > ``` > [accordion] 503: restore version > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Someone ran a bad cleanup against the `eval_restore` table and rows went missing. Roll the table back to the version immediately before the deletion, so the missing rows are back. > ``` > [accordion] 504: tag version > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We're about to run a risky migration on the `eval_tag_create` table. Tag its current version as `prod-baseline` so we can refer back to it later. > ``` > [accordion] 505: read at tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_tag_read` table's version tagged `release-v1` is what we shipped. Without modifying the table, compare then and now: how many rows did it have at the `release-v1` tag, and how many does it have now? End your answer with two lines of exactly this form: > > TAGGED: <rows at the release-v1 tag> > NOW: <rows now> > ``` > [accordion] 506: move tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `latest` tag on the `eval_tag_move` table still points at an old version, but the table has moved on since. Update the `latest` tag so it points at the table's current version. Leave any other tags alone. > ``` > [accordion] 507: delete tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `deprecated` tag on the `eval_tag_delete` table is obsolete. Remove that tag — leave any other tags alone. > ``` > [accordion] 508: compare two versions > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Compare version 3 and version 7 of the `eval_history_compare` table and explain, in plain English, what happened to it in between — cover the schema, the indexes, and the data. This is a read-only investigation: do not modify the table. > > Report only what changed AFTER version 3, up to and including version 7 — version 3 is the starting point, so whatever happened at version 3 itself is not one of the changes. > > End your answer with three lines of exactly these forms. The first two are comma-separated lists of column names (or NONE): the columns added in that range, and the columns that gained an index in that range. The third is exactly one of the five words offered, describing the row-level data changes in that range: > > COLUMNS_ADDED: <column_name>[, <column_name>...] > INDEXES_ADDED: <column_name>[, <column_name>...] > DATA_CHANGES: APPEND_THEN_DELETE | DELETE_THEN_APPEND | APPEND_ONLY | DELETE_ONLY | NONE > ``` > [accordion] 509: changes since date > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our last schema review of the `eval_history_since` table signed off at {cutoff}. Did any schema or index changes happen to that table since then? Explain in plain English what you find, and say which changes were not schema or index changes so we know they were considered. This is a read-only investigation: do not modify the table. > > This table also has columns and indexes that predate that timestamp — those are not what the review is asking about, so report only what changed at or after it. > > End your answer with four lines of exactly these forms: every table version at or after that timestamp that changed the schema or an index — version numbers only, comma-separated, ascending (or NONE); the column added by a schema change at or after that timestamp (or NONE); the column covered by an index built at or after that timestamp (or NONE); and every table version at or after that timestamp whose change was NOT a schema or index change — version numbers only, comma-separated, ascending (or NONE): > > CHANGED_VERSIONS: <version>[, <version>...] > COLUMN_ADDED: <column_name> > INDEX_ADDED: <column_name> > OTHER_CHANGES: <version>[, <version>...] > ``` > [accordion] 510: trace column to job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Someone added a column called `foo` to the `eval_history_column_job_{db}` table and nobody wrote down why. Find the exact version where `foo` appeared, then find the background job that was pinned to that same table version and report what it is doing and its current state. There are several jobs on this table, pinned to different versions of it, so make sure the one you report is the one pinned to that version. This is a read-only investigation: do not cancel or modify anything. > > End your answer with four lines of exactly these forms (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose: > > VERSION: <version_number> > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` ### Column metadata and lineage > [accordion] 601: add all metadata types > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Document the two image-embedding columns in the `eval_add_metadata` table: write a clear description for each, tag each with its field type, the model that produced it, and its version, mark the newer one as the latest, and group both under a single logical column. > ``` > [accordion] 602: delete one metadata key > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `model` tag on the `image_clip_v1` column of `eval_delete_metadata` is wrong. Remove just that tag — leave the column's description and other tags alone. > ``` > [accordion] 603: explain column origin > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Some columns in the `eval_lin_origin` table were generated by the platform rather than loaded with the data. Investigate the column `title_sentiment`: is it produced by a UDF or by a SQL expression, what produces it, and which columns does it read? This is a read-only investigation: do not modify the table. > > End your answer with lines of exactly these forms — one INPUT line per input column. Write the generator exactly as the table's own metadata records it (the UDF's registered name, or the SQL expression), not a paraphrase: > > KIND: <udf or expression> > GENERATOR: <udf name or SQL expression> > INPUT: <input_column_name> > ``` > [accordion] 604: find downstream dependents > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We want to drop the `price_usd` column from the `eval_lin_deps` table, but some of the table's generated columns are derived from other columns. Find every column that depends on `price_usd` — directly, or indirectly through another generated column. This is a read-only investigation: do not modify the table. > > End your answer with one line per dependent column, each of exactly this form (do not list `price_usd` itself): > > DEPENDENT: <column_name> > ``` > [accordion] 605: trace column refresh job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The generated column `discounted_price` in the `eval_lin_job_{db}` table is filled in by a background refresh job, and we need to know which job that is. There is more than one job on this table (a long-lived database can also hold finished or cancelled leftovers), so make sure the one you report is the currently-running job that refreshes `discounted_price`. This is a read-only investigation: do not cancel or modify anything. > > End your answer with three lines of exactly these forms (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose: > > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` ### Namespaces > [accordion] 701: create namespace > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a namespace called `analytics` in this database, ready for new tables to be organized under it. > ``` > [accordion] 702: create table in namespace > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Under the `staging` namespace of this database, create a table called `sessions` with columns `session_id` (string) and `duration_s` (float64), holding exactly these 2 rows: > > | session_id | duration_s | > |------------|------------| > | a1b2 | 12.5 | > | c3d4 | 3.25 | > ``` > [accordion] 703: list namespace tables > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What tables live inside the `warehouse` namespace of this database? This is a read-only check. End your answer with one line per table, each of exactly this form: > > TABLE: <table_name> > ``` > [accordion] 704: query namespace table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our SRE dashboards read from the `ops` namespace of this database, which holds a `latency` table of per-service p99 latency readings. Which service has the highest `p99_ms`, and what is that value? This is a read-only check. End your answer with two lines of exactly this form: > > SERVICE: <service_name> > P99: <p99_ms value> > ``` ### Table branches > [accordion] 801: create branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a branch called `experiment-reindex` on the `eval_create_branch` table, off its current state. > ``` > [accordion] 802: switch branch and write > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Switch to the `wip-branch` branch of the `eval_switch_branch` table and add a description to its `category` column. The change should land on `wip-branch`, not on main. > ``` > [accordion] 803: cherry pick branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `ready-to-cherry-pick` branch of the `eval_cherry_pick` table has been reviewed and approved. Cherry-pick it onto main so its changes land on the main table. > ``` > [accordion] 804: delete branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We no longer need the `stale-2024` branch on the `eval_delete_branch` table. Delete it. > ``` ### Background jobs > [accordion] 901: list running jobs > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What jobs are currently running against the `eval_job_list_{db}` table? Give each one's type and current state. This is a read-only check — do not cancel or modify anything. End your answer with one line per currently-running job, each of exactly this form (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose — a compaction job that had failed would read `RUNNING: j1-xy-0ab-cdef | table_compaction | failed`: > > RUNNING: <job_id> | <job_type> | <current_state> > ``` > [accordion] 902: describe job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > An automated maintenance job was recently started against the `eval_job_describe_{db}` table. Find it and report what kind of job it is and its current status. Do not cancel or modify it. End your answer with lines of exactly these forms (full job id, no truncation). Write the type and state exactly as the API reports them, not as synonyms or prose — a compaction job that had failed would read `TYPE: table_compaction` and `STATE: failed`: > > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` > [accordion] 903: cancel job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A cache-prewarm job against the `eval_job_cancel_{db}` table is hogging resources. Cancel it, and leave every other job alone. End your answer with a line of exactly this form (the full id of the job you cancelled, no truncation): > > CANCELLED: <job_id> > ``` ### Multi-step workflows > [accordion] 1001: create embed search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Set up a small semantic-search demo from scratch in this database. Create a new table called `eval_embed_search` with exactly three columns: `id` (int64), `text` (string), and `embedding` — a fixed-size vector of floats holding an embedding of `text`, computed with the `all-MiniLM-L6-v2` sentence-transformers model (embed each `text` exactly as written; use that same model for every row and for the query below). Populate it with exactly these 8 rows: > > | id | text | > |----|------| > | 1 | Espresso machine with a 15-bar pump for rich, crema-topped coffee | > | 2 | Burr coffee grinder for fresh, evenly ground espresso beans | > | 3 | Pour-over coffee kettle with a gooseneck spout for slow brewing | > | 4 | Reusable coffee filter for drip brewers and pour-over cones | > | 5 | Waterproof hiking boots for rocky mountain trails | > | 6 | Lightweight hiking backpack with a hydration sleeve for day trails | > | 7 | Trekking poles for steep mountain trail descents | > | 8 | Merino wool hiking socks for long days on the trail | > > Then run two vector searches against the table, both using cosine distance: (1) a 'similar items' search using row 2's own stored embedding as the query, returning the 3 nearest OTHER rows; (2) a text search — embed the query `gear for a mountain hike` with the same model and return the 3 nearest rows. End your answer with two lines of exactly this form, ids comma-separated, nearest first: > > NEAREST: <id>,<id>,<id> > QUERY_HITS: <id>,<id>,<id> > ``` > [accordion] 1002: build all indexes > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_index_all` table is about to back our product search page. The page will run: visual similarity search on the `image_clip_v2` embeddings (cosine distance), keyword search over `body_text`, exact-match filters on `category`, and range filters on `price_usd` — often combined with the searches. Today the table has no indexes at all. Build all the indexes this table will need to make search fast, and make sure every one of them finishes building. Don't build indexes the page won't use — each one costs build time and slows writes — and note that `image_clip_v1` is a legacy column nothing queries anymore. Do not modify the table's rows or schema. > ``` > [accordion] 1003: embedding models in branches > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We're choosing an embedding model for the `body_text` column of the `eval_embed_branches` table (24 product descriptions) and want to compare 3 candidates side by side without touching the production data. The candidates: `all-MiniLM-L6-v2`, `bge-small-en-v1.5`, and `gte-small`. Run the experiment on branches: for each candidate, create a branch of the table off main and, on that branch only, add a fixed-size float vector column called `body_embedding` holding that model's embedding of every row's `body_text` (embed the text exactly as stored). Then run the same search on each branch, using cosine distance — the 3 products most similar to the query `a paperback novel to read on the beach`, embedded with that branch's model — so we can compare what each model returns. Main must be left exactly as it is: no new column, no new rows, no other writes. End your answer with one line per branch, each of exactly this form (the model named the way its provider does, e.g. `all-MiniLM-L6-v2`; the three ids comma-separated, most similar first): > > BRANCH: <branch_name> | <embedding_model> | <id>,<id>,<id> > ``` > [accordion] 1004: parquet to lance embed > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Convert this Parquet dataset to Lance and add a vector column from the description field. The dataset is `products.parquet` in your working directory. Load it into a new table called `eval_parquet_products` in this database, keeping every Parquet column and row exactly as they are, and add a column `description_embedding`: a fixed-size vector of floats holding an embedding of each row's `description`, computed with a text-embedding model of your choice (the same model for every row). > ``` # LanceDB Lakehouse Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/catalog LanceDB Lakehouse objects are organized into a catalog of databases, namespaces and tables -- connect to a database to work with them. ## Catalog Hierarchy A catalog keeps track of named data objects, such as tables and views, so applications can discover and access them. In LanceDB Enterprise, the catalog is the top-level entry point: it organizes databases, which in turn organize namespaces and tables -- similar to a catalog in Postgres, Snowflake, or other database systems. The catalog itself has no name of its own -- it's just the root -- and an Enterprise deployment's catalog is identified by its endpoint, not a name like the objects beneath it. LanceDB Embedded has no catalog at all. Connect directly to a [database](#connecting-to-database) instead of going through a catalog. A database contains namespaces that group related tables and views. Namespaces can also contain other namespaces, letting teams organize data by project, environment or purpose. For example, a search application can keep production and staging data in separate namespaces within the same database, with `prod` further split into a nested `search` namespace: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD catalog["root catalog"] --> database["ai_data · database"] database --> prod["prod · namespace"] database --> staging["staging · namespace"] prod --> search["search · namespace"] search --> search_docs["documents · table"] search --> search_view["recent_documents · view"] search --> search_fn["embed · function"] staging --> staging_docs["documents · table"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` | Object | What it represents | | - | - | | [Catalog](/enterprise/v1-12-0/management/catalog) | The unnamed root of an Enterprise deployment, identified by its endpoint; lists, creates and drops databases. Not present in Embedded. | | [Database](/enterprise/v1-12-0/management/database) | A container for namespaces and their data objects. | | [Namespace](/enterprise/v1-12-0/management/namespace) | A named group of catalog objects -- tables, views, secrets, functions, storage integrations, or nested namespaces -- addressed by its namespace path. | | [Table](/enterprise/v1-12-0/management/table) | Data stored as rows and columns. | | [View](/enterprise/v1-12-0/management/view) | A saved query, evaluated when read. Available in Enterprise. | | [Materialized view](/enterprise/v1-12-0/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. | | [Secret](/enterprise/v1-12-0/management/secret) | A named credential that a Function binds by reference. Available in Enterprise. | | [Storage integration](/enterprise/v1-12-0/management/storage-integration) | A named credential for reading or importing from storage outside the deployment's own tables, such as an S3 prefix or a HuggingFace repository. Available in Enterprise. | | [Function](/enterprise/v1-12-0/management/function) | Registered code used to compute column values. Available in Enterprise. | ### Namespace name and path A namespace's **name** is just its own component, such as `search`. Its **path** is the full sequence of names from the database down to it: in the diagram above, `search` sits inside `prod`, so its path is the sequence `prod`, `search`. A namespace path is never written by joining those names with `.` -- a dot is a valid character inside a name, so a dot-joined path couldn't always be split back into its components unambiguously. The two forms below are how SQL actually writes one. ### Schema SQL addresses a namespace path as a **schema**, the ANSI standard's term for the same concept: a nested path collapses into one identifier, its components joined by `$` instead of `.`. The path's length changes what the schema looks like: | Path | Schema | | - | - | | `[]` (the database root) | `public` -- the reserved name for the empty path | | `["prod"]` | `prod` -- one component needs no joining | | `["prod", "search"]` | `` `prod$search` `` -- joined, and backtick-quoted because `$` isn't a bare-identifier character | `$` can't appear in an ordinary name, so a schema can always be split back into its exact path, unlike a dot-joined one. (This "schema" is the namespace path as a SQL identifier -- distinct from a table's Arrow schema, its column names and types.) ### Object identifier An object -- a table, view, function, secret, or storage integration -- is addressed in SQL by the ANSI three-part identifier `database.schema.name`, where `schema` is exactly the `$`-joined path above. The `documents` table in `search`, nested inside `prod`, in database `ai_data`, is ``ai_data.`prod$search`.documents``. One directly under the database root uses `public`: `ai_data.public.documents`. See [Namespace](/enterprise/v1-12-0/sql/ddl/namespace) for the full `CREATE`/`ALTER`/`DROP` syntax. ## Connecting You always run table and query operations within a **database**; cross-database operations go through SQL instead. The same Python, TypeScript and Rust SDKs reach a database and the catalog separately. ### Connecting to Catalog `connect_catalog(endpoint)` connects to Enterprise's root catalog, which can list, create and drop databases across the whole deployment. Its `connect_database(name)` and `create_database(name)` then return the same kind of database connection `lancedb.connect()` does. This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a database, never directly against the catalog. Local filesystem and object-store deployments have no catalog to connect to -- each is already scoped to one database. ### Connecting to Database `lancedb.connect(uri)` opens one database in a single call -- a local directory, an object-storage path, or (with a `db://` URI) a specific Enterprise database. The table below shows which URI reaches which kind of database directly. | URI | Mode | Where queries run | | - | - | - | | A local path, such as `./data` | Embedded | In your process | | `s3://`, `gs://` or `az://` | Embedded | In your process, reading object storage | | `db://` | Enterprise | On your cluster | #### A local directory Embedded in your application, LanceDB reads and writes the tables in a directory on disk. ```python Python (sync) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" db = lancedb.connect(uri) ``` ```python Python (async) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" async_db = await lancedb.connect_async(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("ex_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("ex_lancedb").execute().await?; ``` #### Object storage With an object storage URI the library is still embedded: your process runs every query and reads and writes the bucket directly, with credentials from its environment or its connection's `storage_options`. ```python Python (sync) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". db = lancedb.connect(uri) ``` ```python Python (async) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". async_db = await lancedb.connect_async(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". const db = await lancedb.connect(uri); ``` In Rust, pass the same URI to `connect`. LanceDB supports these object storage backends: | Backend | URI scheme | Credentials | | - | - | - | | AWS S3, and S3-compatible stores (MinIO, Tigris, ...) | `s3://` | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, or `storage_options`. Compatible stores also need `endpoint` and `region`. | | Google Cloud Storage | `gs://` | `GOOGLE_SERVICE_ACCOUNT` (path to a service account JSON), or `storage_options` | | Azure Blob Storage | `az://` | `AZURE_STORAGE_ACCOUNT_NAME` + `AZURE_STORAGE_ACCOUNT_KEY` (or a SAS token), or `storage_options` | | Tencent COS | `cos://` | `TENCENTCLOUD_SECRET_ID` / `TENCENTCLOUD_SECRET_KEY`, or `storage_options` | | GooseFS (a cache layer over COS or S3) | `goosefs://` | Reads from the GooseFS client environment | Pass credentials as environment variables (uppercase), or as a `storage_options` dict at connection or table level (lowercase keys); a table's `storage_options` inherit the connection's and override on a per-key basis. Choosing among these is a tradeoff between latency, scalability, cost and operational complexity, before you even pick a cloud-specific backend: object storage (S3, GCS, Azure Blob) has the highest latency but is the cheapest and scales storage effectively without limit; networked file storage (EFS, Filestore, Azure Files) and third-party stores (MinIO, WekaFS) sit in between; block storage (EBS, Persistent Disk, Managed Disk) and local NVMe are the fastest but tie data to one instance, so scaling means sharding or copying it yourself. ##### S3-compatible stores ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://bucket/path", storage_options={ "region": "us-east-1", "endpoint": "http://minio:9000", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3Minio() { const db = await lancedb.connect("s3://bucket/path", { storageOptions: { region: "us-east-1", endpoint: "http://minio:9000", }, }); return db; } ``` If the endpoint is `http://` (common in local development), also set `ALLOW_HTTP=true` or pass `allow_http=True` in `storage_options`. ##### S3 Express ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://my-bucket--use1-az4--x-s3/path", storage_options={ "region": "us-east-1", "s3_express": "true", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3Express() { const db = await lancedb.connect( "s3://my-bucket--use1-az4--x-s3/path", { storageOptions: { region: "us-east-1", s3Express: "true", }, }, ); return db; } ``` Consult AWS's networking requirements for S3 Express before enabling it. ##### Server-side encryption with KMS Set `aws_server_side_encryption` to `aws:kms` and `aws_sse_kms_key_id` to the key ID or ARN to encrypt at rest with an AWS KMS key. The same options apply at connection or table level, and combine with bucket-level default encryption. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://bucket/path", storage_options={ "aws_server_side_encryption": "aws:kms", "aws_sse_kms_key_id": "<your-kms-key-id-or-arn>", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3SseKms() { const db = await lancedb.connect("s3://bucket/path", { storageOptions: { awsServerSideEncryption: "aws:kms", awsSseKmsKeyId: "<your-kms-key-id-or-arn>", }, }); return db; } ``` The IAM principal needs `kms:Encrypt`, `kms:Decrypt` and `kms:GenerateDataKey` on the configured KMS key. > [!NOTE] > > **Tencent COS and GooseFS build availability.** Both are bundled by > default in the Python wheel. In the Node binding, GooseFS is bundled by > default but COS is not -- build with the `cos` Cargo feature enabled to > use it there. In Rust, neither is in the default feature set; build with > the `cos` or `goosefs` Cargo feature enabled to use either one. #### LanceDB Enterprise A `db://` URI connects directly to one database in LanceDB Enterprise, where your cluster runs queries and background work. Get the database URI, API key, region and endpoint from your administrator, then replace the placeholders below. Use your cluster's region in place of `us-east-1`. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` In Rust, enable the crate's `remote` feature; the connection builder then takes the same settings through `api_key`, `region` and `host_override`. To use OAuth instead of an API key, see [Authentication](/enterprise/v1-12-0/enterprise/authentication); for every connection option, see [Database](/enterprise/v1-12-0/management/database#deployment). ## Organization and access control * **Separate projects and environments.** Keep production and staging tables in distinct namespaces, even when they use the same table names. * **Find shared datasets.** Give teams a consistent place to discover and access the data they work with. * **Control access in Enterprise.** Use permissions on databases, namespaces and tables to manage who can access shared data and what they can do with it. ## Learn more * [Catalog](/enterprise/v1-12-0/management/catalog): initial access to a new deployment, and the superuser bootstrap. * [Databases](/enterprise/v1-12-0/management/database): connect to and manage a database. * [Namespaces](/enterprise/v1-12-0/management/namespace): create groups and address tables within them. * [Tables](/enterprise/v1-12-0/management/table): create, inspect and manage your data. * [Views](/enterprise/v1-12-0/management/view) and [materialized views](/enterprise/v1-12-0/management/materialized-view): work with query-defined data. * [Secrets](/enterprise/v1-12-0/management/secret): store a credential that a Function can bind by reference. * [Storage integrations](/enterprise/v1-12-0/management/storage-integration): read or import from storage outside your own tables. * [Authorization](/enterprise/v1-12-0/governance/authorization): configure Enterprise access permissions. # Embedded vs Enterprise Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/embedded-vs-enterprise A feature-by-feature comparison between LanceDB Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. [LanceDB Enterprise](/enterprise/v1-12-0/enterprise/index) distributes query execution, indexing, maintenance and refresh work across a cluster of many machines, outside your application. Both are built on the same [Lance](/enterprise/v1-12-0/basics/lance) columnar file format, so moving data from one edition to the other does not require a data conversion step. See [Architecture](/enterprise/v1-12-0/index#architecture) for how each one's components fit together. ## How they differ | Dimension | LanceDB Embedded | LanceDB Enterprise | What the difference means | | :- | :- | :- | :- | | **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | | **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/enterprise/v1-12-0/search/vector-search#expected-performance) and [full-text search](/enterprise/v1-12-0/search/full-text-search#expected-performance) for representative measurements. | | **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/v1-12-0/enterprise/data-page-cache). | | **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/enterprise/v1-12-0/indexing/). | | **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | | **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | | **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/enterprise/v1-12-0/curation) over SQL. See [SQL reference](/enterprise/v1-12-0/sql). | | **Native vector dedup** | Not available | `dedupe()` / `duplicate_pairs()` | Index-partition deduplication as a SQL table function, with no full pairwise scan. See [DEDUPE](/enterprise/v1-12-0/sql/dql/dedupe). | | **Materialized views** | Not available | Server-side, distributed compute | Enterprise derives and refreshes a table from a query as a background job. See [Materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views). | ## Compare features | Area | Feature | Embedded | Enterprise | | - | - | :-: | :-: | | **Data Ingestion** | [Insert data](/enterprise/v1-12-0/ingestion/insert) | ✅ | ✅ | | | [RTE Write (Upsert)](/enterprise/v1-12-0/ingestion/realtime-write) | ✅ | ✅ | | | [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write) | ❌ | ✅ | | | [Attach Database](/enterprise/v1-12-0/ingestion/migrate-from-embedded) | ❌ | ✅ | | | [Import Datasets](/enterprise/v1-12-0/ingestion/import) | ❌ | ✅ | | | [Distributed Write](/enterprise/v1-12-0/enterprise/distributed-write) | ❌ | ✅ | | **Search** | [Vector search](/enterprise/v1-12-0/search/vector-search) | ✅ | ✅ | | | [Full-text search](/enterprise/v1-12-0/search/full-text-search) | ✅ | ✅ | | | [Hybrid search](/enterprise/v1-12-0/search/hybrid-search) | ✅ | ✅ | | | [Filtering](/enterprise/v1-12-0/search/filtering) | ✅ | ✅ | | | [Reranking](/enterprise/v1-12-0/reranking) | ✅ | ✅ | | | [Distributed Search](/enterprise/v1-12-0/enterprise/distributed-search) | ❌ | ✅ | | | [RTE Read](/enterprise/v1-12-0/search/realtime-read) | ✅ | ✅ | | | [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read) | ❌ | ✅ | | | [Cache Prewarm](/enterprise/v1-12-0/enterprise/cache-prewarm) | ❌ | ✅ | | **Data Curation** | [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) | ❌ | ✅ | | | [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) | ❌ | ✅ | | | [Selective Sampling](/enterprise/v1-12-0/curation/selective-sampling) | ✅ | ✅ | | | [Aggregation and profiling](/enterprise/v1-12-0/curation/aggregate) | ❌ | ✅ | | | [Joins](/enterprise/v1-12-0/curation/join) | ❌ | ✅ | | | [Blob Late Materialization](/enterprise/v1-12-0/curation/blob-late-materialization) | ❌ | ✅ | | | [Ranking](/enterprise/v1-12-0/curation/windowing) | ❌ | ✅ | | | [Near-duplicate detection](/enterprise/v1-12-0/curation/dedupe) | ❌ | ✅ | | | [Chunking](/enterprise/v1-12-0/curation/chunking) | ❌ | ✅ | | | [Changes since a version](/enterprise/v1-12-0/curation/changes) | ❌ | ✅ | | **Feature Engineering** | [Computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) | ❌ | ✅ | | | [Incremental Refresh](/enterprise/v1-12-0/enterprise/incremental-refresh) | ❌ | ✅ | | | [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) | ❌ | ✅ | | | [Checkpointing](/enterprise/v1-12-0/enterprise/checkpointing) | ❌ | ✅ | | | [Adaptive Execution](/enterprise/v1-12-0/enterprise/adaptive-execution) | ❌ | ✅ | | | [Refresh Materialized View](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) | ❌ | ✅ | | | [Embedding registry](/enterprise/v1-12-0/embedding) | ✅ | ✅ | | **Training** | [PyTorch data loader](/enterprise/v1-12-0/training/data-loading) | ✅ | ✅ | | | [Training Cache](/enterprise/v1-12-0/training/training-cache) | ❌ | ✅ | | | [Permutations](/enterprise/v1-12-0/training/permutation) | ✅ | ✅ | | | [Distributed training](/enterprise/v1-12-0/training/distributed-training) | ✅ | ✅ | | | [Observability](/enterprise/v1-12-0/training/observability) | ✅ | ✅ | | | [Checkpointing](/enterprise/v1-12-0/training/checkpointing) | ✅ | ✅ | | | [Resuming](/enterprise/v1-12-0/training/resuming) | ✅ | ✅ | | **Management** | [Catalog](/enterprise/v1-12-0/management/catalog) | ❌ | ✅ | | | [Database](/enterprise/v1-12-0/management/database) | ✅ | ✅ | | | [Namespace](/enterprise/v1-12-0/management/namespace) | ✅ | ✅ | | | [Table](/enterprise/v1-12-0/management/table) | ✅ | ✅ | | | [View](/enterprise/v1-12-0/management/view) | ❌ | ✅ | | | [Materialized view](/enterprise/v1-12-0/management/materialized-view) | ❌ | ✅ | | | [Secret](/enterprise/v1-12-0/management/secret) | ❌ | ✅ | | | [Function](/enterprise/v1-12-0/management/function) | ❌ | ✅ | | | [Storage integration](/enterprise/v1-12-0/management/storage-integration) | ❌ | ✅ | | | [Console](/enterprise/v1-12-0/enterprise/console) | ❌ | ✅ | | **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/v1-12-0/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | | | [Vector Indexing](/enterprise/v1-12-0/indexing/vector-index) | ✅ | ✅ | | | [FTS Indexing](/enterprise/v1-12-0/indexing/fts-index) | ✅ | ✅ | | | [Scalar Indexing](/enterprise/v1-12-0/indexing/scalar-index) | ✅ | ✅ | | | [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing) | ✅ | ✅ | | | [Distributed Indexing](/enterprise/v1-12-0/enterprise/distributed-indexing) | ❌ | ✅ | | | [GPU Indexing](/enterprise/v1-12-0/indexing/gpu-indexing) | ✅ | ✅ | | | [Compaction](/enterprise/v1-12-0/maintenance/compaction) | ✅ | ✅ | | | [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction) | ❌ | ✅ | | | [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup) | ✅ | ✅ | | | [Distributed Compaction](/enterprise/v1-12-0/enterprise/distributed-compaction) | ❌ | ✅ | | | [Advanced Conflict Resolution](/enterprise/v1-12-0/enterprise/advanced-conflict-resolution) | ❌ | ✅ | | **Security** | [Authentication](/enterprise/v1-12-0/enterprise/authentication) | ❌ | ✅ | | | [Authorization](/enterprise/v1-12-0/governance/authorization) | ❌ | ✅ | | | [Audit Log](/enterprise/v1-12-0/governance/audit-log) | ❌ | ✅ | | **Deployment** | [Horizontal Scaling](/enterprise/v1-12-0/enterprise/horizontal-scaling) | ❌ | ✅ | | | [OpenTelemetry](/enterprise/v1-12-0/deployment/opentelemetry) | ✅ | ✅ | | | [Kubernetes](/enterprise/v1-12-0/enterprise/deployment/kubernetes) | ❌ | ✅ | | | [Multicloud](/enterprise/v1-12-0/deployment/multicloud) | ❌ | ✅ | | | [Slurm](/enterprise/v1-12-0/deployment/slurm) | ❌ | ✅ | ## Usage differences between Enterprise and Embedded The [quickstart](/enterprise/v1-12-0/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...` connections. Once connected to LanceDB, the table API is largely the same: create a table, search, filter, evolve the schema, and store multimodal records. However, there are some semantic differences worth understanding when your code is talking to LanceDB Enterprise. ### 1. Connection model In LanceDB Enterprise, your app connects via a `db://...` URI and sends requests to the cluster API. The cluster executes table operations on your behalf. Your code is coupled to a **managed service endpoint**, whereas LanceDB Embedded is directly coupled to local or object-storage paths. ### 2. Returned table type Connecting to an Enterprise table via `open_table(...)` returns a `RemoteTable`, unlike LanceDB Embedded, which returns a `LanceTable`. `RemoteTable` is a catalog-backed table accessed through a server/cluster, and does not support all the same methods as `LanceTable` (see below). ### 3. Materialization APIs For Python users working with LanceDB Enterprise, `RemoteTable` does not support table-level materialization methods like `table.to_arrow()` or `table.to_pandas()`. This protects users from accidentally materializing tables that are too large to fit in memory. Instead, materialize results through query/search builders, for example `table.search(...).limit(...).to_pandas()` for a vector or full-text search, or `table.search().where(...).limit(...).to_arrow()` for a filtered scan. For quick previews, use `table.head()`. ### 4. Maintenance lifecycle In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and `cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients reject `optimize()` as not supported. That means maintenance is managed by platform behavior and cluster configuration, not by explicit per-table maintenance calls in your application code. ### 5. Guardrails and limits Enterprise can enforce platform-level guardrails, such as index/table limits and safety checks around operations like `merge_insert` when too many rows are unindexed. LanceDB Embedded mostly exposes storage/format-level behavior, and you tune many lifecycle tasks yourself. This means an operation in LanceDB Enterprise can fail due to service-level policy, not just because of local table shape or schema mismatch. > [!NOTE] > > As a rule of thumb, all you need to remember is this: treat `db://...` as a network service boundary, > use query builders to fetch results, and otherwise interact with your tables as you would in LanceDB > Embedded. ## Which one should I use? [It's very simple to get started with LanceDB Embedded](/enterprise/v1-12-0/quickstart/): Get started with `pip install lancedb` and begin ingesting your data and vectors into LanceDB. LanceDB Embedded (open source) makes sense when your dataset fits on one machine, traffic is still modest, and your team is comfortable handling maintenance tasks such as compaction or reindexing itself. Move to LanceDB Enterprise when retrieval becomes shared infrastructure for your business: your data or traffic has outgrown a single machine, you need private deployment options, or you want platform support for monitoring, security, and large-scale feature workflows. If these sound like your use cases, [reach out to us](https://www.lancedb.com/contact) and we can help you scope your workload and arrange an Enterprise proof of concept. # Guarantees Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/guarantees Understand table commits, concurrent writes and the boundaries of recovery. ## Atomic table writes A table transaction commits its changes atomically: readers see the committed table version, not a partially applied transaction. For example, a committed append adds its rows together. This boundary is one table transaction. A workflow that updates several tables or runs a background job can contain multiple commits. Do not assume the whole workflow is atomic. Schema changes are also part of table history. Changing a column's type can rewrite data; adding a derived column can write the new column independently. ## Consistent reads A read of a table uses a consistent snapshot. A consistent snapshot can still be older than another writer's latest commit. [Consistency](/enterprise/v1-12-0/tables/consistency) explains how LanceDB Embedded and LanceDB Enterprise choose the version a reader sees. For an experiment that must keep using the same data, select a specific retained table version rather than relying on a connection's default freshness. ## Concurrent writes Lance uses optimistic concurrency control. Writers prepare changes, then check compatibility with intervening commits. Compatible changes can be committed; conflicts may be retried or returned as errors. Applications must handle failed writes. Concurrent appends are compatible, but that does not promise success through storage failures or exhausted retries. Do not rely on a particular ordering between independent writers. The [Lance transaction specification](https://lance.org/format/table/transaction/) describes commit behavior and compatibility between operations. ## Storage durability A committed table version is stored in the table’s configured storage. LanceDB Embedded uses your local filesystem or object store; LanceDB Enterprise uses the cluster’s configured storage. Table version history does not replace backups. Configure storage redundancy and backups to meet your recovery requirements. ## Background job completion In LanceDB Enterprise, operations such as index builds and column refreshes can run as background jobs. Receiving a job handle confirms submission. Wait for the job to succeed before relying on its result. Some operations save results in batches. If a job fails or is cancelled, batches already committed can remain in the table. Each operation’s guide explains whether it can leave partial results. ## Writes after a client timeout If a client times out while waiting for a write, the write may already have committed. Retrying an append can therefore insert the same records again. Check whether the intended records were written before retrying. For an operation submitted as a background job, check its status using the job handle. ## Version history and recovery Retained table versions let you inspect earlier data or restore a table to a previous version. Cleanup can remove those versions and their underlying files, so configure retention to cover the history you need. Dropping a table is different from deleting records. Table version history cannot undo `drop_table`. ## Learn more * [Consistency](/enterprise/v1-12-0/tables/consistency): control when reads observe updates. * [Table versioning](/enterprise/v1-12-0/management/table#versioning): inspect and restore history. * [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup): configure retention and understand protected versions. * [Job Framework](/enterprise/v1-12-0/basics/jobs): distinguish submission, completion and cancellation. * [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column): understand partial progress. * [Architecture](/enterprise/v1-12-0/index#architecture): understand storage and background maintenance. # Job Framework Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/jobs Track background work from submission to completion. **Applies to:** Embedded ❌, Enterprise ✅ ## Job handles A job handle lets you track an operation, such as an index build or a computed column refresh. Use it to check progress, wait for completion and inspect failures. Methods such as Python's `create_index_async` and TypeScript's `createIndexAsync` return job handles. In LanceDB Embedded, the work runs in your application process; in Enterprise, it runs on server workers or through the SQL query backend. A returned handle can represent an operation that has already finished, so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = tbl.create_index_async("vector", replace=True) print(job.id) print(job.job_type) print(job.status()) ``` ## Submit and wait for a job 1. **Submit the operation.** Keep the returned job handle. For an Enterprise registry job, also keep its ID if another process needs to look it up later. 2. **Check progress.** Read the current status while the operation runs. 3. **Wait for completion.** Check that the job succeeded before using its result. If it failed or was cancelled, inspect the failure details and any results it committed before stopping. In Python, `job.status()` reports the current state and `job.wait()` waits for completion, raising if the job fails or is cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. If the timeout expires while disconnected, the wait raises `ConnectionError` with the job ID and instructions to resume waiting. A timeout while connected raises `TimeoutError`. The job may still be running; timing out does not cancel it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb.exceptions import JobFailedError, JobCancelledError job = tbl.create_index_async("vector", replace=True) job_id = job.id # Save the ID to reopen an Enterprise registry job later. try: result = job.wait(timeout=timedelta(minutes=10)) except JobFailedError: print(f"job failed: {job.failure}") except JobCancelledError: print("job was cancelled") except ConnectionError as exc: print(exc) # The job may still be running on the server. except TimeoutError: print(f"still running: {job.status()}") ``` After connectivity returns, reopen an Enterprise registry job by its saved ID and continue waiting on the existing operation: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.open_job(job_id) result = job.wait(timeout=timedelta(minutes=10)) ``` For SQL-backed jobs, call `wait()` again on the original handle. These jobs cannot be reopened with `db.open_job()`; see [SQL-backed job handles](#sql-backed-job-handles). ## Inspect and cancel jobs | Task | What to do | | - | - | | Inspect progress | Check status and refresh the handle to retrieve details. Enterprise job events can help explain ongoing work or failures. | | Reattach from another process | Open an existing server job with its ID, such as Python's `db.open_job(job_id)`. The server must still retain the job record. | | Diagnose a failure | Inspect failure details and relevant events. Enterprise SQL also provides `SHOW ERRORS`. | | Request cancellation | Call the job's cancellation method. Cancellation may take time, and work already committed is not rolled back. | Reopening a job retrieves the existing operation; it does not restart failed work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.open_job(job_id) # raises JobNotFoundError if unknown job.refresh() # pull the latest status from the server print(job.status()) events = job.events(limit=100) print(events.to_pylist()) job.cancel() ``` List jobs on a connection, paging through the results: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for info in db.list_jobs(page_limit=50): print(info.job_id, info.job_type, info.state) ``` Event responses have [row limits](/enterprise/v1-12-0/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. ## Embedded and Enterprise execution The following table describes LanceDB Embedded operations and registry jobs on LanceDB Enterprise. SQL-backed job handles follow the query lifecycle described below. | | Embedded | Enterprise registry job | | - | - | - | | Execution | In your application process | On server workers | | Job identity | No server ID | A server ID for looking up the job | | Event history | No server event history | Available through the jobs API | | Reattaching after a client restart | No server job to reopen | Reopen by ID while the record is retained | ### SQL-backed job handles On Enterprise, several catalog operations return a job handle backed by the SQL query engine rather than the job registry: | Operation | SDK methods | Behavior | | - | - | - | | Materialized views | `create_materialized_view_async()`, `refresh_async()`, `drop_materialized_view_async()` | Synchronous variants wait on the same SQL execution. Drop removes the catalog binding immediately; physical cleanup continues in the background. | | Functions | Registration, `drop_function_async()` | Registration waits for catalog publication before returning the immutable FunctionVersion. Drop confirms catalog removal while cleanup continues separately. | | Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. | | Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. | All of these report `job.job_type` as `"query"`, with `job.id` holding the connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect one. Unlike registry handles, they don't expose event history, can't be reopened through `open_job()` or reattached after a client restart, and cancellation depends on the SQL server's support for it. ### Object teardown The "physical cleanup continues in the background" behavior above, for a dropped table, view, materialized view, Secret or Function, is a job type of its own: `drop_object` deletes the dropped object's content, then clears it from the database's cleanup backlog. You trigger it indirectly, by dropping one of those objects or a [namespace](/enterprise/v1-12-0/management/namespace) -- it runs as this job rather than inline with the call. Whether a dropped table runs as `drop_object` or as [`drop_table`](/enterprise/v1-12-0/management/table#drop), which fences the table's directory with its own marker instead, depends on how the deployment stores its catalog. ## Learn more * [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing): submit index work. * [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column): populate derived values. * [SQL job commands](/enterprise/v1-12-0/sql/ddl/job): list jobs and inspect errors. * [SDKs](/enterprise/v1-12-0/basics/sdk): find the job API for your client. # Lance format Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/lance The open format for multimodal data behind LanceDB. ## Lance format overview [Lance](https://lance.org/) is an open-source, columnar format designed for multimodal AI. It defines how data is stored and organized into versioned tables. LanceDB Embedded and LanceDB Enterprise both use Lance as their storage foundation. The format is developed as an independent open-source project, with its own specification and tools. ## Multimodal data A Lance table can hold images, video, audio, text, embeddings and structured metadata together. For example, a video dataset can keep each clip alongside its caption, labels and embeddings, so applications can search and work with those fields together. ## Data access, versioning and column updates * **Efficient data access.** Read individual rows for retrieval and training, or scan columns for analytics. * **Versioned data.** Read an earlier table version to reproduce an experiment or inspect previous results, while that version is retained. * **Independent column updates.** Add embeddings or other derived features without rewriting the existing image, video or text columns. ## Opening Lance datasets in Python Any `.lance` dataset directory is a LanceDB table. Pass the parent directory to `lancedb.connect()` and open the table by its directory stem: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("/data") # pass storage_options=... for S3, GCS or Azure tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a version ``` Use `lancedb` for search, retrieval, data curation, multimodal blob access and application code. Install `pylance` (`import lance`) only when building query engines or connectors, calling format-level fragment APIs directly, or converting plain-scan lazy blob handles or legacy blob bytes with `to_pandas()`. See [Multimodal data and blobs](/enterprise/v1-12-0/management/table#multimodal) for native v2 blob conversions that do not require `pylance`. | `pylance` (`import lance`) | `lancedb` (`import lancedb`) | | - | - | | `lance.dataset("/data/frames.lance")` | `lancedb.connect("/data").open_table("frames")` | | `lance.write_dataset(data, "/data/frames.lance")` | `lancedb.connect("/data").create_table("frames", data)` | | `lance.vector.vec_to_table(mat)` | `db.create_table(name, pa.table({"vector": list(mat)}))` | | `lance.blob_field("video")` | `lancedb.blob("video")` | | `ds.take_blobs("video", ids=row_ids)` | `tbl.fetch_blob_files("video", row_ids)` (seekable handles) or `tbl.fetch_blobs("video", row_ids)` (`pa.LargeBinaryArray`) | | `ds.to_table(columns=cols, filter=expr, limit=n)` | `tbl.search().where(expr).select(cols).limit(n).to_arrow()` | | `ds.to_batches(batch_size=k)` | `tbl.search().to_batches(k)` | | `ds.take(offsets)` | `tbl.__getitems__(offsets)` (preserves offset order) or `tbl.take_offsets(offsets).to_arrow()` (unordered) | | `ds.versions()`, `ds.checkout_version(v)`, `ds.restore()` | `tbl.list_versions()`, `tbl.checkout(v)`, `tbl.restore()` | | `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(compaction_options=..., cleanup_older_than=...)` | ## Learn more * [Lance format specification](https://lance.org/format): how the format works. * [Multimodal data and blobs](/enterprise/v1-12-0/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. * [Table versioning](/enterprise/v1-12-0/management/table#versioning): read and manage table versions. * [Computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column): add derived features to your data. * [Architecture](/enterprise/v1-12-0/index#architecture): how LanceDB Embedded and Enterprise build on Lance. # LanceDB Embedded Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/lancedb-embedded The open-source, embedded retrieval library that runs inside your application process. **LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database server to deploy. It reads and writes tables on local disk or in object storage from inside your application process, on the same [Lance](/enterprise/v1-12-0/basics/lance) format and table model that [LanceDB Enterprise](/enterprise/v1-12-0/enterprise/index) builds on. ![LanceDB Embedded architecture](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/overview/lancedb-embedded.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=e3fe4d7d4bd9f648eb43517c867fddf1) LanceDB Embedded: the LanceDB SDK and the Lance format run in your application, reading and writing tables on local disk or in object storage. ## Why use LanceDB Embedded? LanceDB Embedded fits local retrieval applications, notebooks, development, and single-node data pipelines, where your application controls its own compute resources and [table maintenance](/enterprise/v1-12-0/maintenance/compaction). * **No infrastructure to run** -- the library runs inside your process. There is no server to deploy, configure, or keep available. * **Free and open source** -- `pip install lancedb` (or the TypeScript or Rust equivalent) and start reading and writing tables, with no account or service to set up first. * **Full local control** -- your application decides where table data lives, when maintenance such as compaction and indexing runs, and how much compute each operation gets. * **The same table format as Enterprise** -- Embedded and [Enterprise](/enterprise/v1-12-0/enterprise/index) share the same Lance format and table model, so moving to a distributed deployment later does not require a data conversion step. ## Get started > [card] [Quickstart](/enterprise/v1-12-0/quickstart) > > Create a table, add data, and run your first search in a few lines of code. > [card] [Choose an SDK](/enterprise/v1-12-0/basics/sdk) > > Pick between the Python, TypeScript, and Rust SDKs. When your data or traffic outgrows a single machine, or you need managed infrastructure, private deployment, or platform support, see [LanceDB Enterprise](/enterprise/v1-12-0/enterprise/index) and the [feature-by-feature comparison](/enterprise/v1-12-0/basics/embedded-vs-enterprise). # Limits Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/limits Find fixed constraints, configurable bounds and what happens when you reach them. This page lists limits for job events, SQL error reports, sampling and full-text indexing. Each table identifies the affected API and what happens when a request reaches its limit. SQL and server job limits apply to Enterprise. [Naming Rules](/enterprise/v1-12-0/basics/naming) is the reference for name lengths, characters and namespace depth. Client and server versions can differ in which rules they enforce. ## Fixed API limits | Operation | Scope | Limit and behavior | | - | - | - | | Job event retrieval | Enterprise | At most 10,000 rows per response. Results can be truncated without a truncation indicator. | | `SHOW ERRORS ... LIMIT` | Enterprise SQL | Accepts 1 through 100,000. Values outside the range are rejected. | | `SHOW ERRORS` without `FOR JOB` | Enterprise SQL | Inspects up to the 32 most recent failed jobs. Use `FOR JOB` to inspect a specific job. | | Percentage sampling | Enterprise SQL | `TABLESAMPLE` accepts percentages from 0 through 100. Values outside the range are rejected. | | Row-count sampling | Enterprise SQL | `TABLESAMPLE (... ROWS)` requires a whole number. | See [SQL job commands](/enterprise/v1-12-0/sql/ddl/job#errors) and [Sampling](/enterprise/v1-12-0/sql/dql/sampling) for syntax and restrictions on supported table types. Data-type and index constraints belong to the operation you choose. Check [Data types](/enterprise/v1-12-0/sql/data-types) and [Vector indexes](/enterprise/v1-12-0/indexing/vector-index) before choosing a schema or index. For materialized views, confirm your source table meets your deployment's requirements with your administrator before creating one over it. ## Configurable limits | Setting | What it controls | | - | - | | Job event `limit` | Requests more or fewer event rows. The default is 1,000; the 10,000-row maximum still applies. | | FTS `max_token_length` | The maximum indexed token length. The default is 40; longer tokens are excluded from the index. | | Enterprise capacity and quotas | Storage, request rate and concurrency are governed by your deployment's resources and configuration. Confirm these with your administrator or LanceDB support. | ## Handling rejected or incomplete results * **Rejected requests:** correct the input before retrying, such as a sampling percentage outside the accepted range. * **Truncated responses:** do not assume that a returned event list is the full history. Increasing `limit` cannot exceed the maximum; use filters to narrow the events you inspect. * **Excluded data:** an FTS token-length setting can affect which words are searchable. Choose it for your text and indexing requirements. ## Learn more * [Naming Rules](/enterprise/v1-12-0/basics/naming): choose portable names and paths. * [Job Framework](/enterprise/v1-12-0/basics/jobs): track work and inspect events. * [Full-text indexes](/enterprise/v1-12-0/indexing/fts-index): configure tokenization. * [SQL](/enterprise/v1-12-0/basics/sql) and [SDKs](/enterprise/v1-12-0/basics/sdk): check interface support. * [Enterprise support](/enterprise/v1-12-0/deployment/support): discuss deployment capacity. # Naming rules Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/naming Choose portable names for your data objects and namespace paths. ## Naming rules Databases, namespaces, tables and views all have names. Choose names that describe their purpose, such as `documents`, `prod` or `training_2026`. Consistent names make data easier to find and application code easier to read. Use the following rules for names that work across LanceDB Embedded and LanceDB Enterprise. | Object | Characters | Length | | - | - | - | | Table, materialized view, view | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Namespace component | ASCII letters and digits, `-`, `_`, `.` | 1 to 64 characters; at most 10 components in a path | | Database | ASCII letters and digits, `-`, `_`, `.`, with `/` between components | 1 to 64 characters for the whole name | | Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Function | ASCII letters and digits, `_` | 1 to 128 characters | * Names and individual namespace or database components must not be empty. * Table, view, namespace and database components cannot be `.` or `..`. * Secret names cannot be `.` or `..`. * Avoid `$` and `:` because they separate parts of qualified identifiers. * A namespace path beginning with `public` cannot contain another component. ## Namespace paths A namespace path is a list of names. `["prod", "search"]` identifies the `search` namespace within `prod`. A table named `documents` belongs to that namespace; its table name remains `documents`. Use the SDK's namespace-path argument to supply the list. A period inside an SDK name is a character in that name, not a separator that creates another namespace. SQL uses its own qualified-name syntax; see [SQL namespace paths](/enterprise/v1-12-0/sql/dql/select#namespaces). The empty path `[]` identifies the root namespace. ## Examples | Name or path | Guidance | | - | - | | `documents`, `user-events.v2`, `train_2026` | Portable table names | | `["prod", "search"]` | A two-component namespace path | | `my table` | Use `my_table` instead of a space | | `orders$2026` | Use `orders_2026`; `$` is reserved | | `résumés` | Use an ASCII name such as `resumes` | | `["public", "search"]` | Invalid nesting under `public`; use a different parent namespace | ## Learn more * [Namespaces](/enterprise/v1-12-0/management/namespace): create namespaces and address tables. * [Limits](/enterprise/v1-12-0/basics/limits): check other constraints before designing your schema. # SDKs Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/sdk Choose a LanceDB SDK and find the API reference for your language. Use a LanceDB SDK to create tables, add data, build indexes and run searches from your application. Python, TypeScript and Rust work with both LanceDB Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. LanceDB Enterprise distributes query execution, indexing, maintenance and refresh work across the service, outside your application. The [quickstart](/enterprise/v1-12-0/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see [Connect to LanceDB](/enterprise/v1-12-0/basics/catalog). ## Client versions for these guides The database release and the client SDK version are separate choices. These guides use the following client baselines: | Client | Embedded 0.41.0 | Enterprise 1.12.0 | | - | - | - | | Python | `lancedb==0.41.0` | `lancedb==0.42.0b8` from the LanceDB preview index | | TypeScript | `@lancedb/lancedb@0.41.0` | `@lancedb/lancedb@0.42.0-beta.8` | | Rust | `lancedb` 0.41.0 for the general API; standalone quickstart examples pin 0.31.0 | Enable `remote`; examples use the pinned client revision below | Install the Python or TypeScript client used by the Enterprise examples: ```bash Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --extra-index-url https://pypi.fury.io/lancedb/ "lancedb==0.42.0b8" ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb@0.42.0-beta.8 ``` The Rust Function examples use the client revision bundled with Enterprise 1.12.0: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cargo add lancedb --git https://github.com/lancedb/lancedb \ --rev bff93ff314eee34f625d05bd92b73d95867fe787 --features remote ``` The released Rust 0.41.0 crate also includes APIs for registering, listing, fetching and dropping Functions. The source pin above selects the bundled client as the example baseline. A newer SDK does not add server capabilities: these guides still describe the limits of server 1.12.0. ## Official SDKs | SDK | API reference | | - | - | | Python | [Python reference](https://lancedb.github.io/lancedb/python/python/) | | TypeScript | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | | Rust | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | Guides show the available language examples together. Use the API reference for method signatures and options; SDKs do not expose every feature through the same methods. In Rust, enable the `remote` feature to connect to Enterprise. For SQL joins, aggregations and window functions, use [SQL](/enterprise/v1-12-0/basics/sql). Python provides a SQL client, and applications in other languages can use a Flight SQL client. TypeScript's table query API does not provide a SQL execution method. ## Lance Namespace SDKs LanceDB Enterprise's catalog and table operations follow the [Lance Namespace Client SDK Specification](https://lance.org/format/namespace), an open specification for describing access to tables in a multimodal lakehouse. Any client that implements it can integrate with LanceDB this way, not only the official SDKs above -- useful for a language or tool without a LanceDB SDK. For SQL queries, connect through [Flight SQL](/enterprise/v1-12-0/basics/sql) instead. | Language | Package | Used by | | - | - | - | | Java | `org.lance:lance-namespace-core` | Spark, Flink, Kafka, Trino, Presto; also LanceDB's Java client | | Python | `lance-namespace` | Core interface and connect functionality | | Rust | `lance-namespace` | Core interface, in [lance-format/lance](https://github.com/lance-format/lance) | LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated `LanceNamespace` interface talking to Enterprise's Namespace endpoint. The [real time engine](/enterprise/v1-12-0/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of the Lance Namespace Client SDK Specification. See [lance.org/format/namespace](https://lance.org/format/namespace) for the full specification and its other catalog implementations (Directory, Apache Polaris, Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more). ## Community SDKs These clients are maintained by the community. Check each project's supported features, installation instructions and releases before choosing one. | Language | Project | | - | - | | Go | [lancedb-go](https://pkg.go.dev/github.com/lancedb/lancedb-go/pkg/lancedb) | | Ruby | [Lancelot](https://github.com/scientist-labs/lancelot) | | Swift | [LanceDbSwiftKit](https://github.com/RyanLisse/LanceDbSwiftKit) | | R | [lancedb](https://github.com/CathalByrneGit/lancedb) | | Flutter | [flutter_lancedb](https://github.com/Alexcn/flutter_lancedb) | ## Related guides > [card] [SQL](/enterprise/v1-12-0/basics/sql) > > Query Enterprise tables with SQL from Python or a Flight SQL client. > [card] [PyTorch Data Loader](/enterprise/v1-12-0/training/data-loading) > > Use LanceDB tables in a DataLoader, including multiple worker processes. > [card] [Agentic Skills](/enterprise/v1-12-0/basics/agentic-skills) > > Use the LanceDB plugin to help a coding agent work with your data. # SQL Source: https://docs.lancedb.com/enterprise/v1-12-0/basics/sql Query LanceDB Enterprise with SQL from Python or an Arrow Flight SQL client. Use SQL in LanceDB Enterprise to filter records, join tables, calculate aggregates, and prepare datasets. SQL queries work with the same Lance tables you create and update through the SDKs, without exporting the data to another system. This guide starts with when to reach for SQL instead of SDK table operations, then covers the three ways to run SQL, connection settings, a first query, parameterized queries, and how to read and manage the results. ## Choose SQL or SDK table operations An SDK gives you a programming-language-specific API for invoking LanceDB's functionality: create a table, insert rows, build an index, run a vector search, each its own method call. Every one of those functionalities also has a corresponding SQL operation. SQL covers a wider surface than any one SDK method and lets you chain operations together in a single statement -- running a vector search and then joining the results with another table, for example -- where SDK methods stay separate calls. Use **SQL** for joins, aggregations, window functions, analytical queries, and whenever you want to chain operations together. Use **SDK table operations** to build applications around table management, ingestion, filtering, and search, including applications that run with LanceDB Embedded, where SQL is not available. You can combine them. For example, create and populate a table with an SDK, then query it with SQL to prepare a training dataset. In Python, both workflows can use the same Enterprise connection. Both interfaces work with the same Lance tables, through the same Arrow schema. Applications in different languages can work with the same tables: connect to the same database and namespace, use the appropriate credentials, and account for [read consistency](/enterprise/v1-12-0/tables/consistency) when another process writes data. A fixed-size vector column stores vectors of a consistent dimension; see the [data types reference](/enterprise/v1-12-0/sql/data-types) for the supported element types and other column types. ### Common SQL operations Several tasks are available through both interfaces, but the methods and SQL statements do not have identical coverage. SDK support also differs by language. These SQL reference pages describe the supported statements: | Task | SQL reference | | - | - | | Create a table | [CREATE TABLE](/enterprise/v1-12-0/sql/ddl/table) | | Insert or change rows | [INSERT](/enterprise/v1-12-0/sql/dml/insert), [UPDATE](/enterprise/v1-12-0/sql/dml/update), [DELETE](/enterprise/v1-12-0/sql/dml/delete) | | Build an index | [CREATE INDEX](/enterprise/v1-12-0/sql/ddl/index) | | Join and aggregate data | [SELECT](/enterprise/v1-12-0/sql/dql/select) | | Save a query as a view | [CREATE VIEW](/enterprise/v1-12-0/sql/ddl/view) | [Computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) store SQL expressions whose values are populated by a refresh. They are separate from registered Python Functions. See the computed-column and [materialized-view](/enterprise/v1-12-0/management/materialized-view) guides for their SDK and SQL operations and Enterprise setup requirements. ## Access LanceDB with SQL There are three ways to run SQL against LanceDB Enterprise, all against the same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) endpoint, returning results as Arrow record batches: 1. **`db.execute_query()`** on the Python SDK's Enterprise connection, shown below, or **`Connection::execute_query_async()`** on the Rust SDK's. These are LanceDB's native SQL execution methods, and we recommend them for the best performance -- see [Adaptive query execution](#adaptive). 2. **An Arrow Flight SQL client.** Use this from TypeScript, whose LanceDB SDK does not expose a SQL execution method, or from any tool with its own Flight SQL integration. A LanceDB-specific SDK is not required to submit SQL. 3. **The LanceDB CLI.** Open an interactive SQL shell, or run a statement or file, directly from the command line with no code at all. The [SQL reference](/enterprise/v1-12-0/sql#connecting) shows a query from Python. See [SDKs](/enterprise/v1-12-0/basics/sdk) for the LanceDB language clients. ### Adaptive query execution A standard Flight SQL client calls `GetFlightInfo` to plan a query and then `DoGet` to fetch rows -- two round trips every time, even when the server could stream results back immediately. `execute_query()` skips that extra round trip when it can. It calls `DoGet` directly for a query with no parameters, or `DoExchange` when [binding parameters](#parameters), and sends a `lancedb-sql-protocol: adaptive-v1` header. The server decides per query whether to stream results on that same call or defer execution and return a poll ticket; when it defers, `execute_query()` follows up with `PollFlightInfo` automatically, with no extra code on your side. A generic Flight SQL client does not send that header, so it always takes the slower `GetFlightInfo` path. ### Connection settings Get the following values from your Enterprise administrator: * Database URI, such as `db://your-database`. * API key and region. * API endpoint for `host_override`. * Flight SQL endpoint for `sql_host_override`, including its scheme and port. The Flight SQL endpoint must be enabled and reachable from your client. Pass it explicitly as `sql_host_override` in Python, as in the example below. The API and SQL endpoints may use different hosts or ports. See [Connect to Enterprise](/enterprise/v1-12-0/basics/catalog#enterprise) for other connection options. SQL runs in Enterprise. Connections to a local directory or an object-storage bucket use LanceDB Embedded and cannot execute SQL statements. Use SDK table operations to query those tables. ## Run a query in Python Install the SDK with `pip install lancedb`. Replace the connection placeholders with your Enterprise settings, including the region and both endpoint URLs. This example reads an existing `frames` table, with a `video_id` and a `caption` column describing each frame. Change the query to match your table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect( "db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-api-endpoint", sql_host_override="https://your-sql-endpoint:443", ) reader = db.execute_query("SELECT frame_id, video_id, caption FROM frames LIMIT 10") table = reader.read_all() print(table.to_pylist()) ``` In application code, load credentials from environment variables or a secrets manager. The [connection guide](/enterprise/v1-12-0/basics/catalog#enterprise) shows that setup. `execute_query()` returns a blocking Arrow reader; see [Adaptive query execution](#adaptive) for how it starts streaming. The example above uses `read_all()` to collect the small result in memory. For larger results, or to track and cancel a running query, see [Read and manage results](#results). To submit a query and check its status separately, use `execute_query_async()`. ## Parameters in SQL queries Pass a `parameters` argument to bind values into a query, instead of formatting them into the SQL string: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np reader = db.execute_query( "SELECT id FROM docs ORDER BY distance(vector, $1) LIMIT $2", parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) ``` Values travel as Arrow, not interpolated SQL text, so a vector binds as a fixed-size list with no manual formatting and no injection risk. Reference a parameter with `$1`, `$2`, ... for positional binding, or `$name` for named binding: * A list or tuple binds positionally, in order, to `$1`, `$2`, ... * A dict binds by key to `$name`. * A one-row `pyarrow.RecordBatch` or `Table` binds its columns, by name and by position. * A 1-D NumPy or Arrow array becomes a single fixed-size-list value -- use this form for a vector argument, as shown above. > [!NOTE] > > `parameters` is a LanceDB-specific mechanism, separate from the Flight SQL > protocol's `PREPARE`/bind step, which a deployment does not implement; see > [Prepared statements](#prepared-statements) below. Bind values with > `parameters` from the Python SDK; a generic Flight SQL client has no > equivalent. ## Prepared statements A Flight SQL client can prepare a statement before it runs it. A deployment accepts that, but it keeps no plan between runs and does not accept the parameter values described above at this protocol layer. > [!WARNING] > > There is no SQL `PREPARE` / `EXECUTE` here. Preparation is part of the > **Arrow Flight SQL protocol**, so you reach it through your client rather than > by sending a statement. A script containing `PREPARE name AS SELECT ...` will > not run. A Flight SQL client takes these steps, whatever it calls them: 1. **Prepare:** send the SQL and get back a handle and the result schema. The statement is parsed and planned at this point, so a syntax or name error surfaces here rather than at execution. 2. **Execute:** run the handle and read the result. The deployment plans the statement again each time it runs, so reusing a handle does not save planning time. 3. **Close:** release the handle. A client that binds values to placeholders such as `$1` and `$2` at this protocol layer gets a "not implemented" error when it executes the statement. Use `parameters` [above](#parameters) instead; do not put untrusted input directly into prepared statement text, since quoting it does not protect the statement the way binding a parameter would. Prepare a statement when your client requires it, or to get a statement's result schema and catch syntax and name errors without running it. Preparing does not make a repeated statement faster. To give a reusable query a name, create a [view](/enterprise/v1-12-0/management/view). To store its result for later queries, create a [materialized view](/enterprise/v1-12-0/management/materialized-view). ## Read and manage results * **Collect the results** when you want a list, Arrow table or DataFrame that fits in memory. Use a result limit and select only the columns you need. * **Read batches** when you want to process a large result incrementally. Reading batches avoids loading the entire result into application memory. It does not guarantee that the query can return its first batch immediately. ### Asynchronous clients An async client lets your application do other work while a request is waiting. That is separate from whether you collect results or read them in batches. Python offers synchronous and asynchronous clients; TypeScript uses async APIs. Check the SDK reference for the methods available in your client. ### Query handles and background jobs An Enterprise SQL query handle lets you inspect query execution and request cancellation. Background operations such as index builds return a [job](/enterprise/v1-12-0/basics/jobs) handle instead. Use the API for the returned handle to check status and retrieve results. ## Query plans Use query plans to understand how LanceDB reads data, applies filters and uses indexes. `explain_plan()` shows the planned operations. `analyze_plan()` runs the query and adds measurements, including execution time and rows processed. ### Inspect a plan or measure execution | Operation | Python / Rust | TypeScript | | :- | :- | :- | | Inspect the plan without executing the query | `explain_plan()` | `explainPlan()` | | Execute the query and report runtime measurements | `analyze_plan()` | `analyzePlan()` | Use the first to inspect query structure and the second to investigate work actually performed. Operator names and available measurements can differ between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/enterprise/v1-12-0/sql/dql/explain). > [accordion] Explain and analyze a query in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > query = table.search([1.0, 0.0]).select(["id", "text", "_distance"]).limit(2) > print("Plan:", query.explain_plan()) > print("Measured execution:", query.analyze_plan()) > rows = query.to_list() > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const query = table > .vectorSearch([1.0, 0.0]) > .select(["id", "text", "_distance"]) > .limit(2); > console.log("Plan:", await query.explainPlan()); > console.log("Measured execution:", await query.analyzePlan()); > const rows = await query.toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > println!("Plan: {}", query.explain_plan(false).await?); > println!("Measured execution: {}", query.analyze_plan().await?); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > This tiny table demonstrates the API, not a performance benchmark. The plan > uses a scan because the example has no vector index. The following larger > example illustrates how to read scans, filters and index operations. ### Read scans, filters and result retrieval The recorded example below uses 1.2 million rows sampled from the [Wikipedia dataset](https://huggingface.co/datasets/wikimedia/wikipedia). The counts describe that run. The table initially has no indexes, so the plan shows a scan. This Enterprise plan includes `RemoteTake` and hides storage paths as `uri=***`. A local plan shows the dataset path instead, and fetches the result rows with Lance's `Take` or, depending on the library version, a second `LanceRead` whose `source` is `stream(_rowid)`. Let's examine a vector search query that: * Filters rows where `identifier` is between 0 and 1,000,000 * Returns the top 100 matches * Projects specific columns: `chunk_index`, `title`, and `identifier` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # explain_plan query_explain_plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .explain_plan(True) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // explain_plan const explainPlan = await table .search(queryEmbed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .explainPlan(true); ``` #### Execution Plan Components > [accordion] Read the recorded vector plan operator by operator > > The execution plan reveals the sequence of operations performed to execute your query. Let's examine each component: > > ``` > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" > CoalesceBatchesExec: target_batch_size=1024 > GlobalLimitExec: skip=0, fetch=100 > FilterExec: _distance@3 IS NOT NULL > SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false] > KNNVectorDistance: metric=l2 > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 > LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false > ``` > > ##### 1. Base Layer (LanceScan) > > * Initial data scan loading only specified columns to minimize I/O > * Unordered scan enabling parallel processing > > ``` > LanceScan: > - projection=[vector, identifier] > - row_id=true, row_addr=false, ordered=false > ``` > > ##### 2. First Filter > > * Apply requested filter on `identifier` column > * Reduces the number of vectors that need KNN computation > > ``` > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 > ``` > > ##### 3. Vector Search > > * Computes squared L2 distances between query vector and all vectors that passed the filter > > ``` > KNNVectorDistance: metric=l2 > ``` > > ##### 4. Results Processing > > * Filters out null distance results > * Sorts by distance and takes top 100 results > * Coalesces output into batches targeting 1,024 rows in this plan > > ``` > SortExec: TopK(fetch=100) > - expr=[_distance@3 ASC NULLS LAST] > - preserve_partitioning=[false] > FilterExec: _distance@3 IS NOT NULL > GlobalLimitExec: skip=0, fetch=100 > CoalesceBatchesExec: target_batch_size=1024 > ``` > > ##### 5. Data Retrieval > > * `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version > * Handles efficient data retrieval from remote storage locations > * Fetches specific rows and columns needed for the final output > * Optimizes network bandwidth by only retrieving required data > > ``` > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" > ``` > > ##### 6. Final Output > > * Returns only requested columns and maintains column ordering > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] > ``` > > This plan demonstrates a basic search without index optimizations: it performs a full scan and filter before vector search. ### Non-vector queries Query plans also cover filters and full-text search. Python can show both sub-plans of a hybrid query. Check where a filter runs and how many rows flow through each operator; a separate `FilterExec` does not by itself establish that the plan is inefficient or that an index is missing. #### FTS queries ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} plan = ( table.search("puppy", query_type="fts") .where("category = 'animals'", prefilter=True) .limit(10) .explain_plan(True) ) print(plan) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const plan = await table .query() .fullTextSearch("puppy") .where("category = 'animals'") .limit(10) .explainPlan(true); ``` Look for the text-index operation and any scan of unindexed rows. A scan can be needed to include records written after the index was built. Use index coverage and execution measurements to determine whether that extra work matters. Check filter placement separately from text-index use. #### Hybrid queries For hybrid queries, `explain_plan` returns the reranker label followed by the vector and FTS sub-plans, indented for readability: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} plan = ( table.search("flower moon", query_type="hybrid") .where("category = 'film'", prefilter=True) .limit(10) .explain_plan(True) ) print(plan) # RRFReranker(...) # <vector sub-plan> # <FTS sub-plan> ``` `analyze_plan` executes both sub-queries and labels them `Vector Search Plan:` and `FTS Search Plan:`. Compare their filter placement and execution measurements. `analyze_plan` executes the query and returns the physical plan annotated with runtime metrics such as elapsed time, rows produced, bytes read and index comparisons. Where [`explain_plan`](#inspect-a-query-plan) tells you what a query intends to do, analysis shows the work performed. > [!NOTE] > > The SQL equivalent is [`EXPLAIN ANALYZE`](/enterprise/v1-12-0/sql/dql/explain). ### Read execution measurements Executes the query and provides detailed runtime metrics, including: * Operation duration (`_elapsed_compute_`) * Data processing statistics (`_output_rows_`, `_bytes_read_`) * Index effectiveness (`_index_comparisons_`, `_indices_loaded_`) * Resource utilization (`_iops_`, `_requests_`) ### Measure the example query Let's use `analyze_plan` to run the query and analyze the query performance, which will help us identify potential bottlenecks: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # analyze_plan query_analyze_plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .analyze_plan() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // analyze_plan const analyzePlan = await table .search(queryEmbed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .analyzePlan(); ``` #### Performance Metrics Analysis > [accordion] Inspect the recorded execution measurements > > ``` > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance], metrics=[output_rows=100, elapsed_compute=1.424µs] > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title", metrics=[output_rows=100, elapsed_compute=175.53097ms, output_batches=1, remote_takes=100] > CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=100, elapsed_compute=2.748µs] > GlobalLimitExec: skip=0, fetch=100, metrics=[output_rows=100, elapsed_compute=1.819µs] > FilterExec: _distance@3 IS NOT NULL, metrics=[output_rows=100, elapsed_compute=10.275µs] > SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false], metrics=[output_rows=100, elapsed_compute=39.259451ms, row_replacements=546] > KNNVectorDistance: metric=l2, metrics=[output_rows=1099508, elapsed_compute=56.783526ms, output_batches=1076] > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000, metrics=[output_rows=1099508, elapsed_compute=17.136819ms] > LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1200000, elapsed_compute=21.348178ms, bytes_read=1852931072, iops=78, requests=78] > ``` > > ##### 1. Data Loading (LanceScan) > > * Scanned 1,200,000 rows from the LanceDB table > * Read 1.86GB of data in 78 I/O operations > * Only loaded necessary columns (`vector` and `identifier`) > * Unordered scan for parallel processing > > ##### 2. Filtering and Search > > * Applied prefilter condition (`identifier > 0 AND identifier < 1000000`) > * Reduced dataset from 1.2M to 1,099,508 rows > * KNN search used L2 (Euclidean) distance metric > * Vector comparisons processed in 1076 batches > > ##### 3. Results Processing > > * KNN results sorted by distance (TopK with fetch=100) > * Null distances filtered out > * Batches coalesced to target size of 1024 rows > * Additional columns fetched for final results > * Remote take operation for 100 results > * Final projection of required columns #### Distributed metrics on LanceDB Enterprise Enterprise When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers: | Mode | What it shows | When to use it | | :- | :- | :- | | `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. | | `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. | | `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. | Python exposes this option through `distributed_metrics`. In TypeScript, pass the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python queries on LanceDB Embedded ignore the distributed mode and return single-node measurements. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Show a per-worker breakdown for a query on LanceDB Enterprise plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .limit(100) .analyze_plan(distributed_metrics="per_worker") ) print(plan) ``` > [!NOTE] > > Use `per_worker` or `full` sparingly; the plan output grows with the size of your worker pool. Stick with the default `aggregate` mode for routine tuning. #### Identify expensive operations * The query computes distances for 1,099,508 vectors; inspect timings to assess its contribution to latency * The scan reads 1.86 GB in this recorded run * Full table scan due to lack of indices * Compare this scan with an indexed plan using the same query ### Compare the query after adding indexes > [accordion] Compare the recorded indexed and unindexed plans > > The recorded query after adding vector and scalar indexes produced this plan: > > ``` > ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] > RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" > CoalesceBatchesExec: target_batch_size=1024 > GlobalLimitExec: skip=0, fetch=100 > SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] > ANNSubIndex: name=vector_idx, k=100, deltas=1 > ANNIvfPartition: uuid=83916fd5-fc45-4977-bad9-1f0737539bb9, nprobes=20, deltas=1 > ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) > ``` > > #### Optimized Plan Analysis > > ##### 1. Scalar Index Query > > ``` > ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) > metrics=[ > output_rows=2 > index_comparisons=2,301,824 > indices_loaded=2 > output_batches=1 > parts_loaded=562 > elapsed_compute=86.979354ms > ] > ``` > > * Range filter using scalar index > * Only 2 index files and 562 scalar index parts loaded > * 2.3M index comparisons for matches > > ##### 2. Vector Search > > ``` > ANNSubIndex: name=vector_idx, k=100, deltas=1 > metrics=[ > output_rows=2,000 > index_comparisons=25,893 > indices_loaded=0 > output_batches=20 > parts_loaded=20 > elapsed_compute=111.849043ms > ] > ``` > > * IVF index with 20 probes > * Only 20 index parts loaded > * 25,893 vector comparisons > * 2,000 matching vectors > > ##### 3. Results Processing > > ``` > SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] > GlobalLimitExec: skip=0, fetch=100 > CoalesceBatchesExec: target_batch_size=1024 > ``` > > * Sorts by distance > * Limits to top 100 results > * Batches into groups of 1024 > > ##### 4. Data Fetching > > ``` > RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" > metrics=[output_rows=100, elapsed_compute=113.491859ms, output_batches=1, remote_takes=100] > ``` > > * Single output batch > * One remote take per row > > ##### 5. Final Projection > > ``` > ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] > ``` > > * Returns specified columns: chunk_index, title, identifier, and distance > > #### Performance Improvements > > ##### 1. Initial Data Access > > ``` > ScalarIndexQuery metrics: > - indices_loaded=2 > - parts_loaded=562 > - output_batches=1 > ``` > > * Before: Full table scan of 1.2M rows, 1.86GB data > * After: Only 2 indices and 562 scalar index parts loaded > * Benefit: Eliminated table scans for prefilter > > ##### 2. Vector Search Efficiency > > ``` > ANNSubIndex: > - index_comparisons=25,893 > - indices_loaded=0 > - parts_loaded=20 > - output_batches=20 > ``` > > * Before: L2 calculations on 1,099,508 vectors > * After: > * About 97.6% fewer vector comparisons (25,893 versus 1,099,508) > * Decreased output batches from 1,076 to 20 > > ##### 3. Data Retrieval Optimization > > ``` > RemoteTake: > - remote_takes=100 > - output_batches=1 > ``` > > * RemoteTake operation remains consistent ### Choose a change to measure #### 1. Index Implementation ##### When to Create Indices * Columns used in WHERE clauses * Vector columns for similarity searches * Join columns used in `merge_insert` ##### Index Type Selection | Data Type | Recommended Index | Use Case | | - | - | - | | Vector | IVF_PQ/IVF_HNSW_SQ/IVF_HNSW_FLAT | Approximate nearest neighbor search | | Scalar | B-Tree | Equality and range filters | | Categorical | Bitmap | Multi-value filters and set operations | | `List` | Label_list | Multi-label classification and filtering | > [card] Index Coverage Monitoring > > Use `table.index_stats()` to monitor index coverage. > Unindexed rows can add scan work. Use their count alongside query measurements > to decide when index maintenance is needed. #### 2. Query Plan Optimization ##### Common Patterns and Fixes | Plan Pattern | Optimization | | - | - | | Scan with high bytes read or I/O count | Check index coverage and whether the query can use an index | | | Use `select()` to limit returned columns | | | Check whether the dataset has been compacted | | Multiple filters | Check their placement and row counts; compare the plan after changing the query | > [!NOTE] > > Regularly analyze your query plans to identify and address performance > bottlenecks. The `analyze_plan` output provides detailed metrics to guide > optimization efforts. #### 3. Getting Started with Optimization Keep the query, data and result limit fixed while changing one factor. Compare rows processed, bytes read, timings and returned results. For ANN changes, measure recall too: doing less work is useful only if retrieval quality meets your application's needs. See [vector indexes](/enterprise/v1-12-0/indexing/vector-index) and [scalar indexes](/enterprise/v1-12-0/indexing/scalar-index) for index choices. ## Vector and full-text search SQL vector search support depends on the Enterprise server version and query form. Versions that support `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan can plan indexed or flat vector search. Check that your server version supports this form, then use [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain) to inspect the query plan. The [SDK vector search API](/enterprise/v1-12-0/search/vector-search) is also available in LanceDB Enterprise and LanceDB Embedded. Use it when you prefer the SDK query builder or need to search embedded tables. For full-text search in SQL, use the [`fts()`](/enterprise/v1-12-0/sql/dql/fts) table function or the [`contains_tokens`](/enterprise/v1-12-0/sql/dql/contains-tokens) predicate. ## SQL syntax and API references The [SQL reference](/enterprise/v1-12-0/sql) documents statement syntax, supported expressions, and data types. For SDK methods and their arguments, use the [Python](https://lancedb.github.io/lancedb/python/python/), [TypeScript](https://lancedb.github.io/lancedb/js/), or [Rust](https://docs.rs/lancedb/latest/lancedb/index.html) API reference. > [card] [SQL Reference](/enterprise/v1-12-0/sql) > > Statement syntax, expressions, and data types for LanceDB SQL. ## Next steps > [card] [Quickstart](/enterprise/v1-12-0/quickstart) > > Run a complete create, insert and search example. > [card] [Search](/enterprise/v1-12-0/search) > > Choose vector, full-text or hybrid retrieval. > [card] [Filtering](/enterprise/v1-12-0/search/filtering) > > Narrow results with predicates. > [card] [SDKs](/enterprise/v1-12-0/basics/sdk) > > Compare language clients and find their API references. # Profiling a dataset Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/aggregate Measure coverage, missing values and class balance before selecting a dataset. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL aggregates to summarize a dataset: count records, find missing values, and compare groups. These summaries help you understand the data before selecting records for search, evaluation or training. ## Example data Connect with an [Enterprise SQL client](/enterprise/v1-12-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Count records and missing values Use `count(*)` to count rows and `count(column)` to count non-null values. Add `DISTINCT` to count unique values: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*) AS records, count(DISTINCT doc_id) AS documents, count(caption) AS captioned, count(*) FILTER (WHERE caption IS NULL) AS missing_caption FROM curation_documents; ``` The example returns **6 records, 4 documents, 4 populated captions and 2 missing captions**. `count(column)` excludes null values; it does not check whether a string is empty or whether a value is useful for the task. ## Group records by label Use `GROUP BY` to calculate a summary for each label: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT label, count(*) AS documents FROM curation_labels GROUP BY label ORDER BY documents DESC, label; ``` There are **2 cats and 1 dog** in the label table. Document 40 is absent, so this query does not measure labeling coverage across all source documents. Use a [left join](/enterprise/v1-12-0/curation/join#join-type) to find documents without labels. Decide whether the distribution matches your intended use. A uniform random sample tends to preserve the source distribution; it does not balance classes. To cap the number selected per label, use [ranking within a group](/enterprise/v1-12-0/curation/windowing#per-group). ## Count records that match a condition ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT source, count(*) AS records, count(*) FILTER (WHERE score >= 0.9) AS high_score, count(*) FILTER (WHERE caption IS NULL) AS missing_caption FROM curation_documents GROUP BY source ORDER BY source; ``` `FILTER` applies a condition to one aggregate. Here, `books` has 2 records, 1 high-score record and no missing captions. `web` has 4 records, 1 high-score record and 2 missing captions. Counts are per record, so repeated document IDs still contribute more than once. ## Group numeric values into ranges Use `count(DISTINCT column)` for the number of distinct non-null values. For numeric fields, group by a range or summarize their distribution. For example, this query counts records in score buckets of width 0.1: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT floor(score * 10) / 10 AS score_bucket, count(*) AS records FROM curation_documents GROUP BY score_bucket ORDER BY score_bucket; ``` For time-based data, group by the time interval relevant to the task. The [aggregation reference](/enterprise/v1-12-0/sql/dql/aggregation) and [scalar function reference](/enterprise/v1-12-0/sql/dql/scalar-functions) cover additional summaries, including approximate counts and percentiles. Use an approximate aggregate when an estimate is sufficient; use an exact count when the result must be precise. ## Aggregate over a Function's result An aggregate can summarize a [Function](/enterprise/v1-12-0/curation/create-function)'s output the same as any other expression -- the engine computes the Function once per row, then aggregates. Register `caption_quality` the same way any other curation Function is registered: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT source, avg(caption_quality(caption)) AS avg_quality FROM curation_documents WHERE caption IS NOT NULL GROUP BY source ORDER BY source; ``` Filtering out null captions first avoids calling the Function on rows with nothing to score. ## Profile a sample A [sample](/enterprise/v1-12-0/curation/statistical-sampling) can help you explore a large dataset before a full scan. Report the sample size and method alongside the result. A sample can miss rare classes, and fragment sampling can reflect the order in which records were written. Before accepting a curated dataset, check its required fields and key constraints directly rather than inferring them from a small sample. ## Continue curating Use these measurements to choose a [sample](/enterprise/v1-12-0/curation/statistical-sampling), [attach missing metadata](/enterprise/v1-12-0/curation/join), or [select one record per document](/enterprise/v1-12-0/curation/windowing). See [Aggregation](/enterprise/v1-12-0/sql/dql/aggregation) for complete SQL syntax. # Blob Late Materialization Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/blob-late-materialization Deferring a wide BlobV2 or vector column's read until after a join has already narrowed down which rows survive. **Applies to:** Embedded ❌, Enterprise ✅ A join that includes a wide column -- a [BlobV2](/enterprise/v1-12-0/management/table#managed-blobs) or an embedding -- can multiply that column's read far past the result's own row count: a naive plan reads the wide column for every candidate row the join considers, then throws most of that work away once the join condition filters non-matches. Blob late materialization is the optimizer rewrite that avoids this, deferring the wide read until after the join has already settled which rows survive. ## The two plan shapes ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph Naive["Naive: wide column read before filtering"] direction TB N1["Scan wide column<br/>for every row"] --> N2["Join"] N2 --> N3["Rows that didn't match<br/>are discarded --<br/>their wide read was wasted"] end subgraph Deferred["Late materialization: wide column read after filtering"] direction TB D1["Scan only the join key<br/>(+ early columns)"] --> D2["Join on the key"] D2 --> D3["RemoteTake:<br/>fetch the wide column,<br/>once per surviving row"] end classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class D3 accent ``` In the naive plan, the wide column is read once per **candidate** row -- every row either side of the join could possibly produce -- before the join has thrown any of them away. In the rewritten plan, the join operates on a narrowed schema (the key, any small "early" columns, and a row id), and a `RemoteTake` node fetches the wide column afterward, once per row that actually **survived** the join. ## Eligibility This is a physical-plan optimizer rewrite, not something you opt into with special syntax -- the optimizer decides whether a given join qualifies. It applies to a plain inner equi-join (a single `ON left_col = right_col` condition, no additional filter fused into the join, no `LIMIT` fused into it) where one side -- and only one side -- bottoms out at a single, otherwise-unfiltered table scan: no existing row filter, scan range, fragment subset, deleted-row handling, or [RTE write](/enterprise/v1-12-0/ingestion/realtime-write) tier. If both sides would otherwise qualify, the side with a BlobV2 column is preferred over the other; if neither or both sides have one, the rewrite declines rather than guessing which to narrow. Which columns actually get deferred differs by which side of the join is narrowed: * **The side that builds the join's hash table:** every column beyond the join key is deferred, regardless of size. The hash table holds everything this side reads for the lifetime of the join, so even a modestly-sized column adds up across every row the join holds in memory at once. * **The side that probes the hash table:** only columns wide enough to cross a size heuristic are deferred; small columns stay in the initial scan, since reading them eagerly doesn't carry the same memory risk. A BlobV2 column's **descriptor** (small, pointer-like) is early and stays in the scan either way -- only the raw **bytes** of the blob are late and deferred, so narrowing doesn't lose track of which rows have a blob at all, just postpones reading its payload. ## Where the deferred read actually happens The take itself runs through the same replica-group-aware routing as any other distributed table read (see [Horizontal Scaling](/enterprise/v1-12-0/enterprise/horizontal-scaling)) -- it is not shipped back to the query node to be joined there directly. Routing is resolved once per query and reused across every batch the take processes, rather than re-resolved per batch, which is what keeps repeated takes in the same query hitting a cache that's already warm instead of bouncing between replica groups. Where the executing node already holds the needed data, the take can also resolve natively without a separate network round trip at all. ## Confirming it happened A join written this way is a **candidate** for the rewrite, not a guarantee -- confirm it per query with [`EXPLAIN`](/enterprise/v1-12-0/basics/sql#query-plans). A `Take` or `RemoteTake` node by itself isn't proof either way -- it's the general operator that fetches columns for selected rows from remote storage, and shows up in an ordinary, join-free query just as it does here (see the [recorded vector-search plan](/enterprise/v1-12-0/basics/sql#5-data-retrieval)); the rewrite itself inserts a plain `Take`, which only a later, separate pass turns into `RemoteTake`. What confirms the deferral specifically is a `Take`/`RemoteTake` node sitting above a `HashJoinExec`, fetching a column set that includes `__join_late_materialization_key` -- that key column only exists when this rewrite fired. Join on a narrow, selective key and project the wide columns only in the final select list, rather than alongside the join condition: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT s.frame_id, f.image, f.embedding FROM selected AS s JOIN frames AS f ON f.frame_id = s.frame_id ``` `selected` is narrow -- just the frame IDs an earlier curation step already kept. `frames` is wide -- a BlobV2 `image` and a vector `embedding` alongside its key. Neither a passing query nor an `EXPLAIN` that omits `RemoteTake` tells you how much I/O a plan did or did not save on its own -- use [`EXPLAIN ANALYZE`](/enterprise/v1-12-0/sql/dql/explain) for the plan's actual row and byte counts, since plain `EXPLAIN` shows the planned shape without executing the query. ## What to read next > [card] [Joining datasets](/enterprise/v1-12-0/curation/join) > > Join types, duplicate keys, and calling a Function across a join. > [card] [Joins](/enterprise/v1-12-0/sql/dql/join) > > Join syntax and semantics in the SQL reference. > [card] [Query plans](/enterprise/v1-12-0/basics/sql#query-plans) > > Reading `EXPLAIN` output in general. > [card] [Horizontal Scaling](/enterprise/v1-12-0/enterprise/horizontal-scaling) > > The replica-group routing a RemoteTake's read goes through. # Scope curation to what changed Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/changes Process only the rows added since your last curation run, instead of rescanning the whole table. **Applies to:** Embedded ❌, Enterprise ✅ A curation task you run repeatedly -- chunking, deduplication, profiling -- does not need to rescan rows it already processed. `CHANGES` reads only the rows appended to a table since an earlier [version](/enterprise/v1-12-0/management/table#versioning), so a recurring job can scope itself to what is new. ## Example data `curation_batches` gets a batch of new documents appended periodically, with no updates or deletes between appends: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR); INSERT INTO curation_batches VALUES (1, 'web', 'A cat on a chair'), (2, 'web', 'A dog in a field'); -- note the version after this insert, for example 5 INSERT INTO curation_batches VALUES (3, 'books', 'A bird in a tree'), (4, 'books', 'A cat by a window'); -- the table is now at a later version, for example 7 ``` ## Read only what is new `CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)` reads the rows appended after version 5 -- documents 3 and 4 -- without rescanning 1 and 2: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` Record the table's version after each curation run, then start the next run's `CHANGES` from it. See [Versioning](/enterprise/v1-12-0/management/table#versioning) for the APIs that read a table's current version. ## Chain it into a curation task `CHANGES` is a relation, like any other table reference, so it composes with the rest of this page: chunk, dedupe, or join only the new rows, instead of the whole table. Materializing the result keeps a running, append-only table of work already done: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSERT INTO curated_batches SELECT doc_id, source, text FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) WHERE source = 'books' ``` A [chunker Function](/enterprise/v1-12-0/curation/chunking) or a [`dedupe`](/enterprise/v1-12-0/sql/dql/dedupe) call works the same way: put the `CHANGES` relation where the source table would otherwise go, and only the new rows flow through it. ## Strictly append-only The clause is named for what it requires, not just what it does. If anything other than a pure append happened to the table between the starting version and the current one -- an update, a delete, a merge -- the query is refused rather than silently returning an incomplete or wrong result: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- refused if any row in curation_batches was updated or deleted after version 5 SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` When that happens, either re-run from a later starting version that is itself after the non-append write, or read the table in full instead of incrementally for that run. See [Changes since a version](/enterprise/v1-12-0/sql/dql/changes#strict) for the complete set of refused forms. ## What to read next > [card] [CHANGES](/enterprise/v1-12-0/sql/dql/changes) > > The full SQL syntax, placement rules, and unsupported forms. > [card] [Table](/enterprise/v1-12-0/management/table#versioning) > > How table versions work, and how to find one to start from. # Chunk records into multiple rows Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/chunking Expand one source row into many derived rows -- documents into passages, videos into clips, images into tiles. **Applies to:** Embedded ❌, Enterprise ✅ Every other curation task on this page keeps the row count the same or smaller: profiling, sampling, joining, deduplicating. Chunking goes the other way -- one source row becomes many derived rows, each carrying its parent's columns along with it. Use it to split a document into passages for embedding, a video into clips, or an image into tiles. ## Define a chunking Function A Function that returns a `list` produces more than one value per input row. A chunker is a Function whose output is a list -- of structs, of strings, of anything -- registered like any other Function. See [Create a Function](/enterprise/v1-12-0/curation/create-function) for CPU, GPU and remote-service Functions, and scalar versus batch calling, if you have not registered one before. A function that splits text into fixed-size passages turns a `documents` table into one row per passage. Registration details, environment and dependency declarations, and how a version stays immutable once rows are filled from it, are the same for a chunker as for any other Function -- register it from Python, or the same function from SQL with [`CREATE FUNCTION`](/enterprise/v1-12-0/sql/ddl/function#create): **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is a method of..." (long text) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb.functions import function @function( output_schema=pa.list_( pa.struct([ pa.field("chunk_index", pa.int64(), nullable=False), pa.field("chunk_text", pa.utf8(), nullable=False), ]) ), ) def split_into_passages(text: str) -> list[dict]: size = 200 return [ {"chunk_index": i, "chunk_text": text[i : i + size]} for i in range(0, len(text), size) ] version = db.create_function_async(split_into_passages).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION split_into_passages(text utf8) RETURNS list<struct<chunk_index: int64, chunk_text: utf8>> LANGUAGE python AS ' def split_into_passages(text): size = 200 return [ {"chunk_index": i, "chunk_text": text[i:i+size]} for i in range(0, len(text), size) ] ' ``` ## Explode it in a query Wrap the function call in `UNNEST` in the `SELECT` list, with an alias: it yields one row per element of the list the function returns, with every other selected column repeated. Reference the exploded struct's fields through that alias in a query over this one: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH exploded AS ( SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p FROM documents ) SELECT doc_id, title, p.chunk_index, p.chunk_text FROM exploded ``` A document with five 200-character passages becomes five output rows, each carrying `doc_id` and `title` from its parent. This is the fastest way to check a chunker before committing to a materialized view: run it over a few rows and inspect the output shape. ## Video into frames Chunking a blob column is the same shape, with the chunker producing timestamps rather than text spans, and a second Function pulling the actual frame for each one. `videos` holds raw clips in a [Blob v2](/enterprise/v1-12-0/management/table#managed-blobs) column, with each row's duration already known: **Source: `videos`** | video_id | video | duration_seconds | | - | - | - | | "clip-1" | (Blob v2 bytes) | 12.0 | A chunker that samples one timestamp per second needs no blob access at all \-- it only looks at `duration_seconds`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function( output_schema=pa.list_( pa.struct([ pa.field("frame_index", pa.int64(), nullable=False), pa.field("ts", pa.float64(), nullable=False), ]) ), ) def sample_frame_timestamps(duration_seconds: float) -> list[dict]: every = 1.0 # one frame per second count = int(duration_seconds // every) return [{"frame_index": i, "ts": i * every} for i in range(count)] version = db.create_function_async(sample_frame_timestamps).wait() ``` A second Function reads the blob -- incrementally, through a `BlobReader`, rather than loading the whole clip -- and returns one JPEG per call: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb import BlobReader @function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], input_schema=pa.schema([ lancedb.blob("video"), pa.field("ts", pa.float64(), nullable=False), ]), output_schema=lancedb.blob("jpeg", nullable=False), ) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # decode the frame at ts, encode as JPEG, return its bytes extract_version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) ``` Compose both in one query: explode `videos` into one row per sampled timestamp, then call `extract_frame` on each row to produce its image: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH sampled AS ( SELECT video_id, video, UNNEST(sample_frame_timestamps(duration_seconds)) AS f FROM videos ) SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg FROM sampled ``` A 12-second clip becomes 12 output rows, each with its own extracted JPEG. A Function in `FROM` position yields one row per list element the same way regardless of what the list holds; whether the second step produces a blob, a plain value, or another struct does not change the explosion. ## Persist it as a materialized view Wrap either query in [`CREATE MATERIALIZED VIEW`](/enterprise/v1-12-0/sql/ddl/materialized-view) to keep a real table that stays current as the source changes, instead of recomputing the explosion on every query: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW chunks AS WITH exploded AS ( SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p FROM documents ) SELECT doc_id, title, p.chunk_index, p.chunk_text FROM exploded ``` **Derived: `chunks`** (1:N expansion) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning is a method..." | | 1 | "Intro to AI" | 1 | "...of teaching computers..." | The view refreshes like any other materialized view: new source rows are chunked and inserted, deleted source rows drop their children, and an updated row's old children are replaced by freshly chunked ones on the next [refresh](/enterprise/v1-12-0/feature-engineering/refresh-column). A single `UNNEST(...)` -- whether unnesting a Function's list output directly, as above, or an existing list column -- is the only lateral expansion a materialized view can carry, and it can't be combined with `GROUP BY`, so keep aggregation or further curation in a second step over the chunked table. ## Chunk, then curate A freshly chunked table is a normal table: [dedupe](/enterprise/v1-12-0/curation/dedupe) it to collapse near-identical chunks, [sample](/enterprise/v1-12-0/curation/statistical-sampling) it for a quick look, or [profile it](/enterprise/v1-12-0/curation/aggregate) to check how many chunks each source row produced. Continue with [choosing a curation task](/enterprise/v1-12-0/curation#questions). # Cluster records by index partition Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/clustering Group records by the partition an existing IVF vector index already assigns them to, without training a new clustering model. **Applies to:** Embedded ❌, Enterprise ✅ `ivf_partition` groups records by the partition a vector falls into, using the centroids of an IVF-family vector index you already built for search -- no separate clustering model to train or maintain. Use it as a `GROUP BY` key to aggregate per cluster, or to sample across clusters instead of across rows. ## Example data Connect with an [Enterprise connection](/enterprise/v1-12-0/basics/catalog#enterprise). > [accordion] Create the example table > > Use the same `curation_embeddings` fixture as [dedupe](/enterprise/v1-12-0/curation/dedupe#example-data) > \-- eight records, where rows 10 and 20 are near-identical, 30, 40 and 50 > form one looser cluster, and 60, 70 and 80 are each distinct and > increasingly far apart -- but build the index with more partitions. > Clustering wants partitions fine-grained enough to tell the two clusters > apart; deduplication only needs a distance threshold within one: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.create_index("embedding", config=IvfFlat(num_partitions=5, distance_type="l2")) > table.wait_for_index(["embedding_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > await table.createIndex("embedding", { > config: lancedb.Index.ivfFlat({ numPartitions: 5, distanceType: "l2" }), > }); > await table.waitForIndex(["embedding_idx"], 300); > ``` > > ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::time::Duration; > > use lancedb::index::vector::IvfFlatIndexBuilder; > use lancedb::index::Index; > use lancedb::DistanceType; > > table > .create_index( > &["embedding"], > Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(5).distance_type(DistanceType::L2)), > ) > .execute() > .await?; > table.wait_for_index(&["embedding_idx"], Duration::from_secs(300)).await?; > ``` > > `ivf_partition` reads an existing index's trained centroids; it does not > train one. The column needs an up-to-date, single-segment IVF-family index > before the function runs, the same requirement [`dedupe`](/enterprise/v1-12-0/curation/dedupe#example-data) > has. ## Group records by partition `ivf_partition(column)` returns the partition each row's vector falls into. Rows closer to the same centroid than to any other land in the same partition, so the near-identical cat photos (10, 20) group together, the three dog photos (30, 40, 50) group together, and the three increasingly distant photos (60, 70, 80) are more likely to each keep their own partition: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids, count(*) AS n FROM curation_embeddings GROUP BY cluster ORDER BY cluster ``` The exact partition numbers depend on how the index's centroids were trained, but rows that are close together in embedding space consistently land in the same group. Aggregate anything per cluster this way -- `count(*)` for cluster sizes, `avg(score)` for a per-cluster quality signal, or `array_agg(id)` to collect candidate rows for a downstream pass. ## Sample across clusters instead of across rows Pass a selection mode to group by only a subset of the index's partitions, instead of all of them: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- The first 2 partitions, deterministically SELECT ivf_partition(embedding, 'first', 2) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster; -- 2 partitions chosen at random, reproducible via the seed SELECT ivf_partition(embedding, 'random', 2, 42) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster; ``` `'first'` takes the first `count` partitions and accepts no seed, since the result is already deterministic. `'random'` requires a seed, so the same call reproduces the same partitions. Either way, the result is a spatially-stratified sample across the embedding space: one that covers each selected region of the data, rather than a plain row sample that can easily pick many near-duplicate rows from a dense cluster and miss a sparse one entirely. ## Keep a clustering current with a materialized view Wrap a `GROUP BY ivf_partition(...)` query in a [materialized view](/enterprise/v1-12-0/management/materialized-view) so the grouping stays current as new records arrive: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW curation_embeddings_clustered AS SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster ``` A refresh reassigns every row's partition from the index's current centroids, so retraining the index with [`replace=True`](/enterprise/v1-12-0/feature-engineering/add-computed-column) regroups the view on the next refresh. See [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) for manual and automatic refresh options. ## A typical use case: deduplication Near-duplicate records are close together in embedding space, so they consistently land in the same or a neighboring partition. Grouping by `ivf_partition` first, then comparing distances only within each group, finds near-duplicate candidates without a full pairwise scan across the whole table. This is exactly the approach [`dedupe` and `duplicate_pairs`](/enterprise/v1-12-0/curation/dedupe) use internally, packaged as a table function with a `distance_threshold` instead of a `GROUP BY` clause to write yourself. Reach for those directly for deduplication; use `ivf_partition` when the task is a different kind of per-cluster grouping or sampling, not deduplication specifically. ## Related guides > [card] [IVF_PARTITION](/enterprise/v1-12-0/sql/dql/ivf-partition) > > The full function signature: arguments, sampling modes, and positional syntax. > [card] [Deduplicate near-duplicates](/enterprise/v1-12-0/curation/dedupe) > > The packaged table function for the deduplication use case above. > [card] [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) > > Row-level and fragment-level sampling, without clustering. # Create a Function Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/create-function Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Early access Some curation steps cannot be written as a SQL expression: an embedding model, an image decode, a call to an external service. A Function is a Python callable registered with the database, versioned, and then applied as a column or called in a query -- the code runs where the data is, not pulled into your process first. This page covers how to shape one; later curation tasks such as [Chunking](/enterprise/v1-12-0/curation/chunking) assume you have read it. The full registration, listing, refresh and drop lifecycle is covered on the [Function management reference](/enterprise/v1-12-0/management/function); the examples below focus on shaping a Function for common curation tasks. ## Scalar: once per row The plain form takes one row's values and returns one result. Types are inferred from the annotations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col, function @function(pip=["numpy==2.2.0"]) def score(value: float) -> float: return value * 2 version = db.create_function_async(score).wait() table.add_columns({"doubled": version(value=col("value"))}) ``` `pip` declares the worker's dependencies; they are part of the function's immutable version, so changing one produces a new version rather than altering rows a previous version already filled. ## Batch: once per call, many rows at a time A function is called once per batch instead of once per row when its parameters are annotated `pyarrow.Array`, or when it takes a single `pyarrow.RecordBatch` parameter to read more than one column together. The same doubling logic, vectorized over a whole batch at once: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pyarrow.compute as pc from lancedb import function @function( pip=["numpy==2.2.0"], batch_size=32, row_timeout_seconds=90, input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.float64(), ) def score_batch(value: pa.Array) -> pa.Array: return pc.multiply(value, 2) ``` Batching amortizes per-call overhead across many rows, which matters most once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. `batch_size` caps the number of input rows in each execution batch; actual batches may be smaller. `row_timeout_seconds` bounds each Python call: one row for scalar Functions or the entire batch for vectorized Functions. It does not include the instance's `__init__`. Both settings are part of the registered version. Enterprise 1.12.0 does not support a per-Function call-concurrency setting. Batch annotations such as `pa.Array` do not specify element types. Supply both `input_schema` and `output_schema`, as above. ## Stateful Functions: load once, call many times A `@function`-decorated **class** is the same callable with state. Each remote instance calls `__init__` once, calls `__call__` for every row or batch it processes, and calls `close()`, if defined, once when it retires: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import function @function class scale: def __init__(self, factor: float, offset: float = 0.0): self.factor = factor self.offset = offset def __call__(self, value: float) -> float: return value * self.factor + self.offset ``` Constructor parameters are **initialization fields**, bound once per binding rather than read per row -- mixed with per-row columns in the same call: `version(value=col("value"), factor=2.0)`. Load models, open clients, and build rate limiters in `__init__`; every batch the instance serves then reuses them, since an instance's state is shared across its own batches but never across other instances or workers. This is the pattern GPU inference and remote-API Functions both build on below. ## GPU: batch inference, loaded once `db.list_gpu_classes()` lists the GPU classes configured for the deployment. Each record reports the operator's hardware description and limits; it does not mean a GPU is currently free. Listing requires the System Usage permission. Pass a returned class name to `gpu_class` to fix that placement in the Function version. `gpu=True` remains required: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb import function gpu_class = next( gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G" ) @function( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), output_schema=pa.list_(pa.float32(), list_size=384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): import torch from sentence_transformers import SentenceTransformer device = "cuda" if torch.cuda.is_available() else "cpu" self.model = SentenceTransformer(model_name, device=device) def __call__(self, text: pa.Array) -> pa.Array: texts = [t or "" for t in text.to_pylist()] embeddings = self.model.encode(texts) return pa.array(embeddings.tolist(), type=pa.list_(pa.float32(), list_size=384)) version = db.create_function_async(embed_text).wait() table.add_columns({"embedding": version(text=col("caption"))}) ``` Older servers that do not implement `GET /v1/gpu/classes` raise `NotImplementedError`. Without `gpu_class`, the deployment's default GPU class is used. The class is immutable with the Function version; set a per-refresh class or aggregate GPU budget through [`refresh_column_async`](/enterprise/v1-12-0/feature-engineering/refresh-column#resources). The model loads once per worker instance, in `__init__`; `__call__` only encodes the batch it was handed. Registering the same logic as a plain function instead would reload the model on every single row. ## Calling a remote service A function that calls an external API needs a credential without putting it in the function's source. A Secret is a database-scoped named credential: `db.create_secret` stores the value once, and binding it at registration time puts it in the environment variable the function reads, without ever returning it from any API or recording it in the function's own definition. Combine it with the stateful form so the HTTP client -- and any rate limiter around it -- is built once, not reopened on every row. There is no built-in retry or per-row error-skip policy -- a function that calls a flaky service should handle timeouts and retries itself, inside `__call__`. See [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret#specify) for the full worked example, how the bound value actually reaches a running evaluation, and how that differs from rotating or revoking it later. ## Read and produce blobs A Function can bind a [Blob v2 column](/enterprise/v1-12-0/management/table#managed-blobs) and return another blob, including a blob nested inside a struct field, not only at the top level. In row mode, a top-level blob parameter arrives as Python `bytes`, or `None` for a nullable input, after the worker has read the payload. Return bytes and let the destination table store the Managed payload and descriptor. This section extracts a frame from a stored video and captions it, continuing as one example across chaining, persisting and incremental reads below. `videos` holds raw clips in a `video` Blob v2 column; `frames` names one timestamp per clip to extract, with a `selected` flag to skip some: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa videos = db.create_table("videos", schema=pa.schema([ pa.field("id", pa.utf8(), nullable=False), lancedb.blob("video", nullable=False), ])) frames = db.create_table("frames", [ {"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True}, {"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True}, ]) ``` ### Produce a blob Declare blob inputs and outputs explicitly. `extract_frame` reads one frame out of a video at a timestamp and returns it as a JPEG, without loading the whole clip first -- see [Read a blob incrementally](#incremental) below for how the `video: BlobReader` parameter does that: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb import BlobReader, col from lancedb.functions import function @function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], input_schema=pa.schema([ lancedb.blob("video"), pa.field("ts", pa.float64(), nullable=False), ]), output_schema=lancedb.blob("jpeg", nullable=False), ) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # decode the frame at ts, encode as JPEG, return its bytes extract_frame_version = db.create_function_async(extract_frame).wait( timeout=timedelta(minutes=15) ) ``` An empty byte string is a filled result. A scalar output cannot be nullable, because a physical NULL marks an unfilled computed row. To return a nullable blob as a value, use a named-struct output schema with a nullable blob field; the struct itself records whether the result has been filled. Read a nested blob with `table.fetch_blobs("payload.image", hits)`. A list or large-list output may also contain Blob v2 elements; inputs and fixed-size lists do not support this layout. List-nested values are queryable as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their payloads. > [!WARNING] > > `output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2 > rather than plain Arrow `binary`. Returning `bytes` from a function whose > output type is inferred from a bare annotation, with no explicit > `lancedb.blob(...)` output schema, persists as ordinary `binary`: the column > still holds the right bytes, but it skips the Managed storage path, descriptor > reads, and `fetch_blobs`. Declare it explicitly on every function whose output > should be a blob, not just the first one in a chain. ### Chain a Function on its output A second Function can bind a blob another Function produced. Register `caption` the same way, consuming a blob instead of producing one: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(gpu=True, pip=["transformers==4.47.0"]) def caption(jpeg: bytes) -> str: ... # run a vision-language model over the JPEG, return one sentence caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15)) ``` Compose both in one SQL statement over a join, instead of applying each as its own column. The join supplies `video` and `ts` from two different tables, and `caption` reads `extract_frame`'s result as it is computed, before anything is written: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true ``` [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain) on a query like this shows `RemoteTake`: the blob is read once, where the worker runs, and never pulled into the query node first. ### Persist it as a column, or a materialized view Apply the same registered version with `add_columns` to persist its output as an ordinary table column, on a table that already has both of its inputs -- here, a single-clip table with its own `video` and `ts`, rather than the two tables the join above reads from: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} clips = db.create_table("clips", schema=pa.schema([ pa.field("frame_id", pa.int64(), nullable=False), lancedb.blob("video", nullable=False), pa.field("ts", pa.float64(), nullable=False), ])) clips.add_columns({"jpeg": extract_frame_version(video=col("video"), ts=col("ts"))}) result = clips.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15)) assert result.rows_failed == 0 hits = clips.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow() values = clips.fetch_blobs("jpeg", hits).to_pylist() ``` Or wrap the join and both Functions in a [materialized view](/enterprise/v1-12-0/sql/ddl/materialized-view) instead, so the extracted frame and its caption stay current as new videos and frames arrive. See [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for keeping either one fresh without calling refresh yourself. On deployments that support computed-column inputs, another Function can bind to `col("jpeg")` directly, the same as the SQL join above does through its own expression. Refresh the producer first, then the consumer. Once outputs are current, a later refresh fills appended rows. A filtered refresh preserves payload references for unselected Managed outputs. An unfiltered refresh can recompute a whole fragment when it cannot establish that the fragment's outputs are current. Function output blobs follow the same compaction and cleanup lifecycle as ingested Managed blobs. Retained versions continue to own their payloads; cleanup reclaims an object only after its retained references are gone. ### Read a blob incrementally Annotate a row Function parameter with `BlobReader` to read a Blob v2 input incrementally, the way `extract_frame` above does, instead of materializing the whole payload first. The signature selects the access mode without another registration option. A minimal example, reading only the first MP4 box type without loading the rest of the video: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import BlobReader, function @function def first_box_type(video: BlobReader) -> bytes: video.seek(4) return video.read(4) ``` The worker passes a seekable reader backed by the stored blob -- `video.seekable()` is `True`. `read(size)` reads from the current cursor; `read_range(offset, length)` reads a byte range without moving it, the same bytes a `seek(offset)` followed by `read(length)` would read. `size()` returns the payload size without reading it. Each row call receives its own reader, which closes when the call returns or raises. Do not retain it for another invocation. Use `video: bytes` when the Function needs the complete payload. Bytes inputs materialize before invocation and remain subject to eager input limits. Reader inputs keep the unread payload out of the input batch, but calling `video.read()` without a size loads all remaining bytes in Python. Reader inputs are supported in row mode. Return values remain ordinary values such as `bytes`; this feature does not add streamed outputs. ## What to read next > [card] [Function](/enterprise/v1-12-0/management/function) > > List, describe and drop registered Function versions. > [card] [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret) > > Bind a credential by reference instead of putting it in the function's source. > [card] [Chunk records into multiple rows](/enterprise/v1-12-0/curation/chunking) > > A Function whose output is a list, exploded into one row per element. > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Filling the column a Function is bound to, and re-filling it as inputs change. # Deduplicate near-duplicate records Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/dedupe Collapse records that are only approximately alike, judged by embedding distance, without a pairwise scan. **Applies to:** Embedded ❌, Enterprise ✅ [Ranking](/enterprise/v1-12-0/curation/windowing#dedup) removes records by an explicit rule, such as keeping the latest version of a known key. This page covers the other kind of duplicate: records with no shared key that are still nearly identical, judged by distance between their embeddings -- a stopped camera holding one pose for a few seconds, or two scraped pages with the same paragraph reworded. `dedupe` and `duplicate_pairs` find these directly over a vector index, without a pairwise scan. ## Example data Connect with an [Enterprise connection](/enterprise/v1-12-0/basics/catalog#enterprise). A small fixture keeps the distances easy to check by hand. > [accordion] Create the example table > > `curation_embeddings` has eight records. Rows 10 and 20 are near-identical; > rows 30, 40 and 50 form one looser cluster; the rest are distinct. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import pyarrow as pa > from lancedb.index import IvfFlat > > schema = pa.schema([ > pa.field("id", pa.int64(), nullable=False), > pa.field("caption", pa.utf8()), > pa.field("embedding", pa.list_(pa.float32(), 2)), > ]) > table = db.create_table("curation_embeddings", [ > {"id": 10, "caption": "a cat on a chair", "embedding": [0.0, 0.0]}, > {"id": 20, "caption": "a cat on the chair", "embedding": [0.0, 0.03]}, > {"id": 30, "caption": "a dog in a field", "embedding": [5.0, 5.0]}, > {"id": 40, "caption": "a dog in the field", "embedding": [5.0, 5.05]}, > {"id": 50, "caption": "a dog out in a field", "embedding": [5.0, 5.10]}, > {"id": 60, "caption": "a bird in a tree", "embedding": [10.0, 10.0]}, > {"id": 70, "caption": "a boat on the water", "embedding": [20.0, 20.0]}, > {"id": 80, "caption": "a car on the road", "embedding": [30.0, 30.0]}, > ], schema=schema) > > table.create_index("embedding", config=IvfFlat(num_partitions=1, distance_type="l2")) > table.wait_for_index(["embedding_idx"]) > ``` > > `dedupe` and `duplicate_pairs` read the vector index, so the column needs one > before either function runs; a query against unindexed fragments is rejected > rather than silently returning stale or wrong results. > > For an `l2` index, `distance_threshold` and the `distance` column below are > both **squared** L2, not the plain L2 a plain SQL `distance()` call returns. ## Collapse near-duplicates `dedupe` returns one representative row per cluster of records within `distance_threshold` of each other -- rows 10/20 collapse to one, 30/40/50 collapse to one, and the four distinct rows pass through unchanged, leaving ids 10, 30, 60, 70 and 80: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, caption FROM dedupe( 'curation_embeddings', 'embedding', distance_threshold => 0.003 ) ORDER BY id ``` Every other column survives unchanged, since `dedupe` returns full rows, not just which ones matched. Clustering is transitive: 30 and 40 are within `distance_threshold` of each other, and so are 40 and 50, so all three collapse into one representative even though 30 and 50 alone sit outside the threshold. Pass `resolution => 'direct_representative'` for a simpler, non-transitive selection instead, if a chained cluster like that should not merge into one representative. Which row survives as the representative is not guaranteed to stay the same across appends: a later row that bridges two previously separate clusters can change which id represents the merged cluster. Do not treat a representative's id as a stable identifier for its cluster. ## Inspect the pairs instead `duplicate_pairs` returns the matching edges themselves, without collapsing anything -- useful for review, or for a threshold that is still being tuned: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id_a, id_b, distance FROM duplicate_pairs( 'curation_embeddings', 'embedding', distance_threshold => 0.003, id_column => 'id' ) ORDER BY id_a ``` This returns the pairs `(10, 20)`, `(30, 40)` and `(40, 50)` -- note 30 and 50 are not a direct pair here (their squared L2 distance is `0.01`, outside the threshold), even though `dedupe` merges all three transitively above. ## Keep it current with a materialized view Wrap either call in a [materialized view](/enterprise/v1-12-0/management/materialized-view) so the deduplicated set stays current as new records arrive, instead of recomputing it from scratch on every curation pass: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW curation_embeddings_deduped AS SELECT * FROM dedupe( 'curation_embeddings', 'embedding', distance_threshold => 0.003 ) ``` See [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) for manual and automatic refresh options to keep it current as new records land. ## At production scale [LeRobotDataset](/enterprise/v1-12-0/integrations/lerobotdataset) runs the same `dedupe` call over 27.6 million real embedding rows to remove near-static frames from a robotics training set in under 30 seconds -- the mechanism does not change with scale, only the table it runs against. ## Continue with the curated data [Profile the result](/enterprise/v1-12-0/curation/aggregate) to check how much a threshold removes before committing to it, or go back to [choosing a curation task](/enterprise/v1-12-0/curation#questions). # Distributed Shuffle Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/distributed-shuffle How a SQL query's intermediate results move between plan executors for a join, aggregate or sort. **Applies to:** Embedded ❌, Enterprise ✅ A distributed SQL query plans as a sequence of **stages**, each with its own set of partitions, connected by an **exchange**: a streaming gRPC service that carries one stage's output to the next stage's plan executors. [Distributed Search](/enterprise/v1-12-0/enterprise/distributed-search) covers how a query gets placed on the fleet in the first place; this page covers what happens between placement and the final result, for a query whose plan needs data repartitioned across machines -- a hash join or a grouped aggregate, for example, where rows with the same key must land on the same worker regardless of which plan executor originally read them. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph Stage1["Stage: scan"] direction TB PE1["Plan executor<br/>reads its partition"] PE2["Plan executor<br/>reads its partition"] end EX["Exchange<br/>streaming gRPC,<br/>repartitions by join/group key,<br/>backpressure via a byte budget"] subgraph Stage2["Stage: join / aggregate"] direction TB PE3["Plan executor<br/>probes its share of keys"] PE4["Plan executor<br/>probes its share of keys"] end PE1 --> EX PE2 --> EX EX --> PE3 EX --> PE4 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class EX accent ``` ## Pipelined, not batched The exchange moves data as a gRPC stream of row batches, not a file a later stage waits for: a consuming plan executor pulls batches as they become available, and a slow consumer throttles its producer through a byte budget on unread messages rather than letting memory grow without bound. A partition that stops being read -- for example the probe side of a hash join whose build side turned out empty -- is drained rather than left to stall the budget for every other partition sharing the same connection. ## What to read next > [card] [Distributed Search](/enterprise/v1-12-0/enterprise/distributed-search) > > How a query gets placed on the query-serving fleet in the first place. > [card] [Query plans](/enterprise/v1-12-0/basics/sql#query-plans) > > Inspect a specific query's plan and its actual execution metrics. # Data curation Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/index Prepare datasets for search, evaluation and training by profiling, selecting and combining records. Data curation turns a collection of records into a dataset suited to a task. You might select labeled examples for training, prepare a fixed evaluation set, or remove duplicate documents from a search corpus. Start with the result you need. Then inspect the source data, choose which records belong, and save the selected data or the rules used to produce it. ## Choose a curation task | Task | What it helps you decide | | - | - | | [Create a Function](/enterprise/v1-12-0/curation/create-function) | How to run your own Python -- on CPU, on GPU, or against a remote service -- as part of SQL. | | [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret) | How a bound Secret's value actually reaches a running Function. | | [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) | How to query a table, a HuggingFace dataset, or an object-storage dataset the same way, and import without a separate download step. | | [Chunk records](/enterprise/v1-12-0/curation/chunking) | How to split one record into several -- passages, clips, or tiles. | | [Scope to what changed](/enterprise/v1-12-0/curation/changes) | How to process only the rows added since your last run. | | [Profile a dataset](/enterprise/v1-12-0/curation/aggregate) | Whether coverage, missing values and class balance suit the task. | | [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. | | [Selective Sampling](/enterprise/v1-12-0/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. | | [Join datasets](/enterprise/v1-12-0/curation/join) | How to attach labels, metadata or scores stored elsewhere. | | [Rank and deduplicate](/enterprise/v1-12-0/curation/windowing) | Which records to keep when several share an explicit key. | | [Cluster by index partition](/enterprise/v1-12-0/curation/clustering) | How to group records by vector proximity without training a new clustering model. | | [Deduplicate near-duplicates](/enterprise/v1-12-0/curation/dedupe) | Which records to collapse when they only look alike, with no shared key. | The analytical examples in this section use **Enterprise SQL**. Connect with the [SQL guide](/enterprise/v1-12-0/basics/sql). For a random subset through the Python SDK in LanceDB Embedded or LanceDB Enterprise, see [Permutation](/enterprise/v1-12-0/training/permutation). ## Prepare a labeled document dataset Suppose you need one labeled record per document for a training experiment. Inspect the source records, choose the latest version of each document, then join its label. Finally, check the class balance of the selected records. ### Example data Connect with an [Enterprise SQL client](/enterprise/v1-12-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. The following query chooses the latest record for each document, then keeps only documents with a label: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS rn FROM curation_documents ) SELECT d.row_id, d.doc_id, d.caption, l.label FROM ranked AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.rn = 1 ORDER BY d.doc_id; ``` The result contains documents **10, 20 and 30**, with labels **cat, dog and cat**. Document 40 is excluded because this particular task requires a label. The `row_id` tie-breaker makes the choice for document 30 deterministic; choose a tie-breaker that fits your own data. The example assumes one label per document. Duplicate keys in the label table would multiply the result rows. The [joining guide](/enterprise/v1-12-0/curation/join#labels) shows how to check that assumption. ## Check the selected dataset Compare the result with the task's requirements: are the expected documents present, are required fields populated, and is the class distribution suitable? This example has two cats and one dog. That distribution may be appropriate for exploration, but it does not establish a representative evaluation set. [Profiling](/enterprise/v1-12-0/curation/aggregate) provides the counts to inspect. [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) and [ranking](/enterprise/v1-12-0/curation/windowing) help you adjust the selection without changing the original records. ## Save and reuse the result Choose the output according to how you will use it: * **A fixed dataset:** save the query result in a new table with [`CREATE TABLE AS SELECT`](/enterprise/v1-12-0/sql/ddl/table#create). Keep that output unchanged when comparing experiments. * **A reusable selection:** save the query as a [view](/enterprise/v1-12-0/management/view). A view stores the query definition, so it is not a frozen evaluation set. * **Stored results that you refresh:** use a [materialized view](/enterprise/v1-12-0/management/materialized-view) when its supported query and refresh behavior fit the workflow. Record the source versions and selection rules alongside the output. Continue with [data loading](/enterprise/v1-12-0/training/data-loading) to use the curated data in a training pipeline. # Inspect Datasets Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/inspect-datasets Query a table, a HuggingFace dataset, or a dataset in object storage the same way, with plain SELECT, WHERE, projection and LIMIT. **Applies to:** Embedded ❌, Enterprise ✅ The same `SELECT` statement inspects three kinds of source: a table already in your database, a HuggingFace dataset, or a dataset in object storage -- once a [storage integration](/enterprise/v1-12-0/management/storage-integration) covers the latter two. Nothing is downloaded or imported until you choose to import it. ## The basics: project, filter, limit A table name, a HuggingFace URI, and an object-storage URI all work the same way after `FROM`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM documents WHERE text IS NOT NULL LIMIT 100 ``` * **Project** -- name the columns you need (`id, text`) instead of `SELECT *`, especially for a source with large or many columns. * **Filter** -- `WHERE` narrows rows before they come back; combine predicates with `AND`/`OR` the same as any other table. * **Limit** -- `LIMIT n` caps how many rows return. It bounds the result, not the read: a remote source is still fetched at file or row-group granularity, so a small `LIMIT` on a source with large files or row groups can still touch more data than the row count suggests. The rest of this page swaps `documents` for a HuggingFace or object-storage source -- the `SELECT`/`WHERE`/`LIMIT` syntax above doesn't change. ## Inspect a HuggingFace dataset A single-quoted HuggingFace dataset URI works directly in a SQL `FROM` clause, the same as a table name -- no separate download, no intermediate file on disk: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM 'hf://datasets/owner/repo/data/train-*.parquet' WHERE text IS NOT NULL LIMIT 100 ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query(""" SELECT id, text FROM 'hf://datasets/owner/repo/data/train-*.parquet' WHERE text IS NOT NULL LIMIT 100 """) sample = reader.read_all().to_pylist() ``` The URI is `hf://datasets/<owner>/<repo>[@<revision>]/<path>`. `<path>` can be one Parquet file, a directory, or a glob: `*` matches within one directory, `**` matches across directories, and a repository root selects every Parquet file beneath it. Select a dataset configuration or split by including it in the path. The default revision is `main`; each statement resolves the revision to a commit once, so every worker reads the same snapshot. This source reads Parquet files -- it does not run a dataset's own generation scripts, and it does not compute embeddings or build indexes, so [chunk](/enterprise/v1-12-0/curation/chunking), embed, or index the result as a separate step, the same as data from any other source. > [!NOTE] > > Files matched by one statement must have compatible schemas, and an > unmatched path is an error rather than a silent fallback to a different > split. Nested Parquet values come through as-is; a floating-point list is > not automatically converted into a fixed-size vector column. ## Inspect a dataset in object storage An `s3://`, `gs://` or `az://` prefix covered by a storage integration reads an existing **Lance** dataset at that prefix, the same way as a managed table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM 's3://customer-data/raw/documents.lance' WHERE text IS NOT NULL LIMIT 100 ``` This reads a dataset another process already wrote in Lance format, not an arbitrary file format -- there is no Parquet-style reader for cloud storage the way there is for `hf://`. See [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration#read-import) for every provider's setup. ## Access a private repository or bucket A private HuggingFace repository, one subject to HuggingFace's authenticated rate limits, or any non-public bucket needs a [storage integration](/enterprise/v1-12-0/management/storage-integration) covering it. For HuggingFace that integration is bound to a token [Secret](/enterprise/v1-12-0/management/secret); for a non-public S3 bucket it can instead be an IAM role integration, which needs no Secret at all -- see [AWS S3](/enterprise/v1-12-0/ingestion/define-storage-integration#aws). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_secret("hf_token", "<your-hugging-face-token>") # create_storage_integration is not in a released SDK yet; use the SQL # form below until it ships. db.execute_query(""" CREATE STORAGE INTEGRATION private_hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token """).read_all() reader = db.execute_query( "SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10" ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET hf_token TYPE = GENERIC_STRING SECRET_STRING = '<your-hugging-face-token>' CREATE STORAGE INTEGRATION private_hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10 ``` A query never names the integration: the planner matches the most specific `STORAGE_PREFIX` that covers the URI being read, across every integration the caller has `USAGE` on. A HuggingFace integration always needs `HUGGINGFACE_TOKEN_SECRET`; creating one without it is rejected. For public access, register no integration for that prefix at all -- an `hf://` read that matches no integration is anonymous, with no environment-variable fallback. See [Storage Integration](/enterprise/v1-12-0/management/storage-integration) for every provider and the full credential model. ## Import into a table Once you've inspected a source and it looks right, `CREATE TABLE ... AS SELECT` imports it: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' """).read_all() table = db.open_table("imported") ``` This `CREATE TABLE AS SELECT` runs as a distributed import when the deployment has an available plan-executor fleet: the planner assigns disjoint file and row-group ranges to workers, each worker writes uncommitted Lance files directly to the destination, and a coordinator commits the completed table from their transaction metadata once every worker finishes. A query with a global limit, aggregation or join keeps its usual coordination; a small import can run as one local task without a fleet. The table becomes queryable only after that final commit -- nothing partial is ever visible, and a failed or cancelled import can resume the same durable job from its retained attempt rather than restarting from nothing. To start over after a failed one-off import instead, drop the partial table and rerun the statement. > [!NOTE] > > Importing requires a native database with `database_manifest_enabled`. > Combining a HuggingFace source with a WAL-backed destination table in one > CTAS is rejected, since the import cannot publish a base-only read that > omits the destination's unflushed data. ## What to read next > [card] [Storage Integration](/enterprise/v1-12-0/management/storage-integration) > > The credential object behind private repository access. > [card] [Create a Function](/enterprise/v1-12-0/curation/create-function) > > Add embeddings or derived columns to the imported data. > [card] [Chunk records into multiple rows](/enterprise/v1-12-0/curation/chunking) > > Split long text or media fields after importing. > [card] [Table](/enterprise/v1-12-0/sql/ddl/table#create) > > `CREATE TABLE AS SELECT` syntax and options in full. # Joining datasets Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/join Combine records with labels or metadata, and check for missing or duplicate matches. **Applies to:** Embedded ❌, Enterprise ✅ A SQL join combines records from two tables using a shared key. Use joins to attach labels, metadata or model scores to your documents. Choose an inner join to keep matching records, or a left join to retain records without a match. ## Example data Connect with an [Enterprise SQL client](/enterprise/v1-12-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Basic join An inner join keeps matching records: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.row_id, d.doc_id, l.label FROM curation_documents AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id ORDER BY d.row_id; ``` This returns **5 rows**: both records for document 10, one for document 20, and both records for document 30. To produce one row per document, [deduplicate the source records](/enterprise/v1-12-0/curation/windowing#dedup). ### Find records without a match A left join keeps every record from the left table and fills missing right-side values with `NULL`. Add `WHERE l.doc_id IS NULL` to return only unlabeled documents: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT DISTINCT d.doc_id FROM curation_documents AS d LEFT JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE l.doc_id IS NULL ORDER BY d.doc_id; ``` The result is **document 40**. You might send it for annotation, retain it for an unlabeled-data workflow, or exclude it from a task that requires labels. ## Handle duplicate keys This example joins `curation_documents.doc_id` to `curation_labels.doc_id`. First check whether the label table contains more than one row per document: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT doc_id, count(*) AS labels FROM curation_labels GROUP BY doc_id HAVING count(*) > 1; ``` The example returns no rows. If your data returns duplicates, decide whether they represent valid multiple labels or records that need consolidation. A join does not enforce one-to-one matching. ## Call a Function across the join A [Function](/enterprise/v1-12-0/curation/create-function) can read columns from either side of a join, the same as any other expression -- it runs once the join has matched rows, not before. Register `caption_quality` first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.row_id, l.label, caption_quality(d.caption) AS quality FROM curation_documents AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.caption IS NOT NULL ORDER BY d.row_id; ``` Scoring after the join, rather than before, means `caption_quality` only runs on rows that actually matched a label -- a document with no label never pays for the Function call. ## Join tables across namespaces Use a table's qualified path to address it in another [namespace](/enterprise/v1-12-0/management/namespace). For example, a table named `images` in `prod.media` is addressed as `prod.media.images`. The same matching-key and join-type rules apply; your identity needs access to the source objects. ## Combine search results with metadata A [SQL full-text search](/enterprise/v1-12-0/sql/dql/fts) returns rows that can be joined to other tables. Join using an identifier retained in the search result, then check whether the metadata has one or several matches per result. For an SDK search, retain the matching IDs and combine them with metadata in your application or save the selected records to a table for further SQL work. See [SQL search interfaces](/enterprise/v1-12-0/basics/sql#no-vector-sql) for supported query forms. ## Join performance Check the row count, unmatched keys and duplicate matches before using a joined dataset. Select only the columns needed for the next step, especially when source records include large media or embedding columns. Use [Query plans](/enterprise/v1-12-0/basics/sql#query-plans) to see how the query reads and combines data. Check the plan to see whether the query uses indexes and how it performs the join. An index on a key does not guarantee that the join will use it. ### Defer wide columns until after the join When one side of a join carries a BlobV2 column, an embedding, or both, join on a narrow key first and project the wide columns only in the final select list, so the planner can defer reading them until after the join has already narrowed down which rows survive. See [Blob Late Materialization](/enterprise/v1-12-0/curation/blob-late-materialization) for the mechanism, eligibility, and how to confirm it happened. ## Save the result or continue curating Keep the query for reuse or [save the selected data](/enterprise/v1-12-0/curation#next). See [Joins](/enterprise/v1-12-0/sql/dql/join) for join types and exact SQL behavior. # Selective Sampling Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/selective-sampling Fetch specific rows by row ID, row address or offset instead of drawing a random fraction. **Applies to:** Embedded ✅, Enterprise ✅ Selective sampling fetches specific, already-known rows -- by row ID, row address or offset -- rather than drawing a random fraction of the table. Use it to re-fetch rows a previous query identified, resume from a saved position, or pull a batch by index for a data loader. For a random subset instead, see [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling). LanceDB exposes three ways to address a row: | Identifier | Stability | Typical source | | - | - | - | | Row ID (`_rowid`) | Stable across compaction, with [stable row IDs](/enterprise/v1-12-0/basics/guarantees) enabled | A previous query's result, or `function_errors()` | | Row address (`_rowaddr`) | Changes on compaction; encodes `(fragment_id << 32) \| row_offset` | A previous query's result, when you need the physical location | | Offset | Table-wide position; **not** stable -- a row's offset shifts when an earlier row is deleted | `range(len(table))`, since every valid offset is known in advance | ## From Python The SDK takes a list of row IDs or offsets directly, without going through SQL: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # By row ID -- from a previous search or scan that selected "_rowid" rows = tbl.take_row_ids([1001, 1002, 1005]).to_arrow() # By offset -- the full range is always [0, len(tbl)) rows = tbl.take_offsets([0, 1, 2]).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // By row ID -- from a previous search or scan that selected "_rowid" const rowsById = await tbl.takeRowIds([1001n, 1002n, 1005n]).toArray(); // By offset -- the full range is always [0, tbl.countRows()) const rowsByOffset = await tbl.takeOffsets([0, 1, 2]).toArray(); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::query::ExecutableQuery; // By row ID -- from a previous search or scan that selected "_rowid" let rows_by_id = tbl.take_row_ids(vec![1001, 1002, 1005]).execute().await?; // By offset -- the full range is always [0, tbl.count_rows().await?) let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?; ``` Both methods return a query builder; call `.to_arrow()`, `.to_list()` or similar to execute it. > [!NOTE] > > The guarantees for row IDs below apply to SDK releases containing > [the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826). > Earlier releases may collapse repeated IDs and return rows in a different > order. `take_row_ids` returns matching rows in the order of the input IDs and preserves repeated IDs in both LanceDB Embedded and LanceDB Enterprise. For example, `take_row_ids([1005, 1001, 1005])` returns row 1005, row 1001, then row 1005 again if both IDs exist. Missing or deleted IDs are omitted. This supports sampling with replacement. In Rust, an explicit nonempty `QueryBase::order_by` list overrides the requested order; limits and offsets apply after restoring repeated rows. `take_offsets` also preserves repeated offsets, but does not guarantee input order. It tracks `_rowoffset` internally to restore repeated rows and drops that column from the output unless you explicitly `select` it. Add `_rowoffset` to your selection when you need to align a `take_offsets` result with the input offsets. > [!NOTE] > > Ordered takes by row ID collect all matching batches, combine them into one > batch and reorder the rows before returning output batches. Even > `to_batches(max_batch_length=1)` only limits the returned batch size; it > does not bound working memory. For large requests or rows with large > column values, split the input IDs into smaller requests and use > `.select(...)` to fetch only the columns you need. Offsets are mostly useful for sampling: the valid range is always `[0, len(table))`, so you can draw a random sample of offsets without reading the table first. Row IDs require you to already have them, from an earlier query's `_rowid` column -- but unlike offsets, a row ID keeps addressing the same logical row even after compaction, as long as the table has stable row IDs enabled. ## From SQL The same three identifiers are available as [pseudo-columns](/enterprise/v1-12-0/sql/data-types#pseudo-columns) -- select or filter on them like any other column: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- By row ID SELECT * FROM documents WHERE _rowid IN (1001, 1002, 1005); -- By row address SELECT * FROM documents WHERE _rowaddr IN (4294967296, 4294967297); -- Including the identifier in the result, to save for a later take SELECT _rowid, * FROM documents WHERE score > 0.9; ``` There is no dedicated Python method for taking by row address -- use `.where("_rowaddr IN (...)")` on the SDK query builder, or the SQL form above, since the expression language is the same either way. ## Related guides [Query plans](/enterprise/v1-12-0/basics/sql#query-plans) show whether a row-ID or offset filter reads the whole table or seeks directly to the requested rows. See [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) for a random fraction instead of specific rows, and [Permutation](/enterprise/v1-12-0/training/permutation) for shuffled, batched reads through the Python SDK. # Statistical Sampling Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/statistical-sampling Draw a random subset of a table with SQL TABLESAMPLE, by rows or by fragments. **Applies to:** Embedded ❌, Enterprise ✅ Statistical sampling draws a random subset of a table's rows using SQL's `TABLESAMPLE` clause, attached directly to a table in `FROM`. Use it to explore unfamiliar data, run a smaller experiment, or estimate aggregate statistics without reading every row. For a random subset through the Python SDK instead -- in Embedded or Enterprise -- see [Permutation](/enterprise/v1-12-0/training/permutation). To select specific, known rows rather than a random fraction, see [Selective Sampling](/enterprise/v1-12-0/curation/selective-sampling). ## Example data Connect with an [Enterprise SQL client](/enterprise/v1-12-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Basic sampling A percentage selects a fraction of the source; `ROWS` requests a row count: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (3 ROWS); ``` A percentage sample does not guarantee an exact number of rows. Use a count when the desired sample size is the main constraint, and inspect the result rather than assuming it contains every category you need. `TABLESAMPLE` requires a table that is not WAL-backed. See the [sampling reference](/enterprise/v1-12-0/sql/dql/sampling#refused) for this restriction; do not change a production table's write configuration just to try an example. ## Sampling methods Choose a method according to how records should be selected: | Method | Selection | When to use it | | - | - | - | | `BERNOULLI` (default) | Select individual rows | When records should be sampled independently of their storage fragments | | `SYSTEM` | Select whole Lance fragments | When reducing reads matters and grouping by fragment is acceptable | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE BERNOULLI (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE SYSTEM (50); ``` If write order groups records by label, date or source, a fragment sample can reflect that grouping. On a tiny table stored in one fragment, it may include all records or none. Row sampling also needs an adequate sample size to represent rare groups; check that the resulting sample covers the groups you need. ## Repeatable samples A seed requests a repeatable draw: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` Keep the source data and sampling configuration fixed when comparing draws. For a lasting evaluation set, save the selected records rather than relying on a seed to preserve membership as the source changes: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE curation_eval AS SELECT * FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` Create this output once with a fresh name and keep it unchanged. Record the source version and selection policy. Sampling records independently can place revisions of the same document into different splits; decide the [grouping policy](/enterprise/v1-12-0/curation/windowing#splits) before using the result for training or evaluation. ## Sampling with joins Sampling both input tables independently changes which pairs can match. For a one-to-one match, independent 10% row samples retain a given pair with about 1% probability, not 10%. To sample documents while retaining their available labels, sample only the document table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT curation_documents.row_id, curation_documents.doc_id, l.label FROM curation_documents TABLESAMPLE (50) JOIN curation_labels AS l ON l.doc_id = curation_documents.doc_id; ``` This samples source records, not distinct documents. If you need to sample the result of a join or deduplication, first save that result as a table suitable for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result. ## Apply a Function to a sample Sample first, then call a [Function](/enterprise/v1-12-0/curation/create-function) only on the rows you drew -- useful for trying an expensive Function on a subset before running it over the whole table. Register `caption_quality` first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, caption, caption_quality(caption) AS quality FROM curation_documents TABLESAMPLE (50) WHERE caption IS NOT NULL; ``` The Function runs only on the sampled rows, not the whole table -- a quick way to check a Function's output, cost or latency before committing to a full [column refresh](/enterprise/v1-12-0/feature-engineering/refresh-column). ## Related guides Count the sampled rows and [inspect their distribution](/enterprise/v1-12-0/curation/aggregate) before using them. Preserve the selected data when the exact membership matters. See [SQL sampling](/enterprise/v1-12-0/sql/dql/sampling) for the complete syntax and restrictions, and [Permutation](/enterprise/v1-12-0/training/permutation) for a random subset through the Python SDK. # Vend a Secret to a Function Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/vend-secret Bind a Secret to a Function by reference, and how its value reaches running code during SQL evaluation and refresh. **Applies to:** Embedded ❌, Enterprise ✅ Early access A Function that calls an external service needs a credential without putting it in the function's source -- see [Create a Function](/enterprise/v1-12-0/curation/create-function#remote) for how to register one. A [Secret](/enterprise/v1-12-0/management/secret) is a database-scoped named credential: you create it once, then bind it *by reference* -- by name, not by value -- when you register the Function that needs it. ## Specify the Secret when you register the Function Store the credential, then bind it to an environment variable the function's code already reads: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb import EnvVarSecret, udf db.create_secret("embedding-api-key", os.environ["EMBEDDING_API_KEY"]) @udf class embed_remote: def __init__(self, model: str = "text-embedding-3-small"): import os from openai import OpenAI self.client = OpenAI(api_key=os.environ["EMBEDDING_API_KEY"]) self.model = model def __call__(self, text: str) -> list[float]: response = self.client.embeddings.create(input=text, model=self.model) return response.data[0].embedding version = db.create_function_async( embed_remote, secrets=[ EnvVarSecret(secret_name="embedding-api-key", env_variable="EMBEDDING_API_KEY") ], ).wait() ``` The function's own code never names the Secret -- it reads `EMBEDDING_API_KEY` the same way it would outside LanceDB. The binding, in `secrets=[...]`, is what connects that variable to the stored credential. It is checked for shape at registration (valid variable name, not reserved, not repeated) but not resolved yet: the Secret does not have to exist until a column actually uses this Function version, so you can create the Function and its Secret in either order. ## Hugging Face models For a model loaded from the Hugging Face Hub, store the token as a Secret and bind it to the variable the Hub client reads. Use a class Function so the model is loaded once per remote instance rather than once per row: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb import EnvVarSecret, col, udf db.create_secret("hf-token", os.environ["HF_TOKEN"]) @udf( name="embed_text", pip=["sentence-transformers==3.3.1"], ) class EmbedText: def __init__(self, revision: str): from sentence_transformers import SentenceTransformer self.model = SentenceTransformer( "sentence-transformers/all-MiniLM-L6-v2", revision=revision, ) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() embed_fn = db.create_function( EmbedText, secrets=[EnvVarSecret(secret_name="hf-token", env_variable="HF_TOKEN")], ) table = db.open_table("documents") table.add_columns( { "embedding": embed_fn( text=col("text"), revision="<full-40-character-commit-sha>", ) } ) table.refresh_column("embedding") ``` A decorated class calls `__init__` once per remote instance and `__call__` for each row or batch. The class's `__init__` parameters are binding initialization values, so `revision` is fixed for this binding and the model is reused for all rows handled by that instance. Instances are not shared across workers. Use a full 40-character commit SHA for `revision`. A branch or tag can move; a commit pins the model version. See the official Hugging Face documentation for [`HF_TOKEN`](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hftoken) and [downloading a specific revision](https://huggingface.co/docs/huggingface_hub/guides/download#revision). `HF_TOKEN` authenticates Hub requests, but a cached model and a pinned revision are not a guarantee of offline execution. The Hub client may still request metadata or missing files, and authentication does not guarantee that requests will avoid rate limits. ## How the value reaches a running evaluation The Secret's value is resolved fresh for each job, never read once and cached in the Function's definition: | Step | What happens | | - | - | | `add_columns` with this Function version | Every bound Secret must now exist. The column pins this exact version, not a value. | | A refresh starts -- `refresh_column`, or a materialized view's refresh | Every bound Secret must still exist, checked before any row is computed. | | The job captures each bound Secret's current value | LanceDB looks up the value once, when the job starts, and sets it as that environment variable for every row the job evaluates, including its retries. No other environment variable carries over. | This is why rotating a Secret needs no new Function version and no column change: `alter_secret` changes the value a *future* lookup returns. The agent captures that value once, when a job starts, and reuses its own captured copy for that job's full run and any of its retries -- a refresh already running keeps the value it started with for every row, and only a job that starts *after* the rotation sees the new one. ### Rotate and revoke `alter_secret` and `drop_secret` never interrupt work in progress, so a routine rotation cannot fail a backfill halfway through: | Action | Running jobs | Next job | New Function version? | | - | - | - | - | | `alter_secret` | A running job and its retries keep the value captured at start; only a new job gets the latest value | Uses the latest value | No | | `drop_secret` | Run to completion on the last value | Refused, naming the Secret | No | | Revoke the key at its provider | Fails on their next call to the provider | Fails until a new value is set | No | | Re-create a dropped name | Keeps the dropped Secret's last value | Picks up the new Secret | No | Because a rotation creates no new Function version, it also reaches columns pinned to a version registered before it. Binding a Function to a *different* Secret or variable does register a new version, and existing columns keep the binding they were declared with. > [!WARNING] > > To stop a credential from being used **now**, revoke it at its provider, > for example by deleting the key in the OpenAI console. A value already > handed to a running job cannot be recalled. `drop_secret` cannot be undone, and it does not check for Functions still bound to the Secret. > [!NOTE] > > Reading a column this Function already filled needs only `SELECT` on the > table. No Function runs on the read path, so a reader needs no grant on the > Function or its Secrets -- only someone triggering a refresh does. ## Vending during SQL evaluation specifically A computed column's expression and a `CREATE MATERIALIZED VIEW` query both plan and execute as SQL, so a Function called from either one is vended its Secrets the same way: at the evaluation that fills the column or refreshes the view, not at declaration time. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT f.frame_id, caption(f.jpeg) AS caption FROM frames f ``` `caption` here is a Function bound to a Secret through the Python SDK when it was registered -- SQL has no syntax for the binding itself, only for calling the already-registered Function. The `CREATE MATERIALIZED VIEW` statement's initial population, and every `REFRESH MATERIALIZED VIEW` after it, each look up the bound Secret's current value independently. ## Troubleshooting **403 when adding or refreshing a Function column**: you need `USAGE` on the Function *and* on every Secret it binds, in addition to the table privilege. The error names the object you are missing. **The Function runs but its provider rejects the key**: a misspelled *environment variable* cannot be caught at registration, because nothing knows which variables a Function reads. Check that `env_variable` matches what the Function's code reads, such as `EMBEDDING_API_KEY` above. ## Related guides > [card] [Create a Function](/enterprise/v1-12-0/curation/create-function#remote) > > Write the function that reads the credential. > [card] [Secret](/enterprise/v1-12-0/management/secret) > > Create, rotate, list and drop the credential itself. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges#sql) > > Grant and revoke privileges on a Secret. > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Running the evaluation that vends the Secret. # Ranking Source: https://docs.lancedb.com/enterprise/v1-12-0/curation/windowing Choose records with explicit ranking rules and deterministic tie handling. **Applies to:** Embedded ❌, Enterprise ✅ Window functions calculate values across related rows while keeping each row in the result. Use them to rank documents, keep one record per item, or compare a record with the one before it. ## Example data Connect with an [Enterprise SQL client](/enterprise/v1-12-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Keep one record per document `row_number()` numbers rows within each group. `PARTITION BY` defines the group, and `ORDER BY` determines which record comes first. This query selects the latest version of each document, using `row_id` to break ties: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS rn FROM curation_documents ) SELECT row_id, doc_id, version, caption FROM ranked WHERE rn = 1 ORDER BY doc_id; ``` This returns row IDs **2, 3, 5 and 6**. For document 30, rows 4 and 5 have the same version; the example deliberately chooses the larger `row_id`. Without a complete ordering, the selected row among ties is not determined by the query. Use `rank()` instead of `row_number()` when tied records should all survive, and order only by the fields that define a tie. Adding a unique tie-breaker would make every rank distinct. The outer query filters the calculated rank because window functions are evaluated after the inner query's `WHERE` clause. ## Select the highest-scoring records per class Deduplicate first, then rank the labeled documents within each class: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH latest AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS version_rank FROM curation_documents ), ranked AS ( SELECT d.doc_id, l.label, d.score, row_number() OVER ( PARTITION BY l.label ORDER BY d.score DESC, d.doc_id ) AS class_rank FROM latest AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.version_rank = 1 ) SELECT doc_id, label, score FROM ranked WHERE class_rank <= 1 ORDER BY label; ``` The result is **document 10 for cat and document 20 for dog**. Change the cap from `1` to the maximum number you want per class. A class with fewer records cannot supply the full cap. This selects by score, not at random. For a random subset, use [sampling](/enterprise/v1-12-0/curation/statistical-sampling) instead of ordering by score or ID. ## Training and evaluation splits Ranking can divide ordered records into groups, but ordering by ID does not make those groups random or representative. `ntile()` produces approximately equal-sized buckets within a partition; small classes may not populate every bucket. Choose the split policy for the task. Keep related records, such as revisions of one document or frames from one video, in the same split to avoid leakage. A time-based evaluation may instead require a cutoff date. Save the final assignments or resulting datasets so later updates do not silently change the evaluation population. ## Compare neighboring records `lag()` and `lead()` read neighboring rows in the specified order. For example, inspect how scores change across a document's records: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT doc_id, row_id, score, lag(score) OVER ( PARTITION BY doc_id ORDER BY version, row_id ) AS previous_score FROM curation_documents ORDER BY doc_id, version, row_id; ``` The first record in each document has no previous score. In this dataset, row 2 follows a score of 0.80 and row 5 follows a score of 0.70. ## Window query performance Window operations can require sorting. Filter out records you do not need before ranking, and inspect the [query plan](/enterprise/v1-12-0/basics/sql#query-plans) when cost matters. For cumulative counts, sums and other running summaries, use an aggregate with an explicit window order and frame. The [window reference](/enterprise/v1-12-0/sql/dql/window#window) covers those expressions. ## Continue with the curated data [Profile the selected records](/enterprise/v1-12-0/curation/aggregate) and [save the result](/enterprise/v1-12-0/curation#next) for downstream use. See [Window functions](/enterprise/v1-12-0/sql/dql/window) for the full syntax and function list. # Support Source: https://docs.lancedb.com/enterprise/v1-12-0/deployment/support Where to get help: community Discord and email for LanceDB Embedded, dedicated support for LanceDB Enterprise. ## LanceDB Embedded For a quick question, the [Discord community](https://discord.gg/AUEWnJ7Txb) has channels for Python, TypeScript and Rust where you can ask the community for help. Use GitHub for discussions and issues that others can search and follow: | | | | - | - | | [GitHub Discussions](https://github.com/lancedb/lancedb/discussions) | Open-ended questions, design questions, "what's the right way to do X" | | [GitHub Issues](https://github.com/lancedb/lancedb/issues) | A specific bug, or a feature request | For anything the community can't resolve, email [support@lancedb.com](mailto:support@lancedb.com). ### What to include A faster answer usually depends on the same handful of details, whether you post in Discord or email: | | | | - | - | | SDK and version | `lancedb.__version__` (Python), `package.json` (TypeScript), the crate version (Rust) | | Connection type | embedded path, or a `db://` deployment | | The exact error | full traceback or error message, not a paraphrase | | A minimal repro | the smallest table schema and call that reproduces it | ## LanceDB Enterprise Talk to your account executive, file a support ticket, or reach the LanceDB support and engineering team directly for dedicated assistance. # Adaptive Execution Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/adaptive-execution How a Function refresh's part size, resource class, worker count and checkpoint frequency adjust themselves to observed behavior. **Applies to:** Embedded ❌, Enterprise ✅ Early access When a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) or [materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) is filled by a registered [Function](/enterprise/v1-12-0/curation/create-function), LanceDB Enterprise adapts the refresh to the Function's actual behavior along several axes -- how many rows go in one unit of work, how much CPU, memory and GPU one invocation gets, how many worker processes run inside one worker, and how many workers run at all -- rather than running it at one fixed shape regardless of how slow, fast, or resource-hungry that Function turns out to be. See [Architecture](/enterprise/v1-12-0/index#architecture). ## Part size follows observed throughput A Function refresh starts with a small probe part -- 10 rows -- and grows it based on an exponentially-weighted average of rows processed per millisecond, aiming each next part at roughly 45 seconds of work. A part can grow or shrink by at most 16x from the previous one, so one unusually slow or fast part doesn't swing sizing to an extreme; the ceiling is 1,000,000 rows per part regardless of how fast the Function appears to run. A consistently slow Function converges on small parts that finish reliably; a fast one converges on large parts that keep worker overhead \-- a fresh scanner and registry round trip per part -- small relative to the work done. ## Resource class follows observed consumption Each invocation is measured -- wall time, CPU time and utilization, peak memory, out-of-memory events, and for a GPU Function, compute and memory utilization per GPU -- and that measurement decides whether the *next* invocation runs with more resources, fewer, or the same: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR I["Invocation runs<br/>wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} D -->|"OOM, or memory/CPU/GPU<br/>over target utilization"| P["Promote:<br/>next size up"] D -->|"fast task, low CPU,<br/>known memory"| Dm["Demote:<br/>one size down,<br/>never past a floor"] D -->|neither| S["Stay:<br/>same class"] P --> N["Next invocation"] Dm --> N S --> N N --> I classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` **Promotion** happens on an out-of-memory event, memory utilization above 70% of the class's limit, or CPU pegged at 85%+ for a sample long enough (5 seconds) that one fast spike isn't mistaken for sustained saturation. A GPU Function promotes the same way on GPU compute or GPU memory saturation. **Demotion** is more conservative: only a task that both finished fast (under 30 seconds) and used 25% or less of its CPU budget demotes, one size down at a time rather than jumping straight to the smallest class, and never below a configured floor. Either way, the class actually chosen is the smallest one whose memory and CPU both cover the observed peak with roughly 40% headroom, so sizing tracks what the Function actually consumes rather than a static guess made once at registration. ## Process and worker count follow the resource budget Within one worker, the number of executor processes is chosen to be the largest count that still fits the worker's memory budget, since memory per process shrinks as the count grows. Across workers, the fleet claims as many additional workers as the configured CPU, memory and GPU budget has room for, given what's already running -- the worker count grows to use available budget rather than running at a single fixed count regardless of how much of the budget sits idle. ## Checkpoint granularity follows part size A refresh checkpoints once per part, not on a separately-tuned interval -- so checkpoint frequency is a direct consequence of the same EWMA-driven part sizing described above, not a second knob. A Function that converges on small parts checkpoints often, losing little work if a worker dies mid-refresh; one that converges on large parts checkpoints less often, trading that for lower per-part overhead. See [Checkpointing](/enterprise/v1-12-0/enterprise/checkpointing) for the mechanism itself. ## Overriding the defaults A refresh can request a GPU class and count, or cap the maximum rows per Function call directly, instead of relying on this adaptive behavior -- see [Configure workers and resources](/enterprise/v1-12-0/feature-engineering/refresh-column#resources) for the full set of overrides, SQL and SDK alike. Setting `batch_size` caps the rows passed to each Function call for that refresh; the adaptive part sizing described above still decides how many rows each part covers. ## What to read next > [card] [Incremental Refresh](/enterprise/v1-12-0/enterprise/incremental-refresh) > > How the rows a Function refresh works on are chosen in the first place. > [card] [Checkpointing](/enterprise/v1-12-0/enterprise/checkpointing) > > How a part's progress survives a failure or restart. # Auto Refresh Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/auto-refresh Let a computed column or materialized view refresh itself on a schedule, instead of calling refresh explicitly. **Applies to:** Embedded ❌, Enterprise ✅ Both a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) and a [materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) can refresh themselves on a schedule instead of waiting for an explicit `refresh_column()`, `view.refresh()`, or `REFRESH` statement. Either way, `auto_refresh_enabled` turns it on and `auto_refresh_interval_seconds` sets a minimum delay before the next automatic refresh is eligible -- omit the interval to let the server decide. What that delay is measured from differs between the two; see [Pacing follows different state for each](#history) below. See [Architecture](/enterprise/v1-12-0/index#architecture) for the scheduler's place among the jobs fleet. ## Where the two differ A computed column's auto-refresh setting is per output: each column declared in the same `add_columns` call gets its own independent interval, set when you declare it or changed later. Automatic execution additionally needs the deployment's `column_refresh.enabled` switch, which is off in the base configuration. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = true; ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_interval_seconds = 300; ``` A materialized view's setting is whole-view -- there is no per-column granularity the way a computed column has one setting per output. The view's *initial* population always happens regardless of this setting; only the refreshes after that are gated. Unlike a computed column, a view's setting is declared at `CREATE` time, but it can still be changed afterward with `ALTER`: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW my_view WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT * FROM source_table; ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = false; ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = true; ALTER MATERIALIZED VIEW my_view SET auto_refresh_interval_seconds = 300; ``` Each `SET` above changes the scheduling setting immediately and synchronously; it does not itself run a refresh. Whether and when a refresh actually runs next is a separate, asynchronous decision the scheduler makes against the pacing rules below. If values stop appearing after a `SET`, check the column's Job Registry history rather than assuming the setting itself failed to apply. ## Pacing follows different state for each A computed column's pacing is measured from the last successful refresh recorded in the Job Registry's live history, not from a separate timestamp LanceDB keeps elsewhere. If completed jobs are archived before the column's configured interval has elapsed, the scheduler can lose that last-success record and refresh earlier than the interval implies. Leave archival disabled, or retain live history for at least the longest configured interval you rely on. A deployment archives completed jobs by default, after a default seven-day retention threshold; check with your deployment operator if you rely on a different setting. A materialized view's pacing instead reads a timestamp the view itself persists for when it was last checked, not Job Registry history -- so archival doesn't affect it. Once the interval has elapsed, the scheduler also skips the refresh outright if the source table's version is unchanged since the view's last check, rather than re-running a refresh that would produce the same rows. ## Catching up Re-enabling a column's auto-refresh after it was off catches up the entire accumulated backlog in one pass, not just rows written from that point on -- "catch up," not "resume cadence." Disabling never skips or drops writes either: rows written while disabled simply commit with no computed value yet, the same as a row written before the column existed. ## What to read next > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Manual refresh, partial refreshes, and what happens on failure. > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > Manual refresh and what happens on failure, for a view. # Cache Prewarm Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/cache-prewarm Populate the tiered index cache ahead of a request, instead of filling it lazily on first read. **Applies to:** Embedded ❌, Enterprise ✅ Cache Prewarm loads the [tiered index cache](/enterprise/v1-12-0/enterprise/tiered-index-cache) a plan executor keeps as part of Enterprise's serving layer, instead of leaving it to fill lazily on first read. You configure which tables to prewarm; on startup, each plan executor loads those tables' indexes into cache before it joins the fleet. The executor does not accept queries until prewarming finishes, so it never serves a request against a cold cache. LanceDB Embedded has no such cache, so there is nothing for it to warm there. Embedded does have its own, separate `prewarm_index()` on a table -- an idempotent hint that loads a built index into memory ahead of a query. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR List[("Configured list<br/>of tables to prewarm")] Start["Plan executor starts<br/>(not ready — no queries served)"] --> Warm["Loads the configured<br/>tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,<br/>starts serving queries"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Warm,List accent ``` ## Why it matters Without prewarming, a fresh or restarted executor would fill its indexes lazily, so the first queries it serves pay the cost of loading and deserializing them from object storage. Holding the executor out of the fleet until its configured tables are warm means every query it ever serves gets a warm cache, so performance stays consistent through restarts and rollouts instead of dipping right after each one. [Contact us](https://www.lancedb.com/contact) to learn more about how prewarming is configured for your deployment. ## What to read next > [card] [Data Page Cache](/enterprise/v1-12-0/enterprise/data-page-cache) > > The raw-data-page cache -- a separate cache from the one prewarm fills. > [card] [Tiered Index Cache](/enterprise/v1-12-0/enterprise/tiered-index-cache) > > The deserialized-index cache prewarm fills. > [card] [Architecture](/enterprise/v1-12-0/index#architecture) > > Where plan executors and query nodes sit in the serving fleet. # Function Refresh Checkpointing Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/checkpointing How a Function refresh's progress survives a worker failure or restart, part by part. **Applies to:** Embedded ❌, Enterprise ✅ Early access This page is about checkpointing a [Function refresh](/enterprise/v1-12-0/enterprise/adaptive-execution) specifically -- not [PyTorch training checkpointing](/enterprise/v1-12-0/training/checkpointing), a different, unrelated mechanism covered elsewhere. A Function refresh fills a column in [parts](/enterprise/v1-12-0/enterprise/adaptive-execution#part-size), each one a bounded range of rows. Every part's lifecycle is recorded as a durable, append-only event -- started, then completed -- in a log scoped to the data file that part belongs to. A worker failure or restart does not require redoing the refresh from scratch: the next attempt reads that log, finds which parts already completed, and only works on what's left. Retrying is at-least-once at the part level, not exactly-once: a part that started but never recorded completion is redone in full on the next attempt, so a Function with external side effects (a remote API call, for example) can have those side effects repeated for that part's rows. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Part started<br/>event recorded"] --> E["Function executes"] E --> C["Part completed<br/>event recorded"] C --> M{"More parts?"} M -->|yes| S M -->|no| F["Finalized:<br/>digest-verified assembly<br/>into the real data file"] S -. "worker dies here" .-> R["Next attempt reads the log,<br/>sees no completion,<br/>redoes only this part"] C -. "worker dies here" .-> R2["Next attempt reads the log,<br/>sees this part done,<br/>inherits it, moves on"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class R,R2 accent ``` ## What gets recorded, and when Each part contributes two events to its data file's log: one when a worker starts it, one when it completes with the rows it filled, the rows it skipped, and how long it took. A completed part additionally carries enough identity that a *different* job -- one that took over after the part's original job died -- can verify the part is really done and adopt it rather than redo it. Once every part for a data file has completed, one last event finalizes it: the assembled file's checksum is verified against what the parts actually wrote before it's accepted as the real data file, not just assumed correct because every part reported success. Writes to this log are batched, not one durable write per event, so checkpointing a fast-finishing part costs a fraction of a write rather than a full one. ## The Blob v2 optimization A Function whose output includes a [Blob v2](/enterprise/v1-12-0/management/table#managed-blobs) column needs an identifier for every blob it writes. Allocating those IDs piggybacks on the same durable event that already records a part starting: the event log itself hands out the next unclaimed range, computed from the highest range any earlier part in this log has already claimed. This means: * **No separate allocation round trip.** The ID range arrives for free inside a write the part was already going to make durably. * **A retried part can't collide with itself or with other parts.** Each attempt at a part writes a new part-started event and gets a fresh range past the highest range already claimed in this log, so no two attempts -- of the same part or of different parts -- ever hold overlapping ranges. Re-sending the *same* event, for example after a lost acknowledgement, is idempotent and returns the range it was already given. A range left behind by a failed attempt is not reclaimed. ## What to read next > [card] [Adaptive Execution](/enterprise/v1-12-0/enterprise/adaptive-execution) > > Part sizing, and why checkpoint frequency follows it. > [card] [Create a Function](/enterprise/v1-12-0/curation/create-function) > > Shaping a Function, including ones that return Blob v2 output. # Console Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/console A web UI for running SQL, browsing tables, and monitoring jobs on LanceDB Enterprise. **Applies to:** Embedded ❌, Enterprise ✅ The **Console** is a web UI for LanceDB Enterprise -- an alternative to the SDK for people who want to explore and operate a deployment from a browser instead of writing code. It ships with every Managed and BYOC deployment, reachable at the URL your deployment provisions. ## What you can do in the Console * **Run SQL.** A workspace for writing and running [SQL](/enterprise/v1-12-0/sql) against your tables, with results rendered as a browsable grid -- the same engine the SDK and `lancedb` CLI use, reachable without either one. Multimodal columns render inline, so an image column shows as a thumbnail in the grid instead of raw bytes. * **Browse tables.** Inspect a table's schema, row count, and recent versions, and preview rows, without writing a query first. * **Monitor jobs.** Follow the running, queued, completed, and failed jobs behind [refreshes](/enterprise/v1-12-0/feature-engineering/refresh-column), [materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views), and maintenance, including per-job progress and errors. * **Manage access.** Sign in with your organization's identity provider, and manage who else on your team can reach the deployment. [Reach out to us](https://www.lancedb.com/contact) if you'd like to see the Console as part of a LanceDB Enterprise deployment. ## Related guides > [card] [LanceDB Enterprise](/enterprise/v1-12-0/enterprise/index) > > What Enterprise is, and why teams use it. > [card] [SQL reference](/enterprise/v1-12-0/sql) > > The SQL the Console's workspace runs. > [card] [Job management](/enterprise/v1-12-0/sql/ddl/job) > > The job states and history the Console's job view surfaces. > [card] [Deployment and governance](/enterprise/v1-12-0/enterprise/index#deployment-and-governance) > > Managed and BYOC deployment models the Console ships with. # Data Page Cache Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/data-page-cache How LanceDB Enterprise caches table data pages to avoid re-reading object storage. **Applies to:** Embedded ❌, Enterprise ✅ The data page cache holds fixed-size pages of raw table data read from object storage, keyed by their location, so a later read of the same range is served from memory or local disk instead of round-tripping to the backing store. Plan executors and query nodes each keep their own cache for the pages they serve. A background prewarm job can populate a cache ahead of a request that needs it, rather than filling it lazily on first read. See [Architecture](/enterprise/v1-12-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Read request<br/>for a data page"] --> M{"In memory?"} M -->|hit| Return["Served from memory"] M -->|miss| D{"In local disk cache?"} D -->|hit| Promote["Loaded into memory,<br/>served"] D -->|miss| O[("Object storage")] O --> Fill["Fills memory and disk,<br/>served"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` A table's local disk cache shares one configurable budget with the [tiered index cache](/enterprise/v1-12-0/enterprise/tiered-index-cache#disk-budget)'s disk tier where both are enabled on the same executor. ## Why it matters Object storage is durable and cheap, but every round trip to it adds latency and egress cost. For workloads that read the same ranges repeatedly -- a hot subset of embeddings, a frequently-filtered column -- the data page cache turns most of those reads into local memory or disk hits instead, so performance stays predictable as traffic grows and you pay object storage once per page, not once per read. [Contact us](https://www.lancedb.com/contact) to learn more about how caching is sized and tuned for your workload. ## Cache interfaces * [Tiered Index Cache](/enterprise/v1-12-0/enterprise/tiered-index-cache) for the related cache that holds deserialized index structures instead of raw data pages. * [Query plans](/enterprise/v1-12-0/basics/sql#query-plans) for inspecting what a query actually read. # Distributed RTE Read Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-real-time-read How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine. **Applies to:** Embedded ❌, Enterprise ✅ [RTE Read](/enterprise/v1-12-0/search/realtime-read) covers what a query against an RTE-enabled table returns: base-table rows merged with the fresh tier, fresh rows superseding base rows with the same primary key. On a single Embedded process that merge is one function call against one Lance dataset. In LanceDB Enterprise, the base table and the fresh tier are usually served by different machines -- plan executors for the base table, an [RTE node](/enterprise/v1-12-0/tables/realtime-engine#wal-nodes) for the table's shards -- so a query has to combine their results across the network instead. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>plans the query"] subgraph PE["Plan executors"] direction TB B1["Base-table arm<br/>index-covered scan or ANN search"] end subgraph WN["RTE node (owns this table's shards)"] direction TB W1["SSTable arm<br/>index-covered"] W2["Active memtable arm<br/>vector: in-memory HNSW*<br/>FTS/scalar: indexed"] end U["Union exec<br/>PK-keyed last-write-wins dedup,<br/>top-K cut on distance"] Q --> B1 Q --> W1 Q --> W2 B1 --> U W1 --> U W2 --> U U --> R["Merged result"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class U accent ``` ## An extra exec node, not a parallel system The distributed plan for an RTE-enabled table is an ordinary plan executor query plan with one additional node spliced in: a union exec that queries the owning RTE node's shard and merges its rows into the base arm's stream by primary key, keeping the newest generation on a collision and cutting back to the requested top-K once both sides have contributed. An optimizer pass inserts this node only when the query actually touches an RTE-enabled table; a query that touches none produces a plan identical to one with no RTE tables involved at all, so RTE adds no overhead to queries that never use it. Because the base arm already read through the plan-executor fleet's ordinary caches and index structures, the only new network hop this adds is the one to the RTE node that owns the table's shards -- the same RTE node [Real Time writes](/enterprise/v1-12-0/ingestion/realtime-write) land on, found by the query node through the same consistent hash of database and table name. ## Search stays index-covered Every tier the union exec reads from -- the base table, the RTE node's SSTables, and its currently-active memtable -- is covered by a maintained index, for vector, full-text, and scalar search alike: | Layer | Vector search | Full-text / scalar search | | - | - | - | | Base table | ANN index | Maintained index | | SSTables | ANN index | Maintained index | | Active memtable | In-memory HNSW graph\* | Maintained index | ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR B["Base table"] --> I1["Vector, full-text, and<br/>scalar index coverage"] S["SSTables"] --> I1 M["Active memtable"] --> I2["Full-text and scalar index<br/>coverage; vector via<br/>in-memory HNSW*"] I1 --> R["No unindexed data<br/>left to scan in full"] I2 --> R classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class R accent ``` For full-text and scalar search, a maintained index covers every tier the union exec reads from -- the base table, the RTE node's SSTables, and its currently-active memtable -- so a row written a moment ago is just as index-searchable as one written yesterday. If a resident memtable predates an index being added to the maintained set, the query is rejected outright rather than silently missing that memtable's rows; there is no code path that quietly returns an incomplete result. Vector (ANN) search follows the same rule for the base table and SSTables. The active memtable's rows are ANN-searchable too: it builds its own in-memory HNSW graph as rows land, so writes stay vector-searchable within milliseconds without waiting for a freeze into an SSTable. \* That graph search steps aside for a full scan of the memtable only when it can't honor the query correctly through a graph: a prefilter predicate (graph traversal can't apply an arbitrary filter first), a primary-key override that could let a stale near vector occupy a top-K slot a newer row should have, a distance lower bound (only a full scan can exclude the nearest rows before the top-K cut), or before the memtable has any index yet on a cold start. Outside those cases, every committed row -- base table, SSTables, and the active memtable alike -- is covered by a real index, with no sliver of unindexed data left to scan in full. Both guarantees depend on the table's RTE write spec actually maintaining the index in question -- by default every index is maintained, but a deployment that pins a smaller set with `with_maintained_indexes` loses the guarantee for whatever it leaves out, and a query against an unmaintained index is rejected the same way, rather than silently searching the base table alone. ## What to read next > [card] [RTE Read](/enterprise/v1-12-0/search/realtime-read) > > What a query returns, and how Embedded does this same merge in-process. > [card] [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write) > > How writes reach the RTE node this page's queries read from. > [card] [Distributed Search](/enterprise/v1-12-0/enterprise/distributed-search) > > The ordinary plan-executor path this layers on top of. # Distributed RTE Write Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-real-time-write How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it. **Applies to:** Embedded ❌, Enterprise ✅ [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write) describes `table.enable_rte(spec)` as one call that works the same way on either connection. On Enterprise, that call does not run locally -- it posts to the server, which installs the write path on a dedicated, horizontally scalable serving tier instead of running it in your process. This page covers that tier: how it shards a table's writes, the one real limit sharding does not remove, and the throughput you can expect. ## How writes are routed Enabling RTE on a remote table sends the spec to the server, which installs the write path on the dataset instead of running it in your process. From then on, the query node routes every request for that table -- reads and writes alike -- to a single owning **RTE node**, a stateful component separate from the query nodes and plan executors that serve ordinary queries. A query node routes different tables to different RTE nodes, and a single RTE node can host shards from many different tables at once. RTE nodes share nothing but the underlying object storage; no node talks to another one directly. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>routes each table's shards to an RTE node"] subgraph W0["RTE node A"] direction TB S0["Shard 0 — table 'frames'"] S1["Shard 0 — table 'events'"] end subgraph W1["RTE node B"] direction TB S2["Shard 0 — table 'metrics'"] S3["Shard 1 — table 'metrics'"] end Q -- "'frames'" --> W0 Q -- "'events'" --> W0 Q -- "'metrics'" --> W1 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` ## Shards scale one table, replicas scale the cluster `RTEWriteSpec::bucket(column, num_buckets)` splits a table into `num_buckets` **table shards**, each a separate, independently-appending stream, giving the table that many parallel write paths instead of one. A shard's identity is derived from the table itself, not assigned by an operator, so a shard survives the table being claimed by a different RTE node later. This is where the horizontal scaling actually happens: splitting `frames` into 8 shards gives it 8 independent append streams instead of 1, raising that table's own write ceiling. Adding RTE node replicas spreads shard ownership across more nodes, so the cluster can host more tables -- and more shards -- without any one node becoming a bottleneck for everything it serves. `RTEWriteSpec::identity(column)` and `RTEWriteSpec::unsharded()` both resolve to a single table shard -- `bucket` is the sharding mode that actually parallelizes write throughput; the other two are about routing semantics, not scaling. ## Throughput A table shard is the unit of capacity: measured runs show it sustaining roughly 85-90 MB/s of durable append before acknowledgement, and throughput scaling nearly linearly with shard count up to at least 8 shards on one node -- the bottleneck is the durable write itself, not CPU or memory. This is observed capacity, not an enforced quota; nothing in the deployment caps a shard's or a table's throughput below it. [Contact support](https://www.lancedb.com/contact) if your workload needs more write throughput than this provides. ## What to read next > [card] [RTE Write (Upsert)](/enterprise/v1-12-0/ingestion/realtime-write) > > Enable RTE and write to a table; the same call on Embedded or Enterprise. > [card] [How the real time engine works](/enterprise/v1-12-0/tables/realtime-engine) > > MemWAL, shards, memtables and SSTables -- the shared architecture. > [card] [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read) > > How reads combine the WAL tier's fresh rows with the base table across the fleet. # Distributed Search Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-search How LanceDB Enterprise distributes index execution, data reads, and caching across query nodes and executors. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB Enterprise separates query planning from index execution and data reads so that search can use the memory, CPU, and caches of multiple machines. A query node plans and coordinates a query. Executors search indexes, read table data, and return partial results for the query node to combine. For the service components and overall request paths, see [Architecture](/enterprise/v1-12-0/index#architecture). ## Search architecture LanceDB Enterprise prioritizes horizontal scalability. Index execution on a single node can be limited by the memory available to cache the index for fast search and by the CPU available to execute queries. Dividing one logical index into multiple **index segments** lets each segment be distributed to an executor, cached independently, and searched in parallel with other segments. The two serving components have different responsibilities: | Component | Responsibility | | - | - | | Query node (query planning + routing fleet) | Accept requests, plan queries, distribute work, and combine results. | | Executor (executor + cache fleet) | Cache index structures and table data, execute subplans from the query node, and return partial results. | Eligible scalar index operations can also execute on executors. See [scalar indexes](/enterprise/v1-12-0/indexing/scalar-index) and [filtering](/enterprise/v1-12-0/search/filtering) for index types and query syntax. For example, consider a vector index with six segments served by three executors. Each executor searches its two segments and returns its best 10 candidates. The query node compares the candidates returned by all three executors and selects the final 10. This example assumes enough matching rows and the default search path without additional reranking. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB Client["Application: vector search, limit 10"] QueryNode["Query node<br/>Plan, distribute, combine"] Index["One logical vector index<br/>Six index segments"] PlanExecutor1["Executor 1<br/>Cache and search segments A and B"] PlanExecutor2["Executor 2<br/>Cache and search segments C and D"] PlanExecutor3["Executor 3<br/>Cache and search segments E and F"] Merge["Query node<br/>Select final top 10 from up to 30 candidates"] Client --> QueryNode Index -.-> PlanExecutor1 Index -.-> PlanExecutor2 Index -.-> PlanExecutor3 QueryNode -->|Search subplan| PlanExecutor1 QueryNode -->|Search subplan| PlanExecutor2 QueryNode -->|Search subplan| PlanExecutor3 PlanExecutor1 -->|Up to 10 candidates| Merge PlanExecutor2 -->|Up to 10 candidates| Merge PlanExecutor3 -->|Up to 10 candidates| Merge Merge --> Result["Application receives up to 10 results"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Merge accent ``` ### Tiered index cache Executors cache index structures in memory, and extend that cache onto local disk when the disk tier is enabled. See [Tiered Index Cache](/enterprise/v1-12-0/enterprise/tiered-index-cache) for how the two tiers work together and how the disk tier's budget is shared and sized; ask your deployment operator about enabling it on your cluster. ### Create and query an IVF-RQ index Use the regular table API. These examples assume `table` is an open Enterprise table with a `vector` column and the query vector is compatible with that column. For connection setup, see [connect to LanceDB](/enterprise/v1-12-0/basics/catalog). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import IvfRq table.create_index("vector", config=IvfRq(num_bits=5, distance_type="cosine")) # Run after the background index build is complete. results = table.search(query_vector).distance_type("cosine").limit(10).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { Index } from "@lancedb/lancedb"; await table.createIndex("vector", { config: Index.ivfRq({ numBits: 5, distanceType: "cosine" }), }); // Run after the background index build is complete. const results = await table .vectorSearch(queryVector) .distanceType("cosine") .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; use lancedb::index::{vector::IvfRqIndexBuilder, Index}; use lancedb::query::{ExecutableQuery, QueryBase}; use lancedb::DistanceType; table .create_index( &["vector"], Index::IvfRq( IvfRqIndexBuilder::default() .num_bits(5) .distance_type(DistanceType::Cosine), ), ) .execute() .await?; // Run after the background index build is complete. let results: Vec<arrow_array::RecordBatch> = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10) .execute() .await? .try_collect() .await?; ``` Enterprise builds indexes in the background. Submitting index creation does not mean the index is ready; check index status before evaluating indexed search. These examples explicitly select 5 bits per dimension. See the shared docs for [RaBitQ and `num_bits`](/enterprise/v1-12-0/indexing/vector-index#using-rabitq), [index creation parameters](/enterprise/v1-12-0/indexing/vector-index#build-time-parameters), and [vector search](/enterprise/v1-12-0/search/vector-search#vector-search-with-ann-index). For the `fast`, `normal`, and `accurate` latency/recall modes, see [tuning `approx_mode`](/enterprise/v1-12-0/search/vector-search#tuning-approx-mode). The Rust SDK currently exposes that query setting; the examples above use the default mode. ## Distributed full-text search FTS work is organized by inverted index. Compatible operations targeting the same table and text column can execute together on executors over that index's segments. Operations targeting different indexed columns can execute separately, with their results combined on the query node according to the query. For example, suppose an `articles` table has separate FTS indexes on `title` and `body`. A query asks for rows whose title matches the exact term `vector` **or** whose body contains the phrase `nearest neighbor`: 1. The query node plans the title and body index searches separately. 2. Executors search the relevant segments of each index. 3. The query node combines the scored rows according to the cross-column query's semantics and returns the requested results. ### Local and global scoring Distributed FTS defaults to **local scoring**. For indexed searches, each executor uses statistics from its assigned segments to calculate BM25 scores. This avoids a separate statistics round, but document frequencies and average document lengths can differ between executors. Merging their scores can therefore produce a different ranking from scoring with statistics across the entire index. **Global scoring for indexed searches** adds a statistics round before search. The query node collects and aggregates document counts, token counts, and query-term document frequencies across the target FTS index. Executors then score with the shared statistics before the query node combines their results. The statistics are global to that index, not blended across all text columns in the table. Both modes combine results. The difference is the statistics used during scoring on executors; global mode does not rescore the returned rows on the query node. It trades an additional statistics round for consistent BM25 statistics across executors. When term frequencies and document lengths are similarly distributed across index segments, local scoring can produce rankings comparable to global scoring. If segments contain substantially different document populations, prefer global scoring for consistent statistics across the index, at the cost of an additional statistics round and higher query latency. Eligible flat searches over entirely unindexed text also use this setting. In **local mode**, the scoring corpus is split by ownership of table data. Each executor computes BM25 statistics over its assigned documents before candidate selection, then returns matching rows. This takes one FTS execution round without a global statistics barrier; the query node applies the final top-k. Changing executor ownership can change scores and ranking even when the table data is unchanged. In **global mode**, an eligible unindexed flat search sends its complete scoring corpus to a single executor, which computes statistics and scores together. This preserves global BM25 for that corpus without a separate statistics round. The query node still performs the final sorting and top-k. Inputs for flat search that cannot be safely partitioned retain their complete scoring domain. If executor capabilities or routing are unavailable, execution can remain on the query node. Global scoring is a query node setting, configured at the deployment level. See [full-text search](/enterprise/v1-12-0/search/full-text-search) for query syntax and [FTS indexes](/enterprise/v1-12-0/indexing/fts-index) for index configuration. ## Distributed data search A table can be larger than any single node's local storage. Enterprise keeps the durable table in object storage and distributes data reads and caches across executors. An executor needs capacity for its cached working set rather than a complete local copy of the table. With fragment-based data routing, reads for a data fragment go to a serving executor. Different fragments can be served and cached on different executors. The following example shows six fragments served by three executors: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB QueryNode["Query node<br/>Plan data reads and assemble results"] PlanExecutor1["Executor 1<br/>Read fragments 1 and 2<br/>Local NVMe disk cache"] PlanExecutor2["Executor 2<br/>Read fragments 3 and 4<br/>Local NVMe disk cache"] PlanExecutor3["Executor 3<br/>Read fragments 5 and 6<br/>Local NVMe disk cache"] Store[("Object storage<br/>Durable table fragments")] QueryNode -->|Read subplan| PlanExecutor1 QueryNode -->|Read subplan| PlanExecutor2 QueryNode -->|Read subplan| PlanExecutor3 PlanExecutor1 -->|Cache miss| Store PlanExecutor2 -->|Cache miss| Store PlanExecutor3 -->|Cache miss| Store classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Store accent ``` ### NVMe data caching The data page cache stores pages read from table fragments on **local disk, including NVMe SSDs**. On a cache hit, the executor reads the page from local disk; on a miss, it fetches the page from object storage and fills the cache for subsequent reads. The cache holds accessed pages, not necessarily every byte of each fragment assigned to an executor. See [Data Page Cache](/enterprise/v1-12-0/enterprise/data-page-cache) for how it's structured and sized. ## Inspect execution Use `analyze_plan()` (`analyzePlan()` in TypeScript) to understand how a query executes and troubleshoot slow searches. It runs the query and returns the execution plan with runtime metrics. Using the same table and query vector as above: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = table.search(query_vector).distance_type("cosine").limit(10) print(query.analyze_plan()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const query = table.vectorSearch(queryVector).distanceType("cosine").limit(10); console.log(await query.analyzePlan()); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::query::{ExecutableQuery, QueryBase}; use lancedb::DistanceType; let query = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10); println!("{}", query.analyze_plan().await?); ``` Inspect the plan to check which indexes are used, which operations run on query nodes or executors, and where execution time is spent. Compare index search with data retrieval to identify expensive work. Repeating the query can also help distinguish cold-cache reads from warm-cache performance. # Distributed Write Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-write How LanceDB Enterprise distributes a CTAS import's writes across plan executors. **Applies to:** Embedded ❌, Enterprise ✅ Distributed write applies specifically to importing data with `CREATE TABLE ... AS SELECT`: the query node that planned the statement partitions the source -- Parquet files from a HuggingFace dataset, or row-group ranges of an existing Lance dataset in object storage -- across plan executors, each of which writes its own uncommitted Lance data files and reports back. The query node collects those results and commits them together as the new table's first version; no separate coordinator service is involved. See [Architecture](/enterprise/v1-12-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Source<br/>HuggingFace Parquet, or an<br/>existing Lance dataset in<br/>S3 / GCS / Azure"] Q["Query node<br/>plans the CTAS,<br/>commits the result"] PE1["Plan executor<br/>writes uncommitted files"] PE2["Plan executor<br/>writes uncommitted files"] PE3["Plan executor<br/>writes uncommitted files"] S --> Q Q --> PE1 Q --> PE2 Q --> PE3 PE1 --> Q PE2 --> Q PE3 --> Q classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Q accent ``` An ordinary `INSERT` or `merge_insert`, from SQL or the SDK, does not distribute this way -- it runs as a single write, on whichever node or process executes it. Only a CTAS import fans the write itself out across machines. ## Write interfaces * [Import Datasets](/enterprise/v1-12-0/ingestion/import) for the CTAS syntax this distributes. * [Insert data](/enterprise/v1-12-0/ingestion/insert) and [Merge](/enterprise/v1-12-0/ingestion/merge-insert) for the ordinary, non-distributed write paths. * [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) for configuring the source a CTAS import reads from. # Incremental Refresh Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/incremental-refresh Why refreshing a computed column only recomputes fragments that hold a row whose inputs actually changed. **Applies to:** Embedded ❌, Enterprise ✅ Refreshing a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) is incremental: it fills rows that have no value yet and recomputes the fragments that hold a row whose input changed since it was last computed, leaving every other fragment alone. A second refresh with nothing changed does nothing. The planner finds the rows that actually need work by checking which fragments still carry stale or empty values for the column, then groups them into claimable units a fleet of job workers can pick up in parallel \-- see [Architecture](/enterprise/v1-12-0/index#architecture). > [!NOTE] > > A **materialized view** doesn't track stale rows the way a computed > column does -- there's no smaller unit than the whole view to recompute > from a saved query. In LanceDB Embedded, every refresh rebuilds the view > completely with no incremental step; LanceDB Enterprise's server chooses > the refresh mode instead, unless the caller forces a full rebuild. See > [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view). ## Why this matters Appending rows is cheap: the next refresh only fills what's new, not what it already computed. Updating an input row is also cheap in the same way -- the derived column keeps its old value until the next refresh notices the input changed. Staleness is tracked per fragment, not per row: the refresh recomputes every row in a fragment where at least one input moved, which can re-evaluate rows whose own value didn't actually need it, not strictly only the row that changed. Nothing is recomputed between refreshes, so a derived column can be stale right up until you call for one. ## What to read next > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column#idempotent) > > The exact fill/recompute/leave-alone rules, with examples. > [card] [Adaptive Execution](/enterprise/v1-12-0/enterprise/adaptive-execution) > > How the units this planner produces get sized and run. # LanceDB Enterprise Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/index Features and benefits of LanceDB Enterprise. **LanceDB Enterprise** is the production deployment option for teams that want to run LanceDB as a private cloud or bring-your-own-cloud (BYOC) **multimodal lakehouse**. If you are new to multimodal lakehouses, the short version is this: LanceDB keeps vectors, metadata, and source data together in open table storage, while Enterprise adds the distributed infrastructure needed to serve real production workloads on top of that data. It is designed for teams that need more scale, more operational visibility, and more control than a single embedded process can provide. LanceDB Enterprise distributes query execution, indexing, maintenance and refresh work across the service, outside your application. If you need private deployments, high performance at extreme scale, or if you have strict security requirements, [reach out to our team](https://www.lancedb.com/contact) to set up a LanceDB Enterprise cluster in your environment. ![LanceDB Enterprise architecture](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/overview/lancedb-distributed.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=d1951b6668315b87ca22d2e6e231a51c) LanceDB Enterprise: the LanceDB SDK connects to the Enterprise service, where a query fleet, executor and cache fleets, the realtime engine, and a jobs fleet run on top of the Lance format and object storage. ## Why use LanceDB Enterprise? If you are evaluating LanceDB for a production AI system, Enterprise is built around three practical needs: handling very large vector workloads, running feature engineering close to the data, and operating the platform with production visibility. ### 1. Scale shared workloads LanceDB Enterprise is built for demanding workloads that exceed the capabilities of a single machine, whether from extremely large data volumes or a high number of concurrent queries. Instead of asking your application to own caching, query scaling, and maintenance, Enterprise turns those into **platform** capabilities. This matters when your AI application moves past a prototype and starts serving real users, larger datasets, and more concurrent requests. * **Low-latency tiered cache**: Enterprise keeps frequently read data closer to compute, so common queries do not need to fetch the same data from object storage over and over again. That helps reduce wait times and makes performance more predictable as traffic increases. * **Horizontal query throughput**: Instead of relying on one application process to answer every query, Enterprise can spread search traffic across multiple nodes. This lets teams add capacity as usage grows, rather than re-architecting the application each time demand spikes. * **Background maintenance**: Enterprise builds indexes and compacts tables on background workers, reducing the maintenance work your application needs to schedule. ### 2. Feature engineering For many teams, retrieval is only part of the problem. They also need a reliable way to derive new columns, run backfills, and keep feature pipelines close to the data they already store in LanceDB. This is what [feature engineering](/enterprise/v1-12-0/feature-engineering) enables. * **Derived features**: Create new columns from existing data and user-defined logic without standing up a separate feature platform first. * **Large-table backfills**: Update or recompute features across large datasets without wiring your own distributed batch system around LanceDB Embedded tables. * **Shared workflows**: Manage feature engineering work -- clusters, jobs, and their configuration -- in one place. ### 3. Enterprise-grade monitoring Production retrieval systems need more than search or training performance. Teams also need to observe the system, choose how it is deployed, and satisfy security and compliance requirements. * **Metrics and traces**: Integrates with existing observability systems for monitoring and distributed tracing using OpenTelemetry. * **Deployment choice**: Run LanceDB as a managed deployment or install it inside your own cloud account with [BYOC](#deployment-and-governance). * **Private networking and compliance**: Designed for production environments that need encryption at rest, private connectivity options, and compliance coverage such as SOC 2 Type II and HIPAA. ## Deployment and governance LanceDB Embedded is included as part of your binary, Docker, or serverless function. The footprint is small, and no extra services run beside it. LanceDB Enterprise comes in three deployment models, all supporting AWS, GCP, and Azure: **Managed** is a private deployment of LanceDB Enterprise: applications run in cloud accounts managed by LanceDB, in the same location as your client applications. This hands-off approach suits teams that do not want to manage the infrastructure themselves. LanceDB can provision either a public or private load balancer for access. **Bring-your-own-cloud (BYOC)** installs LanceDB Enterprise into your own cloud account, so data never leaves it. Reach for this when data-residency requirements preclude data from leaving your account, or when other applications need to access the object storage directly. An identity is provisioned in your account with permissions to manage the infrastructure. **Custom deployments** cover requirements beyond the two models above -- [reach out to our support team](https://www.lancedb.com/contact). Both Managed and BYOC are designed for private networking, compliance, and operational oversight. ## See how Enterprise compares to Embedded > [card] [Embedded vs Enterprise](/enterprise/v1-12-0/basics/embedded-vs-enterprise) > > A feature-by-feature comparison: architecture, latency, throughput, caching, maintenance, and day-to-day usage > differences. [Reach out to us](https://www.lancedb.com/contact) to set up LanceDB Enterprise in your organization, or to arrange a proof of concept for your workload. # Tiered Index Cache Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/tiered-index-cache How LanceDB Enterprise caches deserialized index structures across memory and local disk. **Applies to:** Embedded ❌, Enterprise ✅ The tiered index cache holds deserialized vector, full-text and scalar index structures in memory, backed by a local-disk tier beneath it. When memory fills, the cache serializes evicted entries and spills them to disk instead of dropping them; a later hit on a spilled entry promotes it back into memory. This lets a plan executor serve an index larger than its available memory without re-reading and re-deserializing it from object storage on every eviction. See [Architecture](/enterprise/v1-12-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Index lookup"] --> M{"In memory?"} M -->|hit| Return["Served from memory"] M -->|miss| D{"Spilled to disk?"} D -->|hit| Promote["Deserialized,<br/>promoted into memory,<br/>served"] D -->|miss| O[("Object storage")] O --> Fill["Deserialized,<br/>loads into memory,<br/>served"] Evict["Memory eviction"] -.->|serialize, don't drop| D classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` ## Sharing the disk budget Where enabled, the index disk tier and the [data page cache](/enterprise/v1-12-0/enterprise/data-page-cache)'s disk tier draw from one combined, configurable disk allocation per executor, split between the two tiers so neither one needs its own dedicated volume. ## Why it matters Vector, full-text, and scalar indexes can easily outgrow available memory on large tables. Without this cache, an eviction means re-reading and re-deserializing that index from object storage on the next request -- slow, and repeated on every eviction. Spilling to local disk instead keeps index lookups fast even when the working set is larger than memory, without giving every executor enough memory to hold every index at once. [Contact us](https://www.lancedb.com/contact) to learn more about how caching is sized and tuned for your workload. ## Index cache interfaces * [Cache Prewarm](/enterprise/v1-12-0/enterprise/cache-prewarm) for warming this cache ahead of the first request. * [Data Page Cache](/enterprise/v1-12-0/enterprise/data-page-cache) for the related cache that holds raw table data pages instead of deserialized index structures. * [Vector indexes](/enterprise/v1-12-0/indexing/vector-index), [full-text indexes](/enterprise/v1-12-0/indexing/fts-index), and [scalar indexes](/enterprise/v1-12-0/indexing/scalar-index) for the index types this cache serves. # Create a computed column Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/add-computed-column Declare a column from a SQL expression. Nothing is evaluated until you refresh it. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Lance can write a new column without rewriting the columns already in the table. That matters most on a table that also holds large images, video or embeddings, where rewriting everything just to add one small derived field would be wasteful. See [Lance format](/enterprise/v1-12-0/basics/lance) for the storage model this relies on. A computed column is how LanceDB formalizes that capability for feature engineering specifically: instead of writing the derived values immediately, it is declared with an expression and starts with no values. Declaring it is cheap on any table size, because nothing is evaluated until [a refresh](/enterprise/v1-12-0/feature-engineering/refresh-column) asks for it. > [!NOTE] > > `computed` requires LanceDB Enterprise. Ordinary eager `add_columns` > transforms, without `computed`, remain available in LanceDB Embedded. ## Fill a column with a Function Enterprise When the value cannot be expressed in SQL -- an embedding, a model call, an image decode -- the column is filled by a registered [function](/enterprise/v1-12-0/management/function) instead of a SQL expression. It needs a deployment with Functions enabled. Connect with an [Enterprise connection](/enterprise/v1-12-0/basics/catalog#enterprise). Continuing the [`caption` Function](/enterprise/v1-12-0/curation/create-function#chain) registered in Create a Function, against a `frames` table that already has a `jpeg` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} version = db.create_function_async(caption).wait() table.add_columns({"caption": version(jpeg=col("jpeg"))}) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames ADD COLUMN caption AS caption(jpeg) WITH (version = 'fv_1') ``` A Function application is called with its parameters bound to source columns through `col(...)`, keyed by the output column name. It commits a new, empty table version the same way a SQL expression does, so the usual [versioning](/enterprise/v1-12-0/management/table#versioning) applies. Both a Function application and a SQL expression accept `auto_refresh_enabled` and `auto_refresh_interval_seconds`, and both refresh and toggle the same way; see [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh). Enterprise 1.12.0 supports the automatic-refresh enable and interval settings above. Aggregate resource budgets for automatic Function refreshes are not supported in this release. For a budget on an explicit refresh, use the [SQL refresh options](/enterprise/v1-12-0/feature-engineering/refresh-column#resources). ## Fill a column with a SQL expression A value that SQL can compute doesn't need a Function. Declare it with `computed` instead, as an expression evaluated over the row: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) # AddColumnsResult(version=2) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 ``` That commits a new table version with the column present and empty. It is an ordinary table version, so the usual [versioning](/enterprise/v1-12-0/management/table#versioning) applies, including that you can travel back to before the column existed. The expression can reference any column in the table, including another computed column -- declaration order is dependency order, so it may reference one declared earlier in the same mapping, but not one declared after it: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns(computed={ "power_score": "cast(x as double) / 2.0", "is_strong": "power_score > 0.5", }) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN power_score AS cast(x as double) / 2.0 ALTER TABLE computed_demo ADD COLUMN is_strong AS power_score > 0.5 ``` The functions available are the ones the [SQL dialect](/enterprise/v1-12-0/sql/dql/functions) documents. A literal in the expression has to fit the column it meets: `x / 2.0` is refused when `x` is an integer column, so write `cast(x as double) / 2.0`. > [!WARNING] > > Keep the expression to top-level columns. A column refresh can fail on an > expression that reads a field inside a struct, such as > `stats.magic + stats.strength`. Try a new expression on a small table first. ## Compute now or on refresh `add_columns` takes either, and the difference matters: * **SQL expressions in `transforms`** are evaluated *now*, for every row, as part of the call. Good for a small table, or a column you want populated immediately. A `FunctionApplication` passed through `transforms` instead declares empty Function-bound columns, which a refresh fills; that needs a deployment with Functions enabled, and the embedded library refuses it. * **`computed`** stores the expression and evaluates nothing. The column is committed empty and filled later by [`refresh_column`](/enterprise/v1-12-0/feature-engineering/refresh-column). `computed` and `transforms` cannot be combined in one call. Reach for `computed` when the table is large enough that you would rather control when the work happens. Automatic refresh is on by default for each computed column, and takes effect when your Enterprise deployment enables its refresh scheduler. Until then, call [`refresh_column`](/enterprise/v1-12-0/feature-engineering/refresh-column) yourself. Pass `auto_refresh_enabled=False` to opt a column out, or `auto_refresh_interval_seconds` to set how often it refreshes: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns( computed={"doubled": "x * 2"}, auto_refresh_interval_seconds=300, ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 WITH (auto_refresh_interval_seconds = 300) ``` See [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for the full behavior, including how to change the setting later. An eager `transforms` call looks like this, starting from a small product table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_add_example", data, mode="overwrite") ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a discounted price column (10% discount) table.add_columns({"discounted_price": "cast((price * 0.9) as float)"}) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE schema_evolution_add_example ADD COLUMN discounted_price AS cast((price * 0.9) as float) ``` SQL's `ADD COLUMN ... AS` always declares the column empty and defers the expression to a refresh, the same as `computed` does -- there is no SQL form of eager `transforms`. The Python call above is the only way to get discounted_price filled immediately; declaring it in SQL fills it only once [`REFRESH COLUMN`](/enterprise/v1-12-0/sql/dml/refresh-column) runs. For feature engineering on large existing tables, group related derived features into one `add_columns` call instead of running many separate writes: this creates one new table version for the schema change and computes every new column from the existing rows in it, rather than growing the table's version history with many small updates. > [!NOTE] > > On local tables, Python `add_columns` also accepts pandas or Polars > DataFrames, PyArrow Tables, RecordBatches, RecordBatchReaders, and iterables > of batches. Pass only the new columns, with exactly one row per current live > table row in storage scan order. DataFrame indexes are ignored, and reader > batch boundaries need not match table fragments. Keep the table unchanged > between computing the values and adding them. Readers are consumed once. > > Data inputs cannot be combined with `computed` columns and are not supported > on remote tables. Python callables and batch UDFs are not accepted; compute > those values first, then pass the result as a DataFrame or reader. ## Change columns used by a computed column > [!WARNING] > > While a computed column's declaration references another column, that column > cannot be renamed, retyped, or dropped. Drop the computed column first > if you need to change one of its inputs. This is worth knowing before deriving a column from something you expect to reshape later. Dropping the computed column releases the constraint. ## Related guides > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Fill the rows that lack values. > [card] [Functions](/enterprise/v1-12-0/management/function) > > Fill a column with Python. # Feature engineering Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/index Derive columns and tables from data already in the lakehouse, without moving it somewhere else to compute. Use feature engineering to turn raw data into features for search, analysis and model training. LanceDB stores derived columns and materialized views alongside the source data, so you can reuse the results across those workflows. [Functions](/enterprise/v1-12-0/management/function) and [materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views) are ordinary [catalog objects](/enterprise/v1-12-0/basics/catalog). Create them through the SDK or SQL, then refresh the derived data when its inputs change. > [!NOTE] > > In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/enterprise/v1-12-0/sql/ddl/table#alter) to declare a column and [REFRESH COLUMN](/enterprise/v1-12-0/sql/dml/refresh-column) to fill it. ## Computed columns and materialized views Computed columns and materialized views both keep derived data in the lakehouse, but they fill it differently, and the difference decides what a refresh costs: | | Computed column | Materialized view | | - | - | - | | Declaring or creating it | records the expression; no values are written | runs the query and stores its rows, unless created empty | | A refresh | fills rows with no value and recomputes rows whose inputs changed | rebuilds the view completely from its source query | | A refresh when nothing changed | fills nothing | still rebuilds the view and commits a new version | | In LanceDB Enterprise | runs as a [job](/enterprise/v1-12-0/basics/jobs) | runs as a server-side materialization job | ### Computed columns fill incrementally A [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) separates **declaring** from **filling**: * Declaring is cheap and immediate. It records the expression in the schema and commits a new table version, with no data written. It does not evaluate the expression over existing rows. * Fill the column with a separate refresh call that you can retry. In LanceDB Enterprise, submit the refresh as a [job](/enterprise/v1-12-0/basics/jobs) and track its progress. **Refresh new and changed rows.** A [refresh](/enterprise/v1-12-0/feature-engineering/refresh-column) gives values to rows that lack them and recomputes rows whose inputs changed since they were computed. It leaves the rest alone, so calling it twice is not twice the work, and appending rows means the next refresh handles only the new ones. **Computed values update when you refresh.** If a column derives from `price` and a row's `price` is later updated, the derived value keeps its old value until the next refresh recomputes it. Schedule refreshes after changing the source data when consumers need up-to-date features. ### Materialized views store query results A [materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) has no separate declaration step: creating one runs its query and stores the result, so the view is ready to read. A refresh rebuilds the stored result completely from the source query; see [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) for the full behavior, including automatic refresh. Enterprise runs materialization on remote compute, as a server-side job. ## Choose a feature engineering workflow | | What it produces | Filled by | Available | | - | - | - | - | | [View](/enterprise/v1-12-0/feature-engineering/view) | a saved query, no stored rows of its own | nothing -- it runs on every read | Enterprise | | [Computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Enterprise | | [Materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Enterprise | | [Function](/enterprise/v1-12-0/management/function) | a computed column filled by Python | registered code | Enterprise | | [Geneva](/enterprise/v1-12-0/geneva) | columns filled by Python, for existing pipelines | the `geneva` package | Enterprise | **A view** has no refresh and no staleness window, because it stores the query rather than its result. Reach for one first, before a computed column or a materialized view, when the query is cheap enough to simply re-run on every read. **Computed columns** are the common case: a column declared with a SQL expression, filled by [a refresh](/enterprise/v1-12-0/feature-engineering/refresh-column). **Materialized views** derive a whole table (a filtered, projected, or aggregated view of a source) and bring it up to date on each refresh. The result is an ordinary table: queryable, indexable, searchable. **Functions** run Python where the data is, for work SQL cannot express: embedding a column, calling a model, decoding an image. Registered once, versioned, then applied as a column. They are the way to do that on a deployment; [Geneva](/enterprise/v1-12-0/geneva) remains available for existing pipelines. A materialized view can select computed columns. A computed column can be filled by a registered function. ## Where the work runs Enterprise Locally, a refresh runs in your process. With LanceDB Enterprise it runs across the cluster, and the API reflects that: `refresh_column` raises, and `refresh_column_async` returns a [job](/enterprise/v1-12-0/basics/jobs) handle instead. Computed columns are off by default in LanceDB Enterprise, and its administrator has to enable them before a column can be declared there. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("power_score") result = job.wait() result.rows_assigned ``` A backfill over a large table can therefore be started, left, and checked on from a different process: the connection does not have to stay open. Enterprise manages the compute for the refresh. Declaring a computed column doesn't refresh it on a schedule unless your deployment enables automatic refresh; see [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh). That is also why a function must declare the environment it needs. ## Recovering from a failure A function that raises fails the job. There is no per-row retry or skip policy in the function definition, so a function calling a flaky external service should handle that itself, inside the function body. When a refresh fails, fix the cause and run the refresh again. The new refresh fills what is still empty or stale. How much of the failed run was kept depends on where it ran (see [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column#failures)), and a retry can recompute values that were already written, so do not count on it costing only the rows that did not complete. ## Related guides > [card] [Create a view](/enterprise/v1-12-0/feature-engineering/view) > > A saved query, with no storage or refresh of its own. > [card] [Create a computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) > > Declare a column from a SQL expression. > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Fill the rows that lack values, locally or as a job. > [card] [Create a materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) > > Store a query's result as a table. > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > Bring a derived table up to date with its source. > [card] [Functions](/enterprise/v1-12-0/management/function) > > Register Python to fill a column with. # Create a materialized view Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/materialized-views Store the result of a query as a table, ready to query, index and search. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view stores the result of a query as a table. Use it to keep a filtered or transformed dataset that you can query, index and search repeatedly, instead of recomputing the query every time you read it. > [!NOTE] > > In SQL this is [`CREATE MATERIALIZED VIEW`](/enterprise/v1-12-0/sql/ddl/materialized-view#create). ## Create a view A materialized view is defined by a SQL query, so it is created with one. From Python, run the statement on an [Enterprise connection](/enterprise/v1-12-0/basics/catalog#enterprise) with [`execute_query`](/enterprise/v1-12-0/basics/sql#sql-from-python); the SQL is the same either way: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() view = db.open_materialized_view("frames_captioned") ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` `execute_query` returns once the result stream is readable, not once the statement has finished, so `.read_all()` waits out the full creation before the next line opens it. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for captioning. There is no separate, more limited form for defining one -- joins and [Functions](#functions) in the select list work the same way any other `SELECT` does, within the query shapes your deployment's LanceDB Enterprise version and configuration accept; see the [SQL reference](/enterprise/v1-12-0/sql/ddl/materialized-view#create). Creating the view computes its rows, so it is ready to read immediately. [`db.open_materialized_view`](/enterprise/v1-12-0/management/materialized-view#manage) gets a handle back for reading, refreshing or inspecting it from Python; the view itself is also an ordinary table, queryable by name like any other. Your administrator manages stable row IDs and other source-table requirements for materialized views on the server; confirm support for your source table's shape before creating a view over it. ## Selecting a Function's output Enterprise A `SELECT` expression is SQL text, so it can call a registered [Function](/enterprise/v1-12-0/curation/create-function) the same way a computed column's expression can. Continuing the [`caption` Function](/enterprise/v1-12-0/curation/create-function#chain) registered in Create a Function, against a `frames` table that already has a `jpeg` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, jpeg, caption(jpeg) AS caption FROM frames WHERE selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, jpeg, caption(jpeg) AS caption FROM frames WHERE selected = true ``` A query that joins tables works the same way, with no separate syntax for it. Continuing the join and chained Functions from [Create a Function](/enterprise/v1-12-0/curation/create-function#chain), producing `jpeg` from a separate `videos` table and captioning it in the same statement: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) AS SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) AS SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true ``` See [Joins](/enterprise/v1-12-0/curation/join) for the join itself, and [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for what `WITH` sets here. ## Automatic refresh at creation Set `auto_refresh_enabled` and `auto_refresh_interval_seconds` in the `WITH` clause to schedule refreshes instead of calling [`refresh`](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) yourself: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` Omit `auto_refresh_enabled` to let the server decide whether to enable it, and omit `auto_refresh_interval_seconds` to let the server decide the pacing. See [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for how scheduling behaves once the view exists. ## Working with the view `view.table` is the underlying table, for querying, indexing, or search. `view.definition` has a single field, `query` -- the recorded query, in the canonical spelling the server stores. Use it to inspect the query without inferring it from the rows. Both are properties; on an async view, the definition is read with `await view.definition()`. Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/enterprise/v1-12-0/management/materialized-view#manage). ## Related guides > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > Bring the view up to date with its source. > [card] [Versioning](/enterprise/v1-12-0/management/table#versioning) > > Inspect the table history and read a particular version. # Refresh a computed column Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/refresh-column Populate a computed column and update it when its inputs change. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Refresh a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) to fill new rows and recompute values whose inputs changed. The example below continues with the `doubled` column from the computed-column guide. > [!NOTE] > > Computed columns require LanceDB Enterprise. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("doubled") job.wait() table.search().to_arrow().sort_by("x").to_pandas() # x doubled # 0 1 2 # 1 2 4 ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table ``` > [!NOTE] > > `table.refresh_column(...)` (sync) is also a local, blocking form, but it > raises on an Enterprise connection -- use `refresh_column_async`, shown > above, or the SQL form instead. See > [Run a refresh on Enterprise](#async) below for what the returned job > supports. The refresh commits ordinary table versions (the values, then a metadata-only record of the inputs they were computed from), so [versioning](/enterprise/v1-12-0/management/table#versioning) applies to it like any other write. > [!NOTE] > > The SQL form is [`REFRESH COLUMN`](/enterprise/v1-12-0/sql/dml/refresh-column), with the same resource options. ## What a refresh recomputes Without a `WHERE` predicate, a refresh fills unassigned rows and recomputes values whose inputs changed since they were computed. Every other row is left alone, so a second refresh with nothing changed does nothing. This supports two common workflows. **Appending is cheap.** Rows added since the last refresh are filled by the next one; filled rows whose inputs are unchanged are skipped. Backfilling a column and then ingesting more data does not mean recomputing the backfill. **A filled value catches up with its input at the next refresh.** If `doubled` derives from `x` and a row's `x` is later updated, `doubled` keeps its old value until the next refresh recomputes it. That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived column is stale between an update and the next refresh. ## Automatic refresh A computed column can refresh itself on a schedule instead of waiting for an explicit call here. See [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for enabling it, the SQL and SDK forms for changing the setting, and how catch-up works when it's re-enabled after being off. ## Refreshing part of a table Enterprise A refresh can be scoped to a predicate, with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice first and checking it before committing to the whole table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01'", ) job.wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` A filtered refresh recomputes **every matching live row**, including rows whose outputs are already current. Repeating the same predicate repeats those Function calls and their cost. To select only null outputs within a slice: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01' AND embedding IS NULL", ) job.wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even when their inputs changed, and can recompute outputs that were successfully computed as `NULL`. Use an unfiltered refresh to let LanceDB track which outputs need updating. > [!NOTE] > > **Enterprise job type:** `computed_refresh` for a SQL-expression column, > `function_refresh` for one filled by a registered [function](/enterprise/v1-12-0/management/function). ## Run a refresh on Enterprise Enterprise With an Enterprise cluster that enables computed columns, the refresh runs on the cluster. `refresh_column` raises there; use `refresh_column_async`, which returns a [job](/enterprise/v1-12-0/basics/jobs) you can wait on or poll instead of holding a connection open: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("doubled") result = job.wait() result.rows_assigned # 2 job.status() # 'finished' ``` Poll with `status()`, resolve with `wait()`. `status()` is a point snapshot and does not raise, which is what makes it safe in a loop; `wait()` raises `JobFailedError`, `JobCancelledError` or `TimeoutError`. A long backfill can therefore be started, left, and checked on from a different process. ### Configure workers and resources SQL exposes the worker budget directly, which is the lever when a backfill is too slow or too expensive: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` The resource values cap the Function workers together: this example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. For Enterprise 1.12.0, use the SQL form above to set a complete CPU, memory and GPU budget. Include all three fields; use `gpu_count = 0` for a CPU-only Function. The Python 0.42.0b8 client does not accept the nested `resource_budget` keyword. The SDK can change GPU placement with the top-level `gpu_count` and `gpu_class` options shown below. Omitting them preserves the server defaults. Automatic-refresh resource budgets and per-call concurrency controls are not supported by Enterprise 1.12.0. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to `error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for failing rows and record them in the error store, subject to failure limits. See the [SQL refresh options](/enterprise/v1-12-0/sql/dml/refresh-column#options). For a column filled by a registered Function, the Python and Rust job APIs can override the Function's GPU placement for this refresh: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} classes = db.list_gpu_classes() gpu_class = next(gpu.name for gpu in classes if gpu.gpu_model == "NVIDIA H100") job = table.refresh_column_async( "embedding", gpu_class=gpu_class, gpu_count=4, batch_size=32, ) ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::{Connection, Table, table::RefreshColumnOptions}; async fn refresh( conn: &Connection, table: &Table, ) -> Result<(), Box<dyn std::error::Error>> { let gpu_class = conn .list_gpu_classes() .await? .into_iter() .find(|class| class.gpu_model.as_deref() == Some("NVIDIA H100")) .map(|class| class.name) .ok_or("H100 GPU class is not configured")?; let _job = table .refresh_column_async_with_options( "embedding", RefreshColumnOptions::default() .gpu_class(gpu_class) .gpu_count(4) .batch_size(32), ) .await?; Ok(()) } ``` `gpu_count` is the aggregate GPU budget for the refresh's Function workers, not a request for that many GPUs per worker. It must be positive and preserves the deployment's CPU and memory defaults. `gpu_class` must name a class returned by `list_gpu_classes()`; class names are lowercase DNS labels. Omit either option to use the Function's registered class or the server's configured budget. `list_gpu_classes()` requires System Usage permission, and raises `NotImplementedError` when the server predates GPU class discovery. > [!NOTE] > > The Rust GPU discovery and refresh controls are not in the latest Rust > release. TypeScript does not expose GPU class discovery; pass `gpuClass` > and `gpuCount` in the `refreshColumnAsync` options. Function outputs become visible when their fragment is published. Enterprise 1.12.0 does not support a row-count publication threshold. The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed to new rows (see [what a filter recomputes](#partial)) and told to skip rows whose Function call fails: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01'", error_policy="skip", max_failed_fraction=0.01, row_timeout_seconds=30, ) ``` ```typescript theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const job = await table.refreshColumnAsync("embedding", { where: "created_at > date '2026-01-01'", errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, }); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::{function::FunctionErrorPolicy, table::RefreshColumnOptions}; let _job = table .refresh_column_async_with_options( "embedding", RefreshColumnOptions::default() .where_clause("created_at > date '2026-01-01'") .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) .row_timeout_seconds(30.0), ) .await?; ``` `max_failed_rows`, `init_timeout_seconds`, `num_workers` and `max_executor_processes_per_worker` are accepted the same way; the [SQL refresh options](/enterprise/v1-12-0/sql/dml/refresh-column#options) describe each one. The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a timeout that is not a positive number and a zero worker or process count before sending the request; the server validates everything else. A LanceDB Embedded refresh rejects every option other than `batch_size`, `gpu_class` and `gpu_count`; in particular, it rejects `resource_budget` rather than silently ignoring it. ## When a refresh fails What a failure keeps depends on where the refresh ran. The local, blocking `refresh_column` writes the column in one commit, so a failure leaves the column as it was. A refresh job in LanceDB Enterprise -- always `refresh_column_async` or `REFRESH COLUMN` there, never the blocking form -- commits finished batches as it goes, so some values can remain after a failure. Either way, recover by fixing the cause and refreshing again. The new refresh fills rows that are still empty or whose inputs changed, and normally skips values that were kept. That is not guaranteed: a refresh can recompute values that were already written (for example when the record of the inputs they were computed from was not saved), so do not count on a retry costing only the rows that did not complete. For a column filled by a [function](/enterprise/v1-12-0/management/function), the usual cause is the worker environment rather than the data. See [environment mismatches](/enterprise/v1-12-0/management/function#mismatch-symptoms) for the symptoms, which rarely name their cause. ## Related guides > [card] [Job Framework](/enterprise/v1-12-0/basics/jobs) > > Waiting on, inspecting, and cancelling server-side work. > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > The same idea, for a whole derived table. > [card] [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) > > Refresh on a schedule instead of calling this yourself. # Refresh a materialized view Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/refresh-materialized-view Bring a materialized view up to date after its source data changes. **Applies to:** Embedded ❌, Enterprise ✅ Refresh a [materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) to bring its stored rows up to date after the source table changes. > [!NOTE] > > In SQL this is [`REFRESH MATERIALIZED VIEW`](/enterprise/v1-12-0/sql/dml/refresh-materialized-view). ## Refresh a view ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} view.refresh() ``` In LanceDB Embedded, every refresh rebuilds the view completely from its source query -- there is no incremental refresh there. Calling it again with no source changes still rebuilds and commits a new table version. In LanceDB Enterprise, the server chooses the refresh mode instead; pass `full=True` to force a full rebuild there too. In LanceDB Embedded, the result reports what the refresh did: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = view.refresh() result.rows_written # rows in the rebuilt view result.source_version # the source table version the view now reflects result.version # the view's own new table version ``` LanceDB Enterprise refreshes run through its SQL job adapter, which doesn't expose these metrics: `mode`, `rows_written` and `source_version` are all `None` on an Enterprise result, even though the refresh itself ran. Pass `source_version=N` to refresh against a particular source version instead of the latest. This is a LanceDB Embedded capability only -- LanceDB Enterprise's SQL refresh does not support pinning a source version: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} view.refresh(source_version=12) # LanceDB Embedded only ``` Use `view.table.count_rows()` for the view's row count at any time; on LanceDB Embedded it always matches `rows_written` from the most recent refresh. ## Automatic refresh A materialized view can refresh itself on a schedule instead of waiting for an explicit `refresh()` call. See [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) for enabling it at creation, the SQL and SDK forms for changing the setting afterward, and how it differs from a computed column's per-output granularity. ## When a refresh fails A refresh replaces the view's stored rows in one commit, so a failure leaves the view as it was after its last successful refresh. Fix the cause and refresh again. ## Related guides > [card] [Create a materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) > > Define the query a view stores. > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > The same idea, for a single derived column. > [card] [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh) > > Refresh on a schedule instead of calling this yourself. # Create a view Source: https://docs.lancedb.com/enterprise/v1-12-0/feature-engineering/view Define a derived dataset as a saved query, with no storage or refresh of its own. **Applies to:** Embedded ❌, Enterprise ✅ A view is the lightest way to derive a feature-engineered dataset: it stores a **query**, not rows, so there is nothing to refresh and nothing that can fall out of date. Reach for one before [a computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) or [a materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) when the underlying query is cheap enough to simply re-run on every read. ## Define a view A view over a products table, selecting and deriving a few columns: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE VIEW "discounted_products" AS SELECT id, name, price, price * 0.9 AS sale_price FROM "products" WHERE in_stock = true ``` The statement resolves the view's schema from the query at creation time. Anything the [SQL dialect](/enterprise/v1-12-0/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions -- the same expressiveness as [a computed column's](/enterprise/v1-12-0/feature-engineering/add-computed-column#expressions) SQL expression, just over a whole derived table instead of one column. ## Read it like a table ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM "discounted_products" WHERE sale_price < 20 ``` Every read runs the saved query against current data, so `sale_price` reflects whatever `price` is right now -- there is no staleness window to reason about, unlike a materialized view between refreshes. A predicate applied when reading the view composes with the query inside it, rather than filtering the view's output afterward, so a selective filter does not pay for rows the view would have produced and then discarded. ## When to use a view instead | | View | Computed column / materialized view | | - | - | - | | Stores | the query | derived values | | Freshness | always current | as of the last refresh | | Read cost | the full query, every read | a column or table scan | | Write cost | none | a refresh | Reach for a view when the query is cheap, or when reading a stale value would be wrong for the workload. Reach for a computed column or a materialized view when the query is expensive and the data changes less often than it is read. See [View](/enterprise/v1-12-0/sql/ddl/view#choosing) for the full SQL reference comparison, including the separate privileges each one needs. ## What to read next > [card] [View](/enterprise/v1-12-0/sql/ddl/view) > > CREATE VIEW, DROP VIEW, and listing views alongside tables. > [card] [Create a materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views) > > The stored-rows counterpart, and when a refresh is worth paying for. # Dependency Verification Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/deployment/dependency-verification Diagnose and resolve package version mismatches between local and distributed worker environments. When running Geneva UDFs on distributed workers, your code is serialized locally and executed on remote workers. If the worker environment differs from your local environment, you may encounter subtle and difficult-to-debug errors. ## Example environment mismatch errors | Symptom | Likely Cause | | - | - | | `TypeError: Enum.__new__() missing 1 required positional argument` | `attrs` version mismatch | | `TypeError: Can't instantiate abstract class` | Package structure differences | | `ArrowInvalid: cannot cast` / serialization errors | NumPy 1.x vs 2.x mismatch | | `ModuleNotFoundError` on workers | Package only installed locally | | Model loading failures | PyTorch version mismatch | | Permission denied errors | Missing API keys in envrionment variables | These issues are notoriously difficult to debug because the error messages often don't indicate the root cause. ## The `compare_ray_environments` Tool Geneva provides a diagnostic tool to compare your local environment against Ray workers. If you are encountering a hang or exception you can use the following diagnosis worklflow to resolve the problem. **Step 1** **Run the diagnostic tool** programatically or via the CLI. **Step 2** **Check PACKAGES and ENV VARS output sections for mismatches**. **Step 3** **Identify critical packages**: numpy, torch, pyarrow, attrs, pydantic. **Step 4** **Identify inconsistent environment variables**: `AWS_*`, `GOOGLE_APPLICATION_CREDENTIALS` **Step 5** **Fix with manifest** for quick testing: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest.builder import PipManifestBuilder manifest = PipManifestBuilder.create("fix").pip(["numpy==1.26.4"]).build() ``` **Step 6** **OPTIONAL: Build custom image** for production (if using KubeRay). ### Programmatic Usage ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray.compare_env import compare_ray_environments # Compare and print (requires Geneva context to be initialize via `with db.context(..)`) result = compare_ray_environments() # Compare environments, filtering environment variables with specified prefix result = compare_ray_environments(env_prefix="PY") ``` ### CLI Usage ```bash CLI icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Connect to existing Ray cluster python -m geneva.runners.ray.compare_env # Start new local Ray cluster python -m geneva.runners.ray.compare_env --address local # Filter env vars by prefix python -m geneva.runners.ray.compare_env --env-prefix RAY # Show full JSON snapshots python -m geneva.runners.ray.compare_env --show-all # Skip sys.path comparison python -m geneva.runners.ray.compare_env --no-sys-path ``` ## Understanding the Output The tool outputs several sections to help you identify mismatches. ### PYTHON / PLATFORM Shows Python version and OS information for both environments: ``` === PYTHON / PLATFORM === Local: Python: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0] Impl : CPython Exec : /home/user/.venv/bin/python OS : Linux 5.15.0-generic (x86_64) Remote: Python: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0] Impl : CPython Exec : /home/ray/anaconda3/bin/python OS : Linux 5.4.0-aws (x86_64) ``` > [!WARNING] > > Watch for different Python versions or different OS types (macOS local vs Linux remote). #### Architecture Mismatch (macOS to Linux) If you see different OS types (e.g., `Darwin` locally vs `Linux` remotely), compiled extensions may fail with `ModuleNotFoundError` or segfaults. **Solution**: Run Geneva from the same OS/architecture as your cluster (typically Linux x86_64). Use a Linux VM, container, or remote development environment. ### Environment Variables Environment variables present in only one environment: ``` === ENV VARS: keys only in LOCAL === + CONDA_PREFIX + VIRTUAL_ENV === ENV VARS: keys only in REMOTE === + RAY_ADDRESS + KUBERNETES_SERVICE_HOST ``` > [!WARNING] > > Missing `AWS_*` or `GOOGLE_APPLICATION_CREDENTIALS` can cause storage authentication failures. #### Passing Environment Variables to Workers If critical environment variables are missing on workers, you can pass them via the manifest or cluster configuration. Set the values in the shell before starting the Python program: ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export AWS_ACCESS_KEY_ID="your-access-key-id" export AWS_SECRET_ACCESS_KEY="your-secret-access-key" export MY_API_KEY="your-api-key" ``` **Option 1: Via Manifest** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest.builder import PipManifestBuilder import os manifest = ( PipManifestBuilder.create("my-manifest") .env_vars({ "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"], "AWS_SECRET_ACCESS_KEY": os.environ["AWS_SECRET_ACCESS_KEY"], "MY_API_KEY": os.environ["MY_API_KEY"], }) .build() ) ``` **Option 2: Via Cluster Configuration** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder import os cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": { "env_vars": { "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"], "AWS_SECRET_ACCESS_KEY": os.environ["AWS_SECRET_ACCESS_KEY"], } } }) .build() ) ``` > [!WARNING] > > Avoid hardcoding secrets. Use `os.environ` to pass values from your local environment, or use a secrets manager in production. ### Packages The tool shows version mismatches and packages only present in one environment: ``` === PACKAGES: version mismatches === * numpy: local=1.26.4 remote=2.2.6 * torch: local=2.0.1 remote=2.8.0+cpu * attrs: local=23.2.0 remote=24.2.0 * pyarrow: local=14.0.1 remote=17.0.0 === PACKAGES: only in LOCAL === + my-custom-package + dev-tools === PACKAGES: only in REMOTE === + kuberay-client ``` > [!WARNING] > > Watch for major version differences (NumPy 1.x vs 2.x) and PyTorch version mismatches. #### Common Package Issues | Issue | Symptoms | Fix | | - | - | - | | **NumPy 1.x vs 2.x** | `ArrowInvalid`, `ValueError: cannot convert`, serialization failures | Pin `numpy==1.26.4` | | **PyTorch mismatch** | Model loading failures, CUDA errors, unexpected inference results | Pin to matching `torch` version | | **attrs mismatch** | `TypeError: Enum.__new__() missing 1 required positional argument` | Pin `attrs` to local version | | **Missing package** | `ModuleNotFoundError: No module named 'xyz'` | Add package to manifest | #### Fixing Package Mismatches **Option 1: Manifest pip Dependencies** Specify packages in a Geneva manifest for a quick fix: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.manifest.builder import PipManifestBuilder manifest = ( PipManifestBuilder.create("my-manifest") .pip([ "numpy==1.26.4", "torch==2.0.1", "attrs==23.2.0", ]) .build() ) conn = geneva.connect("s3://my-bucket/my-db") conn.define_manifest("my-manifest", manifest) with conn.context(cluster="my-cluster", manifest="my-manifest"): conn.open_table("my-table").backfill("my-column") ``` *Pros*: Quick, reusable across sessions, stored with your database. *Cons*: Slower startup (downloads packages), may not work for complex dependencies. **Option 2: Custom Ray Worker Image** For KubeRay deployments, build a custom worker image: ```dockerfile Dockerfile icon="docker" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Dockerfile.ray-worker FROM rayproject/ray:2.30.0-py311 # Install exact versions RUN pip install \ numpy==1.26.4 \ torch==2.0.1 \ attrs==23.2.0 \ geneva==0.8.0 # Copy any custom packages COPY ./my_udfs /app/my_udfs ``` Then reference in RayCluster spec: ```yaml Kubernetes icon="kubernetes" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} spec: workerGroupSpecs: - template: spec: containers: - image: your-registry/ray-worker:latest ``` *Pros*: Fastest startup, reproducible. *Cons*: Requires image build/push workflow. **Option 3: Conda Environment** Use a conda environment on workers via the cluster builder: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": {"conda": "environment.yml"} }) .build() ) ``` Or specify conda channels and dependencies inline: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": { "conda": { "channels": ["conda-forge"], "dependencies": [ "python=3.10", "ffmpeg<8", "torchvision=0.22.1", ], }, "config": {"eager_install": True}, } }) .build() ) ``` *Pros*: Best for complex dependencies with native libraries (ffmpeg, CUDA). *Cons*: Slower environment creation, requires conda on workers. ## API Reference For detailed API documentation on the environment comparison functions, see the [Geneva Diagnostics API Reference](https://lancedb.github.io/geneva/api/diagnostics). # Deploy Geneva using Helm Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/deployment/helm Learn how to deploy Geneva on Kubernetes using the Geneva Helm Chart > [!TIP] > > **Feature Engineering is deployed automatically in LanceDB Enterprise** > > In self-managed environments, Geneva can be installed into existing Kubernetes clusters using Helm. Please [contact LanceDB](https://lancedb.com/contact/) for access to the Helm Chart and related resources. ## Pre-requisites * An existing Kubernetes cluster * An existing node pool(s) for Geneva workloads. By default, Geneva uses node selector `{"geneva.lancedb.com/ray-head": "true"}` for Ray head nodes, and `{"geneva.lancedb.com/ray-worker-cpu": "true"}` and `{"geneva.lancedb.com/ray-worker-gpu": "true"}` for Ray CPU worker and Ray GPU worker nodes respectively. This can be overridden in the Geneva client. * Geneva Helm chart. Please [contact LanceDB](https://lancedb.com/contact/) for access to the Helm Chart and related resources. For more information on deploying the required cloud resources, see the [manual deployment instructions](/enterprise/v1-12-0/geneva/deployment/). ## Geneva Helm Chart The Helm chart includes resources required for running [Geneva](https://lancedb.com/docs/geneva/) in Kubernetes. It includes services, service accounts, RBAC roles, etc. that are used by the Geneva client to manage resources. ## Install 1. Authenticate with Kubernetes cluster, i.e. update kubeconfig 2. Configure Helm chart values In values.yaml, configure the service account, node selectors, and cloud resources, if applicable. ``` geneva: # Object storage root URI rootUri: value: "s3://my-data-bucket" serviceAccount: # Service account for Geneva worker pods and services annotations: # Set per-CSP annotations to provide access to CSP resources, i.e. # eks.amazonaws.com/role-arn: arn:aws:iam::0123456789:role/geneva_service_role # iam.gke.io/gcp-service-account: geneva-service-account@my-project.iam.gserviceaccount.com gcp: # GCP service account email for the Geneva client. # It should have access to the GKS cluster and "roles/storage.objectUser" # permissions on the object storage bucket. # e.g., geneva-client-sa@project-id.iam.gserviceaccount.com clientServiceAccount: "" aws: # AWS IAM role ARN to be assumed by the Geneva client. # This role should have an access entry to the cluster with username matching the role ARN. # It should also have r/w access to the object storage bucket. # e.g., arn:aws:iam::123456789012:role/geneva-client-role clientRoleArn: "" azure: # Azure managed identity client ID for the Geneva client. # This identity should have a federated credential for the LanceDB namespace # and Storage Blob Data Contributor role on the storage account. clientPrincipalId: "" ``` 3. Install kuberay operator ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export NAMESPACE=lancedb helm repo add kuberay https://ray-project.github.io/kuberay-helm/ helm repo update helm install kuberay-operator kuberay/kuberay-operator -n $NAMESPACE --create-namespace ``` 4. Install NVIDIA device plugin (if using GPU nodes) For GPU support, the NVIDIA device plugin must be installed in your EKS cluster: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v0.17.0/deployments/static/nvidia-device-plugin.yml > nvidia-device-plugin.yml kubectl apply -f nvidia-device-plugin.yml ``` 5. Install Geneva Helm chart ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} helm install geneva ./geneva -n $NAMESPACE --create-namespace ``` ## Default cluster and manifest In LanceDB Enterprise, backfill and refresh jobs run on a **default cluster** (the compute pool jobs run on) and a **default manifest** (the Python dependency environment — image and packages). Configuring these in the LanceDB Enterprise chart lets jobs run out of the box without per-job configuration. They are set under `geneva.defaults` in the chart's `values.yaml`: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} geneva: defaults: cluster: cluster_type: external_ray name: deployment-default ray_address: "ray://raycluster-kuberay-head-svc.lancedb.svc.cluster.local:10001" manifest: name: deployment-default pip: [geneva, pyarrow, lancedb, pylance] head_image: rayproject/ray:2.54.0-py312 worker_image: rayproject/ray:2.54.0-py312 skip_site_packages: true ``` If no default is configured, jobs must specify a manifest explicitly. Individual transforms can override the default manifest by pinning one with `@udf` / `@chunker` / `@udtf` (see [Advanced Job Configuration](/enterprise/v1-12-0/geneva/jobs/advanced-job-configuration)); to override the cluster at runtime, use an [Advanced Execution Context](/enterprise/v1-12-0/geneva/jobs/contexts). ## Providing a Ray cluster The LanceDB Helm chart can be configured to deploy a static KubeRay cluster, provision KubeRay clusters on demand per job, or use an existing Ray cluster. ### Use default LanceDB Enterprise Ray cluster (default) By default, LanceDB Enterprise will use a shared, statically provisioned Ray cluster for job execution. This can be enabled in the Helm chart by setting the following values. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raycluster: enabled: true global: rayclusterUri: "ray://raycluster-kuberay-head-svc.lancedb.svc.cluster.local:10001" ``` Configuration for the Ray cluster can be specified by modifying raycluster.yaml Helm values. ### Provision KubeRay clusters on demand Set `global.rayclusterUri` to an empty value to provision ephemeral KubeRay clusters on-demand for each execution job. The default KubeRay cluster configuration is specified in `geneva.defaults.cluster`, i.e. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} geneva: defaults: cluster: cluster_type: kuberay name: deployment-default kuberay: namespace: lancedb config_method: IN_CLUSTER head_group: service_account: geneva-service-account num_cpus: 2 memory: 8Gi image: rayproject/ray:2.54.0-py312 worker_groups: - name: cpu service_account: geneva-service-account num_cpus: 4 memory: 8Gi replicas: 2 min_replicas: 0 max_replicas: 4 idle_timeout_seconds: 60 node_selector: geneva.lancedb.com/ray-worker-cpu: "true" image: rayproject/ray:2.54.0-py312 ``` ### Use an external Ray cluster Self-managed enterprise customers can bring an existing Ray cluster to run Geneva jobs. Simply set the rayclusterUri property in the Helm chart to a Ray address that can be accessed from the LanceDB Enterprise deployment. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} global: rayclusterUri: "ray://my-ray-cluster.my-ns.svc.cluster.local:10001" ``` # Manual Deployment on Kubernetes Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/deployment/index Learn how to deploy Geneva on Kubernetes using KubeRay for distributed feature engineering workflows on GKE and EKS. > [!TIP] > > **Feature Engineering is deployed automatically in LanceDB Enterprise** > > For manual installation in self-managed environments, follow the instructions below. Feature Engineering can be deployed as part of LanceDB Enterprise in managed or self-managed environments. First class support is provided for Azure, AWS, and GCP, including deployment automation via Terraform and Helm. ## Prerequisites * Kubernetes cluster with KubeRay 1.1+ operator installed * Ray 2.43+ See below for manual installation instructions for: * Amazon Web Services (AWS) Elastic Kubernetes Service (EKS) * Google Cloud Platform (GCP) Google Kubernetes Engine (GKE) ## Basic Kubernetes Setup > [!TIP] > > Kubernetes resources can be deployed automatically via [Helm](/enterprise/v1-12-0/geneva/deployment/helm/) or manually > via the instructions below. In the following sections we'll use these variables: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name ``` ### Kubernetes Service Account (KSA) Inside your Kubernetes cluster, you need a Kubernetes service account which provides the credentials your k8s pods (Ray) run with. Here's how to create your KSA. #### Create a Kubernetes Service Account (KSA) ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl create namespace $NAMESPACE # skip if it already exists kubectl create serviceaccount $KSA_NAME \ --namespace $NAMESPACE ``` You can verify using: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl get serviceaccounts -n $NAMESPACE $KSA_NAME ``` The Kubernetes service account (KSA) needs RBAC permissions inside the k8s cluster to provision Ray clusters via CRDs. #### Create a k8s Role Create a k8s role that can access the Ray CRD operations. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl apply -f - <<EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: ${KSA_NAME}-role rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch"] - apiGroups: ["ray.io"] resources: ["rayclusters"] verbs: ["get", "patch", "delete"] EOF ``` #### Bind the ClusterRole to Your KSA ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl apply -f - <<EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: ${KSA_NAME}-binding subjects: - kind: ServiceAccount name: ${KSA_NAME} namespace: ${NAMESPACE} roleRef: kind: ClusterRole name: ${KSA_NAME}-role apiGroup: rbac.authorization.k8s.io EOF ``` Now confirm your permissions: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl auth can-i get pods --as=system:serviceaccount:${NAMESPACE}:${KSA_NAME} ``` ## Geneva on GKE Google Kubernetes Engine (GKE) is a GCP service that deploys Kubernetes and can manage on-demand provisioning of cluster nodes. Ray can be deployed on GKE clusters using the KubeRay k8s operator. GKE provides the option for an out-of-the-box KubeRay operator deployment. The version of KubeRay is tied to the version of GKE you have deployed. Currently these versions are supported: * GKE 1.30 / KubeRay 1.1 * GKE 1.31 / KubeRay 1.2 Alternatively, you can also deploy your own KubeRay operator to get the latest KubeRay 1.3 version. The following sections describe in more details other required configuration settings required for Geneva to perform distributed execution. ### GKE Node Pools GKE allows you to specify templates for virtual machines in "node pools". These allow you to manage and configure resources such as the number of CPUs, number of GPUs, amount of memory, and if instances are spot or regular virtual machines. You can define your node pools however you want but Geneva uses three specific Kubernetes labels when deploying Ray pods on GKE: `ray-head`, `ray-worker-cpu`, `ray-worker-gpu` * **Head nodes** are where the Ray dashboard and scheduler run. They should be non-spot instances and should not have processing workloads scheduled on them. Geneva looks for nodes with the `geneva.lancedb.com/ray-head` k8s label for this role. * **CPU Worker nodes** are where distributed processing that does not require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-cpu` k8s label when these nodes are requested. * **GPU Worker nodes** are where distributed processing that require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-gpu` k8s label when these nodes are requested. ### GKE + k8s Permissions Geneva needs the ability to deploy a KubeRay cluster and submit jobs to Ray. The workers in the Ray cluster need the ability to read and write to the Google Cloud Storage (GCS) buckets. This requires setting up the proper k8s permissions and GCP IAM grants. There are three main areas to setup and verify: * Kubernetes Service Account (KSA) * Google Service Account (GSA) * GKE settings (GKE workload identity) ![geneva-security-reqs](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/geneva/geneva-security-reqs.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=eb13ca8f374392867dd18ab25e4830a4) #### Geneva Security Requirements In the following sections we'll use these variables. `STORAGE_URI` is the underlying `gs://` storage path used for bucket permissions and storage access; it is separate from `LANCEDB_URI`, the database's `db://` URI used to connect. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name PROJECT_ID=... # replace with your google cloud project name GSA_EMAIL=${KSA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com STORAGE_URI=gs://bucket/db # the bucket path your database is stored under ``` #### Google Service Account (GSA) To give your k8s workers the ability to read and write from your LanceDB buckets, your KSA needs to be bound to a Google Cloud service account (GSA) with those grants. With this setup, any pod using the KSA will automatically get a token that lets it impersonate the GSA. Let's set this up: **Create a Google Cloud Service Account** ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts create ${KSA_NAME} \ --project=${PROJECT_ID} \ --description="Service account for ray workloads in GKE" \ --display-name="Ray Runner GSA" ``` You can verify this using: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts list --filter="displayName:Ray Runner GSA" ``` > **Warning**: You need `roles/iam.serviceAccountAdmin` or minimally `roles/iam.serviceAccountTokenCreator` rights to run these commands. Next, you'll need to verify that your KSA is bound to your GSA and has `roles/iam.workloadIdentityUser`: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts get-iam-policy $GSA_EMAIL \ --project=$PROJECT_ID \ --format="json" | jq '.bindings[] | select(.role=="roles/iam.workloadIdentityUser")' ``` Give your GSA rights to access the LanceDB bucket: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud storage buckets add-iam-policy-binding ${STORAGE_URI} \ --member="serviceAccount:${KSA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/storage.objectAdmin" ``` #### GKE Workload Identity A GKE workload identity is required to enable k8s workloads access Google Cloud services securely and without needing to manually manage service account keys. The workload identity is attached to Google Cloud service accounts (GSA) and mapped to a Kubernetes service account (KSA). This feature needs to be enabled on the GKE cluster. You can confirm that your workers have abilities to read/write to the LanceDB bucket: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl run gcs-test --rm -it --image=google/cloud-sdk:slim \ --serviceaccount=${KSA_NAME} \ -n ${NAMESPACE} \ -- bash echo "hello" > test.txt gsutil cp test.txt ${STORAGE_URI}/demo-check/test-write.txt ``` Confirm the identity inside the pod: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -H "Metadata-Flavor: Google" \ http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email ``` ## Geneva on AWS EKS Geneva can be used to provision Ray clusters running in Amazon Web Services (AWS) Elastic Kubernetes Service (EKS). In the following sections we'll use these variables: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different CLUSTER=geneva # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name ``` ### EKS Node Groups EKS allows you to specify templates for virtual machines in "node groups". These allow you to manage and configure resources such as the number of CPUs, number of GPUs, amount of memory, and if instances are spot or regular virtual machines. You can define your node groups however you want but Geneva uses three specific Kubernetes labels when deploying Ray pods on EKS: `ray-head`, `ray-worker-cpu`, `ray-worker-gpu` * **Head nodes** are where the Ray dashboard and scheduler run. They should be non-spot instances and should not have processing workloads scheduled on them. Geneva looks for nodes with the `geneva.lancedb.com/ray-head: true` k8s label for this role. * **CPU Worker nodes** are where distributed processing that does not require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-cpu: true` k8s label when these nodes are requested. * **GPU Worker nodes** are where distributed processing that require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-gpu: true` k8s label when these nodes are requested. ### Install KubeRay Operator Using Helm Geneva requires the KubeRay operator to be installed in your EKS cluster. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} helm repo add kuberay https://ray-project.github.io/kuberay-helm/ helm repo update helm install kuberay-operator kuberay/kuberay-operator -n $NAMESPACE ``` ### Install NVIDIA Device Plugin For GPU support, the NVIDIA device plugin must be installed in your EKS cluster: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v0.17.0/deployments/static/nvidia-device-plugin.yml > nvidia-device-plugin.yml kubectl apply -f nvidia-device-plugin.yml ``` ### Configure Access Control ![eks-auth](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/geneva/eks-auth.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=1c38c1300aafb59c3ee85a5971fe013a) #### Environment IAM Principal Geneva must be run in an environment with access to [AWS credentials](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) with permissions to `sts:AssumeRole` on the Geneva Client IAM Role. For example, this could be a laptop with credentials provided by environment variables, or an EC2 instance with credentials provided via Instance Profile. #### Create IAM Role for Geneva Client The Geneva Client IAM Role is assumed by the Geneva client to provision the Kuberay cluster and run remote jobs. This role requires IAM permissions to access the storage bucket and Kubernetes API. Create an IAM role with the following policy: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Sid": "ClusterAccess", "Action": [ "eks:DescribeCluster", "eks:AccessKubernetesApi" ], "Effect": "Allow", "Resource": "<your eks cluster arn>" }, { "Sid": "AllowListBucket", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::<your storage bucket>" }, { "Sid": "AllowAllS3ObjectActions", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:HeadObject" ], "Resource": "arn:aws:s3:::<your storage bucket>/*" } ] } ``` This role should also have a trust policy with `sts:AssumeRole` permissions for any principal initiating the Geneva client. When using Geneva, this role can be specified with the `role_name` RayCluster parameter. #### Create EKS Access Entry Create an [EKS access entry](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html) to allow the Geneva Client Role to access the Kubernetes API for the EKS Cluster. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws eks create-access-entry --cluster-name $CLUSTER --principal-arn <your geneva client role ARN> --type STANDARD aws eks associate-access-policy --cluster-name $CLUSTER --principal-arn <your geneva client role ARN> --access-scope type=cluster --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy ``` #### Create EKS OIDC Provider Create an OIDC provider for your EKS cluster. This is required to allow Kubernetes Service Accounts (KSA) to assume IAM roles. See [AWS documentation](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html#_create_oidc_provider_console). #### Create IAM Role for Service Account An IAM role is required for the Kubernetes Service Account (KSA) that will be used by the Ray head and worker pods. This role must have permissions to access the storage bucket and to describe the EKS cluster: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Sid": "ClusterAccess", "Action": [ "eks:DescribeCluster" ], "Effect": "Allow", "Resource": "<your eks cluster arn>" }, { "Sid": "AllowListBucket", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::<your storage bucket>" }, { "Sid": "AllowAllS3ObjectActions", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:HeadObject" ], "Resource": "arn:aws:s3:::<your storage bucket>/*" } ] } ``` In addition, it must have a trust policy allowing the EKS OIDC provider to assume the role from the Kubernetes Service Account: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "<OIDC Provider ARN>" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "<OIDC Provider>:aud": "sts.amazonaws.com", "<OIDC Provider>:sub": "system:serviceaccount:$NAMESPACE:$KSA_NAME" } } } ] } ``` #### Associate the IAM Role with the Kubernetes Service Account Modify the Kubernetes Service Account created in "Basic Kubernetes setup" to associate it with the IAM role created above. The role ARN is specified using `eks.amazonaws.com/role-arn` annotation: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl annotate serviceaccount "$KSA_NAME" \ -n "$NAMESPACE" \ "eks.amazonaws.com/role-arn=$ROLE_ARN" \ --overwrite ``` ### Initialize the Ray Cluster Initialize the Ray cluster using the node selectors and metadata from above: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray._mgr import ray_cluster from geneva.runners.ray.raycluster import (K8sConfigMethod, _HeadGroupSpec, _WorkerGroupSpec) head_spec = _HeadGroupSpec( service_account="geneva-ray-runner", num_cpus=1, memory=2048, node_selector={"geneva.lancedb.com/ray-head": "true"}, ) worker_spec = _WorkerGroupSpec( name="worker", min_replicas=1, service_account="geneva-ray-runner", num_cpus=2, memory=4096, node_selector={"geneva.lancedb.com/ray-worker-cpu": "true"}, ) with ray_cluster( name="my-ray-cluster", namespace="lancedb", cluster_name="geneva", config_method=K8sConfigMethod.EKS_AUTH, region="us-east-1", use_portforwarding=True, head_group=head_spec, worker_groups=[worker_spec], role_name="geneva-client-role", ) as cluster: table.backfill("embedding") ``` # Troubleshooting Geneva Deployments Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/deployment/troubleshooting Learn how to diagnose and resolve common issues with Geneva deployments, including version compatibility, permissions, and serialization errors. We'll cover common problems you may encounter when using Geneva and troubleshooting tips to solve them. ## Common Issues to Verify Here are some areas to verify to identify the source of problems with your Geneva deployment: * **Versions compatibility** (Ray, Python, Lance) * **Remote Ray execution** and hardware resource availability * **Sufficient permissions** to access data * **Worker code** only returns serializable values (no open files, no GPU resident buffers) ## Confirming Dependency Versions Geneva uses Ray for distributed execution. Ray requires the version deployed cluster services and clients to be exactly the same. Minor versions of Python must match both on client and cluster services (e.g. 3.10.3 and 3.10.5 are ok, but 3.10.3 and 3.12.1 are not.) Geneva has been tested with Ray 2.44+ and Python 3.10.x and 3.12.x. You can run this code in your notebook to verify your environment matches your expectations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} !python --version !pip show lancedb # need 0.22.0b0+ !echo $VIRTUAL_ENV ``` ## Confirming Remote Ray Execution Geneva allows you to specify the resources of your worker nodes. You can verify that your cluster has the resources (e.g. GPUs) available for your jobs and that remote execution is working properly. You can get some basic information about resources available to your Ray: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(ray.available_resources()) ``` You can verify basic remote execution via Ray: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @ray.remote def check_remote(): return "Hello from a worker" print(ray.get(check_remote.remote())) ``` You can also verify that versions of specific libraries are present in the execution environment: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # does ray have cuda? @ray.remote def check_pyarrow(): import pyarrow return pyarrow.__version__ print(ray.get(check_pyarrow.remote())) ``` > **Note**: You should execute Geneva code from a machine or VM that has the same architecture and OS type as the nodes in your cluster. This will allow for shared libraries to be shipped. For example, if you use a Mac to host a Jupyter notebook, Geneva will push Mac libraries to your Linux cluster and likely result in module not found errors due to OS/architecture differences. For GPU-dependent UDFs and jobs, you can verify that GPU worker nodes have the CUDA library: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # does ray have cuda? @ray.remote(num_gpus=1) def check_cuda(): import torch return torch.version.cuda, torch.cuda.is_available() print(ray.get(check_cuda.remote())) ``` ## Confirming Sufficient Permissions While your notebook or working environment may have credentials to read and write to particular buckets, your jobs need sufficient rights to read and write to them as well. Adding `import geneva` to any remote function can help verify that your workers have sufficient grants. Here we add `import geneva` to help trigger potential permissions problems: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @ray.remote(num_gpus=1) def check_cuda(): import geneva # this is currently required before other imports import torch return torch.version.cuda, torch.cuda.is_available() print(ray.get(check_cuda.remote())) ``` ### GCE Permissions Errors in Job Logs If you are using Geneva managed Ray deployed on GKE, the errors may look like this: ``` PermissionError: [Errno 13] google::cloud::Status(PERMISSION_DENIED: Permanent error, with a last message of Caller does not have storage.objects.get access to the Google Cloud Storage object. Permission 'storage.objects.get' denied on resource (or it may not exist). error_info={reason=forbidden, domain=global, metadata={gcloud-cpp.retry.function=GetObjectMetadata, gcloud-cpp.retry.reason=permanent-error, gcloud-cpp.retry.original-message=Caller does not have storage.objects.get access to the Google Cloud Storage object. Permission 'storage.objects.get' denied on resource (or it may not exist)., http_status_code=403}}). Detail: [errno 13] Permission denied ``` This indicates that your workers and/or head node are not being run with the correct service account or with an account that has sufficient access. Please double check the service account's accesses and make sure to add your service account that has access to the buckets as a parameter to your Head and Worker specs. See `service_account="geneva-integ-test"` below: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raycluster = ray_cluster( name= k8s_name, namespace=k8s_namespace, use_portforwarding=True, head_group=_HeadGroupSpec( num_cpus=8, service_account="geneva-integ-test" ), worker_groups=[ _WorkerGroupSpec( name="cpu", num_cpus=60, memory="120G", service_account="geneva-integ-test", ), _WorkerGroupSpec( name="gpu", num_cpus=8, memory="32G", num_gpus=1, service_account="geneva-integ-test", ), ], ) ``` ## Serialization Errors Serialization is a critical subsystem of Geneva. In order to store UDFs and perform distributed execution, both code and data must be serializable. Errors in this area can be subtle and difficult to find. There are a few basic rules: 1. **Python objects** passed to distributed processes or written to LanceDB must be able to be pickled or unpickled using the Python pickle or cloudpickle library. 2. **Python code** used for distributed execution, including UDFs used to calculate values written to columns must be able to be pickled or unpickled using the Python pickle or cloudpickle library. 3. **Python code or objects** need to have the same encoding and representation on the client-side and the server-side. Below is a list of error categories and examples and how to fix them. ### Serialization Library Mismatches Any Python code and objects must be able to be serialized by the client and deserialized on the server side, and vice versa. This includes objects that are generated on the fly such as those using the `attrs` library. The distributed processing engine Geneva uses, Ray, also depends on the `attrs` library. Different versions may create different object signatures that are not compatible when shipped from client-side to server-side and vice versa. This means you'll need to have compatible versions of this library on both sides. Here's an example error message. It is subtle and does not directly point to the `attrs` library: ``` ... File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/common.py", line 414, in _prepare_client_task self._ensure_ref() File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/common.py", line 384, in _ensure_ref self._ref = ray.worker._put_pickled( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/worker.py", line 509, in _put_pickled raise cloudpickle.loads(resp.error) TypeError: Enum.__new__() missing 1 required positional argument: 'value' ``` This was solved by updating the `attrs` module on the client side to use the same version found on the server side. ### Objects with Unserializable Elements Python objects may have internal references to unpickleable objects such as open file handles or open network clients with machine specific state. There are two strategies here: 1. **Remove the reference** to unpickleable objects. 2. **Keep objects with unserializable state** only on the client or only on the server. This could be moving clients into the UDF function, or converting objects into serializable versions before transmitting them. For example, creating clients or opening files must be inside the UDF. You may see pickling-related errors like this: ``` ... raise PicklingError( _pickle.PicklingError: Pickling client objects is explicitly not supported. Clients have non-trivial state that is local and unpickleable. ``` Geneva pulls in your UDFs so they can be sent to remote worker nodes. For the method to be sent, the data must be "pickleable". **So instead of this:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from google.cloud import storage storage_client = storage.Client() # this has unpickleable state bucket = storage_client.bucket(BUCKET_NAME) # this has a reference to storage_client ... @udf def udf_function(video_path: str) -> bytes: # The closure captures bucket and its unpickleable client. return bucket.blob(video_path).download_as_bytes() ``` **Do this:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from google.cloud import storage # ... @udf def udf_function(video_path: str) -> bytes: storage_client = storage.Client() bucket = storage_client.bucket(BUCKET_NAME) # Keep the client inside the worker; return only the downloaded bytes. return bucket.blob(video_path).download_as_bytes() ``` ### Disconnect or Serialization Errors with GPU Dependent UDFs When using GPU code, the typical process loads some values and tensors from CPU memory to GPU memory. Even after moving data (`data.cpu().tolist()`), there may be references to GPU memory. While this is not a problem with local execution, when doing a distributed job it may cause problems because the GPU references are not serializable and not needed. You must take steps to eliminate references to structures in GPU memory since they cannot be serialized and sent between workers. This can be achieved by explicitly disconnecting references to the GPU memory (`data.cpu().detach().tolist()`) to get only-CPU resident fully serializable objects. Here are some typical error messages: ``` Exception in thread Thread-27 (_proxy): Traceback (most recent call last): File "/home/jon/.pyenv/versions/3.10.16/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 772, in run_closure _threading_Thread_run(self) File "/home/jon/.pyenv/versions/3.10.16/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/jon/proj/geneva-deepseek-vl2/src/geneva/runners/ray/_portforward.py", line 172, in _proxy {s1: s2, s2: s1}[s].sendall(data) BrokenPipeError: [Errno 32] Broken pipe Log channel is reconnecting. Logs produced while the connection was down can be found on the head node of the cluster in `ray_client_server_[port].out` 2025-04-11 02:25:21 INFO Starting proxy from pod to client 2025-04-11 02:25:21 INFO Proxy started 2025-04-11 02:25:21 INFO Proxying between <kubernetes.stream.ws_client.PortForward._Port._Socket object at 0x70b2bf9033a0> and <socket.socket fd=230, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 59979), raddr=('127.0.0.1', 32956)> 2025-04-11 02:25:21 INFO Waiting for client connection 2025-04-11 02:25:21,828 ERROR dataclient.py:330 -- Unrecoverable error in data channel. --------------------------------------------------------------------------- ... File ~/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py:1006, in _end_unary_response_blocking(state, call, with_call, deadline) 1004 return state.response 1005 else: -> 1006 raise _InactiveRpcError(state) _InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.NOT_FOUND details = "Failed to serialize response!" debug_error_string = "UNKNOWN:Error received from peer {created_time:"2025-04-11T02:25:22.209209484+00:00", grpc_status:5, grpc_message:"Failed to serialize response!"}" > Unexpected exception: Traceback (most recent call last): File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/ray/util/client/logsclient.py", line 67, in _log_main for record in log_stream: File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py", line 543, in __next__ return self._next() File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py", line 969, in _next raise self grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.NOT_FOUND details = "Logstream proxy failed to connect. Channel for client bd854100340640fb8b5770d2bf173197 not found." debug_error_string = "UNKNOWN:Error received from peer {grpc_message:"Logstream proxy failed to connect. Channel for client bd854100340640fb8b5770d2bf173197 not found.", grpc_status:5, created_time:"2025-04-11T02:25:32.223710374+00:00"}" > ``` # End-to-End Example Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/end-to-end A complete Geneva example on LanceDB Enterprise — create a table, backfill computed columns, and build a materialized view with embeddings. This example walks through a complete Geneva workflow on LanceDB Enterprise: creating a raw table, adding computed columns with a distributed backfill, and materializing a view with embeddings for downstream search. The dataset is a product catalog with titles and descriptions. We'll compute a `word_count` feature column, then create a materialized view that adds text embeddings. ## 0. What you need to run this All you need is an existing **LanceDB Enterprise deployment**. Distributed job execution, clusters, and dependency manifests are managed for you — there is no Kubernetes or cluster setup in this example. Get the database URI, HTTPS endpoint and API key from your LanceDB Enterprise administrator, then replace the placeholders in the example. In application code, load credentials from environment variables or a secrets manager. ## 1. Connect and create a table ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import geneva # Connect to LanceDB Enterprise db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) # Create a raw product table schema = pa.schema([ pa.field("product_id", pa.int64()), pa.field("title", pa.string()), pa.field("description", pa.string()), pa.field("category", pa.string()), pa.field("price", pa.float64()), ]) data = pa.table({ "product_id": [1, 2, 3, 4, 5], "title": ["Chainmail Coif", "Jousting Lance Grip Tape", "Dragon-Repellent Spray", "Sword Squeegee", "Visor Windshield Wipers"], "description": [ "Premium riveted chainmail head covering. Breathable enough for dragon fire, probably.", "Non-slip grip tape for jousting lances. 3000 PSI tensile strength. Void where tilting is prohibited.", "All-natural herbal spray. Dragons hate it. Effectiveness not guaranteed against actual dragons.", "Ergonomic squeegee fits all standard broadswords. Removes blood, mud, and existential dread.", "Hand-cranked windshield wipers for full-face visors. Never ride blind into battle again.", ], "category": ["armor", "tournament", "defense", "maintenance", "armor"], "price": [129.99, 45.00, 59.99, 34.99, 24.99], }) try: db.drop_table("products_raw") except Exception: pass table = db.create_table("products_raw", data=data, schema=schema) ``` ## 2. Define UDFs ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def word_count(description: str) -> int: """Count words in the description.""" return len(description.split()) @udf(data_type=pa.string()) def price_tier(price: float) -> str: """Bucket price into tiers.""" if price < 30: return "budget" elif price < 75: return "mid-range" else: return "premium" ``` ## 3. Register columns and run a backfill Register the UDFs as virtual columns and trigger a backfill. The job runs on your deployment's default distributed execution environment — no cluster or context to configure. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add computed columns table.add_columns({ "word_count": word_count, "price_tier": price_tier, }) # Run the backfills table.backfill("word_count") table.backfill("price_tier") ``` ## 4. Create a materialized view with embeddings The embedding model needs extra Python dependencies (`sentence-transformers`, `torch`). Rather than configuring a deployment-wide environment, we bundle those dependencies **with the UDF** using `@udf(manifest=...)`. The manifest is snapshotted onto the view, so refreshes use it automatically. The materialized view selects a subset of columns from the source table — here we drop `price` and `price_tier`, keeping only what's needed for search — plus a derived `embedding` column. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.manifest import GenevaManifest # Bundle the embedding model's dependencies and attach them to the UDF embed_manifest = ( GenevaManifest.create_pip("embedding-deps") .pip(["sentence-transformers==3.3.1", "torch==2.5.1"]) .build() ) @udf(data_type=pa.list_(pa.float32(), 384), manifest=embed_manifest) class EmbedDescription: def __init__(self): self.model = None def __call__(self, description: str) -> list[float]: if self.model is None: from sentence_transformers import SentenceTransformer self.model = SentenceTransformer("BAAI/bge-small-en-v1.5") return self.model.encode(description, normalize_embeddings=True).tolist() # Build a query that selects search columns plus the derived embedding query = table.search(None).select({ "product_id": "product_id", "title": "title", "description": "description", "category": "category", "word_count": "word_count", "embedding": EmbedDescription(), }) # Create the materialized view and populate it — the embedding UDF runs on refresh db.create_materialized_view("products_enriched", query) enriched = db.open_table("products_enriched") enriched.refresh() ``` ## 5. Query the enriched table ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} enriched = db.open_table("products_enriched") # Vector search results = ( enriched.search([0.1] * 384, vector_column_name="embedding") .limit(3) .to_arrow() ) # Filtered search — armor category only armor_results = ( enriched.search([0.1] * 384, vector_column_name="embedding") .where("category = 'armor'") .limit(3) .to_arrow() ) ``` ## 6. Incremental refresh As new products are added to the source table, backfill the new rows and refresh the view to compute embeddings for them — only the new rows are processed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Append new products new_data = pa.table({ "product_id": [6, 7], "title": ["Moat Floaties", "Knight-Night Sleep Mask"], "description": [ "Inflatable arm floaties in battleship grey. Because even knights can't always swim in full plate.", "Padded silk sleep mask embroidered with your coat of arms. Blocks out 100% of torchlight.", ], "category": ["defense", "armor"], "price": [29.99, 19.99], }) table.add(new_data) # Only null/new values are computed table.backfill("word_count") table.backfill("price_tier") # Incrementally materialize the new rows (including their embeddings) into the view enriched.refresh() ``` > [!TIP] > > To keep source columns in sync automatically, mark their UDFs with `@udf(auto_backfill=True)`. See > [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling/). # Getting Started Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/getting-started Connect to LanceDB Enterprise, define a UDF, and run a distributed backfill — from a notebook or a script. Connect to your LanceDB Enterprise deployment, define a UDF, and run a distributed backfill — all from a notebook or a script. No cluster setup required. ## Installation Geneva is published on [PyPI](https://pypi.org/project/geneva/). Install the latest stable release with [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`. Newer pre-release builds with the latest features are also available on LanceDB's Fury indexes — see [Pre-release builds](#pre-release-builds) below. ### Prerequisites * Python 3.10+ * [uv](https://docs.astral.sh/uv/) (recommended) or `pip` ### Install the latest stable release ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --upgrade geneva ``` ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --upgrade geneva ``` ### Verify ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -c "import geneva; print(geneva.__version__)" ``` ### Pre-release builds To pick up the newest features ahead of a stable release, install a pre-release from LanceDB's Fury indexes. Geneva and its dependencies are published across two indexes: | Package | Index | | - | - | | `geneva`, `lancedb` | `https://pypi.fury.io/lancedb/` | | `pylance` | `https://pypi.fury.io/lance-format/` | ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --pre --upgrade \ --extra-index-url https://pypi.fury.io/lancedb/ \ --extra-index-url https://pypi.fury.io/lance-format \ --index-strategy unsafe-best-match \ geneva ``` ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --pre --upgrade \ --extra-index-url https://pypi.fury.io/lancedb/ \ --extra-index-url https://pypi.fury.io/lance-format \ geneva ``` > [!NOTE] > > The `--index-strategy unsafe-best-match` flag is required with `uv`. By default, `uv` only > considers package versions from the first index that lists a given package (PyPI). Since > `geneva` and `pylance` also appear on PyPI, this flag tells `uv` to pick the best match across > all indexes. ## Quickstart Get the database URI, HTTPS endpoint and API key from your LanceDB Enterprise administrator, then replace the placeholders in the example. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva import pyarrow as pa # Connect to LanceDB Enterprise db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) tbl = db.open_table("my_table") # Define a User Defined Function (UDF) that counts the words in the text column @geneva.udf(data_type=pa.int32()) def word_count(text: str) -> int: return len(text.split()) # Register the UDF as a new virtual column tbl.add_columns({"word_count": word_count}) # Backfill the new column using distributed execution with incremental checkpointing tbl.backfill("word_count") ``` ## Auto-backfill With `auto_backfill=True`, LanceDB Enterprise recomputes the column for you whenever the data or the UDF version changes — no explicit `backfill()` call needed (see [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling/)). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Change the column to use a new UDF version with auto-backfill enabled @geneva.udf(data_type=pa.int32(), auto_backfill=True) def word_count(text: str) -> int: return len(text.split()) tbl.alter_columns({"path": "word_count", "udf": word_count}) # Add new rows. word_count is computed automatically in the background. tbl.add([{"text": "hello world"}]) ``` ## Materialized views and chunkers A [materialized view](/enterprise/v1-12-0/geneva/jobs/materialized-views/) applies UDFs over a query and refreshes incrementally. A [chunker](/enterprise/v1-12-0/geneva/udfs/scalar-udtfs) view expands each source row into many rows (1:N) — useful for splitting documents, videos, or images. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Materialized view: a query with UDF-computed columns, refreshed incrementally query = tbl.search(None).select({"text": "text", "word_count": word_count}) view = db.create_materialized_view("my_view", query) view.refresh() # Chunker view: 1:N row expansion — split each row's text into one row per word from typing import Iterator, NamedTuple class Chunk(NamedTuple): chunk_index: int chunk_text: str @geneva.chunker def split_text(text: str) -> Iterator[Chunk]: for i, word in enumerate(text.split()): yield Chunk(chunk_index=i, chunk_text=word) chunks = db.create_udtf_view( "my_chunks", source=tbl.search(None).select(["text"]), udtf=split_text, ) chunks.refresh() ``` ## Connecting to object storage or a local filesystem Geneva can also run directly against cloud object storage or a local path. In this mode, jobs run on a [distributed execution context](/enterprise/v1-12-0/geneva/jobs/contexts) you provide. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Cloud object storage (S3, GCS, Azure, or any S3-compatible object store) db = geneva.connect("s3://my-bucket/my-database") # Local filesystem db = geneva.connect("/path/to/my-database") ``` # Multimodal Feature Engineering with Geneva Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/index Learn how to do multimodal feature engineering in LanceDB Enterprise to transform raw data into meaningful features for AI models. Enterprise-only When working with multimodal data at scale, [LanceDB Enterprise](/enterprise/v1-12-0/enterprise) makes it easy to define, extract, and transform raw data into useful information and features for your AI applications. LanceDB Enterprise's *Multimodal Feature Engineering* package is designed to improve the productivity of AI engineers operating at immense scale. With an API designed to leverage LanceDB's optimized data storage and retrieval, it streamlines prototyping extraction and transformation tasks, performing experiments, exploring your data, scaling up execution, and moving to production. LanceDB Multimodal Feature Engineering enables researchers to seamlessly transition from experiments in local notebooks to fully-managed distributed job execution on datasets with billions of rows. > [card] > > The `geneva` Python package is currently only available as part of > [LanceDB Enterprise](/enterprise/v1-12-0/enterprise). Please [contact us](https://www.lancedb.com/contact) if you're interested > in scaling up your feature engineering workloads for your AI and multimodal use cases. Feature engineering itself is not Enterprise-only: LanceDB Embedded has [computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) and [materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views), which need no extra package. See [Feature engineering](/enterprise/v1-12-0/feature-engineering) to choose between them and Geneva. The `geneva` package uses Python [User Defined Functions (UDFs)](/enterprise/v1-12-0/geneva/udfs/udfs) to define features as columns in a Lance dataset. Adding a feature is straightforward: **Step 1** Prototype your Python function in your favorite environment. **Step 2** Wrap the function with a small UDF decorator (see [UDFs](/enterprise/v1-12-0/geneva/udfs/udfs)). **Step 3** Register the UDF as a virtual column using `Table.add_columns()`. **Step 4** (Optional, advanced) Override where the job runs — see [Advanced Execution Contexts](/enterprise/v1-12-0/geneva/jobs/contexts). On LanceDB Enterprise, distributed job execution is fully managed, so most users can skip this step. **Step 5** Trigger a `backfill` operation (see [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling/)). > [!TIP] > > You can build your Python feature generator function in an IDE or a notebook using your project's Python versions and dependencies. `geneva` will automate much of the dependency and version management needed to move from prototype to scale and production. Ready to write your first feature? Head to [Getting Started](/enterprise/v1-12-0/geneva/getting-started). ## Continue learning Visit the following pages to learn more about featuring engineering in LanceDB Enterprise: * **Get started**: [Getting Started](/enterprise/v1-12-0/geneva/getting-started) · [What is Feature Engineering?](/enterprise/v1-12-0/geneva/overview/) · [End-to-end example](/enterprise/v1-12-0/geneva/end-to-end) * **UDFs**: [Using UDFs](/enterprise/v1-12-0/geneva/udfs/udfs) · [Blob helpers](/enterprise/v1-12-0/geneva/udfs/blobs/) · [Error handling](/enterprise/v1-12-0/geneva/udfs/error_handling) · [Advanced configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration) * **Jobs**: [Job execution overview](/enterprise/v1-12-0/geneva/jobs/) · [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling/) · [Materialized views](/enterprise/v1-12-0/geneva/jobs/materialized-views/) · [Startup optimizations](/enterprise/v1-12-0/geneva/jobs/startup/) · [Advanced job configuration](/enterprise/v1-12-0/geneva/jobs/advanced-job-configuration/) · [Advanced execution contexts](/enterprise/v1-12-0/geneva/jobs/contexts/) · [Geneva console](/enterprise/v1-12-0/geneva/jobs/console) · [Performance](/enterprise/v1-12-0/geneva/jobs/performance/) * **Deployment**: [Deployment overview](/enterprise/v1-12-0/geneva/deployment/) · [Helm deployment](/enterprise/v1-12-0/geneva/deployment/helm/) · [Troubleshooting](/enterprise/v1-12-0/geneva/deployment/troubleshooting/) ## API Reference * [`geneva.connect()`](https://lancedb.github.io/geneva/api/) — connect to a Geneva database * [Connection](https://lancedb.github.io/geneva/api/connection/) — manage tables, views, jobs, clusters, and manifests * [Table](https://lancedb.github.io/geneva/api/table/) — add columns, backfill, search, and manage table data * [UDF](https://lancedb.github.io/geneva/api/udf/) — define user-defined functions for feature computation # Advanced Job Configuration Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/advanced-job-configuration Pin the dependency manifest a transform's distributed job runs with using @udf, @chunker, and @udtf. Enterprise-only On LanceDB Enterprise, backfill and refresh jobs run on a managed, distributed execution environment configured at deployment time: * the **default cluster** — the compute pool jobs run on, and * the **default manifest** — the Python dependency environment (image and packages) the distributed workers run with. These defaults are set in the [LanceDB Helm chart](/enterprise/v1-12-0/geneva/deployment/helm) and cover most workloads. When a transform needs dependencies that differ from the deployment default, pin a **manifest** on the transform itself, as described below. > [!NOTE] > > To override the **cluster** a job runs on — for example to route an embedding backfill to a > GPU pool — see [Advanced Execution Contexts](/enterprise/v1-12-0/geneva/jobs/contexts). ## Pinning a dependency manifest A manifest pins the Python image and packages the distributed workers run with. Build one with the manifest builders, then attach it to your transform with the `manifest=` argument on `@udf`, `@chunker`, or `@udtf`. The manifest is snapshotted into the column (or view) metadata when the transform is registered, so every backfill or refresh of that transform uses it automatically — there is no per-call manifest argument to remember. > [!NOTE] > > **Manifests are immutable at the column / view level.** When a transform is registered, its > manifest is snapshotted onto the column (or view) metadata. Changing the deployment-default > manifest — or the `GenevaManifest` object in your code — does **not** affect existing columns > or views: they keep using the snapshot taken at creation time. To move a column or view to a > new manifest, re-point it to a new (or updated) UDF / chunker / UDTF — for example with > `alter_columns()` for a column, or by recreating the view. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from typing import Iterator, NamedTuple from geneva import udf, chunker, udtf from geneva.manifest import GenevaManifest # Build a manifest that pins the dependencies these transforms need embed_manifest = ( GenevaManifest.create_pip("embedding-deps") .pip(["sentence-transformers==3.3.1", "torch==2.5.1"]) .build() ) ``` ### `@udf(manifest=...)` Pin dependencies for a 1:1 computed column: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 384), manifest=embed_manifest) def embed(text: str) -> list[float]: from sentence_transformers import SentenceTransformer model = SentenceTransformer("BAAI/bge-small-en-v1.5") return model.encode(text, normalize_embeddings=True).tolist() tbl.add_columns({"embedding": embed}) tbl.backfill("embedding") # the backfill job runs with embed_manifest ``` ### `@chunker(manifest=...)` Pin dependencies for a 1:N [chunker](/enterprise/v1-12-0/geneva/udfs/scalar-udtfs) (scalar UDTF): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Chunk(NamedTuple): chunk_index: int chunk_text: str @chunker(manifest=embed_manifest) def split_document(text: str) -> Iterator[Chunk]: for i, part in enumerate(text.split("\n\n")): yield Chunk(chunk_index=i, chunk_text=part) view = db.create_udtf_view("chunks", source=tbl.search(None), udtf=split_document) view.refresh() # the refresh job runs with embed_manifest ``` ### `@udtf(manifest=...)` Pin dependencies for an N:M [batch UDTF](/enterprise/v1-12-0/geneva/udfs/batch-udtfs): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), ]), manifest=embed_manifest, ) def group_stats(source) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby("label").size().reset_index(name="count") yield pa.RecordBatch.from_pandas(agg) view = db.create_udtf_view("summaries", source=tbl.search(None), udtf=group_stats) view.refresh() # the refresh job runs with embed_manifest ``` ## Capturing your local environment for testing When iterating locally, you often want the workers to run with the *exact* packages from your current environment rather than a curated pip list. `Connection.capture_local_environment()` zips your workspace (and, optionally, your site-packages), uploads the archives through the connection, and returns a ready-to-use `GenevaManifest` you can attach to a transform with `manifest=`. Replace the connection placeholders below with your deployment details. In application code, load credentials from environment variables or a secrets manager. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import geneva from geneva import udf db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) # Capture the local workspace; rely on the worker image for site-packages manifest = db.capture_local_environment(skip_site_packages=True) @udf(data_type=pa.string(), manifest=manifest) def shout(text: str) -> str: return text.upper() tbl = db.open_table("my_table") tbl.add_columns({"shout": shout}) tbl.backfill("shout") # workers run with your captured environment ``` Pass `skip_site_packages=False` (the default) to also upload your local site-packages. ## Manifest resolution For a given transform, the manifest is resolved in this order (first match wins): 1. The manifest pinned on the transform via `@udf` / `@chunker` / `@udtf` `manifest=`. 2. For a materialized view, the manifest snapshotted on the view when it was created. 3. The deployment-default manifest from the [LanceDB Helm chart](/enterprise/v1-12-0/geneva/deployment/helm). > [!NOTE] > > The `manifest=` argument applies to managed enterprise (`db://`) jobs. For direct > object-storage or local-filesystem connections, configure the dependency environment > explicitly with an [Advanced Execution Context](/enterprise/v1-12-0/geneva/jobs/contexts) instead. # Backfilling Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/backfilling Learn how to trigger backfill operations to populate column values in your LanceDB table using Geneva's distributed framework. ## Triggering Backfill Triggering backfill creates a distributed job to run the UDF and populate the column values in your LanceDB table. The Geneva framework simplifies several aspects of distributed execution. **Checkpoints**: Each batch of UDF execution is checkpointed so that partial results are not lost in case of job failures. Jobs can resume and avoid most of the expense of having to recalculate values. ## Auto-backfill Computed columns can be explicitly backfilled or they can be configured to be backfilled automatically as data changes. Set `auto_backfill=True` on the UDF, and the column is automatically recomputed whenever it falls out of sync with its source data. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Mark the column's UDF for automatic backfill @udf(data_type=pa.list_(pa.float32(), 1536), version="1", auto_backfill=True) def embed_udf(text: str) -> list[float]: return embedding_model.encode(text) tbl.add_columns({"embedding": embed_udf}) # No explicit backfill() needed — adding rows triggers recomputation automatically tbl.add(new_rows) ``` The `auto_backfill` flag is recorded in the column metadata when the column is added or altered. LanceDB Enterprise's managed agent watches for columns that need recomputation and dispatches a distributed backfill job for you — there is no manual trigger and no status polling. A column is recomputed when, for example, **new rows are added** (leaving it null for those rows) or the **UDF version changes** (you bump `version=` and `alter_columns()` to the new function). > [!NOTE] > > Auto-backfill is an enterprise feature. On direct object-storage or local-filesystem > connections there is no managed agent, so `auto_backfill=True` has no effect and you must run > `backfill()` explicitly. ## Adaptive checkpoint sizing Geneva can automatically adjust checkpoint sizes during a backfill. It starts with small checkpoints (faster proof-of-life) and grows them as it observes stable throughput, while staying within safe bounds. Planning still uses your configured checkpoint size (`checkpoint_size`), but the actual checkpoint chunks can be smaller when adaptive sizing is enabled. Adaptive sizing is always clamped to bounds: * `max_checkpoint_size`: Upper bound. Defaults to the job's checkpoint size (`checkpoint_size`) and is capped at that value if you set a larger max. * `min_checkpoint_size`: Lower bound. Defaults to 1. When `min_checkpoint_size == max_checkpoint_size`, adaptive sizing is disabled and checkpoints are fixed-size. You can set adaptive bounds in two places: * On the UDF definition via `@udf(..., min_checkpoint_size=..., max_checkpoint_size=...)` * On the backfill call via `table.backfill(..., min_checkpoint_size=..., max_checkpoint_size=...)` Backfill-level values take precedence over UDF defaults. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(min_checkpoint_size=25, max_checkpoint_size=200) def embed_udf(text): ... # Override the UDF defaults for this run tbl.backfill("embedding", min_checkpoint_size=10, max_checkpoint_size=100) ``` ## Managing concurrency One way to speed up the execution of a job to give it more resources and to have it work in parallel. There are a few settings you can use on the backfill command to tune this. * process-level `concurrency` * thread-level `intra_applier_concurrency` Process level concurrency can be set with the `concurrency` parameter. This lets you specify the number of processes calculating values using the UDF. The default is 8 and should be set to the number of GPUs you would like to dedicate to your job. This can also be used based on CPU constraints. So if you have 40 machines with 4 GPUs each, you could set ths value to 160. If you set the value higher than the resources available, Geneva will try to schedule as much of the resources as it can (and potentially auto-scale to get more resources). Thread level concurrency can be set with the `intra_applier_concurrency` parameter. This lets you specify the number of threads in each process is calculating values using the UDF. The default is 1. If you have CPU heavy jobs this may be the best setting to tweak to get more utilization out of your systems. If you set the value higher than the resources available, Geneva will try to schedule as much of the resources as it can get. The two settings can be used in combination. So if your UDF requires 1 CPU and you set `concurrency` to 10 and `intra_applier_concurrency` to 5, you will potentially have 50 instances of the UDFs running in parallel. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # backfill embeddings with 10 * 5 = 50 instances tbl.backfill("embedding", concurrency=10, intra_applier_concurrency=5) ``` ## Managing commit visibility Feature engineering jobs at scale can take days to complete. Two settings can help you present progress to other readers incrementally. * Limit the number of rows processed with `num_frags` * Perform intermediate commits with `commit_granularity` The `num_frags` parameter lets you limit the number of fragments processed before the job is considered complete. If you have a table with 1000 fragments, you could set `num_frags` to 1 to see how your UDF performs and if to validate the values generated. You can then later run with a larger `num_frags` value or without the `num_frags` setting to complete the backfill. Any fragments prevoiusly computed are not computed again. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill 2 fragments so experiement can be done on the sample tbl.backfill("embedding", num_frags=2) ``` The `commit_granularity` parameter lets you specify how many fragments need to be ready to commit before a intermediate commit occurs and makes partial results visible to other readers. So for our example with a table of 1000 fragments, you can set `commit_granularity` to 10 to see progress updates every 10 fragments. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # backfill all fragments and perform an intermediate commit every 10 fragments to expose incremental results. tbl.backfill("embedding", commit_granularity=10) ``` ## Filtered Backfills Geneva allows you to specify SQL-style filters on the backfill operation. This lets you to apply backfills to a specified subset of the table's rows. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' tbl.backfill("content", where="starts_with(filename, 'a')") # only backfill embeddings of only those videos with content tbl.backfill("embedding", where="content is not null") ``` Geneva also allows you to incrementally add more rows or have jobs that just update rows that were previously skipped. If new rows are added, we can run the same command and the new rows that meet the criteria will be updated. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' tbl.backfill("content", where="starts_with(filename, 'a')") # only backfill embeddings of only those videos with content tbl.backfill("embedding", where="content is not null") ``` Or, you can use filters to add in or overwrite content in rows previously backfilled. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' or 'b' but only if content not pulled previously tbl.backfill("content", where="(starts_with(filename, 'a') or starts_with(filename, 'b')) and content is null") # only backfill embeddings of only those videos with content and no prevoius embeddings tbl.backfill("embedding", where="content is not null and embeddding is not null") ``` Reference: * [`backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill) * [`backfill_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill_async) * [`plan_backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.plan_backfill) * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator and UDF configuration options including `checkpoint_size` # Bulk Loading & Updating Columns Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/bulk-load-columns Load or update column data from external sources (Parquet, Lance, IPC) into your LanceDB table using a primary-key join. Beta — introduced in Geneva 0.13.0 ## Overview A common scenario is having column data that **already exists** in an external dataset — embeddings from a vendor, features exported from a data warehouse, or columnar data in cloud storage — that you want to load into an existing LanceDB table. `load_columns` joins value columns from an external source into your table by primary key. It works for both use cases: * **Adding new columns:** If the specified columns don't exist in the destination table, they are created automatically. * **Updating existing columns:** If the columns already exist, matched rows are updated with the source values. Unmatched rows are controlled by the `on_missing` parameter. **Destination table (before):** | pk | col_a | col_b | | - | - | - | | 1 | x | 10 | | 2 | y | 20 | | 3 | z | 30 | **External source (Parquet / Lance / IPC):** | pk | embedding | | - | - | | 1 | \[.1, .2] | | 2 | \[.3, .4] | | 3 | \[.5, .6] | **Destination table (after `load_columns` join on `pk`):** | pk | col_a | col_b | embedding | | - | - | - | - | | 1 | x | 10 | \[.1, .2] | | 2 | y | 20 | \[.3, .4] | | 3 | z | 30 | \[.5, .6] | ### When to use * **Loading new columns:** Attach pre-computed embeddings from a vendor, or add features exported from Spark/BigQuery as Parquet. * **Updating existing columns:** Replace outdated embeddings with a newer model's output, or refresh feature values from an updated export. * **Partial updates:** Update a subset of rows (e.g., only rows whose embeddings were recomputed) while preserving all other values via carry semantics. * **Format consolidation:** Merge columnar data spread across Parquet files into an existing Lance table. ## Basic usage Supports Parquet, Lance, and IPC sources. The format is auto-detected from the URI suffix, or can be overridden with `source_format`. You can load one or more columns in a single call. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("my_db") table = db.open_table("my_table") # Add a new embedding column from a Parquet source table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], ) # Later, update the same column with refreshed embeddings table.load_columns( source="s3://bucket/embeddings_v2/", pk="document_id", columns=["embedding"], ) ``` For non-blocking execution, use `load_columns_async` which returns a `JobFuture` — call `.result()` to block until completion. ## Handling missing keys When the source doesn't cover every row in the destination, the `on_missing` parameter controls what happens to unmatched rows: | Mode | Behavior | | - | - | | `"carry"` (default) | Keep existing value. NULL if the column is new. | | `"null"` | Explicitly set to NULL. | | `"error"` | Raise an error on the first unmatched row. | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Default: unmatched rows keep their current value table.load_columns( source="s3://bucket/partial_embeddings/", pk="document_id", columns=["embedding"], on_missing="carry", ) # Strict mode: fail if source doesn't cover all rows table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], on_missing="error", ) ``` The `carry` mode is particularly important for partial and multi-pass loads — it ensures that previously loaded values are never overwritten. ## Performance tuning ### Concurrency The `concurrency` parameter controls the number of worker processes. The default is 8 — set this to match your available cluster resources. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], concurrency=16, ) ``` ### Checkpointing Bulk load jobs checkpoint each batch for fault tolerance, using the same infrastructure as [backfill jobs](/enterprise/v1-12-0/geneva/jobs/backfilling#adaptive-checkpoint-sizing). Key parameters: * `checkpoint_interval_seconds`: Target seconds per checkpoint batch (default 60s). The adaptive sizer grows or shrinks batch sizes to hit this target. * `min_checkpoint_size` / `max_checkpoint_size`: Bounds for adaptive sizing. > [!TIP] > > If your job is small enough to complete without needing fault tolerance, you can get better performance by effectively disabling checkpoints. Increase `checkpoint_interval_seconds` to a large value and set `min_checkpoint_size` high enough that each worker processes its entire workload in a single batch. ### Commit visibility For long-running jobs, `commit_granularity` controls how many fragments complete before an intermediate commit makes partial results visible to readers. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], commit_granularity=10, ) ``` ### Multi-pass loads for large sources `load_columns` builds an in-memory primary-key index from the source. If the source is too large to fit in memory, split it into chunks and run sequential calls. Carry semantics guarantee correctness across passes. Index memory depends on primary key type: | PK type | \~Memory per row | 100M rows | 1B rows | | - | - | - | - | | int64 | \~8 bytes | \~800 MB | \~8 GB | | string (avg 32 bytes) | \~32 bytes | \~3.2 GB | \~32 GB | Choose N so that `source_size / N` fits in memory: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow.dataset as pads # Discover source files (metadata only, no data I/O) source_files = pads.dataset("s3://bucket/embeddings/", format="parquet").files # Split into N chunks and run sequentially N = 4 total = len(source_files) for i in range(N): chunk = source_files[i * total // N : (i + 1) * total // N] table.load_columns( source=chunk, pk="document_id", columns=["embedding"], ) ``` Each pass reads only its assigned files, so total source I/O stays at 1x. If the source is already partitioned into subdirectories, pass each URI directly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for shard in range(4): table.load_columns( source=f"s3://bucket/embeddings/shard_{shard}/", pk="document_id", columns=["embedding"], ) ``` > [!WARNING] > > Multi-pass loads must run **sequentially**, not concurrently. Two `load_columns` calls running at the same time against the same column produce an interleaved end state. Use a plain `for` loop, not `concurrent.futures`. ## Reference * [`load_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.load_columns) * [`load_columns_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.load_columns_async) # Backfill Conflicts Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/conflicts Learn how Geneva handles conflicts during backfill operations and what to do when they occur. ## Overview Geneva backfills operate on a **point-in-time snapshot** of your table. When other operations modify the table during or between backfills, conflicts can occur. Geneva >=0.9.0 automatically handles most conflict scenarios, reducing unnecessary recomputation and enabling graceful recovery. ## Safe Operations During Backfill These operations can safely run while a backfill is in progress: | Operation | Why It's Safe | | - | - | | `merge_insert` (Insert-only) | Creates new fragments without modifying existing ones | | `add()` / append data | Creates new fragments without modifying existing ones | | Read operations (`search`, `to_arrow`) | Read-only, no fragment modification | | Adding new columns | Schema change only, no fragment rewrite | ## Operations That Cause Conflicts These operations can conflict with running backfills: | Operation | What Happens | | - | - | | `compact_files()` / `optimize()` | Reorganizes fragments, invalidating the backfill's snapshot | | `merge_insert` with updates | Modifies existing rows, causing fragment conflicts | | `delete()` | Modifies existing fragments | > [!WARNING] > > When a conflict occurs, affected fragments fail gracefully. The backfill completes what it can, and you can re-run it to process the remaining rows. ## How Geneva Handles Conflicts ### Concurrent Backfills on Different Columns When multiple backfills run on the same table but different columns, Geneva handles version conflicts automatically: 1. Each backfill writes to different column files (field IDs) 2. If a commit conflict occurs, Geneva retries at the latest version 3. The retry merges the new column data without overwriting other columns This is controlled by the `GENEVA_VERSION_CONFLICT_MAX_RETRIES` environment variable (default: 10). See [Advanced Configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration) for details. ### Compaction Between Backfills When you run compaction between backfills (not during), Geneva handles it efficiently: | Scenario | Behavior | | - | - | | Backfill, compact, re-backfill (same UDF) | Already-computed rows are skipped via `WHERE <col> IS NULL` | | Partial backfill, compact, resume | Incremental processing continues from where it left off | | Backfill, `alter_columns` (new UDF), re-backfill | Full reprocessing with new UDF (intentional) | > [!NOTE] > > Geneva's default behavior is to skip rows that already have values (`WHERE <col> IS NULL`). This means compaction doesn't cause unnecessary recomputation. ## Recovery Steps When a conflict occurs during a backfill: 1. **Wait** for any concurrent operations (compaction, updates) to complete 2. **Re-run** the backfill: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.backfill("column_name") ``` 3. **Only uncomputed rows** will be processed (rows with NULL values in the target column) Checkpoints from the previous run are preserved, so you won't lose progress on successfully computed rows. ## Best Practices ### Sequence Your Operations For the smoothest experience, sequence your operations: ``` 1. Complete all data ingestion 2. Run backfill to compute UDF columns 3. Run compaction/optimization ``` ### Use Insert-Only Operations During Backfill If you need to add data while a backfill is running, use insert-only operations: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Safe: INSERT-only merge_insert tbl.merge_insert("id").when_not_matched_insert_all().execute(new_data) # Unsafe: Updates to existing rows tbl.merge_insert("id").when_matched_update_all().execute(data) # May conflict ``` ### Monitor Backfill Progress Use async backfills to monitor progress and handle errors: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fut = tbl.backfill_async("column_name") while not fut.done(): time.sleep(1) # Check for errors before subsequent operations result = fut.result() ``` ### Disable Auto-Compaction During Large Backfills If using LanceDB Enterprise which has auto-compaction enabled, consider disabling it during large backfill operations to avoid conflicts. ## Related * [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling) - Triggering and configuring backfill operations * [Advanced Configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration) - Environment variables for retry behavior ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `add()`, `merge_insert()`, and other table mutation methods # Geneva Console Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/console The Geneva Console provides a web-based interface for monitoring and managing Geneva jobs, clusters, and manifests. ![geneva-console](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/geneva/console_screenshot.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=7529f79375ef24362c0672d499997708) ## Why a Geneva Console? * Collaboration: The console helps multiple people work together. Individual jobs can be run in a notebook or workflow, but to collaborate on jobs, it helps to be able to see everything that's running on a given database. * History: See what has run in the past and diagnose any problems with your jobs. * Shared resources: The console stores definitions of clusters and manifests, so you can easily tell what resources you want to use to run your job. ## Getting Started The Geneva console is installed with the Geneva Helm chart; [contact LanceDB](https://lancedb.com/contact/) for access to the Helm chart. 1. Install or upgrade the Geneva Helm chart (see [Helm Deployment](/enterprise/v1-12-0/geneva/deployment/helm/)). 2. In your web browser, connect to the Geneva Console UI using the external ingress/load balancer URI configured in your deployment. 3. **Backup (no external ingress):** if your deployment doesn't expose the console via ingress or a load balancer, forward port 3000 from the `geneva-console-ui` service and open `http://localhost:3000`: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl port-forward -n lancedb svc/geneva-console-ui 3000:3000 ``` (Use `-n` to specify the namespace you installed the Helm chart into. We advise `lancedb`.) 4. When prompted, enter your bucket and database, like: ``` s3://my-bucket/my-db ``` ## What's in the Console? ### Jobs Overview The heart of the console is an overview of all jobs that are running on a given database. See each job's status, progress, timing, and initiator. ### Job Details Click on a job's ID to get more details, especially events that have happened in a job's life cycle, and metrics such as number of workers, rows, and fragments written. ### Clusters See the Geneva clusters that you have defined to run jobs. Because clusters can be reused by name, this view can help you run a new job with the same resource constraints as a previous job. ### Manifests See the Manifests you've defined and what packages/dependencies they contain. As with clusters, manifests are reusable, so it's easy to start a new job with the same dependencies as an old one by just specifying the manifest name. ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()`, `list_clusters()`, `list_manifests()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `GenevaCluster` and cluster configuration classes * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — `GenevaManifest` and manifest builder classes # Advanced Execution Contexts Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/contexts Configure the distributed execution backend — clusters and dependency manifests — for Geneva jobs on object-storage and local-filesystem connections. > [!NOTE] > > **This page applies to direct object-storage and local-filesystem connections only.** On > LanceDB Enterprise (`db://`) connections, distributed job execution is fully managed: the > cluster and manifest are configured at deployment time (see > [Helm deployment](/enterprise/v1-12-0/geneva/deployment/helm)) and can be overridden per job with `cluster=` / > `manifest=` (see [Advanced Job Configuration](/enterprise/v1-12-0/geneva/jobs/advanced-job-configuration)). You > do not define execution contexts there. > > When you connect Geneva directly to object storage (`s3://`, `gs://`, …) or a local path, > there is no managed control plane, so you configure the execution backend yourself using the > contexts below. The APIs on this page require Geneva **v0.10.0** or later. Geneva's distributed execution backend is **Ray**. There are 3 ways to connect to a Ray cluster: 1. Local Ray 2. KubeRay: create a cluster on demand in your Kubernetes cluster. 3. Existing Ray Cluster ## Ray Clusters ### Local Ray To execute jobs without an external Ray cluster, you can use `LocalRayContext`. This will auto-create a Ray cluster on your machine. Because it's on your laptop/desktop, this is only suitable for prototyping on small datasets. But it is the easiest way to get started. Simply define the UDF, add a column, call [`Connection.local_ray_context()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.local_ray_context), and trigger the job: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.db import Connection @udf def filename_len(filename: str) -> int: return len(filename) tbl.add_columns({"filename_len": filename_len}) with Connection.local_ray_context(): tbl.backfill("filename_len") ``` Geneva will package up your local environment and send it to each worker process, so they'll have access to all the same dependencies as if you ran a simple Python script yourself. ### KubeRay If you have a Kubernetes cluster with kuberay-operator, you can use Geneva to automatically provision RayClusters. To do so, define a Geneva cluster, representing the resource needs, Docker images, and other Ray configurations necessary to run your job. Make sure your cluster has adequate compute resources to provision the RayCluster. Here is an example Geneva cluster definition: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.cluster import GenevaCluster, K8sConfigMethod from geneva.cluster.builder import KubeRayClusterBuilder db = geneva.connect("s3://my-bucket/my-db") cluster_name = "my-geneva-cluster" # lowercase, numbers, hyphens only service_account = "my_k8s_service_account" # k8s service account that Geneva runs as k8s_namespace = "lancedb" # k8s namespace cluster = ( GenevaCluster.create_kuberay(cluster_name) .namespace(k8s_namespace) .aws_config(region="us-east-1") # only required if using AWS .config_method(K8sConfigMethod.LOCAL) # Load k8s config from `~/.kube.config` # (other options include EKS_AUTH to load from AWS EKS, or IN_CLUSTER to load the # config when running inside a pod in the cluster) .head_group( service_account=service_account, cpus=2, node_selector={"geneva.lancedb.com/ray-head":""}, # k8s label required for head in your cluster ) .add_worker_group( KubeRayClusterBuilder.cpu_worker() .cpus(4) .memory("8Gi") .service_account(service_account) .build() ) .add_worker_group( KubeRayClusterBuilder.gpu_worker() # defaults to 1 GPU .cpus(2) .memory("8Gi") .service_account(service_account) .build() ) .build() ) db.define_cluster(cluster_name, cluster) # define_cluster stores the cluster metadata in persistent storage. The Cluster can then be referenced by name and provisioned when creating an execution context. table = db.get_table("my_table") with db.context(cluster=cluster_name): table.backfill("my_udf") ``` See the API docs for all the parameters [`GenevaCluster.create_kuberay()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.mgr.GenevaCluster.create_kuberay), [`add_worker_group()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.add_worker_group), [`cpu_worker()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.cpu_worker), and [`gpu_worker()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.gpu_worker) can use. #### Exit Modes When you launch multiple async jobs in a single context, the exit mode controls whether the cluster waits for all of them to finish and how it handles failures. You can customize this behavior with the `on_exit` parameter: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray.raycluster import ExitMode with db.context(cluster=cluster_name, manifest=manifest_name, on_exit=ExitMode.DELETE): fut1 = tbl.backfill_async("embedding_a") fut2 = tbl.backfill_async("embedding_b") # No need to call .result() — the context waits for both jobs # Both jobs completed; cluster deleted ``` | Exit Mode | Behavior | | - | - | | `ExitMode.DELETE` (default) | Wait for all async jobs in the context to complete, then delete the cluster. Ideal for batch scripts that launch multiple `backfill_async()` calls in one context. | | `ExitMode.RETAIN_ON_FAILURE` | Wait for all async jobs in the context to complete. If any job failed, the context body raised an exception, or `wait_timeout` was exceeded, retain the cluster for debugging; otherwise delete. | | `ExitMode.RETAIN` | Never delete the cluster, regardless of job outcomes. Useful for notebooks and interactive sessions where you run multiple jobs over time. | ### External Ray cluster If you already have a Ray cluster, Geneva can execute jobs against it too. You do so by defining a Geneva cluster with [`GenevaCluster.create_external()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.mgr.GenevaCluster.create_external) which has the address of the cluster. Here's an example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.cluster import GenevaCluster db = geneva.connect(my_db_uri) cluster_name = "my-geneva-external-cluster" cluster = ( GenevaCluster.create_external(cluster_name, "ray://my_ip:my_port") .build() ) db.define_cluster(cluster_name, cluster) ``` > [!TIP] > > If you need to send environment variables to your workers, in either a KubeRay or External Ray cluster, you can use [`ray_init_kwargs`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.ray_init_kwargs), like so. Set the value in the shell before starting your Python program: > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export AWS_ACCESS_KEY_ID="your-access-key-id" > ``` > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import os > > cluster = ( > GenevaCluster.create_kuberay(cluster_name) # or create_external(cluster_name) > .ray_init_kwargs({ > "runtime_env": { > "env_vars": { > "MY_VAR": "value", > "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"] > }, > }, > }) > # Add other cluster settings here if needed. > .build() > ) > ``` ## Dependencies and Manifests Most UDFs require some dependencies: helper libraries like `pillow` for image processing, pre-trained models like `open-clip` to calculate embeddings, or even small config files. We have three ways to get them to workers: 1. Define dependencies explicitly in a manifest 2. Bake dependencies into an image 3. Auto-upload local dependencies ### Define dependencies explicitly in a manifest We recommend defining dependencies explicitly: it's the easiest way to understand exactly what's running, and the least error-prone. To do so, define a Manifest, like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name="dev-manifest" manifest = ( GenevaManifest.create_pip(manifest_name) .pip(["lancedb", "numpy"]) ).build() db.define_manifest(manifest_name, manifest) ``` After workers start up, this will run `pip install lancedb numpy` on them. You can also use [`.requirements_path(path)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.requirements_path) to point to a local `requirements.txt` file instead of listing packages inline. Note that attempting to use both [`.pip()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.pip) and `.requirements_path()` will raise an exception. For conda-based dependencies, use [`GenevaManifest.create_conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_conda) instead: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest manifest = ( GenevaManifest.create_conda("my-conda-manifest") .conda({"dependencies": ["python=3.10", "numpy"]}) ).build() ``` You can also use [`.conda_environment_path(path)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda_environment_path) to point to a local `environment.yml` file. Note that attempting to use both [`.conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda) and `.conda_environment_path()` will raise an exception. ### Bake dependencies into an image Because the `pip` or `conda` methods involve installing packages, they will incur some startup costs. When your jobs are stable in production, therefore, it will be faster to build all your dependencies into the workers' images, then specify them like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name = "prod-manifest" manifest = ( GenevaManifest.create_pip(manifest_name) .worker_image("myregistry.example.com/my-custom-worker-image:latest") ).build() db.define_manifest(manifest_name, manifest) ``` > [!TIP] > > You can also define images in a cluster via the [`head_group`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.head_group) method and [`cpu_worker`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.CpuWorkerBuilder)/[`gpu_worker`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.GpuWorkerBuilder) methods, e.g.: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > cluster = ( > GenevaCluster.create_kuberay(cluster_name) > .head_group( > image="myregistry.example.com/my-custom-head-image:latest", > ) > .add_worker_group(KubeRayClusterBuilder.cpu_worker() > .image("myregistry.example.com/my-custom-cpu-worker-image:latest") > ) > .add_worker_group(KubeRayClusterBuilder.gpu_worker() > .image("myregistry.example.com/my-custom-gpu-worker-image:latest") > ) > .build() > ) > ``` > > However, if an image is defined in both a Cluster and a Manifest, the definition in the Manifest will take priority. ### Auto-upload local dependencies Geneva can package your local environment and send it to Ray workers. This includes the current workspace root (if you're in a python repo) or the current working directory (if you're not). [`GenevaManifest.create_site()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_site) additionally uploads your Python site-packages (defined by `site.getsitepackages()`) to workers. This is not recommended for production use, as it is prone to issues like architecture mismatches of built dependencies, but it can be a good way to iterate quickly during development. To upload site packages: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name = "dev-manifest" manifest = GenevaManifest.create_site(manifest_name).build() db.define_manifest(manifest_name, manifest) ``` ### What's in a manifest? Here's a summary of what's in a manifest and how you can define it across the three manifest builder types. | Contents | How you can define it | Factory method | | - | - | - | | Local working directory (or workspace root, if in a python repo) | Will be uploaded automatically. | All | | Local python packages (site-packages) | Uploaded automatically. | [`create_site()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_site) | | Pip packages to be installed | Use [`.pip(packages: list[str])`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.pip) or [`.requirements_path(path: str)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.requirements_path). See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | [`create_pip()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_pip) | | Conda packages to be installed | Use [`.conda(deps: dict[str, Any])`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda) or [`.conda_environment_path(path: str)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda_environment_path). See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | [`create_conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_conda) | | Local python packages outside of `site_packages` | Use `.py_modules(modules: list[str])` or `.add_py_module(module: str)`. See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | All | | Container image for head node | Use `.head_image(head_image: str)` or `default_head_image()` to use the default. Note that, if the image is also defined in the GenevaCluster, the image set here in the Manifest will take priority. | All | | Container image for worker nodes | Use `.worker_image(worker_image: str)` or `default_worker_image()` to use the default for the current platform. As with the head image, this takes priority over any images set in the Cluster. | All | If you want to see exactly what is being uploaded to the cluster, set `.delete_local_zips(False)` and `.local_zip_output_dir(path)` then examine the zip files in `path`. ## Putting it all together: Execution Contexts An execution context represents the concrete execution environment (Cluster and Manifest) used to execute a distributed job. Calling `context` will enter a context manager that will provision an execution cluster and execute the Job using the Cluster and Manifest definitions provided. Because you've already defined the cluster and manifest, you can just reference them by name. Note that providing a manifest is optional. Once completed, the context manager will automatically de-provision the cluster. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = geneva.connect(my_db_uri) tbl = db.get_table("my_table") with db.context(cluster=cluster_name, manifest=manifest_name): tbl.backfill("embedding") ``` In a notebook environment, you can manually enter and exit the context manager in multiple steps like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ctx = db.context(cluster=cluster_name, manifest=manifest_name) ctx.__enter__() # ... do stuff ctx.__exit__(None,None,None) ``` ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `context()`, `local_ray_context()`, `list_clusters()`, `list_manifests()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `LocalRayClusterBuilder`, `ExternalRayClusterBuilder`, and worker configuration classes * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — `PipManifestBuilder`, `CondaManifestBuilder`, `SiteManifestBuilder` # Geneva Jobs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/index Learn about Geneva's job execution framework for distributed feature engineering workflows. Geneva provides a comprehensive job execution framework for distributed feature engineering workflows. This section covers the different types of jobs and execution contexts available in Geneva. ## Job Types ### [Backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling/) Trigger distributed jobs to populate column values in your LanceDB table using UDFs. Learn about filtered backfills and incremental updates. ### [Materialized Views](/enterprise/v1-12-0/geneva/jobs/materialized-views/) Create declarative materialized views to manage batch updates of expensive operations. Optimize data layouts for training and simplify orchestration. ### [Startup Optimizations](/enterprise/v1-12-0/geneva/jobs/startup/) Optimize job and session startup times for faster interactive development and production workflows. Learn about caching, pre-warming, and performance tuning. ## Execution Contexts ### [Advanced Execution Contexts](/enterprise/v1-12-0/geneva/jobs/contexts/) Understand how Geneva automatically packages and deploys your Python execution environment to worker nodes for distributed execution. ### [Geneva Console](/enterprise/v1-12-0/geneva/jobs/console/) Set up and access the Geneva Console for monitoring and managing Geneva jobs, clusters, and execution contexts. ## Key Features * **Distributed Processing**: Scale feature computation across multiple nodes * **Checkpointing**: Resume jobs from failures without losing progress * **Incremental Updates**: Only process new or modified data * **Distributed Execution**: Run jobs on Kubernetes or standalone compute clusters * **Environment Management**: Automatic dependency packaging and deployment ## Getting Started 1. **Choose your execution context** based on your infrastructure 2. **Define your UDFs** for feature computation 3. **Trigger backfill operations** to populate your data 4. **Monitor performance** and optimize based on usage patterns For detailed information about each job type and execution context, explore the documentation in this section. ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `backfill_async()`, `refresh()`, `plan_backfill()`, `plan_refresh()`, and other job-triggering methods * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()`, `context()`, and `local_ray_context()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — configure KubeRay and local Ray execution backends * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — package Python environments for remote workers # Job Metrics (Diagnostics) Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/job_metrics Use Geneva Job Metrics to monitor and troubleshoot jobs in real time. ## How to find metrics Job metrics can be found in the [Geneva Console UI](/enterprise/v1-12-0/geneva/jobs/console), by clicking on a job's ID to get to the "Job details" page. ## Core diagnostic metrics | Metric | What it means | Common signal | | - | - | - | | `rows_checkpointed` | Rows finished by read/UDF/checkpoint stage. | High value means upstream compute is progressing. | | `rows_ready_for_commit` | Rows ready for atomic commit (becoming visible to other DB connections). | If much lower than `rows_checkpointed`, writer path is likely bottlenecked. | | `rows_committed` | Rows already visible to other DB connections. | If lagging far behind `rows_ready_for_commit`, commit stage may be bottlenecked. | | `cnt_geneva_workers_active` | Current parallel UDF executors. | Lower than expected means reduced effective parallelism. | | `cnt_geneva_workers_pending` | Deficit from desired parallelism. | Persistently high value usually means scheduling/resource pressure. | | `read_io_time_ms` | Cumulative read IO time. | Dominant value suggests storage/read bottleneck. | | `udf_processing_time` | Cumulative UDF execution time. | Dominant value suggests compute/UDF bottleneck. | | `batch_checkpointing_time` | Cumulative batch checkpoint overhead. | High value suggests checkpoint overhead is expensive. | | `writer_write_time` | Cumulative writer output time. | High value often points to object storage throughput/throttling issues. | | `writer_queue_wait_time_ms` | Cumulative writer queue wait time. | High value can indicate writer starvation/backpressure. | | `commit_time_ms` | Cumulative commit time. | High value means commit itself is expensive. | | `commit_conflict_retries` | Commit retries due to version conflicts. | Non-trivial counts indicate commit contention. | | `commit_backoff_time_ms` | Time spent backing off during commit retries. | High value indicates contention/retry pressure. | | `commit_concurrent_writer_retries` | Retries from "Too many concurrent writers". | High value indicates writer concurrency contention. | ## Quick diagnosis workflow 1. Check `rows_checkpointed` vs `rows_ready_for_commit`. * If `rows_checkpointed` is high but `rows_ready_for_commit` is low, fragment writer is usually the bottleneck. * This often indicates object storage read/write pressure (for example S3). 2. Compare read, UDF, and checkpoint timing. * High `read_io_time_ms`: storage or scan bottleneck. * High `udf_processing_time`: UDF compute bottleneck. * High `batch_checkpointing_time`: checkpoint overhead bottleneck. * Typical mitigations: increase `checkpoint_size`, increase `max_checkpoint_size`, or compact the table to produce larger fragments. 3. Check writer timing. * High `writer_write_time` is commonly object storage throttling/throughput limit. * Typical mitigations: use higher network-bandwidth node types, and keep object storage and compute nodes in the same region. 4. Check commit pressure. * High `commit_conflict_retries`, `commit_backoff_time_ms`, or `commit_concurrent_writer_retries` indicates commit contention. 5. Check parallelism deficit. * If `cnt_geneva_workers_pending` stays high while `cnt_geneva_workers_active` stays low, the job is running below desired parallelism due to cluster/resource constraints. ## Notes * Timing metrics are cumulative and may overlap; do not sum them as exact wall time. * For completed jobs, row counters should settle to stable final values. # Job Lifecycle Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/lifecycle Understanding how Geneva jobs work, their lifecycle states, and how to monitor and manage them. Geneva uses background jobs to execute long-running operations like backfills and materialized view refreshes. This guide explains how jobs work, their lifecycle states, and how to monitor and manage them. ## Overview Jobs in Geneva are asynchronous operations that process data in the background. There are two primary job types: | Job Type | Purpose | Created By | | - | - | - | | **Backfill** | Compute column values using UDFs | `table.backfill()` | | **Materialized View Refresh** | Update precomputed query results | `view.refresh()` | Both job types share the same lifecycle states and monitoring capabilities. ## Job States Every job progresses through a well-defined state machine: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} stateDiagram-v2 [*] --> PENDING PENDING --> RUNNING RUNNING --> DONE RUNNING --> FAILED DONE --> [*] FAILED --> [*] ``` | State | Description | | - | - | | **PENDING** | Job has been created and is queued for execution | | **RUNNING** | Job is actively processing data | | **DONE** | Job completed successfully | | **FAILED** | Job encountered an error during execution | ## Monitoring Jobs The [Geneva Console](/enterprise/v1-12-0/geneva/jobs/console) provides a web-based interface for monitoring job status, progress, and history across your database. This is the recommended way to track jobs in collaborative environments. For programmatic access, you can query job status directly via the API: ### Querying Job Status ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva db = geneva.connect("/path/to/db") # Get job state manager jsm = db._history # Get a specific job job = jsm.get(job_id)[0] print(f"Status: {job.status}") print(f"Started: {job.launched_at}") print(f"Completed: {job.completed_at}") # List jobs for a table pending_jobs = jsm.list_jobs(table_name="my_table", status="PENDING") running_jobs = jsm.list_jobs(table_name="my_table", status="RUNNING") ``` ### Progress Metrics Jobs report progress through metrics: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Access job metrics for metric in job.metrics: print(f"{metric['name']}: {metric['count']}/{metric['total']}") ``` Common metrics include: | Metric | Description | | - | - | | `fragments` | [Fragments](https://lance.org/format/table/?h=fragment#fragments) scheduled for processing | | `writer_fragments` | Fragments written to storage | | `udf_values_computed` | Rows processed by UDFs | | `rows_checkpointed` | Rows saved to checkpoint store | | `rows_committed` | Rows committed to the table | | `workers` | Workers started for parallel execution | ### Job Events Jobs log significant events during execution: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for event in job.events: print(f"{event['timestamp']}: {event['message']}") ``` Example events: * "Job started" * "Checkpointing complete for fragment 42" * "Partial commit: 64 fragments" * "Job completed successfully" ## Fault Tolerance Geneva jobs are designed to be resilient to failures: ### Checkpoint-Based Recovery Jobs save intermediate results to a checkpoint store. If a job fails: 1. **Completed work is preserved** - Checkpointed batches are not lost 2. **Resume from checkpoint** - Restarted jobs skip already-processed data 3. **No duplicate processing** - Each batch is processed exactly once By default, checkpoints are stored in a `_ckp/` subdirectory inside the table's storage location. At scale, you can redirect checkpoints to a separate bucket to avoid IOPS contention. See [Checkpoint Storage configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration#checkpoint-storage) for details. ### Resuming Failed Jobs To resume a failed job, simply re-run the same backfill or refresh command. The job will automatically detect existing checkpoints, skip already-processed fragments, and continue from where it left off. ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `backfill_async()`, `refresh()`, `JobFuture` * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()` # Materialized Views with UDFs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/materialized-views Learn how to use Geneva's materialized view feature to declaratively manage batch updates of expensive operations using UDFs. Geneva provides a materialized view feature that can be used to declaratively manage "batch" updates of expensive operations such as populating UDF columns. These updates are triggered via refresh operation. This can be used to optimize data layouts for training and to simplify some operations that traditionally may require external procedural orchestration (airflow, prefect, dagster). > **Note**: This is similar to how traditional databases offer a materialized view feature to declaratively manage expensive aggregation and join operations. ## Process Overview The process is straightforward: 1. Define a query on table, optionally including UDFs in the select clause. 2. Create the materialized view using `db.create_materialized_view(...)`. 3. Populate the new materialized view table using the `refresh` operation. Just like with backfills, this operation is incremental, checkpointed, and run in a distributed manner. ## Example Let's walk through an example using a raw video table as a base. We want to create a materialized view off the table that adds transcription columns to a subset of the values. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import connect, udf import pyarrow as pa db = connect("/path/to/lancedb") schema = pa.schema([ pa.field("video_id", pa.int64(), nullable=False), pa.field("video_uri", pa.string(), nullable=False), pa.field("upload_ts", pa.timestamp("us"), nullable=False), pa.field("metadata", pa.json(), nullable=True), ]) raw_videos = db.create_table( "raw_videos", schema=schema, primary_key="video_id" ) ``` Define the transforms, then create an empty materialized view. This example uses video paths accessible to the workers. Install `openai-whisper` in the worker environment before running the transcription transform. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf def transcribe(video_uri: str) -> str: from whisper import load_model model = load_model("base") return model.transcribe(video_uri)["text"] @udf(data_type=pa.binary()) def load_video(video_uri: str) -> bytes: from pathlib import Path return Path(video_uri).read_bytes() q = ( raw_videos.search(None) .shuffle(seed=42) .select( { "video_uri": "video_uri", "video": load_video, "transcription": transcribe, } ) ) view_table = db.create_materialized_view("table_view", q) ``` To populate the values, we call `refresh`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # explicitly copy values from the source table, applying UDF on cols. db.refresh("table_view") ``` Note that the UDF is stored on the destination materialized view table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raw_table.add(...) db.refresh("table_view") # only materialize new or modified rows. ``` The operation is incremental. So the next time refresh on the table is called, only new fragments with new data get materialized into the materialized view table. Materialized views are just tables so you can query them as well as modify them by adding new `add_columns`, `backfill` particular columns and deriving other materialized views or views from them. Reference: * [`create_materialized_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_materialized_view) ## FAQ ### Do we copy the UDFs from the source table? No. The UDF does not but any UDF calculated values in the original table come to the materialized table via refresh. New columns defined by the UDFs in the materialized view creation are attached only to the materialized view. They can be backfilled (since the UDF belongs to the view) or refreshed. ### On MV refresh, do we force materialization of UDFs cols on the source table? No. They are managed at the source table only. If it is null the null values are propagated. Future options may force materialization/backfill "recursively". ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `create_materialized_view()`, `create_view()` * [Table](https://lancedb.github.io/geneva/api/table/) — `refresh()`, `plan_refresh()` * [Query](https://lancedb.github.io/geneva/api/query/) — `create_materialized_view()` on query builder # Distributed Job Performance and Cluster Sizing Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/performance Learn how to tune Geneva distributed job performance by scaling compute resources and balancing write bandwidth. When Geneva runs in distributed mode, jobs are deployed against a Kubernetes KubeRay instance that dynamically provisions a Ray cluster. Job execution time depends on sufficient CPU/GPU resources for *computation* and sufficient *write bandwidth* to store the output values. Tuning the performance of a job boils down to configuring the table or cluster resources. ## Geneva defaults Geneva sets the following defaults when creating a KubeRay cluster via GenevaClusterBuilder. These apply as both Kubernetes requests and limits. ### Head Node | Resource | Default | | - | - | | CPU | 4 | | Memory | 8 GiB | | GPU | 0 | | Node Selector | `geneva.lancedb.com/ray-head: true` | | Service Account | `geneva-service-account` | The head node runs the Ray GCS (Global Control Store), the driver task, and the dashboard. It does not run UDF applier actors. ### CPU Workers | Resource | Default | | - | - | | CPU | 4 | | Memory | 8 GiB | | GPU | 0 | | Node Selector | `geneva.lancedb.com/ray-worker-cpu: true` | | Replicas | 1 (min: 0, max: 100) | | Idle Timeout | 60 seconds | ### GPU Workers | Resource | Default | | - | - | | CPU | 8 | | Memory | 16 GiB | | GPU | 1 | | Node Selector | `geneva.lancedb.com/ray-worker-gpu: true` | | Replicas | 1 (min: 0, max: 100) | | Idle Timeout | 60 seconds | ## Scaling computation resources Geneva jobs can split and schedule computational work into smaller batches that are assigned to *tasks* which are distributed across the cluster. As each task completes, it writes its output into a checkpoint file. If a job is interrupted or run again, Geneva will look to see if a checkpoint for the computation is already present and if not will kick off computations. Usually computation capacity is the bottleneck for job execution. To complete all of a job's tasks more quickly, you just need to increase the amount of CPU/GPU resources available. ### Estimating CPU and memory requirements #### CPU Geneva can run up to `concurrency` tasks in parallel. Within each task, it can run up to `intra_applier_concurrency` UDF applications concurrently. If your UDF requests `udf.num_cpus` CPUs, the peak CPU required is approximately: `total_cpus ≈ concurrency * intra_applier_concurrency * udf.num_cpus` `concurrency` and `intra_applier_concurrency` are parameters on `Table.backfill(...)`. In most cases you do not need to change `udf.num_cpus`, unless the UDF itself uses multiple threads. If your UDF is single-threaded but you want to speed it up with more parallelism, prefer increasing `concurrency` first. If you stop seeing meaningful improvements, then try increasing `intra_applier_concurrency`. #### Memory Geneva defaults to checkpoint batches of up to 100 rows (`checkpoint_size=100`). Peak memory usage scales with both the input rows held for processing and the output rows buffered before they are written. A rough upper bound is: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} memory_bytes ≈ input_row_size * min(checkpoint_size * worker_num_cpus, task_size) + output_row_size * min(checkpoint_size * intra_applier_concurrency, task_size) ``` * `worker_num_cpus` is the number of CPUs on the Ray worker. * `task_size` is a tunable parameter (rows per task). It can be set on the UDF (e.g. `@udf(..., task_size=...)`) and on `Table.backfill(..., task_size=...)` (backfill-level values take precedence). If `task_size` is larger than the number of rows in a fragment, it behaves the same as `task_size = fragment_num_rows`. By default, it is: `task_size = num_rows / (concurrency * intra_applier_concurrency * 2)` (where `num_rows` is the number of rows in the table, or the number of rows selected by your filter) * `input_row_size` / `output_row_size` are the average bytes per row after materialization in memory. For primitive numeric columns (ints/floats), these sizes are usually small. For images, videos, embeddings, etc. you may need to explicitly provision more memory (e.g. via `@udf(..., memory=...)`) and/or reduce `checkpoint_size` / `task_size`. Typical per-row sizes: * Images: \~200KB–2MB (depends on dataset and encoding) * Videos: \~10MB–200MB * Embeddings: `dimension * data_type_size` bytes (e.g. float32 embeddings use 4 bytes per value, so a 1536-dim embedding is `1536 * 4 = 6144` bytes) #### Internal Actor Resource Overhead In addition to UDF applier actors, each backfill job creates internal actors that consume resources: | Component | CPU | Memory | Count | | - | - | - | - | | Driver task | 0.1 | — | 1 | | JobTracker | 0.1 | 128 MiB | 1 | | Writer actors | 0.1 | 1 GiB | 1 per applier | | Queue actors | 0 | — | 1 per applier | | Applier actors | UDF `num_cpus * intra_applier_concurrency` | UDF memory | `concurrency` | #### Example For a job with `concurrency=4`, `intra_applier_concurrency=2`, with a UDF that requests 1 CPU and 1GiB memory: | Component | CPU | Memory | Count | | - | - | - | - | | Driver task | 0.1 | — | 1 | | JobTracker | 0.1 | 128 MiB | 1 | | Writer actors | 0.1 | 1 GiB | 4 | | Queue actors | 0 | — | 4 | | Applier actors | 1×2=2 | 1 GiB | 4 | | Total | 0.1 + 0.1 + 4×0.1 + 4×2 = **8.6** | 128 MiB + 4×1GiB + 4×1GiB = **8.125 GiB** | | ### Overall Cluster Sizing Of course, the size of a cluster will vary dramatically for each task. But if you don't know how to estimate your workload, we can recommend the following cluster sizes as a starting point: | Cluster Size | Head Node | Workers | | - | - | - | | **Small** (Dev / CI) | 1 CPU, 8 GB | 4 x 2 CPU, 8 GB | | **Medium** (Staging) | 2 CPU, 8 GB | 4 x 4 CPU, 8 GB | | **Large** (Production) | 4 CPU, 8 GB | 8+ x 8 CPU, 16 GB | ### Validation Thresholds The cluster builder validates memory configuration and warns or errors on suspicious values: | Threshold | Value | Behavior | | - | - | - | | GPU worker minimum memory | `< 4 GiB` | **Error** — build fails if below this | | Large memory warning | `> 100 GB` | **Warning** — may exceed K8s node capacity | | Memory-per-CPU ratio warning | `> 16 GiB per CPU` | **Warning** — unusual ratio, likely misconfigured | ### GKE node pools GKE + KubeRay can autoscale the number of VM nodes on demand. Limitations on the amount of resources provisioned are configured via [node pools](https://cloud.google.com/kubernetes-engine/docs/how-to/node-pools#scale-node-pool). Node pools can be managed to scale vertically (type of machine) or horizontally (# of nodes). Properly applying Kubernetes labels to the node pool machines allows you to control resources for different jobs in your cluster. ### Options on `Table.backfill(..)` The `Table.backfill(..)` method has several optional arguments to tune performance. To saturate the CPUs in the cluster, the main arguments to change are `concurrency` which controls the number of task processes and `intra_applier_concurrency` which controls the number of task threads per task process. `commit_granularity` controls how frequently fragments are committed so that partial results can become visible to table readers. Setting `checkpoint_size` smaller introduces finer-grained checkpoints and can help provide more frequent proof of life as a job is being executed. This is useful if the computation on your data is expensive. Reference: * [`backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill) * [`backfill_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill_async) ## Balancing write bandwidth While computation can be broken down into small tasks, new Lance column data for each fragment must be written out in a serialized fashion. Each fragment has a writer that waits for checkpointed results to arrive, sequences them, and then serially writes out the new data file. Writers can be a bottleneck if a Lance dataset has a small number of fragments, especially if the amount of data being written out is comparatively large. Maximizing parallel write throughput can be achieved by having more fragments than nodes in the cluster. ### Symptom: Computation tasks complete but writers seem to hang Certain jobs that take a small dataset and expand it may appear as if the writer has frozen. An example is a table that contains a list of URLs pointing to large media files. This list is relatively small (\< 100MB) and can fit into a single fragment. A UDF that downloads will fetch all the data and then attempt to write all of it out through the single writer. This single writer can then be responsible for serially writing out 500+GB of data to a single file! To mitigate this, you can load your initial table so that there will be multiple fragments. Each fragment with new outputs can be written in parallel with higher write throughput. ## API Reference * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `CpuWorkerBuilder`, `GpuWorkerBuilder` — configure CPU/GPU/memory resources * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `compact_files()`, `optimize()` * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator options: `num_cpus`, `num_gpus`, `memory`, `batch_size` # Job and Session Startup Optimizations Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/startup Learn how to optimize Geneva job and session startup times for faster interactive development and production workflows. During interactive sessions, there are two main actions where you would interact with Geneva. * Compute cluster creation * Job execution Behind the scenes, Geneva packages your python environment and auto-provisions nodes to execute the jobs. This can be time consuming, taking on the order of 5mins to complete before any work is done. The following sections will describe what happens in these steps and how to diagnose and speed up these interactions. ## Compute cluster creation To execute a Geneva job, you'll need to initialize a compute environment. Here's the basic steps Geneva takes to instantiate that cluster: * User requests a cluster * Scan workspace's python path for modules * Generate local workspace directory zip * Generate python site-packages directory zip(s) * Generate other dirs zip (may include your .venv) * Upload zips * Provision head node * Initialize head node The requests to create an environment can take 5-10 mins to initiate. The most time-consuming steps are generating directory zips and uploading them. AI workloads often require many module packages and can be dependent on specific versions to work. Common modules required for GPU use to run model inferrence can easily be 5GB-10GB of compressed content. On GCE for example, this can take \~5mins to zip all this and \~1min to upload all of this data. To speed this up, Geneva employs caching to help optimize the startup time. There are a few things you can do to make subsequent runs faster, often times \<1 minute: ### Hashing and Caching Geneva generates a hash of each path in the python path that takes into account files and their last modified time. After the first time a directory zip is created and uploaded, the cached copy is used and no new zip is generated or uploaded. However, if there are any changes (e.g. new module added or upgraded) a new hash created and the environment's content is zipped and uploaded. ### Isolate dynamic code and modules If you use a Jupyter notebook environment for your driver, the content of the `.ipynb` file is constantly changing. This means the hash for the directory that contains the notebook will change, even if the subdirectories do not. If your notebook is in your home directory, this could pull in large amounts unneeded code and data. To avoid this you can move your notebook into a subdirectory with no children. When your notebook is executed it is updated but only the notebook content is resent. Other path directories are unchanged, have the same hash and can skip zip and ship. ### Package dependecies into a docker image Geneva has an option to skip the zip and ship of the site-packages. Enabling this assumes that the default docker image is overriden with a custom image that has the `site-package` content preloaded. ### Pre-provision nodes and pods: In your kubernetes configuration, you can tag specific nodes with `geneva.lancedb.com/ray-head` k8s label. These nodes should be configured to be on non-spot instances that are always up. This makes initial kuberay cluster creation quick. ## Job execution A backfill or materialized view jobs triggers the provisioning of worker nodes that will perform the computations and writes. A cold start can be slow because several steps must take place before the UDFs can be applied. However, once nodes and pods are warmed up, the time between submission and execution can be quick. Here's the basic steps Geneva takes to kick off a Geneva job: * User submits job (backfill) * plan scans * provision worker nodes (vms) * load vm * Autoscale workers nodes * provision worker nodes (vms) * load vm * schedule ray actors * download docker images * download zips * execute udf * orchestrate fragment write. In practice, planning the initial distributed step scans require loading vm and pod images. With a cold start, this can take \~5 minutes. Here are some steps you can take to pre-warming worker nodes and pods so that exectuion can be more interactive: **Set worker spec's replicas or min_replicas to a value >0:** When the kuberay cluster is instantiated this also pre-provision vm's so they are ready for k8s to place pod. replicas (for initial # of worker nodes), and minWorkers (to keep a pool for nodes always up) **Make a warmup call:** Making an initial request to ray will load the pod and zips content to the worker node so that subsequent startups will be fast. **Prevent nodes from auto-scaling down:** During cluster creation, you can specify `idle_timeout_seconds` option -- this is the amount of time before a node needs to be idle before it is considered for de-provisioning. # Troubleshooting Geneva Jobs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/jobs/troubleshooting Diagnose and fix common issues when running Geneva backfills, materialized views, and other distributed jobs. This page covers common problems you may hit while running Geneva jobs and how to resolve them. For deployment and cluster issues, see [Troubleshooting Geneva Deployments](/enterprise/v1-12-0/geneva/deployment/troubleshooting). ## Admission control and resource errors Geneva runs **admission control** before starting a job to check that the cluster has enough resources. If the check fails, the job is rejected with `ResourcesUnavailableError` (or a warning if admission is not strict). ### "Job requires GPUs but cluster has no GPU worker groups configured" Your UDF requests GPUs but the cluster has no GPU nodes. **Check your UDF:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @geneva.udf(num_gpus=1) # This requires GPUs def my_udf(x): ... ``` **Fix options:** 1. Remove the GPU requirement if the UDF can run on CPU: `@geneva.udf(num_gpus=0)` (or omit `num_gpus`). 2. Make sure you have a GPU worker group; e.g. in your ClusterBuilder: ``` KubeRayClusterBuilder.create() ... .add_worker_group( KubeRayClusterBuilder.gpu_worker(1) .image(get_ray_image(ray.__version__, _py, gpu=True)) .service_account("geneva-service-account") .node_selector({"geneva.lancedb.com/ray-worker-gpu": "true"}) .build() ) ``` 3. Add GPU worker nodes to your cluster and ensure the cluster definition includes a GPU worker group with the correct node selector (e.g. `"geneva.lancedb.com/ray-worker-gpu": "true"`). ### "UDF requires X CPUs + Y GPUs but no worker group can satisfy all requirements." Of course, if your cluster doesn't have enough GPUs, add them! But if you're surprised how many CPUs/GPUs your UDF is requesting, it may be because of concurrency. Your tasks's actual CPU/GPU requirement is `concurrency × CPUs/GPUs per task`. **Fix:** Lower `concurrency` so that the total CPUs/GPUs needed (concurrency × CPUs/GPUs per task) does not exceed the cluster's CPU/GPU count. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Before: backfill with `num_gpus(1)` needs 8 GPUs table.backfill("col", concurrency=8) # After: cap at 4 GPUs table.backfill("col", concurrency=4) ``` ### "No single node can satisfy all requirements" The UDF asks for a combination of CPU, memory, and GPU that no single node in the cluster has. This often happens on heterogeneous clusters. **Example:** Node A has 8 CPUs and 4 GB memory; Node B has 4 CPUs and 8 GB memory. A UDF that needs 8 CPUs and 8 GB cannot be placed on either node. **Fix options:** 1. **Reduce UDF resource requests** so they fit on your smallest target node (e.g. lower `num_cpus` or memory). 2. **Add larger nodes** that can satisfy CPU, memory, and GPU together. 3. **Use a homogeneous cluster** where nodes have the same shape. ### Job passes admission but hangs at low progress If admission control passes but the job stalls at a low percentage: **1. Ray dashboard – see what’s actually running** * **Local Ray:** After starting a local cluster, Ray usually prints the dashboard URL (e.g. `http://127.0.0.1:8265`). Open that in a browser. If you didn’t capture it, the dashboard is typically on port **8265** on the host where Ray was started. * **KubeRay (Kubernetes):** Port-forward the dashboard from the Ray head pod, then open it locally: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Find the Ray head pod (replace NAMESPACE and cluster name as needed) kubectl get pods -n NAMESPACE -l ray.io/node-type=head # Forward the dashboard port (Ray uses 8265 for the dashboard) kubectl port-forward -n NAMESPACE POD_NAME 8265:8265 ``` Then open **[http://localhost:8265](http://localhost:8265)** in your browser. * **External Ray cluster:** Use the dashboard URL your cluster operator provides (often the head node’s port 8265). **What to look for in the dashboard:** * **Actors** (or **State** → **Actors**): A long list of actors stuck in **PENDING** means Ray cannot place them (e.g. not enough CPUs, GPUs, or memory on any node). That matches “admission passed but nothing runs.” * **Tasks / Jobs:** If your Geneva job shows as a Ray job, open it and check for tasks that stay **PENDING** or **RUNNING** for a long time without finishing. Pending tasks often mean insufficient resources or that workers aren’t joining. * **Cluster / Nodes:** Check that worker nodes are **ALIVE** and that **Available** resources (CPU, memory, GPU) are not zero. Dead or overloaded nodes can cause jobs to hang. * **Unprovisioned GPUs:** Sometimes the CSP doesn't have enough GPUs available, so even though you have correctly requested them, the job may be unable to run. In this case, run on CPU if possible, or try your job again later. **2. Memory pressure** If nodes are full or workers are being OOM-killed, the job can stall or fail. In the Ray dashboard, check node memory usage; in Kubernetes, check pod restarts (`kubectl get pods -n NAMESPACE`) and pod logs for OOM. Also try reducing `concurrency` or the UDF’s memory request, even slightly. **3. Writers / queues** Geneva uses Ray actors for writers and queues. If the job is stuck at a fixed percentage, writers may be blocked (e.g. on storage or version conflicts). Check Ray dashboard **Actors** for writer-like actors that stay **RUNNING** but make no progress, and check cluster or pod logs for errors from Geneva (e.g. commit or connection errors). You can relax or skip admission to narrow down whether the failure is admission vs. scheduling: set `GENEVA_ADMISSION__CHECK=false` or use `_admission_check=False` on the backfill (for testing only). See [Advanced configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration/) for more details. *** ## Ray connection and startup ### "Geneva was unable to connect to the Ray head" The client could not connect to the Ray cluster (e.g. after starting a KubeRay or external cluster). **Common causes:** * **Head not ready** – The Ray head pod may still be starting. Wait a bit and retry, or increase `GENEVA_RAY_INIT_MAX_RETRIES` (default 5). * **Image/architecture mismatch** – The Ray head image may not match the node architecture (e.g. arm64 vs x64). Use an image built for the same architecture as your nodes. (the function [`get_ray_image`](https://lancedb.github.io/geneva/api/utils/) can help find the right image name.) * **Network / firewall** – If using an external Ray cluster, ensure the `ray://` address is reachable and that no firewall is blocking the Ray client port. **Quick check:** From the same network as the client, try connecting with `ray.init("ray://<host>:<port>")` in a small script to see the exact error. ### Ray client "already connected" or init fails on retry If you see errors about the client already being connected (e.g. when re-running a notebook or script), ensure you're not holding an old Ray client connection. Restart the kernel or process so Ray is re-initialized cleanly. Geneva disconnects the client when the context exits; leaving a context open or reusing a stale connection can cause this. ### Head node out of memory If the head node is under-provisioned (e.g. 1 CPU / 2 GB), it can OOM when: * Many workers connect and register with GCS * The Ray dashboard accumulates metrics * Object store spillover occurs **Recommendation**: Use at least 4 CPU / 8 GiB for the head node in any non-trivial deployment. This is the current default. *** ## Serialization library or `attrs` version mismatch Ray and Geneva use cloudpickle and can be sensitive to library versions. If you see `TypeError: Enum.__new__() missing 1 required positional argument: 'value'` or similar pickling errors with no obvious non-serializable object, ensure **client and cluster use the same Python minor version and compatible library versions** (e.g. same `attrs`). Run the job from a machine with the same OS/architecture as the workers when possible so that shipped environments match. *** ## Permissions and storage ### GCS / S3 permission denied in job logs Workers run under a Kubernetes service account (and possibly a cloud IAM role). If you see `PermissionError`, `storage.objects.get` denied, or 403 from object storage: 1. **Service account** – Confirm the Geneva Ray head and worker specs use the intended `service_account`. That account must have read/write to the bucket (e.g. GCS `roles/storage.objectUser` or equivalent S3 permissions). 2. **Workload identity** – On GKE, bind the K8s service account to a Google service account with bucket access. On EKS, use IRSA or node IAM so the pod role can access the bucket. See [Troubleshooting Geneva Deployments](/enterprise/v1-12-0/geneva/deployment/troubleshooting) for permission examples and service account configuration. *** ## Version conflicts and commit retries ### Version conflicts during commit Concurrent backfills or other writers can cause version conflicts when committing. Geneva retries with merging; if conflicts persist, you may see repeated retries or failures. **Options:** * Reduce concurrency or avoid overlapping backfills to the same table/fragments. * Tune retries (e.g. `GENEVA_VERSION_CONFLICT_MAX_RETRIES`, default 10) if you expect transient contention. See [Advanced configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration/). ### Writer stalls or commit timeouts If writers are slow (e.g. under resource contention), they may be considered stalled and restarted. You can increase the idle tolerance with `GENEVA_WRITER_STALL_IDLE_ROUNDS` (default 6 rounds of 5s). For commit timeouts or transient storage errors, `GENEVA_COMMIT_MAX_RETRIES` (default 12) controls how many times Geneva retries the commit. *** ## Materialized views ### Matview refresh fails with resource errors Refreshing a materialized view runs admission control for each UDF in the view. If any UDF’s resource requirements cannot be satisfied, the refresh fails. Ensure the cluster has enough resources for **all** UDFs used in the view (same as for a single backfill), and that no single UDF asks for more than any one node can provide. *** ## Quick checks before running a job * **Versions** – Same Ray version on client and cluster; same Python minor (e.g. 3.10.x) on both. See [Troubleshooting Geneva Deployments](/enterprise/v1-12-0/geneva/deployment/troubleshooting#confirming-dependency-versions). * **Remote execution** – Use `ray.available_resources()` and a simple `@ray.remote` task to confirm the cluster is reachable and has the expected CPUs/GPUs/memory. * **Permissions** – Run a minimal remote task that `import geneva` and touches the same bucket/path as your job to surface permission issues early. ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator options: `num_gpus`, `num_cpus`, `memory` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `CpuWorkerBuilder`, `GpuWorkerBuilder` * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `refresh()` * [Error Handling](https://lancedb.github.io/geneva/api/error_handling/) — `FatalWorkerOOMError`, `FatalWorkerCrashError`, and other worker error types # What is Feature Engineering? Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/overview/index Learn how to transform raw data into meaningful features for AI models using LanceDB's feature engineering capabilities. Scale your feature engineering workflows with distributed processing and UDFs. This section introduces the concept of feature engineering using an example of a product recommendation system. [YouTube video player](https://www.youtube.com/embed/VAO4407nHTM?si=mwS7m8aArzvFR_8T) For your AI models to work well — whether for search, recommendations, or anything else — you need good data. But raw data is usually messy and incomplete. Before you can train a model or use it for search, you have to turn that raw data into clear, meaningful features. Feature engineering is the process of cleaning up your data and creating new signals that actually help your model learn or make better predictions. This step is just as important for preparing training data as it is for powering your AI in production. It can take some work to get from raw data to useful features. Let's look at a simple example to see why this matters and how it's done. ## The Challenge: Manual Feature Engineering Imagine you are building a product recommendation system for a large e-commerce platform. The goal is to find items that are genuinely "similar" to a product a user is currently viewing. This notion of "similarity" must be sophisticated. It goes far beyond a simple text match on the product description. It needs to incorporate nuanced business concepts like popularity, value, brand equity, and key product attributes. ### Step 1: The Raw Data Table We start with a raw data table in our data lakehouse. We'll call it `products_raw`. This table contains the basic, unprocessed information scraped from our product catalog. An embedding model could be applied directly to the `description` column for semantic search. However, that would only capture a fraction of the story. **Table: `products_raw`** | product_id | title | description | category | price | original_price | review_count | avg_rating | | :- | :- | :- | :- | :- | :- | :- | :- | | 101 | V-Neck Tee | "A soft, 100% cotton v-neck shirt." | T-Shirt | 25.00 | 25.00 | 1200 | 4.8 | | 102 | Designer Tee | "Limited edition organic cotton tee." | T-Shirt | 90.00 | 150.00 | 25 | 4.9 | | 103 | New Tee | "A new v-neck t-shirt." | T-Shirt | 22.00 | 22.00 | 1 | 5.0 | ### Step 2: The Problem with Raw Data Using this raw data to generate embeddings for a recommendation model is destined for failure. Critical business signals that define true product similarity are either misleading, hidden, or entirely absent. * **Misleading Popularity:** The "New Tee" boasts a perfect 5.0 rating, but with only a single review. Is it truly more "popular" or "better" than the "V-Neck Tee" with 1200 reviews and a 4.8 rating? A naive model would think so. This leads to poor recommendations. * **Missing Price Context:** The model sees a price of \$90.00 for the "Designer Tee." It has no intrinsic understanding that this represents a steep 40% discount. This is a powerful purchasing signal. The model also doesn't know how this price compares to the average price of other T-shirts. * **Hidden Attributes:** Key attributes like "organic" or "limited edition" are buried within the free-text `description`. They are invisible to any model that doesn't perform sophisticated text analysis. Yet, they are crucial for matching user preferences. ### Step 3: Manual Feature Engineering To address these challenges, a data scientist or ML engineer typically embarks on a manual, code-intensive journey. The goal is to extract hidden signals and craft new, meaningful features. This process often takes place in a Jupyter notebook. It involves several intricate steps. 1. **Engineer `popularity_score`:**\ To create a more accurate measure of popularity, combine the average rating with the volume of reviews. A common approach is to use logarithmic scaling. This prevents products with massive review counts from overwhelming the score. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} popularity_score = log(review_count + 1) * avg_rating ``` 2. **Engineer `price_tier`:**\ To help the model understand value, bucket raw prices into clear tiers such as 'budget', 'mid-range', or 'premium'. **Logic:**\ Use conditional logic (for example, `CASE WHEN` in SQL or `np.select` in Python) to assign a tier based on price thresholds. 3. **Engineer `discount_pct`:**\ To explicitly signal a "deal" to the model, calculate the discount percentage by combining the original and current prices. **Logic:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} discount_pct = (original_price - price) / original_price ``` 4. **Engineer `price_vs_cat_avg`:**\ To contextualize a product's price, compare it to the average price within its category. This requires an aggregation step to compute the average price per category. Then, calculate the feature for each product. **Logic:**\ For each product: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} price_vs_cat_avg = price / avg_price_for_category ``` 5. **Engineer `is_organic`:**\ To surface key product attributes, process the `description` text to identify important keywords. **Logic:**\ Use a regular expression or string search for the keyword "organic" to create a boolean (`true`/`false`) flag. Each of these steps requires careful data manipulation and domain knowledge. Iterative experimentation is also needed to ensure the resulting features are both accurate and useful for downstream models. ### Step 4: The Enriched Table After executing this complex chain of logic, we produce a new, enriched table. The features in this table are more potent and ready to be fed into an embedding model. This produces high-quality vectors for our recommendation system. **Table: `products_engineered`** | product_id | ... | popularity_score | price_tier | discount_pct | price_vs_cat_avg | is_organic | | :- | :- | :- | :- | :- | :- | :- | | 101 | ... | 33.6 | 'budget' | 0.0 | 0.54 | false | | 102 | ... | 15.9 | 'premium' | 0.4 | 1.95 | true | | 103 | ... | 3.5 | 'budget' | 0.0 | 0.47 | false | ## Why Use Feature Engineering? Manual feature engineering works for small datasets. However, things change dramatically at scale. In real-world production systems, you often need to process tens or hundreds of millions of records. Sometimes this must happen in real time. The logic that was simple in a notebook, such as aggregations, conditional logic, or text processing, becomes much harder to manage and execute efficiently. As data grows, so does complexity. You might need to generate features from new sources. These could include user behavior logs, images, or videos. This can involve running large-scale machine learning models for tasks like image captioning or text embedding. These tasks require significant compute resources and robust infrastructure. Managing this at scale means dealing with distributed systems, scheduling, and monitoring. You must ensure that feature pipelines are reliable and reproducible. Experimenting with new features or updating existing ones can require major engineering work. This slows down iteration and innovation. Infrastructure challenges, such as orchestrating batch and streaming jobs, handling dependencies, and scaling inference, often become the main bottleneck. In short, the biggest challenge in modern feature engineering is not just coming up with good features. It is also about building infrastructure that can handle complex, multimodal operations. The goal is to deliver fresh, high-quality features quickly and reliably at massive scale. ## API Reference * [`geneva.connect()`](https://lancedb.github.io/geneva/api/) — connect to a Geneva database * [Connection](https://lancedb.github.io/geneva/api/connection/) — manage tables, views, jobs, clusters, and manifests * [Table](https://lancedb.github.io/geneva/api/table/) — add columns, backfill, search, and manage table data * [UDF](https://lancedb.github.io/geneva/api/udf/) — define transforms as user-defined functions # Advanced Configuration Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/advanced-configuration Learn about environment variables for configuring Geneva behavior. Geneva supports various environment variables that start with `GENEVA_` to configure advanced behavior and fine-tune system settings. > [!TIP] > > All `GENEVA_` environment variables are optional and have sensible defaults. Only set them if you need to override the default behavior. ## Admission Control Admission control validates cluster resources before starting jobs to prevent failures due to insufficient resources. | Variable | Default | Description | | - | - | - | | `GENEVA_ADMISSION__CHECK` | `true` | Enable admission control checks. Set to `false` to skip all checks. | | `GENEVA_ADMISSION__STRICT` | `true` | If `true`, reject the job with `ResourcesUnavailableError` when resources are insufficient. If `false`, log a warning but allow the job to proceed. | | `GENEVA_ADMISSION__TIMEOUT` | `3.0` | Timeout in seconds for Ray API calls during admission control checks. Prevents hanging when the cluster is in a bad state. | ## Commit and Retry Configuration Control retry behavior for commits and version conflicts. | Variable | Default | Description | | - | - | - | | `GENEVA_COMMIT_MAX_RETRIES` | `12` | Maximum number of retries for commit operations. With exponential backoff (1s, 2s, 4s, 8s, 16s, then 16s capped), 12 retries gives \~2.5 minutes total wait time before giving up. | | `GENEVA_VERSION_CONFLICT_MAX_RETRIES` | `10` | Maximum number of retries for version conflicts during commit. Version conflicts occur when concurrent backfills commit to the same fragments. Prevents infinite loops when concurrent commits keep conflicting. | | `GENEVA_WRITER_STALL_IDLE_ROUNDS` | `6` | Number of idle rounds (5s each) before considering a writer stalled during drain. With many concurrent backfills, resource contention can slow writers without them being truly stalled. | ## Lance Retry Configuration This section configures retry logic for Lance I/O operations. Retries occur on `OSError`, `ValueError`, and `RuntimeError("Too many concurrent writers")` exceptions, and are retried with exponential backoff with jitter. | Variable | Default | Description | | - | - | - | | `GENEVA_RETRY_LANCE_ATTEMPTS` | `7` | Maximum number of retry attempts for Lance I/O operations. | | `GENEVA_RETRY_LANCE_INITIAL_SECS` | `0.5` | Initial wait time in seconds for exponential backoff when retrying Lance I/O operations. | | `GENEVA_RETRY_LANCE_MAX_SECS` | `120.0` | Maximum wait time in seconds for exponential backoff when retrying Lance I/O operations. | ## Checkpoint Storage > [!WARNING] > > Checkpoint storage configuration is **experimental**. The environment variable names and behavior may change in a future release. Configure where Geneva stores checkpoint data during job execution. Checkpoints enable fault-tolerant processing by saving intermediate results so that failed jobs can resume without reprocessing completed work. By default, Geneva stores checkpoints in a `_ckp/` subdirectory inside the table's own storage location. This means checkpoints share the same bucket and IOPS budget as the table data. You can override this to store checkpoints in a separate location. | Variable | Default | Description | | - | - | - | | `JOB__CHECKPOINT__OBJECT_STORE__PATH` | *(table dir)*`/_ckp/` | URI where checkpoint data is stored. When set, overrides the default in-table checkpoint location. Accepts any URI supported by Lance (e.g., `gs://bucket/path/checkpoints`, `s3://bucket/checkpoints`). | > [!TIP] > > This variable maps to the config path `job.checkpoint.object_store.path`. It can also be set via config files in `.config/` or `pyproject.toml` under the `[geneva]` section. ### Why use a separate checkpoint path? At scale, checkpoint I/O and data I/O compete for the same object store IOPS budget when they share a bucket prefix. Setting `JOB__CHECKPOINT__OBJECT_STORE__PATH` to a **different bucket or prefix** decouples checkpoint I/O from data I/O, giving each its own IOPS budget and preventing shared-prefix rate limiting. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Example: separate checkpoint bucket from dataset storage JOB__CHECKPOINT__OBJECT_STORE__PATH=gs://my-checkpoints-bucket/ckpts ``` Equivalent programmatic configuration: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.config import override_config_kv override_config_kv({ "job.checkpoint.object_store.path": "gs://my-checkpoints-bucket/ckpts", }) ``` ## Other Configuration | Variable | Default | Description | | - | - | - | | `GENEVA_RAY_INIT_MAX_RETRIES` | `5` | Maximum number of retry attempts for `ray.init()` connection failures. Useful when connecting to Ray clusters that may be temporarily unavailable. | | `GENEVA_K8S_AUTH_MAX_RETRIES` | `3` | Maximum number of retries for Kubernetes authentication operations. Must be at least 1. | | `GENEVA_CONFIG_DIR` | `./.config` | Directory path where Geneva looks for configuration files (`.yaml`, `.json`, `.toml`). Can be an absolute or relative path. | # Batch User-Defined Table Functions (UDTFs) Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/batch-udtfs Use batch UDTFs for N:M transformations like deduplication, clustering, and aggregation across entire tables or partitions. Beta — introduced in Geneva 0.11.0 Geneva's standard UDFs operate **row-at-a-time** — one input row produces exactly one output value. Batch User-Defined Table Functions (UDTFs) lift this restriction, enabling **N:M transformations** where the output can have a completely different schema and row count than the input. | Workflow | Input | Output | Cardinality | | - | - | - | - | | Deduplication | N rows | M rows (M ≤ N) | N:M | | Clustering | N rows | K cluster rows | N:K | | Aggregation | N rows | 1 summary row | N:1 | | Cross-row join/merge | N rows | M rows | N:M | ## Defining a Batch UDTF Use the `@udtf` decorator on a class or function. The UDTF receives a query builder over the source data and **yields** `pa.RecordBatch` objects with an arbitrary output schema. ### Class-based ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udtf import pyarrow as pa from collections.abc import Iterator @udtf( output_schema=pa.schema([ pa.field("row_id", pa.int64()), pa.field("cluster_id", pa.int64()), pa.field("is_duplicate", pa.bool_()), ]), input_columns=["row_id", "phash"], num_cpus=4, memory=8 * 1024**3, # 8 GiB ) class PHashDedupe: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow().select(["row_id", "phash"]) clusters = self._cluster(data) yield pa.RecordBatch.from_pydict({ "row_id": clusters["row_id"], "cluster_id": clusters["cluster_id"], "is_duplicate": clusters["is_duplicate"], }) ``` ### Function-based ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf(output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), pa.field("mean_score", pa.float64()), ])) def group_stats(source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby("label").agg( count=("label", "size"), mean_score=("score", "mean"), ).reset_index() yield pa.RecordBatch.from_pandas(agg) ``` ### Decorator Parameters | Parameter | Type | Description | | - | - | - | | `output_schema` | `pa.Schema` | **Required.** Arrow schema of the output table. | | `input_columns` | `list[str] \| None` | Restrict which source columns are visible. `None` means all. | | `partition_by` | `str \| None` | Column name for partition-parallel execution. | | `partition_by_indexed_column` | `str \| None` | Column name with an IVF index for index-based partitioning. Mutually exclusive with `partition_by`. | | `num_cpus` | `float` | Ray CPU resource request per worker. | | `num_gpus` | `float` | Ray GPU resource request per worker. | | `memory` | `int \| None` | Ray memory resource request in bytes. | | `on_error` | `list[ExceptionMatcher] \| ErrorHandlingConfig \| None` | Error handling configuration (see [Error Handling](#error-handling)). | ## Creating and Refreshing a UDTF View Batch UDTFs are always attached to a persistent view via `create_udtf_view()`. Call `refresh()` to populate or update the view. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} conn = geneva.connect("/data/mydb") images = conn.open_table("images") # Create the UDTF view deduped = conn.create_udtf_view( "deduped_images", source=images.search(None).select(["row_id", "phash"]), udtf=PHashDedupe(threshold=4), ) # Populate the view deduped.refresh() ``` UDTF views use the same cluster infrastructure as other Geneva jobs: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # KubeRay cluster with conn.context(cluster="my-cluster", manifest="my-manifest"): deduped.refresh() # Local Ray with conn.local_ray_context(): deduped.refresh() ``` ### Version-aware refresh On each refresh, Geneva checks the source table's version against the version stored in the view metadata. If the source has not changed, the refresh is skipped entirely — an O(1) check. ## Execution Modes ### Single-worker (no partitioning) When neither `partition_by` nor `partition_by_indexed_column` is set, the UDTF runs as a **single Ray task** with access to the entire source dataset. Use this for global operations that need cross-row visibility. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf(output_schema=...) class GlobalAggregation: def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: all_data = source.to_arrow() result = expensive_cross_row_computation(all_data) yield result.to_batches()[0] ``` ### Partition-parallel (`partition_by`) The framework groups source data by the partition column and dispatches each partition as an independent Ray task. Use this when the computation is naturally parallelizable by some grouping key. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ ("row_id_a", pa.string()), ("row_id_b", pa.string()), ("hamming_dist", pa.int32()), ]), partition_by="partition_id", num_cpus=2, ) class EdgeDetection: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow() edges = self._pairwise_compare(data, self.threshold) if edges: yield pa.RecordBatch.from_pydict(edges) ``` ### Index-based partitioning (`partition_by_indexed_column`) Instead of partitioning by a materialized column, the framework reads partition assignments directly from an existing **IVF vector index** (IVF_FLAT, IVF_PQ, IVF_HNSW_FLAT, IVF_HNSW_SQ, etc.). This avoids materializing a `partition_id` column and keeps partitions synchronized with the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.partitioning import create_ivf_flat_index # 1. Build an IVF index on the source table create_ivf_flat_index(images, "phash", k=16) # 2. Define the UDTF with index-based partitioning @udtf( output_schema=pa.schema([ ("row_id_a", pa.string()), ("row_id_b", pa.string()), ("hamming_dist", pa.int32()), ]), partition_by_indexed_column="phash", num_cpus=2, ) class IndexPartitionedEdgeDetection: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow() edges = self._pairwise_compare(data, self.threshold) if edges: yield pa.RecordBatch.from_pydict(edges) ``` | | `partition_by` | `partition_by_indexed_column` | | - | - | - | | Partition source | Column values (SQL filter) | IVF index partitions (row ID take) | | Requires materialized column | Yes | No — reads from index metadata | | Partition count | Number of distinct values | Number of non-empty index partitions | | Sync with index | Manual | Automatic — always reads latest index | > [!WARNING] > > `partition_by` and `partition_by_indexed_column` are **mutually exclusive**. Setting both raises `ValueError`. ## Yielding Batches The UDTF yields one or more `pa.RecordBatch` or `pa.Table` objects. Each batch must conform to `output_schema`. The framework validates each batch, writes it, and optionally checkpoints it. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Streaming — yield per source batch (memory-efficient) def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: for batch in source.to_batches(batch_size=1024): yield transform(batch) # Bulk — load all, compute, yield once def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: all_data = source.to_arrow() result = expensive_cross_row_computation(all_data) yield result.to_batches()[0] ``` > [!TIP] > > Use the streaming pattern for memory-efficient processing. Use the bulk pattern when the computation inherently requires all data in memory (e.g., clustering, global deduplication). ## Error Handling Error handling operates at **partition granularity** — the unit of work is the entire `__call__()` execution for a partition (or the full table in single-worker mode). | Mode | Behavior | Use case | | - | - | - | | **Fail** (default) | Exception kills the partition, refresh fails | Correctness-critical UDTFs | | **Retry** | Retry the entire partition with configurable backoff | Transient failures (network, OOM) | | **Skip** | Log error, continue with remaining partitions | Best-effort / tolerant workloads | > [!WARNING] > > Unlike standard UDF error handling, there is no row-level skip — UDTFs yield whole batches, so the smallest error unit is the partition. ## Checkpointing Each yielded batch is checkpointed before reporting completion. On resume after a failure, completed batches are skipped and entire partitions with a `__done__` marker are skipped. Checkpoint keys include the source table version, so stale checkpoints from a previous source version are automatically ignored when the source changes. > [!WARNING] > > Checkpointed UDTFs must be **deterministic** — the same input must yield the same batch sequence for resume to work correctly. ## Examples ### K-Means Clustering ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("row_id", pa.int64()), pa.field("cluster_id", pa.int64()), pa.field("distance_to_centroid", pa.float64()), ]), num_cpus=4, memory=16 * 1024**3, ) class KMeansClustering: def __init__(self, k: int = 100): self.k = k def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: import numpy as np embeddings = source.to_arrow().select(["row_id", "embedding"]) row_ids = embeddings.column("row_id").to_pylist() vectors = np.stack(embeddings.column("embedding").to_pylist()) centroids, assignments, distances = self._fit(vectors) chunk_size = 10_000 for start in range(0, len(row_ids), chunk_size): end = min(start + chunk_size, len(row_ids)) yield pa.RecordBatch.from_pydict({ "row_id": row_ids[start:end], "cluster_id": assignments[start:end].tolist(), "distance_to_centroid": distances[start:end].tolist(), }) ``` ### Aggregation ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), pa.field("mean_score", pa.float64()), ]), ) class GroupStats: def __init__(self, group_by: str = "label"): self.group_by = group_by def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby(self.group_by).agg( count=("label", "size"), mean_score=("score", "mean"), ).reset_index() yield pa.RecordBatch.from_pandas(agg) ``` Reference: * [`create_udtf_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) * [UDTF](https://lancedb.github.io/geneva/api/udtf/) — full `@udtf` / `@batch_udtf` decorator reference including `output_schema`, `partition_by`, `num_gpus`, and `on_error` # Blob Types in Geneva UDFs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/blobs Learn how to work with Lance Blobs in Geneva UDFs for handling large binary objects efficiently with lazy reading capabilities. Geneva supports UDFs that take [Lance Blobs](/enterprise/v1-12-0/management/table#multimodal) (large binary objects) as input and has the ability to write out columns with binaries encoded as Lance Blobs. Lance blobs are an optimization intended for large objects (1's MBs -> 100MB's) and provide a file-like object that lazily reads large binary objects. ## Reading Blobs Defining functions that read blob columns is straight forward. For scalar UDFs, blob columns are expected to be of type `BlobFile` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lance.blob import BlobFile @udf def work_on_udf(blob: BlobFile) -> int: assert isinstance(blob, BlobFile) data = blob.read() # do something intresting. return len(data) ``` ## Writing Blobs Defining UDFs that write out `Blob`s to a new column is straightforward. Here we add the standard metadata annotation to the UDF so that Geneva knows to write out Blobs. For scalar udfs, your udf will return `bytes`, explicitly set the `data_type` to `pa.large_binary()`, and add the `field_metadata` that specifies blob encoding. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.large_binary(), field_metadata={"lance-encoding:blob": "true"}) def generate_blob(text: str, multiplier: int) -> bytes: """UDF that generates blob data by repeating text.""" return (text * multiplier).encode("utf-8") ``` For `pa.RecordBatch` batched UDFs you the effort is similar: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.large_binary(), field_metadata={"lance-encoding:blob": "true"}) def batch_to_blob(batch: pa.RecordBatch) -> pa.Array: """UDF that converts RecordBatch rows to blob data.""" import json blobs = [] for i in range(batch.num_rows): # do something that returns bytes blob_data = ... blobs.append(blob_data) return pa.array(blobs, type=pa.large_binary()) ``` ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator for defining blob-processing functions * [Table](https://lancedb.github.io/geneva/api/table/) — `add_columns()`, `backfill()` # Error Handling in Geneva UDFs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/error_handling Learn how configure retry, skip, and fail behaviors for UDFs. Geneva provides three ways to handle errors, in increasing complexity: factory functions, exception matchers, and full Tenacity control. ## Quick Start: Factory Functions Use factory functions for common error handling patterns: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, retry_transient import pyarrow as pa @udf(data_type=pa.int32(), on_error=retry_transient()) def my_udf(x: int) -> int: # Will retry on network errors (ConnectionError, TimeoutError, OSError) return call_external_api(x) ``` Geneva provides four built-in factory functions: | Function | Behavior | | - | - | | `retry_transient()` | Retry `ConnectionError`, `TimeoutError`, `OSError` with exponential backoff | | `retry_all()` | Retry any exception with exponential backoff | | `skip_on_error()` | Return `None` for any exception (skip the row) | | `fail_fast()` | Fail immediately on any exception (default behavior) | ### Customizing Retry Behavior Factory functions accept parameters to customize behavior: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, retry_transient, retry_all # Increase max attempts @udf(data_type=pa.int32(), on_error=retry_transient(max_attempts=5)) def more_retries(x: int) -> int: ... # Change backoff strategy @udf(data_type=pa.int32(), on_error=retry_all(max_attempts=3, backoff="fixed")) def fixed_backoff(x: int) -> int: ... ``` **Parameters:** * `max_attempts` (int): Maximum number of attempts (default: 3) * `backoff` (str): Backoff strategy between retries * `"exponential"` (default): 1s, 2s, 4s, 8s... with jitter, capped at 60s * `"fixed"`: Fixed 1s delay between attempts * `"linear"`: 1s, 2s, 3s, 4s... capped at 60s ## Custom Exception Handling: Matchers For fine-grained control, use `Retry`, `Skip`, and `Fail` matchers: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, Retry, Skip, Fail @udf( data_type=pa.int32(), on_error=[ Retry(ConnectionError, TimeoutError, max_attempts=3), Retry(ValueError, match="rate limit", max_attempts=5), Skip(ValueError), # Other ValueErrors - skip the row Fail(AuthError), # Auth failures - fail immediately ] ) def custom_handling(x: int) -> int: ... ``` **How matching works:** 1. Matchers are evaluated in order (first match wins) 2. More specific matchers should come before general ones 3. Unmatched exceptions fail the job ### Exception Matchers | Matcher | Behavior | Parameters | | - | - | - | | `Retry(...)` | Retry with backoff, then fail | `max_attempts`, `backoff`, `match` | | `Skip(...)` | Return `None` for that row | `match` | | `Fail(...)` | Fail the job immediately | `match` | **Syntax:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Single exception Retry(ConnectionError) # Multiple exceptions Retry(ConnectionError, TimeoutError, OSError) # With parameters Retry(ConnectionError, max_attempts=5, backoff="fixed") # With message matching Retry(ValueError, match="rate limit") ``` ### Message Matching Use the `match` parameter to filter exceptions by their message content. The pattern is a regex: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import Retry, Skip # Simple substring (works because regex matches substrings) Retry(ValueError, match="rate limit") # Matches: ValueError("rate limit exceeded") # Regex pattern Retry(ValueError, match=r"rate.?limit") # Matches: ValueError("rate limit") # Matches: ValueError("ratelimit") # Matches: ValueError("rate_limit") # Case-insensitive matching (use (?i) flag) Retry(ValueError, match=r"(?i)rate limit") # Matches: ValueError("Rate Limit exceeded") # Matches: ValueError("RATE LIMIT hit") # Regex alternation (match multiple patterns) Retry(ValueError, match=r"429|rate.?limit|throttl") # Matches: ValueError("Error 429") # Matches: ValueError("rate limit exceeded") # Matches: ValueError("Request throttled") ``` For example, using matchers to distinguish error types: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf( data_type=pa.string(), on_error=[ # Retry rate limits with more attempts Retry(ValueError, match="rate limit", max_attempts=10), # Skip invalid input Skip(ValueError, match="invalid"), # Fail on other ValueErrors Fail(ValueError), ] ) def api_call(x: str) -> str: ... ``` ### Behavior Summary | Outcome | What Happens | When to Use | | - | - | - | | **Retry** | Retry with backoff, then fail/skip | Transient errors: network issues, rate limits, timeouts | | **Skip** | Return `None` for that row | Bad input data, row-specific failures, optional enrichment | | **Fail** | Kill the job immediately | Fatal errors: auth failures, configuration errors | ## Advanced: Full Tenacity Control For power users who need custom callbacks or complex retry conditions, omit `on_error` and use `error_handling=`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.debug.error_store import ErrorHandlingConfig, UDFRetryConfig from tenacity import wait_random_exponential, stop_after_delay @udf( data_type=pa.int32(), error_handling=ErrorHandlingConfig( retry_config=UDFRetryConfig( retry=my_custom_retry_condition, stop=stop_after_delay(300), wait=wait_random_exponential(min=1, max=120), before_sleep=my_logging_callback, ), ), ) def power_user_udf(x: int) -> int: ... ``` Note: `on_error=` and `error_handling=` cannot be used together. ## Restrictions * **Skip behavior** only works with scalar UDFs (functions that process one row at a time) * For batch UDFs that receive `RecordBatch`, use `Retry` or `Fail` only * **All Retry matchers must use the same backoff strategy.** You cannot mix different backoff strategies in the same `on_error` list: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(on_error=[ Retry(ConnectionError, backoff="exponential"), Retry(TimeoutError, backoff="fixed"), # Error: different backoff! ]) def invalid_backoff(value: str) -> str: return value @udf(on_error=[ Retry(ConnectionError, backoff="fixed"), Retry(TimeoutError, backoff="fixed"), # Same backoff - OK ]) def consistent_backoff(value: str) -> str: return value ``` * **Invalid regex patterns are rejected at construction time:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # This will raise ValueError due to the unclosed bracket Retry(ValueError, match=r"[invalid") # But this will work: Retry(ValueError, match=r"rate.?limit") ``` ## API Reference * [Error Handling](https://lancedb.github.io/geneva/api/error_handling/) — `Retry`, `Skip`, `Fail`, `FatalWorkerOOMError`, `FatalWorkerCrashError`, and all exception matcher classes * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator `on_error` parameter # Understanding Transforms Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/index Understand the three types of user-defined functions in Geneva — UDFs, chunkers (scalar UDTFs), and batch UDTFs — and when to use each. Geneva provides three types of user-defined functions for transforming data. Each type has a different input/output cardinality and is suited to different workflows. ## Choosing the Right Type * **Adding a column to each row?** Use a [**UDF**](/enterprise/v1-12-0/geneva/udfs/udfs). * **Splitting each row into multiple rows?** Use a [**Chunker**](/enterprise/v1-12-0/geneva/udfs/scalar-udtfs). * **Computing across rows with a different output shape?** Use a [**Batch UDTF**](/enterprise/v1-12-0/geneva/udfs/batch-udtfs). ## At a Glance | | UDF | Chunker (Scalar UDTF) | Batch UDTF | | - | - | - | - | | **Cardinality** | 1:1 | 1:N | N:M | | **Decorator** | `@udf` | `@chunker` | `@udtf` | | **Refresh** | Incremental | Incremental | Full | | **Parallelism** | Fragment-parallel | Fragment-parallel | Partition-parallel | | **Inherited columns** | N/A — adds to existing rows | Automatic from query | Independent output schema | | **Registration** | [`table.add_columns()`](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) | [`db.create_udtf_view()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) | [`db.create_udtf_view()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) | ## UDFs (1:1) Standard UDFs produce exactly **one output value per input row**. Use them to add computed columns to existing tables or materialized views. | id | text | **embedding** | | - | - | - | | 1 | "hello world" | **→ \[0.12, 0.34, ...]** | | 2 | "foo bar" | **→ \[0.56, 0.78, ...]** | | 3 | "baz qux" | **→ \[0.90, 0.11, ...]** | Each input row produces exactly one output value. The new column is added to the same table. **Use cases**: Embeddings, data enrichment, format conversion, scoring. See [UDFs](/enterprise/v1-12-0/geneva/udfs/udfs) for the full guide. ## Chunkers (Scalar UDTFs, 1:N) Chunkers — also called scalar UDTFs — **expand each source row into multiple output rows**. The output is a materialized view that inherits parent columns and supports incremental refresh. **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is..." | | 2 | "Data Guide" | "Data pipelines are..." | **Derived: `chunks`** (1:N expansion via `@chunker`) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning..." | | 1 | "Intro to AI" | 1 | "Neural networks..." | | 1 | "Intro to AI" | 2 | "Training data..." | | | | | | | 2 | "Data Guide" | 0 | "Data pipelines..." | | 2 | "Data Guide" | 1 | "ETL processes..." | Each source row produces **one or more** output rows. Parent columns (`doc_id`, `title`) are inherited automatically. **Use cases**: Document chunking, video segmentation, image tiling. See [Chunkers](/enterprise/v1-12-0/geneva/udfs/scalar-udtfs) for the full guide. ## Batch UDTFs (N:M) Batch UDTFs read from a source table (or partition) and **produce output with an arbitrary schema and row count**. They always perform a full refresh. **Source: `sales`** | product | region | amount | | - | - | - | | Widget | East | 100 | | Widget | East | 250 | | Widget | West | 175 | | Gadget | East | 300 | | Gadget | West | 400 | | Gadget | West | 150 | **Derived: `sales_summary`** (N:M aggregation via `@udtf`) | product | total_amount | avg_amount | num_sales | | - | - | - | - | | Widget | 525 | 175.0 | 3 | | Gadget | 850 | 283.3 | 3 | 6 input rows become 2 output rows with a completely different schema. The output shape is determined entirely by the UDTF logic — it could be fewer rows (aggregation), more rows (clustering), or the same count with different columns. **Use cases**: Deduplication, clustering, aggregation, cross-row joins. See [Batch UDTFs](/enterprise/v1-12-0/geneva/udfs/batch-udtfs) for the full guide. ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator and `UDF` class * [UDTF](https://lancedb.github.io/geneva/api/udtf/) — `@udtf`, `@chunker`, `@batch_udtf` decorators and `UDTF`/`Chunker` classes * [Table](https://lancedb.github.io/geneva/api/table/) — `add_columns()`, `backfill()` * [Connection](https://lancedb.github.io/geneva/api/connection/) — `create_udtf_view()`, `create_materialized_view()` # Profiling Stateful UDF Memory Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/profiling-memory Find memory leaks and runaway peak usage in stateful UDFs with memray, before they cause worker OOMs in production. Stateful UDFs are the most common source of worker memory pressure in Geneva. Unlike scalar UDFs, a stateful UDF instance lives for the **entire lifetime of a Ray actor**, processing many batches in sequence. Anything your `setup()` allocates is held for the duration of the job, and anything `__call__` retains accumulates batch after batch — sometimes silently, until a worker OOMs partway through a large backfill. This page shows you how to profile a stateful UDF locally with [memray](https://github.com/bloomberg/memray), what to look for, and the common patterns that leak. > [!TIP] > > If your worker is being OOM-killed and you don't know why, **profile a single actor locally first**. A 5-minute memray run on your laptop is faster than another 45-minute distributed run that fails the same way. ## Why stateful UDFs leak A stateful UDF in Geneva is a class: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @geneva.udf(data_type=pa.list_(pa.float32(), 512)) class MyEmbedding: def __init__(self): self.model = None def setup(self): self.model = load_model() # allocated once per actor def __call__(self, text: str) -> list[float]: if self.model is None: self.setup() return self.model.embed(text) ``` A few facts make memory behavior easy to get wrong: * **One instance per worker, many batches.** Geneva instantiates the class once per Ray actor. The same `self` processes every batch routed to that worker — potentially thousands. * **`setup()` runs once.** Whatever you allocate there stays in memory until the actor dies. That's intentional for things like ML models, but it's a footgun for "lazy" caches that grow. * **`self.<attr>` survives across calls.** Anything you attach to `self` inside `__call__` is retained for the rest of the actor's life. * **Workers don't restart between batches.** Unlike a serverless function, you don't get a fresh process per invocation. Memory accumulates linearly with batch count until the worker hits its memory cap. The result: a leak that looks tiny in unit tests (1 batch, 4 MiB) can blow up an 8-hour backfill (10 000 batches, 40 GiB). ## When to profile Profile your UDF if **any** of these are true: * The UDF loads a model, builds an index, or otherwise allocates more than \~100 MiB in `setup()`. * The UDF maintains a cache, deduplication table, or running statistic in `self`. * A worker is being OOM-killed during backfill (look for `FatalWorkerOOMError`, see [Job troubleshooting](/enterprise/v1-12-0/geneva/jobs/troubleshooting)). * Worker RSS grows steadily during a backfill rather than staying flat after `setup()`. You do **not** need to profile pure functional UDFs (no `self` state) or UDFs that only ever read from `self` — those can't leak by construction. ## Profiling a UDF with memray memray ships as a `dev` dependency in Geneva, so it's already in your environment if you installed with `uv sync`. The trick to profiling under Ray is that **workers run in separate processes**. Wrapping `pytest` with `memray run` only sees the driver, not the actors that actually run your UDF. The cleanest pattern is to have **the UDF instrument itself**, controlled by an environment variable that's only set when you want a profile. ### Step 1 — add an opt-in tracker to your UDF ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os, pathlib, uuid from typing import Any import memray import geneva import pyarrow as pa _MEMRAY_OUT_DIR_ENV = "MY_UDF_MEMRAY_OUT_DIR" @geneva.udf(data_type=pa.list_(pa.float32(), 512)) class MyEmbedding: def __init__(self): self.model = None self._tracker: Any = None # memray.Tracker, when profiling is on def setup(self): # Open a memray tracker per worker process, if requested. Each # worker writes its own .bin file so traces don't collide. out_dir = os.environ.get(_MEMRAY_OUT_DIR_ENV) if out_dir: pathlib.Path(out_dir).mkdir(parents=True, exist_ok=True) bin_path = pathlib.Path(out_dir) / ( f"memray-{os.getpid()}-{uuid.uuid4().hex}.bin" ) self._tracker = memray.Tracker( str(bin_path), native_traces=False, follow_fork=False ) self._tracker.__enter__() self.model = load_model() def __call__(self, text: str) -> list[float]: if self.model is None: self.setup() return self.model.embed(text) ``` The tracker is a no-op when `MY_UDF_MEMRAY_OUT_DIR` isn't set, so leaving this code in your UDF is safe for production runs. ### Step 2 — propagate the env var to Ray workers Ray workers don't inherit driver environment variables by default. When you start a local Ray cluster from Geneva, pass `extra_env` so the variable reaches each worker: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray._mgr import ray_cluster with ray_cluster( local=True, extra_env={"MY_UDF_MEMRAY_OUT_DIR": "/tmp/my-udf-profile"}, ): table.backfill("embedding", concurrency=1) ``` > [!TIP] > > Set `concurrency=1` while profiling. One actor processing all batches sequentially produces a single clean trace; the default of 8 produces 8 noisier traces that you'd have to merge mentally. ### Step 3 — read the trace When backfill finishes, you'll have one (or more) `memray-<pid>-<uuid>.bin` files under `/tmp/my-udf-profile/`. Render and inspect them: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Quick summary — peak heap, total allocations, what's leaked uv run -m memray summary /tmp/my-udf-profile/memray-*.bin # Interactive flamegraph in your browser uv run -m memray flamegraph /tmp/my-udf-profile/memray-*.bin open /tmp/my-udf-profile/memray-*.html # Top allocators by retained bytes uv run -m memray tree /tmp/my-udf-profile/memray-*.bin ``` ## What the numbers mean memray reports two values you'll care about most: * **Peak heap** (`metadata.peak_memory`) — the high-water mark. This is what triggers OOMs. A peak well above your `setup()` allocations means a batch transiently doubles memory before freeing. * **Leaked allocations** (`get_leaked_allocation_records()`) — what was still allocated when the tracker ended. **This is not necessarily a bug** — your `setup()` model is "leaked" in this sense because it lives the actor's lifetime. The signal is *how much above expected baseline* is leaked. A healthy stateful UDF profile, after processing many batches, looks roughly like: ``` peak heap ≈ setup() allocations + 1 batch of working memory leaked ≈ setup() allocations (i.e. nothing extra retained from __call__) ``` An **unhealthy** profile looks like: ``` peak heap ≈ setup() + N × per-call allocation ← grows with batch count leaked ≈ setup() + N × per-call allocation ← per-call state never freed ``` The flamegraph will show a thick stack frame anchored in `__call__` rising as you scroll through time — that's the leak. ## Going deeper: RSS vs Arrow allocations memray gives you the *Python-side* allocation story. For real diagnosis of "where is the worker's memory actually going?", it pays to watch **process RSS** and **Arrow's own allocator** side-by-side — together they tell you which subsystem owns the bytes, often faster than reading a flamegraph. Drop this into your UDF (or anywhere on the worker) to log a snapshot: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import resource, pyarrow as pa def log_memory(seq: int) -> None: rss_bytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # ru_maxrss is bytes on macOS, KiB on Linux: import sys if sys.platform != "darwin": rss_bytes *= 1024 arrow_live = pa.total_allocated_bytes() print( f"seq={seq} " f"rss_mb={rss_bytes // 1024**2} " f"arrow_live_mb={arrow_live // 1024**2} " f"gap_mb={(rss_bytes - arrow_live) // 1024**2}", flush=True, ) ``` The three numbers answer different questions: * **`rss_mb`** — every byte the OS has handed this Python interpreter. Includes Python heap, Arrow, native libraries, and pages the C allocator (`glibc`/`jemalloc`) is holding even though Python freed them. This is what triggers cgroup OOM-kills. * **`arrow_live_mb`** — bytes currently held by *live PyArrow buffers* (`RecordBatch`, `Array`, `ChunkedArray`, etc.). Goes up when you create Arrow data, down when those references are dropped. * **`gap_mb` = rss − arrow_live** — "everything else." This is the Python heap (your own `self.cache`, model weights, dicts, lists), native libraries (PyTorch, ONNX), and allocator retention. ### Diagnostic patterns Log the breakdown every few batches and the *shape of growth over time* tells you which subsystem to fix: | Pattern | Diagnosis | First thing to try | | - | - | - | | `rss` climbs slowly, `arrow_live` flat near zero, big growing `gap` | Allocator retention — Python freed it but `glibc` is keeping the pages | `ctypes.CDLL("libc.so.6").malloc_trim(0)` periodically (Linux only); or set `MALLOC_TRIM_THRESHOLD_=131072` | | `rss` climbs, `arrow_live` climbs in lockstep | Real Arrow leak — your code is holding `RecordBatch` / `Array` references | Find where you're appending batches to `self`, or where checkpoint / error payloads aren't being released | | `rss` spikes hugely on a few calls then settles, eventually one spike OOMs | Peak is too big, not a leak — a single call allocates more than the worker has | Shrink `batch_size`, `blob_read_buffer_size`, or split the work | | `rss` flat for hours then sudden cliff upward | One pathological row — usually one huge blob (a 4K-resolution image, a 50 MB PDF) | Find the offending row by ID; add a size check at the top of `__call__` | | `rss` rises during `setup()`, then flat for the whole run, `gap` constant | Healthy — that's your model loaded once per actor | Nothing to do | > [!TIP] > > The reference UDFs in Geneva's own integration test (`src/stress_tests/_memray_probe.py`) print exactly this breakdown every 32 calls. The workflow's stdout logs are a working example of the "clean" and "leaky" patterns — the leaky one shows the **lockstep with Python heap** signature (the second row above, but with `gap` climbing instead of `arrow_live` — because the leak is `bytearray`, not Arrow). ## Common leak patterns ### 1. The growing cache ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadEmbedding: def __init__(self): self.cache: dict[str, list[float]] = {} def __call__(self, text: str) -> list[float]: if text not in self.cache: self.cache[text] = self.model.embed(text) return self.cache[text] ``` Looks harmless. Fine on a unit test with 10 inputs. **Catastrophic on a backfill of 10M rows**, where most inputs are unique and the cache grows to fill the worker. **Fix:** Use a bounded cache (`functools.lru_cache` with `maxsize`, or a manual size cap), or skip caching when you don't know the cardinality. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from functools import lru_cache class GoodEmbedding: def __init__(self): self._embed = None def setup(self): model = load_model() self._embed = lru_cache(maxsize=1024)(model.embed) def __call__(self, text: str) -> list[float]: if self._embed is None: self.setup() return self._embed(text) ``` ### 2. Accumulating per-call buffers ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadAggregator: def __init__(self): self.history = [] def __call__(self, batch: pa.RecordBatch) -> pa.Array: self.history.append(batch) # holds every batch ever processed ... ``` **Fix:** Don't hold references to inputs past the return of `__call__`. If you need rolling state, summarize into a small aggregate (counts, sums) instead of holding the raw batches. ### 3. Closures capturing batch arrays ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadDeferred: def __init__(self): self.work_queue = [] def __call__(self, x: pa.Array) -> pa.Array: # Lambda captures `x` by reference — the whole Array stays alive self.work_queue.append(lambda: expensive(x)) ... ``` **Fix:** Extract only the small values you actually need into the closure, or execute the work eagerly. ### 4. ML model state that grows Some ML libraries retain per-call state internally (KV caches, gradient buffers, autograd graphs). If you're using PyTorch: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def __call__(self, text: str) -> list[float]: with torch.inference_mode(): # <-- prevents autograd graph retention return self.model.encode(text) ``` For Hugging Face pipelines, ensure you're in `eval()` mode and not accumulating gradients. For long-running stateful UDFs on GPUs, also see `torch.cuda.empty_cache()` between large batches. ## A confidence check A useful "does my profiling actually work?" sanity check: temporarily introduce a deliberate leak and confirm memray catches it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def __call__(self, x): scratch = bytearray(8 * 1024 * 1024) # 8 MiB self._scratches.append(scratch) # <-- deliberate leak return ... ``` If `memray summary` doesn't show leaked bytes growing roughly with batch count after this change, your tracker isn't actually attached (most often: the env var isn't reaching workers — re-check `extra_env`). Geneva's own test suite ships a reference implementation of this pattern in `src/stress_tests/_memray_probe.py` and `src/stress_tests/test_memray_stateful_udf.py`, plus a GitHub Actions workflow (`memray-stateful-udf-profile.yml`) that uploads the per-actor `.bin` and rendered flamegraph as a CI artifact. Feel free to copy that scaffolding for your own project's UDFs. ## Related * [UDFs](/enterprise/v1-12-0/geneva/udfs/udfs) — defining stateful UDFs * [Job troubleshooting](/enterprise/v1-12-0/geneva/jobs/troubleshooting) — diagnosing OOMs and other worker errors * [Advanced configuration](/enterprise/v1-12-0/geneva/udfs/advanced-configuration) — admission control and resource limits * [memray documentation](https://bloomberg.github.io/memray/) — flamegraph, summary, and tree report formats # Gemini Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/providers/gemini Embed text and generate completions using Google's Gemini models. See the API reference for [Gemini UDFs](https://lancedb.github.io/geneva/api/gemini/) and [Embedding UDFs](https://lancedb.github.io/geneva/api/embeddings/) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-gemini]' ``` > [!WARNING] > > Gemini UDFs make API calls that incur **per-token costs**. Each row processed results in one > or more API requests billed to your account. Review > [Gemini pricing](https://ai.google.dev/gemini-api/docs/pricing) before running on large tables. > [!NOTE] > > Set the `GEMINI_API_KEY` environment variable before calling any factory function below. > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export GEMINI_API_KEY="your-api-key" > ``` > > The key is read **at UDF creation time** and serialized with the UDF — no cluster-level > `env_vars` configuration is needed. ## Embeddings Embed text with optional task-type hints for retrieval, classification, and clustering scenarios. See the [API reference](https://lancedb.github.io/geneva/api/embeddings/#geneva.udfs.text.embeddings.gemini_embedding_udf) for all parameters. **Multiple embeddings tuned for different retrieval tasks:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import gemini_embedding_udf table.add_columns({ # Full-dimension embedding for document retrieval "embedding_doc": gemini_embedding_udf( column="body", model="gemini-embedding-001", task_type="RETRIEVAL_DOCUMENT", ), # Compact embedding for semantic similarity "embedding_sim_256": gemini_embedding_udf( column="body", model="gemini-embedding-001", task_type="SEMANTIC_SIMILARITY", output_dimensionality=256, ), }) ``` ## Generation Generate text from Gemini models. Supports text, image, audio, video, and document inputs. See the [API reference](https://lancedb.github.io/geneva/api/gemini/#geneva.udfs.text.gemini.gemini_udf) for all parameters. **Enrich a table with sentiment, captions, and transcriptions at once:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import gemini_udf table.add_columns({ # Classify review sentiment with a fast model "sentiment": gemini_udf( column="review", prompt="Classify the sentiment as positive, negative, or neutral. Return only the label.", model="gemini-2.5-flash", ), # Caption product images with a more capable model "caption": gemini_udf( column="image", prompt="Describe the main subject of this image in one sentence", model="gemini-2.5-pro", mime_type="image/jpeg", ), # Transcribe audio clips "transcript": gemini_udf( column="audio", prompt="Transcribe this audio clip", model="gemini-2.5-flash", mime_type="audio/mp3", ), }) ``` ## API Reference * [Gemini](https://lancedb.github.io/geneva/api/gemini/) — `gemini_udf()` parameters: `column`, `prompt`, `model`, `mime_type`, and more * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `gemini_embedding_udf()` parameters: `column`, `model`, `task_type`, `dimensionality`, `normalize` # Built-in LLM and Embedding UDFs Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/providers/index Geneva ships pre-built UDFs for common LLM providers so you don't have to write custom classes for everyday embedding and generation tasks. | Provider | Embeddings | Generation | Runs locally | Install extra | | - | :-: | :-: | :-: | - | | [OpenAI](/enterprise/v1-12-0/geneva/udfs/providers/openai) | ✓ | ✓ | — | `geneva[udf-text-openai]` | | [Gemini](/enterprise/v1-12-0/geneva/udfs/providers/gemini) | ✓ | ✓ | — | `geneva[udf-text-gemini]` | | [Sentence Transformers](/enterprise/v1-12-0/geneva/udfs/providers/sentence-transformers) | ✓ | — | ✓ | `geneva[udf-text-sentence-transformers]` | OpenAI and Gemini UDFs make remote API calls that incur per-token costs. Sentence Transformers run locally on your workers with no API costs — see [GPU acceleration](/enterprise/v1-12-0/geneva/udfs/providers/sentence-transformers#gpu-acceleration) for performance tips. ## Comparing models and prompts Because `add_columns` accepts a dictionary, you can evaluate multiple models, parameter settings, or prompts in a single pass over your data. Each entry produces its own column, so results sit side by side in the same table for easy comparison. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_udf, gemini_udf, openai_embedding_udf table.add_columns({ # Compare two embedding models "emb_small": openai_embedding_udf(column="body", model="text-embedding-3-small"), "emb_large": openai_embedding_udf(column="body", model="text-embedding-3-large"), # Compare the same task across providers "summary_openai": openai_udf( column="body", prompt="Summarize in one sentence", model="gpt-5-mini", ), "summary_gemini": gemini_udf( column="body", prompt="Summarize in one sentence", model="gemini-2.5-flash", ), }) ``` This works for any combination — different models from the same provider, different providers, different prompts with the same model, or different dimensionality settings. All columns are computed in parallel during the same backfill job. To recompute columns later (e.g., after altering a UDF or adding new rows), use `backfill`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Backfill a single column table.backfill("emb_small") # Backfill only rows missing a value table.backfill("summary_openai", where="summary_openai is null") ``` ## What's included All built-in UDFs share these capabilities: * **API key handling** — Keys are captured from your local environment at UDF creation time and securely serialized with the UDF. No cluster-level environment configuration required. * **Retry with backoff** — Transient API errors (rate limits, timeouts, server errors) are automatically retried with exponential backoff. * **Batch processing** — Embedding UDFs batch multiple rows per API call for better throughput. * **L2 normalization** — Embedding UDFs support optional L2 normalization via the `normalize` parameter (disabled by default since both providers return pre-normalized vectors). ## See also * [Working with UDFs](/enterprise/v1-12-0/geneva/udfs/index) — Write custom scalar, batched, and stateful UDFs * [Error handling](/enterprise/v1-12-0/geneva/udfs/error_handling) — Fine-grained retry and skip policies * [Working with blobs](/enterprise/v1-12-0/geneva/udfs/blobs) — Process binary data (images, audio, video) ## API Reference * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `sentence_transformer_udf()`, `gemini_embedding_udf()`, `openai_embedding_udf()` * [Gemini](https://lancedb.github.io/geneva/api/gemini/) — `gemini_udf()` * [OpenAI](https://lancedb.github.io/geneva/api/openai/) — `openai_udf()`, `openai_embedding_udf()` # OpenAI Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/providers/openai Embed text and generate completions using OpenAI models. See the [API reference](https://lancedb.github.io/geneva/api/openai/) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-openai]' ``` > [!WARNING] > > OpenAI UDFs make API calls that incur **per-token costs**. Each row processed results in one > or more API requests billed to your account. Review > [OpenAI pricing](https://openai.com/api/pricing/) before running on large tables. > [!NOTE] > > Set the `OPENAI_API_KEY` environment variable before calling any factory function below. > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export OPENAI_API_KEY="your-api-key" > ``` > > The key is read **at UDF creation time** and serialized with the UDF — no cluster-level > `env_vars` configuration is needed. ## Embeddings **Compare models by adding multiple embedding columns at once:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_embedding_udf table.add_columns({ # Default model — fast, 1536 dimensions "embedding_small": openai_embedding_udf( column="body", model="text-embedding-3-small", ), # Higher-quality model — 3072 dimensions "embedding_large": openai_embedding_udf( column="body", model="text-embedding-3-large", ), # Same large model, truncated to 256 dimensions for storage efficiency "embedding_large_256": openai_embedding_udf( column="body", model="text-embedding-3-large", output_dimensionality=256, ), }) ``` ## Generation Generate text from OpenAI chat completion models. Supports both text and binary (image) input columns. See the [API reference](https://lancedb.github.io/geneva/api/openai/#geneva.udfs.openai.openai_udf) for all parameters. **Add a summary and an image caption in one call, using different models:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_udf table.add_columns({ # Fast model for bulk text summarization "summary": openai_udf( column="body", prompt="Summarize this document in 3 bullet points", model="gpt-5-mini", ), # More capable model for nuanced image captions "caption": openai_udf( column="image", prompt="Provide a 1 sentence description of the scene", model="gpt-5", mime_type="image/jpeg", ), }) ``` ## API Reference * [OpenAI](https://lancedb.github.io/geneva/api/openai/) — `openai_udf()` and `openai_embedding_udf()` — all parameters including `column`, `prompt`, `model`, `mime_type`, `dimensions`, and `normalize` # Sentence Transformers Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/providers/sentence-transformers Embed text using any HuggingFace Sentence Transformer model locally — no API key needed. See the [API reference](https://lancedb.github.io/geneva/api/embeddings/#geneva.udfs.text.embeddings.sentence_transformer_udf) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-sentence-transformers]' ``` > [!TIP] > > Sentence Transformer models run **locally** on your workers — there are no API calls and no > per-token costs. This makes them a good fit for large-scale embedding jobs where cost is a > concern. ## Embeddings **Compare a lightweight and a high-quality model side by side:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import sentence_transformer_udf table.add_columns({ # Lightweight default model — fast, CPU-friendly "embedding_mini": sentence_transformer_udf( column="body", model="sentence-transformers/all-MiniLM-L6-v2", ), # Larger model with GPU acceleration "embedding_bge": sentence_transformer_udf( column="body", model="BAAI/bge-large-en-v1.5", num_gpus=1.0, ), }) ``` ## GPU acceleration Sentence Transformer models can run on CPU or GPU. Smaller models like `all-MiniLM-L6-v2` work well on CPU, but larger models like `bge-large-en-v1.5` benefit significantly from GPU acceleration. Use the `num_gpus` parameter to request GPU resources for a worker: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # CPU-only (default) — suitable for lightweight models sentence_transformer_udf(column="body", model="sentence-transformers/all-MiniLM-L6-v2") # GPU-accelerated — recommended for larger models sentence_transformer_udf(column="body", model="BAAI/bge-large-en-v1.5", num_gpus=1.0) ``` Setting `num_gpus` to a fractional value (e.g., `0.5`) tells the [Ray scheduler](https://docs.ray.io/en/latest/ray-core/scheduling/accelerators.html) to co-locate multiple workers on the same physical GPU. For example, two UDFs with `num_gpus=0.5` will be scheduled on a single GPU. Note that Ray does not enforce GPU memory limits — it is your responsibility to ensure the combined models fit in GPU memory. ## API Reference * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `sentence_transformer_udf()` — all parameters including `column`, `model`, `num_gpus`, `normalize`, and `batch_size` # Chunkers (Scalar UDTFs) Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/scalar-udtfs Use chunkers (scalar UDTFs) for 1:N row expansion — split videos into clips, chunk documents, or tile images with automatic parent column inheritance and incremental refresh. Beta — introduced in Geneva 0.11.0 Standard UDFs produce exactly **one output value per input row**. **Chunkers** — also called scalar UDTFs — enable **1:N row expansion**: each source row can produce multiple output rows. The results are stored as a materialized view with MV-style incremental refresh. | Source Table | Derived Table | Expansion | | - | - | - | | 1 video row | → N clip rows | Video segmentation | | 1 document row | → N chunk rows | Text chunking | | 1 image row | → N tile rows | Image tiling | For example, a chunker that splits documents into passages turns a `documents` table into a `chunks` table, carrying the parent columns into every child row: **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is..." | | 2 | "Data Guide" | "Data pipelines are..." | **Derived: `chunks`** (1:N expansion) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning..." | | 1 | "Intro to AI" | 1 | "Neural networks..." | | 1 | "Intro to AI" | 2 | "Training data..." | | 2 | "Data Guide" | 0 | "Data pipelines..." | | 2 | "Data Guide" | 1 | "ETL processes..." | Parent columns (`doc_id`, `title`) are inherited automatically; `chunk_index` and `chunk_text` are generated by the chunker. ## Defining a Chunker Use the `@chunker` decorator on a function that **yields** output rows. Geneva infers the output schema from the return type annotation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import chunker from typing import Iterator, NamedTuple class Clip(NamedTuple): clip_start: float clip_end: float clip_bytes: bytes @chunker def extract_clips(video_path: str, duration: float) -> Iterator[Clip]: """Yields multiple clips per video.""" clip_length = 10.0 for start in range(0, int(duration), int(clip_length)): end = min(start + clip_length, duration) clip_data = extract_video_segment(video_path, start, end) yield Clip(clip_start=start, clip_end=end, clip_bytes=clip_data) ``` Input parameters are bound to source columns **by name** — the parameter `video_path` binds to source column `video_path`, just like standard UDFs. > [!TIP] > > A chunker can yield **zero rows** for a source row. The source row is still marked as processed and will not be retried on the next refresh. ### List return pattern If you prefer to build the full list in memory rather than yielding, you can return a `list` instead of an `Iterator`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @chunker def extract_clips(video_path: str, duration: float) -> list[Clip]: clips = [] for start in range(0, int(duration), 10): end = min(start + 10, duration) clips.append(Clip(clip_start=start, clip_end=end, clip_bytes=b"...")) return clips ``` ### Batched chunker For vectorized processing, use `batch=True`. The function receives Arrow arrays and returns a `RecordBatch` of expanded rows. Because the return type `pa.RecordBatch` cannot be inferred, you must supply `output_schema` explicitly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @chunker(batch=True, output_schema=clip_schema) def extract_clips(batch: pa.RecordBatch) -> pa.RecordBatch: """Process rows in batches. Same 1:N semantic per row.""" ... ``` ## Creating a Chunker View Chunkers use the `create_udtf_view` API (passing the chunker as the `udtf` argument): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva db = geneva.connect("/data/mydb") videos = db.open_table("videos") # Create the 1:N materialized view clips = db.create_udtf_view( "clips", source=videos.search(None).select(["video_path", "metadata"]), udtf=extract_clips, ) # Populate — runs the UDTF on every source row clips.refresh() ``` The `query` parameter controls which source columns are inherited. Columns listed in `.select()` are carried into every child row automatically. ## Inherited Columns Child rows automatically include the parent's columns — no manual join required. The columns available in the child table are determined by the query's `.select()`: ### `videos` table (source) | video_path | duration | metadata | | - | - | - | | /v/a.mp4 | 120.0 | \{fps: 30} | | /v/b.mp4 | 60.0 | \{fps: 24} | ### `clips` table (derived, 1:N) | video_path | metadata | clip_start | clip_end | clip_bytes | | - | - | - | - | - | | /v/a.mp4 | \{fps: 30} | 0.0 | 10.0 | b"\x00\x1a..." | | /v/a.mp4 | \{fps: 30} | 10.0 | 20.0 | b"\x00\x2b..." | | /v/a.mp4 | \{fps: 30} | 20.0 | 30.0 | b"\x00\x3c..." | | | | | | | | /v/b.mp4 | \{fps: 24} | 0.0 | 10.0 | b"\x00\x4d..." | | /v/b.mp4 | \{fps: 24} | 10.0 | 20.0 | b"\x00\x5e..." | The first three rows come from the `/v/a.mp4` source row, the last two from `/v/b.mp4`. Inherited columns (`video_path`, `metadata`) are carried over automatically; `clip_start`, `clip_end`, and `clip_bytes` are generated by the UDTF. ## Adding Computed Columns After Creation Since chunker views are materialized views, you can add UDF-computed columns to the child table and backfill them: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 512)) def clip_embedding(clip_bytes: bytes) -> list[float]: return embed_model.encode(clip_bytes) # Add an embedding column to the clips table clips.add_columns({"embedding": clip_embedding}) # Backfill computes embeddings for all existing clips clips.backfill("embedding") ``` This is a powerful pattern: expand source rows with a chunker, then enrich the expanded rows with standard UDFs. ## Incremental Refresh Chunkers support **incremental refresh**, just like standard materialized views: * **New source rows**: The UDTF runs on new rows, inserting child rows. * **Deleted source rows**: Child rows linked to the deleted parent are cascade-deleted. * **Updated source rows**: Old children are deleted, UDTF re-runs, new children inserted. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add new videos to the source table videos.add(new_video_data) # Incremental refresh — only processes the new videos clips.refresh() ``` Only the new source rows are processed. Existing clips from previous refreshes are untouched. ## Chaining Chunker Views Chunker views are standard materialized views, so they can serve as the source for further views: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # videos → clips (1:N) clips = db.create_udtf_view( "clips", source=videos.search(None), udtf=extract_clips ) # clips → frames (1:N) frames = db.create_udtf_view( "frames", source=clips.search(None), udtf=extract_frames ) ``` ## Full Example: Document Chunking ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import connect, chunker, udf from typing import Iterator, NamedTuple import pyarrow as pa class Chunk(NamedTuple): chunk_index: int chunk_text: str @chunker def chunk_document(text: str) -> Iterator[Chunk]: """Split a document into overlapping chunks.""" words = text.split() chunk_size = 500 overlap = 50 for i, start in enumerate(range(0, len(words), chunk_size - overlap)): chunk_words = words[start:start + chunk_size] yield Chunk(chunk_index=i, chunk_text=" ".join(chunk_words)) db = connect("/data/mydb") docs = db.open_table("documents") # Create chunked view — inherits doc_id, title, etc. from source chunks = db.create_udtf_view( "doc_chunks", source=docs.search(None).select(["doc_id", "title", "text"]), udtf=chunk_document, ) chunks.refresh() # Add embeddings to chunks for semantic search @udf(data_type=pa.list_(pa.float32(), 1536)) def embed_text(chunk_text: str) -> list[float]: return embedding_model.encode(chunk_text) chunks.add_columns({"embedding": embed_text}) chunks.backfill("embedding") # Backfills embeddings on all existing chunks # Query — parent columns available alongside chunk columns chunks.search(None).select(["doc_id", "title", "chunk_text", "embedding"]).to_pandas() ``` For a comparison of all three function types (UDFs, Chunkers, Batch UDTFs), see [Understanding Transforms](/enterprise/v1-12-0/geneva/udfs). Reference: * [`chunker` API](https://lancedb.github.io/geneva/api/udtf/#geneva.chunker) * [`create_udtf_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) # User-Defined Functions (UDFs) Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/udfs/udfs Define 1:1 transforms that add computed columns to your tables — embeddings, enrichment, scoring, and more. UDFs are the core building block for feature engineering in Geneva. A UDF wraps a Python function and applies it to every row in a table, producing exactly **one output value per input row** (1:1). Use UDFs to compute embeddings, enrich data with external APIs, transform formats, or derive new features from existing columns. ## Defining a UDF Converting your Python code to a Geneva UDF is simple. There are three kinds of UDFs that you can provide — scalar UDFs, batched UDFs and stateful UDFs. In all cases, Geneva uses Python type hints from your functions to infer the input and output [arrow data types](https://arrow.apache.org/docs/python/api/datatypes.html) that LanceDB uses. ### Scalar UDFs The **simplest** form is a scalar UDF, which processes one row at a time: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf @udf def area_udf(x: int, y: int) -> int: return x * y ``` This UDF will take the value of `x` and value of `y` from each row and return the product. The `@udf` wrapper is all that is needed. ### Batched UDFs For **better performance**, you can also define batch UDFs that process multiple rows at once. You can use `pyarrow.Array`s: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def batch_filename_len(filename: pa.Array) -> pa.Array: lengths = [len(str(f)) for f in filename] return pa.array(lengths, type=pa.int32()) ``` Or take entire rows using `pyarrow.RecordBatch`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def recordbatch_filename_len(batch: pa.RecordBatch) -> pa.Array: filenames = batch["filename"] lengths = [len(str(f)) for f in filenames] return pa.array(lengths, type=pa.int32()) ``` > **Note**: Batch UDFS require you to specify `data_type` in the `@udf` decorator for batched UDFs which defines `pyarrow.DataType` of the returned `pyarrow.Array`. ### Struct outputs A UDF can return multiple related values as a single `struct` column by setting `data_type` to a `pa.struct(...)` and returning a tuple (matched by field order) or a `dict` keyed by field name. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io import pyarrow as pa from geneva import udf @udf( data_type=pa.struct( [pa.field("width", pa.int32()), pa.field("height", pa.int32())] ), ) def dimensions(image: bytes) -> tuple[int, int]: """Extract image dimensions (width, height).""" from PIL import Image img = Image.open(io.BytesIO(image)) return img.size ``` Downstream UDFs can then read individual fields via dot notation in `input_columns` (see below). ### Struct fields and list inputs You can pass nested `struct` fields directly into a UDF by specifying `input_columns` with dot notation. For list-typed inputs, Geneva can pass a NumPy array when the argument is annotated as `np.ndarray` (use `np.ndarray | None` for nullable lists). ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa from geneva import udf struct_type = pa.struct([("vals", pa.list_(pa.int32()))]) schema = pa.schema([pa.field("info", struct_type)]) @udf(data_type=pa.int32(), input_columns=["info.vals"]) def sum_vals(vals: np.ndarray | None) -> int | None: if vals is None: return None assert isinstance(vals, np.ndarray) return int(np.sum(vals)) ``` ### Stateful UDFs You can also define a **stateful** UDF that retains its state across calls. This can be used to share code and **parameterize your UDFs**. In the example below, the model being used is a parameter that can be specified at UDF registration time. It can also be used to parameterize input column names of `pa.RecordBatch` batch UDFS. This also can be used to **optimize expensive initialization** that may require heavy resources on the distributed workers. For example, this can be used to load a model to the GPU once for all records sent to a worker instead of once per record or per batch of records. A stateful UDF is a `Callable` class, with `__call__()` method. The call method can be a scalar function or a batched function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import Callable from openai import OpenAI @udf(data_type=pa.list_(pa.float32(), 1536)) class OpenAIEmbedding(Callable): def __init__(self, model: str = "text-embedding-3-small"): self.model = model # Per-worker openai client self.client: OpenAI | None = None def __call__(self, text: str) -> pa.Array: if self.client is None: self.client = OpenAI() resp = self.client.embeddings.create(model=self.model, input=text) return pa.array(resp.data[0].embeddings) ``` > [!TIP] > > For common providers like OpenAI and Gemini, Geneva ships [built-in UDFs](/enterprise/v1-12-0/geneva/udfs/providers) that handle API keys, retries, and batching for you — no custom class needed. > **Note**: The state is will be independently managed on each distributed Worker. ## UDF options The `udf` can have extra annotations that specify resource requirements and operational characteristics. These are just add parameters to the `udf(...)`. ### Resource requirements for UDFs Some workers may require specific resources such as gpus, cpus and certain amounts of RAM. You can provide these requirements by adding `num_cpus`, `num_gpus`, and `memory` parameters to the UDF. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(num_cpus=1, num_gpus=0.5, memory=4 * 1024**3) def transform(value: str) -> str: # Replace this body with your transformation. return value ``` ### Operational parameters for UDFs #### checkpoint_size `checkpoint_size` controls how many rows are processed before checkpointing, and therefore reporting and saving progress. UDFs can be quite varied: some can be simple operations where thousands of calls can be completed per second, while others may be slow and require 30s per row. So a simple default like "every 1000 rows" might write once a second or once every 8 hours! Geneva will handle this internally, using an experimental feature that will adapt checkpoint sizing as a UDF progresses. However, if you want to see writes more or less frequently, you can set this manually. There are three parameters: * `checkpoint_size`: the seed for the initial checkpoint size * `min_checkpoint_size`: the minimum value that Geneva will use while adapting checkpoint size * `max_checkpoint_size`: the maximum value that Geneva will use while adapting checkpoint size Therefore, to force a checkpoint size (and effectively disable adaptive batch sizing), set all three of these parameters to the same value. ### Error handling Depending on the UDF, you may want Geneva to ignore rows that hit failures, retry, or fail the entire job. For simple cases, Geneva provides a simple parameter, `on_error`, with the following options: | Function | Behavior | | - | - | | `retry_transient()` | Retry `ConnectionError`, `TimeoutError`, `OSError` with exponential backoff | | `retry_all()` | Retry any exception with exponential backoff | | `skip_on_error()` | Return `None` for any exception (skip the row) | | `fail_fast()` | Fail immediately on any exception (default behavior) | If those are not specific enough, Geneva also provides [many more error handling options](/enterprise/v1-12-0/geneva/udfs/error_handling). ## Registering Features with UDFs Registering a feature is done by providing the `Table.add_columns()` function a new column name and the Geneva UDF. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva import numpy as np import pyarrow as pa lancedb_uri="gs://bucket/db" db = geneva.connect(lancedb_uri) # Define schema for the video table schema = pa.schema([ ("filename", pa.string()), ("duration_sec", pa.float32()), ("x", pa.int32()), ("y", pa.int32()), ]) tbl = db.create_table("videos", schema=schema, mode="overwrite") # Generate fake data N = 10 data = { "filename": [f"video_{i}.mp4" for i in range(N)], "duration_sec": np.random.uniform(10, 300, size=N).astype(np.float32), "x": np.random.choice([640, 1280, 1920], size=N), "y": np.random.choice([360, 720, 1080], size=N), "caption": [f"this is video {i}" for i in range(N)] } # Convert to Arrow Table and add to LanceDB batch = pa.table(data, schema=schema) tbl.add(batch) ``` Here's how to register a simple UDF: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf def area_udf(x: int, y: int) -> int: return x * y @udf def download_udf(filename: str) -> bytes: ... # {'new column name': <udf>, ...} # simple_udf's arguments are `x` and `y` so the input columns are # inferred to be columns `x` amd `y` tbl.add_columns({"area": area_udf, "content": download_udf }) ``` ### Registering Multi-Output UDFs Use a multi-output UDF when one expensive read or decode can produce several features. For example, if a table stores image bytes, a single UDF can open the image once and return `height`, `width`, and an embedding column together. This avoids separate UDFs that would each read or decode the same image. Define the output shape with `typing.NamedTuple` and annotate the UDF return type as `geneva.Columns[YourNamedTuple]`. Passing that UDF directly to [`Table.add_columns()`](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) expands the result into multiple sibling columns using the `NamedTuple` field names. If those names need a namespace or would conflict with existing columns, wrap the UDF with `geneva.UnpackedUDF(udf, prefix="...")` before calling `add_columns()`. The prefix is added to each materialized column name while keeping the outputs in one logical feature group. Manage multi-output sibling columns as a group. Backfill, drop, or alter the full group together instead of changing only one sibling column. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from typing import NamedTuple import geneva from PIL import Image db = geneva.connect("/data/mydb") tbl = db.open_table("images") class ImageFeatures(NamedTuple): height: int width: int embedding: list[float] @geneva.udf def image_features(image: bytes) -> geneva.Columns[ImageFeatures]: img = Image.open(io.BytesIO(image)) # Read and decode the image once. embedding = embedding_model.encode(img) return ImageFeatures( height=img.height, width=img.width, embedding=embedding, ) # Adds sibling columns named "height", "width", and "embedding". tbl.add_columns(image_features) # Or add the same outputs with a prefix to avoid name conflicts. tbl.add_columns(geneva.UnpackedUDF(image_features, prefix="image_")) ``` Batched UDFs require return type in their `udf` annotations ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32()) def batch_filename_len(filename: pa.Array) -> pa.Array: ... # {'new column name': <udf>} # batch_filename_len's input, `filename` input column is # specified by the UDF's argument name. tbl.add_columns({"filename_len": batch_filename_len}) ``` or ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32()) def recordbatch_filename_len(batch: pa.RecordBatch) -> pa.Array: ... # {'new column name': <udf>} # batch_filename_len's input. pa.RecordBatch typed UDF # argument pulls in all the column values for each row. tbl.add_columns({"filename_len": recordbatch_filename_len}) ``` Similarly, a stateful UDF is registered by providing an instance of the Callable object. The call method may be a per-record function or a batch function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 1536)) class OpenAIEmbedding(Callable): ... def __call__(self, text: str) -> pa.Array: ... # OpenAIEmbedding's call method input is inferred to be 'text' of # type string from the __call__'s arguments, and its output type is # a fixed size list of float32. tbl.add_columns({"embedding": OpenAIEmbedding()}) ``` ## Changing data in computed columns Let's say you backfilled data with your UDF then you noticed that your data has some issues. Here are a few scenarios: 1. All the values are incorrect due to a bug in the UDF. 2. Most values are correct but some values are incorrect due to a failure in UDF execution. 3. Values calculated correctly and you want to perform a second pass to fixup some of the values. In scenario 1, you'll most likely want to replace the UDF with a new version and recalculate all the values. You should perform a `alter_table` and then `backfill`. In scenario 2, you'll most likely want to re-execute `backfill` to fill in the values. If the error is in your code (certain cases not handled), you can modify the UDF, and perform an `alter_table`, and then `backfill` with some filters. In scenario 3, you have a few options. A) You could `alter` your UDF and include the fixup operations in the UDF. You'd `alter_table` and then `backfill` recalculating all the values. B) You could have a chain of computed columns -- create a new column, calculate the "fixed" up values and have your application use the new column or a combination of the original column. This is similar to A but does not recalculate A and can incur more storage. C) You could `update` the values in the column with the fixed up values. This may be expedient but also sacrifices reproducibility. The next section shows you how to change your column definition by `alter`ing the UDF. ## Altering UDFs You now want to revise the code. To make the change, you'd update the UDF used to compute the column using the `alter_columns` API and the updated function. The example below replaces the definition of column `area` to use the `area_udf_v2` function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.alter_columns({"path": "area", "udf": area_udf_v2} ) ``` After making this change, the existing data already in the table does not change. However, when you perform your next basic `backfill` operation, all values would be recalculated and updated. If you only wanted some rows updated, you could perform a filtered backfill, targeting the specific rows that need the new upates. For example, this filter would only update the rows where area was currently null. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.backfill("area", where="area is null") ``` ## Auto-backfill For columns whose values should always stay in sync with their source data, set `auto_backfill=True` on the UDF. On LanceDB Enterprise (`db://` connections), the column is then recomputed for you automatically — you don't need to call `backfill()` yourself. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32(), version="2", auto_backfill=True) def area_udf(x: int, y: int) -> int: return x * y # Register a new auto-backfill column... tbl.add_columns({"area": area_udf}) # ...or re-point an existing column to an auto-backfill UDF tbl.alter_columns({"path": "area", "udf": area_udf}) ``` ### How it works The `auto_backfill` flag is recorded in the column's metadata when the column is added or altered. LanceDB Enterprise's managed agent watches for columns that need recomputation and dispatches a [distributed backfill job](/enterprise/v1-12-0/geneva/jobs/backfilling/) automatically — there is no manual trigger and no status polling. A column is recomputed when, for example: * **New rows are added** to the table (`tbl.add(...)`), leaving the column null for those rows. * **The UDF version changes** — you bump `version=` and `alter_columns()` to the new function. > [!NOTE] > > Auto-backfill is an enterprise feature. On direct object-storage or local-filesystem > connections there is no managed agent, so `auto_backfill=True` has no effect and you must run > `backfill()` explicitly. Reference: * [`alter_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.alter_columns) * [`add_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) * [UDF](https://lancedb.github.io/geneva/api/udf/) — full `@udf` decorator reference including `data_type`, `num_gpus`, `auto_backfill`, `batch_size`, and other options # LanceDB Source: https://docs.lancedb.com/enterprise/v1-12-0/index Multimodal lakehouse for AI. **LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need one data layer for curation, feature engineering, search and retrieval, and model training. It is built on top of [Lance](/enterprise/v1-12-0/basics/lance), an open-source lakehouse format designed for multimodal AI data. Move from data exploration to model training on one unified platform without needing to manage a fragmented stack of storage, feature, retrieval, and training systems. ## Train on the right data faster Search, curate, and train at petabyte scale, with all your multimodal data in one table. Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. ## Accelerate the data flywheel for model research Keep your AI data in one table. Find the failure, fix the data, and retrain. **1. Find a curated training subset for every failure case** Start from one failed grasp or evaluation example. [Search](/enterprise/v1-12-0/search/) multimodal data, metadata, and embeddings together, retrieve similar examples, and [curate](/enterprise/v1-12-0/curation) them into a targeted training subset. **2. A single dataset for every modality** Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without pipelines to keep them in sync. Table [versions](/enterprise/v1-12-0/management/table#versioning) let you trace each training run back to the exact data it used. **3. More hillclimbing, less babysitting preprocessing jobs** Define the [computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) and [materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views) your experiment needs, such as extracted features or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background jobs on the cluster instead of in your code. **4. Higher GPU utilization, faster convergence** Keep GPUs fed. [`StreamingDataset`](/enterprise/v1-12-0/training/data-loading) streams multimodal training data into PyTorch with globally shuffled, deterministic batches, combining fast random access with high-throughput scans. Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected through the same table model, whether a workflow uses one table or several related ones. ## Architecture: Embedded and Enterprise LanceDB ships as two offerings on the same [Lance](/enterprise/v1-12-0/basics/lance) format and table model, which stores table data, versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale, managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and retrieval, and training workflows. > [card] [LanceDB Embedded](/enterprise/v1-12-0/basics/lancedb-embedded) > > An open-source, embedded retrieval library that runs inside your application process, with no separate > database server to deploy. > [card] [LanceDB Enterprise](/enterprise/v1-12-0/enterprise/index) > > A distributed multimodal lakehouse service for production workloads that need managed infrastructure and > higher-throughput workflows. See [Embedded vs Enterprise](/enterprise/v1-12-0/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including architecture, latency, throughput, and day-to-day usage differences. ## Projects using LanceDB ### Training * [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a fraction of the disk footprint. * [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on the stable-worldmodel platform and its LanceDB data layer. * [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace LeRobot datasets with faster loading across robotics datasets. ### Agentic applications * [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. * [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent memory across sessions, using LanceDB as one of its vector store backends. * [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, features, and training or memory access patterns in one format instead of scattering them across task-specific stores. ## Start with your workload > [card] [Ingest your data](/enterprise/v1-12-0/ingestion) > > Create tables, append records, and update or delete rows as your data changes. > [card] [Build search and retrieval](/enterprise/v1-12-0/search/) > > Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. > [card] [Curate training data](/enterprise/v1-12-0/curation) > > Profile, sample, chunk, join, and deduplicate records before training on them. > [card] [Engineer features in place](/enterprise/v1-12-0/feature-engineering) > > Derive computed columns and materialized views without moving data elsewhere. > [card] [Load data into PyTorch](/enterprise/v1-12-0/training/data-loading) > > Use LanceDB tables and permutations for projected, shuffled, random-access training reads. > [card] [Manage catalog objects](/enterprise/v1-12-0/management) > > Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. # Creating a table Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/create-table Create a table from records or a schema and choose input formats. **Applies to:** Embedded ✅, Enterprise ✅ Create a table from existing records, or define an empty table before data arrives. Define a schema to specify column types, allow or disallow missing values, and set the size of your vectors. ## Create a table with data The Python, TypeScript and Rust blocks below illustrate the corresponding input formats; each assumes a `db` connection already open, as in [Connect to LanceDB](/enterprise/v1-12-0/basics/catalog). For a complete connection-to-result program, expand [the write workflow](#complete-example). Table names follow the [naming rules](/enterprise/v1-12-0/basics/naming). ### From list of objects You can provide a list of objects to create a table. The Python and TypeScript SDKs support lists/arrays of records. The Rust example converts structs to Arrow batches. In Python, pass a list or other batch-like object; a single bare `dict` or single `LanceModel` is rejected. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1}, ] db.create_table("test_table", data, mode="overwrite") tbl = db["test_table"] tbl.head() print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} type Location = { vector: number[]; lat: number; long: number; }; const data: Location[] = [ { vector: [1.1, 1.2], lat: 45.5, long: -122.7 }, { vector: [0.2, 1.8], lat: 40.1, long: -74.1 }, ]; const table = await db.createTable("test_table", data, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} struct Location { vector: [f32; 2], lat: f32, long: f32, } let data = vec![ Location { vector: [1.1, 1.2], lat: 45.5, long: -122.7, }, Location { vector: [0.2, 1.8], lat: 40.1, long: -74.1, }, ]; let schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( data.iter() .map(|row| Some(row.vector.iter().copied().map(Some).collect::<Vec<_>>())), 2, ), ), Arc::new(Float32Array::from_iter_values( data.iter().map(|row| row.lat), )), Arc::new(Float32Array::from_iter_values( data.iter().map(|row| row.long), )), ], ) .unwrap(); let reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema.clone())); let table = db .create_table("test_table", reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### If the table already exists By default, creating a table fails if its name is already in use. Choose whether to open that table or overwrite it. #### Open the existing table Use `exist_ok=True` in Python or `existOk: true` in TypeScript to return the existing table without changing its contents. This is useful for setup code that may run more than once. Any data supplied to the create call is ignored when the table already exists. Inspect the returned table's schema if your code depends on specific columns or types. Opening an existing table does not change its schema to match the data supplied in the create call. #### Overwrite the table Use `mode="overwrite"` in Python or `mode: "overwrite"` in TypeScript to replace the existing table with the supplied data and schema. Choose this only when you intend to replace its previous contents. The following Python program demonstrates both choices: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("conflict_table", data) # Idempotent open: reuse the existing table if it exists. # The provided data is ignored; the schema is validated against the # existing table and a mismatch raises an error. tbl = db.create_table("conflict_table", data, exist_ok=True) # Overwrite: replace the contents with the provided data. tbl = db.create_table("conflict_table", data, mode="overwrite") print("Rows:", tbl.count_rows()) ``` > [!NOTE] > > `exist_ok` / `existOk` does not append the provided data to an existing table. Use > [`table.add()`](/enterprise/v1-12-0/ingestion/insert) for that. If you need to ensure a table exists *and* > contains specific rows, choose an explicit [merge policy](/enterprise/v1-12-0/ingestion/merge-insert). Creating an empty table > and repeatedly appending the same batch does not deduplicate it. ### From a custom schema You can define a custom Arrow schema for the table. This is useful when you want to have more control over the column types and metadata. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa custom_schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 4)), pa.field("lat", pa.float32()), pa.field("long", pa.float32()), ] ) data = [ {"vector": [1.1, 1.2, 1.3, 1.4], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8, 0.4, 3.6], "lat": 40.1, "long": -74.1}, ] tbl = db.create_table( "my_table_custom_schema", data, schema=custom_schema, mode="overwrite" ) print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const customSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("lat", new arrow.Float32()), new arrow.Field("long", new arrow.Float32()), ]); const customSchemaData = lancedb.makeArrowTable( [ { vector: [1.1, 1.2, 1.3, 1.4], lat: 45.5, long: -122.7 }, { vector: [0.2, 1.8, 0.4, 3.6], lat: 40.1, long: -74.1 }, ], { schema: customSchema }, ); const customSchemaTable = await db.createTable( "my_table_custom_schema", customSchemaData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let custom_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let custom_batch = RecordBatch::try_new( custom_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(1.1), Some(1.2), Some(1.3), Some(1.4)]), Some(vec![Some(0.2), Some(1.8), Some(0.4), Some(3.6)]), ], 4, ), ), Arc::new(Float32Array::from(vec![45.5, 40.1])), Arc::new(Float32Array::from(vec![-122.7, -74.1])), ], ) .unwrap(); let custom_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(custom_batch)].into_iter(), custom_schema.clone())); let custom_table = db .create_table("my_table_custom_schema", custom_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` An explicit schema also determines which columns accept missing values (`null`). If later writes omit a non-nullable column, or provide actual nulls for it, ingestion fails; nullable columns can be omitted or written with null values. Without an explicit schema, Python infers list-like vector values as fixed-size `float32` vector fields from the observed dimension. For images, audio, video, or other binary columns whose payloads should load on demand, declare a [blob column](/enterprise/v1-12-0/management/table#multimodal-blob-v2) in the schema. For Python ingestion, malformed vectors fail by default (`on_bad_vectors="error"`). This includes vectors with incorrect sizes, NaNs, or null components, including pandas NaNs converted to Arrow nulls. Use `"drop"` to remove affected rows, or `"null"` to replace affected vectors with nulls. Use `"fill"` to replace NaN or null components with `fill_value` while preserving valid components. This also pads short vectors with `fill_value` and truncates long vectors to the expected dimension. ### From an Arrow Table You can also create LanceDB tables directly from Arrow tables. Rust uses an Arrow `RecordBatchReader` for the same Arrow-native ingest flow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa dim = 16 total = 2 schema = pa.schema( [ pa.field("vector", pa.list_(pa.float16(), dim)), pa.field("text", pa.string()), ] ) data = pa.Table.from_arrays( [ pa.array( [np.random.randn(dim).astype(np.float16) for _ in range(total)], pa.list_(pa.float16(), dim), ), pa.array(["foo", "bar"]), ], ["vector", "text"], ) tbl = db.create_table("f16_tbl", data, schema=schema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const arrowSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 16, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("text", new arrow.Utf8()), ]); const arrowData = lancedb.makeArrowTable( [ { vector: Array(16).fill(0.1), text: "foo" }, { vector: Array(16).fill(0.2), text: "bar" }, ], { schema: arrowSchema }, ); const arrowTable = await db.createTable("f32_tbl", arrowData, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let arrow_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 16), false, ), Field::new("text", DataType::Utf8, false), ])); let arrow_batch = RecordBatch::try_new( arrow_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1); 16]), Some(vec![Some(0.2); 16])], 16, ), ), Arc::new(StringArray::from(vec!["foo", "bar"])), ], ) .unwrap(); let arrow_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(arrow_batch)].into_iter(), arrow_schema.clone())); let arrow_table = db .create_table("arrow_table_example", arrow_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### From a Pandas DataFrame Python Only ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pandas as pd data = pd.DataFrame( { "vector": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]], "lat": [45.5, 40.1], "long": [-122.7, -74.1], } ) db.create_table("my_table_pandas", data, mode="overwrite") db["my_table_pandas"].head() ``` > [!NOTE] > > Data is converted to Arrow before being written to disk. For maximum control over how data is saved, either provide the PyArrow schema to convert to or else provide a PyArrow Table directly. > [!NOTE] > > The **`vector`** column needs to be a [Vector](/enterprise/v1-12-0/integrations/data/pydantic#vector-field) (defined as [pyarrow.FixedSizeList](https://arrow.apache.org/docs/python/generated/pyarrow.list_.html)) type. ### From a Polars DataFrame Python Only Pass a Polars DataFrame as input. Install `polars` for this example; the conversion preserves the table structure through Arrow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import polars as pl data = pl.DataFrame( { "vector": [[3.1, 4.1], [5.9, 26.5]], "item": ["foo", "bar"], "price": [10.0, 20.0], } ) tbl = db.create_table("my_table_pl", data, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ### From Pydantic Models Python Only When you create an empty table without data, you must specify the table schema. LanceDB supports creating tables by specifying a PyArrow schema or a specialized Pydantic model called `LanceModel`. For example, the following Content model specifies a table with 5 columns: `movie_id`, `vector`, `genres`, `title`, and `imdb_id`. When you create a table, you can pass the class as the value of the `schema` parameter to `create_table`. The `vector` column is a `Vector` type, which is a specialized Pydantic type that can be configured with the vector dimensions. It is also important to note that LanceDB only understands subclasses of `lancedb.pydantic.LanceModel` (which itself derives from `pydantic.BaseModel`). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector class Content(LanceModel): movie_id: int vector: Vector(128) genres: str title: str imdb_id: int @property def imdb_url(self) -> str: return f"https://www.imdb.com/title/tt{self.imdb_id}" tbl = db.create_table("movielens_small", schema=Content, mode="overwrite") print("Rows:", tbl.count_rows()) ``` #### Nested schemas Sometimes your data model may contain nested objects. For example, you may want to store the document string and the document source name as a nested Document object: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pydantic import BaseModel class Document(BaseModel): content: str source: str ``` This can be used as the type of a LanceDB table column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector from pydantic import BaseModel class Document(BaseModel): content: str source: str class NestedSchema(LanceModel): id: str vector: Vector(1536) document: Document tbl = db.create_table("nested_table", schema=NestedSchema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` This creates a struct column called "document" that has two subfields called "content" and "source": ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} In [28]: tbl.schema Out[28]: id: string not null vector: fixed_size_list<item: float>[1536] not null child 0, item: float document: struct<content: string not null, source: string not null> not null child 0, content: string not null child 1, source: string not null ``` #### Validators Because `LanceModel` inherits from Pydantic's `BaseModel`, you can combine them with Pydantic's [field validators](https://docs.pydantic.dev/latest/concepts/validators). The example below shows how to add a validator to ensure that only valid timezone-aware datetime objects are used for a `created_at` field. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import datetime from zoneinfo import ZoneInfo from lancedb.pydantic import LanceModel from pydantic import Field, ValidationError, ValidationInfo, field_validator tzname = "America/New_York" tz = ZoneInfo(tzname) class TestModel(LanceModel): dt_with_tz: datetime = Field(json_schema_extra={"tz": tzname}) @field_validator("dt_with_tz") @classmethod def tz_must_match(cls, dt: datetime) -> datetime: assert dt.tzinfo == tz return dt ok = TestModel(dt_with_tz=datetime.now(tz)) try: TestModel(dt_with_tz=datetime.now(ZoneInfo("Asia/Shanghai"))) assert 0 == 1, "this should raise ValidationError" except ValidationError: print("A ValidationError was raised.") pass ``` The example catches a `ValidationError` for the timestamp with a different timezone. A validator runs when the Pydantic model is constructed; declaring a model as the table schema does not make every later write run that validator. > [!NOTE] > > Datasets too large to pass to `create_table` at once are covered separately; > see [Insert data](/enterprise/v1-12-0/ingestion/insert#large-datasets) for batches, file-backed > input and write parallelism. ## Create empty table You can create an empty table for scenarios where you want to add data to the table later. An example would be when you want to collect data from a stream/external file and then add it to a table in batches. An empty table can be initialized via an Arrow schema. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 2)), pa.field("item", pa.string()), pa.field("price", pa.float32()), ] ) tbl = db.create_table("test_empty_table", schema=schema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const emptySchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 2, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("item", new arrow.Utf8()), new arrow.Field("price", new arrow.Float32()), ]); const emptyTable = await db.createEmptyTable( "test_empty_table", emptySchema, { mode: "overwrite", }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let empty_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("item", DataType::Utf8, false), Field::new("price", DataType::Float32, false), ])); let empty_table = db .create_empty_table("test_empty_table", empty_schema) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` Alternatively, define the schema with `LanceModel`, a Pydantic model class provided by `lancedb.pydantic`. Its `Vector` type declares a fixed vector dimension. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector class Item(LanceModel): vector: Vector(2) item: str price: float tbl = db.create_table( "test_empty_table_new", schema=Item.to_arrow_schema(), mode="overwrite" ) print("Rows:", tbl.count_rows()) ``` Once the empty table has been created, you can append to it or modify its contents, as explained in [Ingesting data](/enterprise/v1-12-0/ingestion). ## Open an existing table You can open an existing table by specifying the name of the table to the `open_table` / `openTable` method. If you forget the name of your table, you can always get a listing of all table names. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("test_table", data, mode="overwrite") # List table names print(db.list_tables().tables) # Open existing table tbl = db.open_table("test_table") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const openTableData = [{ vector: [1.1, 1.2], lat: 45.5, long: -122.7 }]; await db.createTable("test_table_open", openTableData, { mode: "overwrite", }); console.log(await db.tableNames()); const openedTable = await db.openTable("test_table_open"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let open_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let open_batch = RecordBatch::try_new( open_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(1.1), Some(1.2)])], 2, ), ), Arc::new(Float32Array::from(vec![45.5])), Arc::new(Float32Array::from(vec![-122.7])), ], ) .unwrap(); let open_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(open_batch)].into_iter(), open_schema.clone())); db.create_table("test_table", open_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); println!("{:?}", db.table_names().execute().await.unwrap()); let opened_table = db.open_table("test_table").execute().await.unwrap(); ``` ## Drop a table Use the `drop_table()` method on the database to remove a table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5}] db.create_table("my_table", data, mode="overwrite") # Drop the table db.drop_table("my_table") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.createTable("my_table", [{ vector: [1.1, 1.2], lat: 45.5 }], { mode: "overwrite", }); await db.dropTable("my_table"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let drop_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), ])); let drop_batch = RecordBatch::try_new( drop_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(1.1), Some(1.2)])], 2, ), ), Arc::new(Float32Array::from(vec![45.5])), ], ) .unwrap(); let drop_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(drop_batch)].into_iter(), drop_schema.clone())); db.create_table("my_table", drop_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); db.drop_table("my_table", &[]).await.unwrap(); ``` Dropping a table removes the table object. Deleting rows keeps the table and changes its contents; retained versions and cleanup are described in [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup). On a local database, dropping a table that does not exist raises an error; in Python, pass `ignore_missing=True` to suppress it. A deployment may report success instead, depending on how it stores its catalog, so do not rely on the error to tell you a table was missing. Python's deployment connection does not take `ignore_missing`. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Define Storage Integration Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/define-storage-integration Set up a reusable credential for AWS, GCP, Azure or HuggingFace before importing data from it. **Applies to:** Embedded ❌, Enterprise ✅ Before you can [import data](/enterprise/v1-12-0/ingestion/import) from external storage or [attach an existing database](/enterprise/v1-12-0/ingestion/migrate-from-embedded), define a storage integration once per location. It is a namespace-scoped catalog object that stores the credential -- neither operation names the integration directly, LanceDB matches the URI you read against whichever integration's prefix covers it. ## What each provider needs | Provider | Credential | Notes | | - | - | - | | AWS S3 | An IAM role to assume, or a static access key pair | A role needs one extra step outside LanceDB: [trust policy setup](#trust). | | Google Cloud Storage | A service account's JSON key | No role-based alternative. | | Azure Blob Storage | A service principal's tenant, client ID and client secret | All three required together. | | HuggingFace | An access token | Always required to create an integration. For anonymous access at HuggingFace's default rate limits, register no integration for that prefix instead. | Every credential option takes a [Secret](/enterprise/v1-12-0/management/secret) reference, never the value directly -- create the Secret first. ## Create one ### AWS S3 Give either an IAM role to assume, or a static access key pair -- mixing the two, or supplying only one half of the key pair, is refused. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ACCESS_KEY_ID_SECRET = aws_key_id STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = aws_key_secret ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "raw", "s3://customer-data/raw/", storage_provider="S3", aws_role_arn="arn:aws:iam::123456789012:role/lancedb-access", ) db.create_storage_integration( "raw", "s3://customer-data/raw/", storage_provider="S3", aws_access_key_id_secret="aws_key_id", aws_secret_access_key_secret="aws_key_secret", ) ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::storage_integration::CreateStorageIntegrationRequest; let info = db.create_storage_integration( "raw", CreateStorageIntegrationRequest::s3( "s3://customer-data/raw/", "arn:aws:iam::123456789012:role/lancedb-access", ), &[], ).await?; ``` ### Google Cloud Storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION gcs STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = 'gs://customer-data/raw/' GCP_CREDENTIALS_JSON_SECRET = gcp_service_account ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "gcs", "gs://customer-data/raw/", storage_provider="GCP", gcp_credentials_json_secret="gcp_service_account", ) ``` The Secret holds the full service-account JSON key. GCP has no role-based alternative. ### Azure Blob Storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION blobs STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = 'az://customer-data/raw/' STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' STORAGE_AZURE_TENANT_ID_SECRET = azure_tenant STORAGE_AZURE_CLIENT_ID_SECRET = azure_client STORAGE_AZURE_CLIENT_SECRET_SECRET = azure_credential ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "blobs", "az://customer-data/raw/", storage_provider="AZURE", azure_storage_account="customeraccount", azure_tenant_id_secret="azure_tenant", azure_client_id_secret="azure_client", azure_client_secret_secret="azure_credential", ) ``` All four options are required together; there is no role-based alternative for Azure. ### HuggingFace ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "hub", "hf://datasets/owner/private/data/", storage_provider="HUGGINGFACE", huggingface_token_secret="hf_token", ) ``` `HUGGINGFACE_TOKEN_SECRET` is required to create this integration; omitting it is rejected, not treated as anonymous. For anonymous access at HuggingFace's default rate limits, register no integration for that prefix at all. ### Finish the AWS trust policy An IAM role integration needs one step outside LanceDB: describing it returns the `trust_policy` and `permissions_policy` documents your role needs. Attach them in AWS, then describe the integration again and check `access_verified` to confirm LanceDB can assume the role. A static access key pair skips this step entirely. See [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) for every provider's complete option reference, S3's two credential modes in full, and the output schema, or [Storage Integration](/enterprise/v1-12-0/management/storage-integration) for the Python and SQL CRUD operations at a glance. ## What to read next > [card] [Import Datasets](/enterprise/v1-12-0/ingestion/import) > > Read or import through the integration once it exists. > [card] [Attach Database](/enterprise/v1-12-0/ingestion/migrate-from-embedded) > > Attach an existing database at a location the integration covers. > [card] [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) > > The complete SQL reference: every provider's options and output columns. # Delete rows Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/delete Select and delete records, verify the remaining rows, and understand storage retention. **Applies to:** Embedded ✅, Enterprise ✅ Deleting rows removes matching records from the current table contents. It keeps the table and schema so you can continue reading and writing. To remove the table itself, see [Drop a table](/enterprise/v1-12-0/ingestion/create-table#drop-a-table). ## Inspect the rows you intend to delete Use the same predicate for inspection and deletion. The example below creates Alice, Bob and Charlie, prints Charlie's row, and deletes it by `id = 3`. Inspection and deletion are separate operations; concurrent writes can change which rows match between them. ## Delete matching records Each program creates Alice, Bob and Charlie in a temporary local database, deletes Charlie, and prints the remaining rows: **Alice and Bob**. The temporary database is removed when the program finishes. * **Python:** install `lancedb`, save the code as `delete_rows.py`, and run `python delete_rows.py`. * **TypeScript:** install `@lancedb/lancedb`, save the code as `delete_rows.mts`, and run `node delete_rows.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 delete`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table( "users", [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}, ], ) predicate = "id = 3" print("Selected:", table.search().where(predicate).to_list()) table.delete(predicate) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print("Remaining:", rows) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const lancedb = await import("@lancedb/lancedb"); const { mkdtemp, rm } = await import("node:fs/promises"); const { tmpdir } = await import("node:os"); const { join } = await import("node:path"); const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); try { const db = await lancedb.connect(uri); const table = await db.createTable("users", [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" }, ]); const predicate = "id = 3"; console.log("Selected:", await table.query().where(predicate).toArray()); await table.delete(predicate); const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); console.log("Remaining:", rows); } finally { await rm(uri, { recursive: true, force: true }); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; use lancedb::query::{ExecutableQuery, QueryBase}; fn make_users_reader(rows: &[(i64, &str)]) -> Box<dyn RecordBatchReader + Send> { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), ], ) .unwrap(); Box::new(RecordBatchIterator::new( vec![Ok(batch)].into_iter(), schema, )) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let directory = tempfile::tempdir()?; let db = lancedb::connect(directory.path().to_str().unwrap()) .execute() .await?; let table = db .create_table( "users", make_users_reader(&[(1, "Alice"), (2, "Bob"), (3, "Charlie")]), ) .execute() .await?; let predicate = "id = 3"; let selected: Vec<RecordBatch> = table .query() .only_if(predicate) .execute() .await? .try_collect() .await?; println!("Selected: {selected:?}"); table.delete(predicate).await?; let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; println!("Remaining: {rows:?}"); assert_eq!(table.count_rows(None).await?, 2); assert_eq!( table .count_rows(Some("id = 1 AND name = 'Alice'".into())) .await?, 1 ); assert_eq!( table .count_rows(Some("id = 2 AND name = 'Bob'".into())) .await?, 1 ); assert_eq!(table.count_rows(Some("id = 3".into())).await?, 0); Ok(()) } ``` Enterprise also supports [`DELETE`](/enterprise/v1-12-0/sql/dml/delete). ## Verify that the rows are absent Query the same predicate after deletion and check the remaining row count. A reader still using an older snapshot may see the earlier contents; see [Consistency](/enterprise/v1-12-0/tables/consistency). Deleted rows are excluded from current query results, including indexed searches. Deletion does not imply immediate physical erasure of every stored copy of the data. ## Understand storage reclamation Compaction rewrites the live data layout; cleanup removes eligible retained versions and files. Retained history can continue to reference data that no longer appears in the latest table version. In LanceDB Embedded, `optimize()` provides maintenance operations. In Enterprise, managed maintenance and retention follow the service configuration. Choose retention according to the history you need, rather than shortening it as part of a routine delete example. See [Compaction](/enterprise/v1-12-0/maintenance/compaction) and [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup) for the separate maintenance workflow. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Import Datasets Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/import Create a table directly from a HuggingFace dataset or an existing Lance dataset in object storage, with one CREATE TABLE AS SELECT. **Applies to:** Embedded ❌, Enterprise ✅ A `CREATE TABLE ... AS SELECT` (CTAS) reads directly from a HuggingFace dataset or an existing Lance dataset in object storage, once a [storage integration](/enterprise/v1-12-0/ingestion/define-storage-integration) covers that location -- the integration is never named in the statement, LanceDB matches it by URI prefix. ## Import a HuggingFace dataset ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' ``` See [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets#import) for the full workflow, including querying a dataset directly without importing it first. ## Import a Lance dataset from object storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE events_copy AS SELECT * FROM 's3://customer-data/raw/events.lance' ``` An `s3://`, `gs://` or `az://` prefix reads an existing **Lance** dataset the same way as a managed table -- use this to copy a dataset another process already wrote in Lance format, not an arbitrary file format. See [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration#read-import) for GCS and Azure examples. ## How the import runs See [Distributed Write](/enterprise/v1-12-0/enterprise/distributed-write) for how an import's writes divide across plan executors, and when a small import instead runs as one local task. > [!NOTE] > > Importing requires a native database with `database_manifest_enabled`. > Combining a HuggingFace source with a WAL-backed destination table in one > CTAS is rejected, since the import cannot publish a base-only read that > omits the destination's unflushed data. ## What to read next > [card] [Define Storage Integration](/enterprise/v1-12-0/ingestion/define-storage-integration) > > Set up the credential an import reads through. > [card] [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) > > Query and import HuggingFace or object-storage datasets in full. > [card] [Distributed Write](/enterprise/v1-12-0/enterprise/distributed-write) > > How an import's writes divide across plan executors. > [card] [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) > > The complete SQL reference for every provider. # Ingesting data Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/index Choose how to create a table, append records or change existing data. **Applies to:** Embedded ✅, Enterprise ✅ Ingestion brings data into a LanceDB table. Start by choosing a schema and creating the table, then choose a write operation according to how incoming records relate to data already stored. ## Choose a write operation | Task | Operation | What happens | | - | - | - | | [Create a table](/enterprise/v1-12-0/ingestion/create-table) | `create_table` / `createTable` | Create a table from data or an explicit schema. | | [Append records](/enterprise/v1-12-0/ingestion/insert) | `add` | Add rows without matching existing keys. | | [Upsert by key](/enterprise/v1-12-0/ingestion/merge-insert) | `merge_insert` / `mergeInsert` | Choose whether matching rows are updated and new keys inserted. | | [Update selected rows](/enterprise/v1-12-0/ingestion/update) | `update` | Change values in rows selected by a predicate. | | [Delete selected rows](/enterprise/v1-12-0/ingestion/delete) | `delete` | Remove matching rows from the current table contents. | Appending the same input twice can create duplicate records. Use merge insert with a stable key when the incoming data should update existing records. ## Connect and prepare the data Use the [connection guide](/enterprise/v1-12-0/basics/catalog) to connect to Embedded or Enterprise. The SDK write operations in this section work with both. Enterprise also supports [SQL write statements](/enterprise/v1-12-0/sql#dml); an SDK filter expression does not require a separate SQL connection. Choose the column types, required fields and vector dimensions before a large load. SDKs support different input representations, including row objects and Arrow batches. The [table creation guide](/enterprise/v1-12-0/ingestion/create-table) covers those choices. ## Try a complete write workflow This example starts with Alice and Bob, appends Charlie, updates Bob's name and login count, then merges a batch containing Charlie and Dana. Finally, it selects Dana's row for inspection and deletes it. > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. ## Verify the result After a write completes, inspect the affected keys and fields and check the row count. SDK return values differ by operation and language; use the relevant API reference when relying on returned counts or version metadata. Readers with older snapshots may not see another handle's writes immediately. See [Consistency](/enterprise/v1-12-0/tables/consistency). A table checked out at a historical version must return to the latest version before it can be modified. ## Load larger datasets Use batches or file-backed input when the dataset is too large to hold in memory. The [insert guide](/enterprise/v1-12-0/ingestion/insert#large-datasets) covers input formats, progress reporting and write parallelism. Keep retry behavior in mind: repeating an append is not the same as retrying a key-based upsert. # Insert data Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/insert Append records, load file-backed data or batches, and verify ingestion. **Applies to:** Embedded ✅, Enterprise ✅ Use `add()` to append records to an existing table. It does not compare incoming keys with stored keys. Choose [merge insert](/enterprise/v1-12-0/ingestion/merge-insert) when the same record may arrive again and should update an existing row. ## Append a first batch Install the Python SDK with `pip install lancedb`. This complete example starts with Alice, appends Bob and Charlie, and prints all three records. ```python append_rows.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add([{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print(rows) ``` The program uses temporary local storage. For a complete TypeScript or Rust example, see [Complete write workflow](#complete-example). Enterprise SQL offers [`INSERT`](/enterprise/v1-12-0/sql/dml/insert), including `INSERT ... SELECT`. ## Prepare the input Match the table's schema, including required fields and vector dimensions. Supported input formats differ by SDK; see [Create a table](/enterprise/v1-12-0/ingestion/create-table). Inspect conversion errors before retrying, and verify the final row count and representative values. ## Choose input for a large load 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. ### Read from files 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. ```python load_parquet.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pyarrow.parquet as pq data_path = "input.parquet" pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path) import pyarrow.dataset as ds dataset = ds.dataset(data_path, format="parquet") table = db.create_table("my_table", schema=dataset.schema, mode="overwrite") table.add(dataset) print("Rows:", table.count_rows()) ``` 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. ### Produce batches during ingestion 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. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 4)), pa.field("item", pa.utf8()), pa.field("price", pa.float32()), ] ) def make_batches(): for i in range(5): yield pa.RecordBatch.from_arrays( [ pa.array( [[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]], pa.list_(pa.float32(), 4), ), pa.array(["foo", "bar"]), pa.array([10.0, 20.0]), ], ["vector", "item", "price"], ) table = db.create_table("batched_table", schema=schema) table.add(make_batches()) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const batchSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("item", new arrow.Utf8()), new arrow.Field("price", new arrow.Float32()), ]); const tableForBatches = await db.createEmptyTable( "batched_table", batchSchema, { mode: "overwrite", }, ); const rows = Array.from({ length: 10 }, (_, i) => ({ vector: [i + 0.1, i + 0.2, i + 0.3, i + 0.4], item: `item-${i + 1}`, price: (i + 1) * 10, })); const chunkSize = 2; for (let i = 0; i < rows.length; i += chunkSize) { const batch = lancedb.makeArrowTable(rows.slice(i, i + chunkSize), { schema: batchSchema, }); await tableForBatches.add(batch); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let batch_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), Field::new("item", DataType::Utf8, false), Field::new("price", DataType::Float32, false), ])); let batches = (0..5) .map(|i| { RecordBatch::try_new( batch_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(3.1 + i as f32), Some(4.1), Some(5.1), Some(6.1)]), Some(vec![ Some(5.9), Some(26.5 + i as f32), Some(4.7), Some(32.8), ]), ], 4, ), ), Arc::new(StringArray::from(vec![ format!("item{}", i * 2 + 1), format!("item{}", i * 2 + 2), ])), Arc::new(Float32Array::from(vec![ ((i * 2 + 1) * 10) as f32, ((i * 2 + 2) * 10) as f32, ])), ], ) .unwrap() }) .collect::<Vec<_>>(); let batch_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(batches.into_iter().map(Ok), batch_schema.clone())); let batch_table = db .create_table("batched_table", batch_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` 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. ### Control 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. ## Track completion and 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`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add( [{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}], progress=report_progress, ) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print("After insertion:", rows) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const lancedb = await import("@lancedb/lancedb"); const { mkdtemp, rm } = await import("node:fs/promises"); const { tmpdir } = await import("node:os"); const { join } = await import("node:path"); const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); try { const db = await lancedb.connect(uri); const table = await db.createTable("users", [{ id: 1, name: "Alice" }]); await table.add( [ { id: 2, name: "Bob" }, { id: 3, name: "Charlie" }, ], { progress: (progress) => console.log(`Rows written: ${progress.outputRows}`), }, ); const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); console.log("After insertion:", rows); } finally { await rm(uri, { recursive: true, force: true }); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; use lancedb::query::ExecutableQuery; fn make_users_reader(rows: &[(i64, &str)]) -> Box<dyn RecordBatchReader + Send> { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), ], ) .unwrap(); Box::new(RecordBatchIterator::new( vec![Ok(batch)].into_iter(), schema, )) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let directory = tempfile::tempdir()?; let db = lancedb::connect(directory.path().to_str().unwrap()) .execute() .await?; let table = db .create_table("users", make_users_reader(&[(1, "Alice")])) .execute() .await?; table .add(make_users_reader(&[(2, "Bob"), (3, "Charlie")])) .progress(|progress| println!("Rows written: {}", progress.output_rows())) .execute() .await?; let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; println!("After insertion: {rows:?}"); assert_eq!(table.count_rows(None).await?, 3); assert_eq!( table .count_rows(Some("id = 1 AND name = 'Alice'".into())) .await?, 1 ); assert_eq!( table .count_rows(Some("id = 2 AND name = 'Bob'".into())) .await?, 1 ); assert_eq!(table.count_rows(Some("id = 3".into())).await?, 1); Ok(()) } ``` 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. 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 Wait for the write operation's result, then check the expected records. Progress callbacks describe activity; they do not establish that a write succeeded. A timeout or connection error can leave a write still running or committed with its response lost. Do not automatically repeat the whole `add()` call: an append can duplicate rows. A request ID helps trace the attempt; it is not an idempotency key. Check the installed SDK's retry behavior too. For example, the Python and TypeScript 0.40.0 clients can resend an Enterprise append after a `504` even when it already committed. Resolve the original attempt before reconciling a fresh snapshot using stable application keys. Missing rows in an immediate query do not prove that the original write cannot commit later; changing to an upsert does not stop that earlier append. ## Configure large uploads Enterprise For LanceDB Enterprise tables (`db://` connections), a large write can use multipart upload. The SDK stages parts under an upload ID before committing the write. Multipart selection and retry behavior depend on the installed SDK; these settings do not affect LanceDB Embedded writes. A large part can exceed the client read timeout while uploading and writing to object storage: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lancedb.remote.errors.HttpError: operation timed out ``` The SDK source pinned by Enterprise 1.12.0 is 0.42.0-beta.8. Its multipart settings have the defaults below; newer SDKs can have different defaults and retry protections. These are client settings, not server request limits, and apply only when the SDK uses multipart upload. | Variable | Default | What it controls | | - | - | - | | `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 8 GiB | Target size of an insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable byte-based cuts. | | `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Target elapsed time per streamed part, in whole seconds. Set to `0` to disable time-based cuts. | A part is cut between input batches after either target is reached. The duration setting triggers a cut in the streamed request body; it does not change the HTTP request deadline. Lower the byte target and use smaller input batches when large uploads hit the read timeout. For Blob data, size caller batches by payload bytes rather than row count, and allow for Arrow encoding overhead and the application's live buffers. A single Blob value is not split by lowering the multipart target; choose an explicit chunk representation only if the application can reconstruct it. Blob storage packing thresholds are separate from upload budgets. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes ``` Uploaded parts and progress updates are not a final table commit. Wait for the write result. A new `add()` call can start a different upload; it does not replay a part from the previous attempt. Follow the [retry guidance](#performance) when a write's outcome is unknown. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Attach Database Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/migrate-from-embedded Point Enterprise at an existing database in object storage with ATTACH DATABASE, without copying data. **Applies to:** Embedded ❌, Enterprise ✅ If your LanceDB Embedded database already lives in object storage -- Embedded reads and writes tables on S3, GCS or Azure as well as local disk -- you can move to Enterprise by attaching that same location, rather than copying any data. A database on local disk has no such path: `ATTACH DATABASE` only accepts an object-storage URI or a path relative to Enterprise's own storage root, never a local filesystem path. Move it to object storage first if it is not there already. ## Prerequisites A [storage integration](/enterprise/v1-12-0/sql/ddl/storage-integration) covering the database's location must already exist. `ATTACH DATABASE` never names an integration explicitly -- Enterprise automatically binds the most specific integration whose `STORAGE_PREFIX` covers the location you attach. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/embedded-db/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' ``` ## Attach the database ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH DATABASE analytics WITH (location = 's3://customer-data/embedded-db/') ``` See [Database](/enterprise/v1-12-0/sql/ddl/database#attach) for the full `ATTACH DATABASE` syntax, including GCS and Azure locations (Azure requires an account-qualified URI), `IF NOT EXISTS`, and quoted names. ## What changes, and what doesn't Attaching makes the location a database LanceDB Enterprise manages the same way as one it created itself: Enterprise writes its own tracking metadata into that location to bring it under management, enabling capabilities Embedded never had there -- every table becomes reachable through Enterprise's SQL and SDK surface immediately, with Enterprise's authorization, Secrets, Functions, and [background maintenance](/enterprise/v1-12-0/basics/jobs) now available to it. Attaching does not rewrite, move, or re-encode any table's own data. [`DROP DATABASE`](/enterprise/v1-12-0/sql/ddl/database#drop) on an attached database unregisters it and releases the storage-integration reference, without deleting the underlying data -- the location can be reattached at any time. ## What to read next > [card] [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) > > Configure the credential an attach depends on, for S3, GCS, or Azure. > [card] [Database](/enterprise/v1-12-0/sql/ddl/database) > > Full ATTACH, CREATE, DESCRIBE and DROP DATABASE syntax. # RTE Write (Upsert) Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/realtime-write Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds. **Applies to:** Embedded ✅, Enterprise ✅ The [real time engine](/enterprise/v1-12-0/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see [RTE reads](/enterprise/v1-12-0/search/realtime-read). `table.enable_rte(spec)` is the same call on both connections, but what it does underneath differs: * **Embedded** runs Lance's MemWAL `ShardWriter` directly in your process -- the WAL buffer, memtables and SSTables all live wherever your table does, and there is no separate serving layer to scale or configure. * **Enterprise** forwards the call to the server, which runs it on a dedicated, horizontally scalable WAL-node tier instead of your table's query-serving fleet. See [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write) for how that tier shards a table's writes and the throughput limits that come with it. ## Getting started ### 1. Create a table with a primary key RTE deduplicates writes by primary key. Create the table with a non-nullable key column, then declare it with `set_unenforced_primary_key`. The key is a single `int32`, `int64`, string, or binary column, and cannot be changed once set. The table below holds frames captioned and embedded as they stream in from a live camera feed, such as a robot recording episodes into a dataset shaped like [LeRobotDataset](/enterprise/v1-12-0/integrations/lerobotdataset)'s `frames` table — `frame_id` is the primary key so a re-captioned frame upserts in place: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta import numpy as np import pyarrow as pa from lancedb import RTEWriteSpec from lancedb.index import FTS, BTree, IvfPq # Embedded: db = lancedb.connect("./my_db") db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") dim = 768 schema = pa.schema([ pa.field("frame_id", pa.int64(), nullable=False), pa.field("video_id", pa.utf8(), nullable=False), pa.field("embedding", pa.list_(pa.float32(), dim)), pa.field("caption", pa.utf8()), ]) frames = db.create_table("frames", schema=schema) frames.set_unenforced_primary_key("frame_id") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; const dim = 768; const schema = new arrow.Schema([ new arrow.Field("frame_id", new arrow.Int64(), false), new arrow.Field("video_id", new arrow.Utf8(), false), new arrow.Field( "embedding", new arrow.FixedSizeList(dim, new arrow.Field("item", new arrow.Float32(), true)), true, ), new arrow.Field("caption", new arrow.Utf8(), true), ]); const frames = await db.createEmptyTable("frames", schema); await frames.setUnenforcedPrimaryKey("frame_id"); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_schema::{DataType, Field, Schema}; let dim = 768; let schema = Arc::new(Schema::new(vec![ Field::new("frame_id", DataType::Int64, false), Field::new("video_id", DataType::Utf8, false), Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), dim), true, ), Field::new("caption", DataType::Utf8, true), ])); let frames = db.create_empty_table("frames", schema).execute().await?; frames.set_unenforced_primary_key(["frame_id"]).await?; ``` Or in SQL: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames SET UNENFORCED PRIMARY KEY (frame_id) ``` ### 2. Create indexes By default, RTE maintains every supported index on the table, including indexes created after it is enabled. A scalar index on the primary key is required for partial updates and deletes. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.create_index("embedding", config=IvfPq()) frames.create_index("caption", config=FTS()) frames.create_index("frame_id", config=BTree()) frames.wait_for_index(["embedding_idx", "caption_idx", "frame_id_idx"], timeout=timedelta(minutes=5)) ``` ### 3. Enable RTE ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.enable_rte(RTEWriteSpec.unsharded()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await frames.enableRTE({ specType: "unsharded" }); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::table::RTEWriteSpec; frames.enable_rte(RTEWriteSpec::unsharded()).await?; ``` Or in SQL: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames SET RTE ``` ### 4. Write > [!WARNING] > > On an RTE table, an upsert through `merge_insert` is the only way to write > rows. Use the form below exactly: `when_matched_update_all()` with no filter, > plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as > conditional updates or deleting rows missing from the source, are rejected. Writes go through `merge_insert` on the primary key, and are visible to queries immediately — see [RTE reads](/enterprise/v1-12-0/search/realtime-read) for querying them back: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} new_frames = pa.table({ "frame_id": pa.array([2000, 2001], pa.int64()), "video_id": pa.array(["clip-9", "clip-9"]), "embedding": pa.FixedSizeListArray.from_arrays( pa.array(np.random.rand(2 * dim).astype("float32")), dim), "caption": pa.array(["a gripper closing on a cup", "a cup set down on the table"]), }, schema=schema) frames.merge_insert("frame_id") \ .when_matched_update_all() \ .when_not_matched_insert_all() \ .execute(new_frames) ``` **Partial updates.** Send the primary key plus only the columns you want to change; omitted columns keep their current values. This requires a scalar index on the primary key. A re-captioning job, for example, only touches `caption`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} patch = pa.table( {"frame_id": [2000, 2001], "caption": ["a two-finger gripper closing on a cup", "the cup resting upright"]}, schema=pa.schema([schema.field("frame_id"), schema.field("caption")]), ) frames.merge_insert("frame_id").when_matched_update_all().when_not_matched_insert_all().execute(patch) ``` **Deletes.** The predicate must bind the primary key to literal values. Ranges, `OR`, and filters on other columns are rejected. Deletes require a scalar index on the primary key. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.delete("frame_id IN (2000, 2001)") ``` ### Disabling RTE Stop writes and wait for in-flight writes to finish, then flush pending writes into the base table and disable. `checkpoint_rte()` only drains writes that existed when it started, so anything written during the checkpoint can be left behind. `disable_rte()` is rejected while the write-ahead log still holds rows, so run `checkpoint_rte()` first. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.checkpoint_rte() frames.disable_rte() ``` ## Write throughput RTE acknowledges a write as soon as it is durable in the write-ahead log, so ingest is no longer limited by how fast the table can commit. On Embedded, durability means your local disk or object store, so throughput is bounded by your own machine's resources. An Enterprise table can be split into shards that write independently, with each shard's durable-append throughput bounded by its WAL node's own capacity -- measured, not an enforced cap. See [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write#throughput) for the numbers. ## Next steps * [RTE reads](/enterprise/v1-12-0/search/realtime-read) — query an RTE table * [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write) — how Enterprise shards and scales this * [How the real time engine works](/enterprise/v1-12-0/tables/realtime-engine#memwal-format) * [Merge insert](/enterprise/v1-12-0/ingestion/merge-insert) * [`ALTER TABLE ... SET RTE`](/enterprise/v1-12-0/sql/ddl/table#properties) # Update rows Source: https://docs.lancedb.com/enterprise/v1-12-0/ingestion/update Select existing rows, change values or expressions, and verify the changes. **Applies to:** Embedded ✅, Enterprise ✅ Use `update` to change rows selected by a predicate. Use [merge insert](/enterprise/v1-12-0/ingestion/merge-insert) instead when matching an incoming dataset against existing keys. ## Select the rows to change Check the predicate with a [filtered query](/enterprise/v1-12-0/search/filtering) before applying the update. These examples target the row with `id = 2`. Review the scope carefully when omitting a predicate, since that can update the entire table. Each example below starts from Alice with 10 logins and Bob with 20. The Python programs create and remove their own temporary database. TypeScript and Rust operation blocks use `db`; a complete program is provided below. ## Assign a new value ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa table = db.create_table( "users_example", data=pa.table( { "id": [1, 2], "name": ["Alice", "Bob"], "login_count": [10, 20], } ), mode="overwrite", ) table.update(where="id = 2", values={"name": "Bobby"}) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable( "users_example", [ { id: 1, name: "Alice", login_count: 10 }, { id: 2, name: "Bob", login_count: 20 }, ], { mode: "overwrite" }, ); await table.update({ where: "id = 2", values: { name: "Bobby" } }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table = db .create_table( "users_example", make_users_reader(vec![1, 2], vec!["Alice", "Bob"], Some(vec![10, 20])), ) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); table .update() .only_if("id = 2") .column("name", "'Bobby'") .execute() .await .unwrap(); ``` The result contains Alice and **Bobby**, with their login counts unchanged. The Python `values` and TypeScript `values` arguments take literal values. Rust's `column` argument is an expression, so the string value includes SQL quotes. ## Calculate a value from the existing row ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa table = db.create_table( "users_example", data=pa.table( { "id": [1, 2], "name": ["Alice", "Bob"], "login_count": [10, 20], } ), mode="overwrite", ) table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable( "users_example", [ { id: 1, name: "Alice", login_count: 10 }, { id: 2, name: "Bob", login_count: 20 }, ], { mode: "overwrite" }, ); await table.update({ where: "id = 2", valuesSql: { login_count: "login_count + 1" }, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table = db .create_table( "users_example", make_users_reader(vec![1, 2], vec!["Alice", "Bob"], Some(vec![10, 20])), ) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); table .update() .only_if("id = 2") .column("login_count", "login_count + 1") .execute() .await .unwrap(); ``` In this separate example, Bob keeps his name and his login count becomes **21**. Python's `values_sql` and TypeScript's `valuesSql` accept expressions. These SDK expressions work with LanceDB Embedded tables; they do not require an Enterprise SQL endpoint. Enterprise also offers [`UPDATE`](/enterprise/v1-12-0/sql/dml/update). ## Verify the affected data Read the selected rows again and inspect the changed fields. For another connection or table handle, account for its [read consistency](/enterprise/v1-12-0/tables/consistency) settings. Python's `update` does not compute embeddings. When changing a configured embedding source column, provide every associated vector column in the same call. This applies to both literal values and SQL expressions, and to synchronous and asynchronous tables. Python 0.41.0 does not check these source/vector pairs before writing: it can change the source while retaining an old vector. Validate the pairs in your application. Python 0.42.0b8 raises `ValueError` for a missing paired vector before writing rows. Use [`merge_insert`](/enterprise/v1-12-0/ingestion/merge-insert) with the new source values to generate embeddings automatically. Nested-field updates are not supported by these operations. For schema changes, see [schema evolution](/enterprise/v1-12-0/management/table#schema). Treat derived values separately: changing an input field is not a guarantee that every stored feature has been recomputed. See [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column). Updates can change index coverage and query cost. After a large update, inspect the workload and follow [index maintenance](/enterprise/v1-12-0/indexing/incremental-indexing) guidance for the backend you use. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Quickstart Source: https://docs.lancedb.com/enterprise/v1-12-0/quickstart Install LanceDB, create a table, and run your first vector search. This quickstart uses LanceDB Embedded with a local database and works without an account or API key. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. ## 1. Install LanceDB Choose your language. Python uses Pandas to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. ```bash Python (pip) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lancedb==0.41.0" pandas ``` ```bash Python (uv) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv venv uv pip install "lancedb==0.41.0" pandas ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb@0.41.0 ``` ```bash Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cargo init --name lancedb_quickstart cargo add lancedb@0.41.0 --features polars,remote cargo add tokio --features macros,rt-multi-thread ``` Run the Rust commands in a new, empty directory. The `polars` feature provides DataFrame output; `remote` also lets this example connect to Enterprise. > [accordion] Python pre-release builds and older CPUs > > ### Python pre-release builds > > To pick up the latest features and bug fixes > before the next stable release, install a pre-release from LanceDB's Fury index. > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb > ``` > > ```bash Python (uv) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > uv venv > uv pip install --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb > > # To add to pyproject.toml, use: > uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb > ``` > > Most applications only need `lancedb`. Install the optional `pylance` extra and > include the Lance preview index only when building query engines or connectors, > calling format-level `lance` APIs directly, converting plain-scan lazy blob > handles with `to_pandas()`, or reading legacy v1 blob bytes into pandas with > Python 0.41.0 or 0.42.0b8. Those clients use the native bytes path for supported > v2 blob queries; they still need `pylance` for legacy pandas bytes conversion: > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install --pre \ > --extra-index-url https://pypi.fury.io/lancedb/ \ > --extra-index-url https://pypi.fury.io/lance-format/ \ > "lancedb[pylance]" > ``` > > ```bash Python (uv) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > uv pip install --prerelease allow \ > --index https://pypi.fury.io/lancedb/ \ > --index https://pypi.fury.io/lance-format/ \ > --index-strategy unsafe-best-match \ > "lancedb[pylance]" > ``` > > The LanceDB preview index contains old `pylance` releases; current Lance previews > are published to the `lance-format` index. By default, uv only considers versions > from the first index containing a package, which can select an old `pylance` or > backtrack to an older LanceDB release. `unsafe-best-match` searches all configured > indexes, like pip; use it only with indexes you trust. Install the extra rather > than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. > > > [!NOTE] > > > > Pre-release builds receive the same level of testing as stable releases, but their availability is not guaranteed > > for more than 6 months after release. For real-world workloads, we recommend you use the latest stable release > > as far as possible. > > ### Older x86_64 CPUs > > The default `lancedb` wheel targets `x86-64-haswell` (AVX2 + FMA + F16C). On older x86_64 CPUs without AVX2 > (Intel Sandy Bridge, Ivy Bridge, Westmere; AMD Bulldozer, Piledriver, Steamroller), `import lancedb` crashes > with `Illegal instruction`. > > Install `lancedb-compat` instead. It exposes the same API (`import lancedb` still works), is built at the > `x86-64-v2` baseline, and uses runtime SIMD dispatch to still use AVX2, FMA, or AVX-512 when available: > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install lancedb-compat > ``` > > The two packages share the same `lancedb/` namespace and conflict at install time, so pick one. To switch, > uninstall the other first (`pip uninstall lancedb && pip install lancedb-compat`). ## 2. Connect to a database ### Local directory LanceDB creates an `ex_lancedb` directory to store your tables. No server is needed. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("ex_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("ex_lancedb").execute().await?; ``` For Python's async API, see [Connecting to a database](/enterprise/v1-12-0/basics/catalog). ### Object storage Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Object storage](/enterprise/v1-12-0/basics/catalog#object-storage) for credentials and provider-specific options. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". const db = await lancedb.connect(uri); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". let db = connect(uri).execute().await?; ``` ### Enterprise Use the database URI, API key, and endpoint provided by your administrator or the LanceDB team. Replace the placeholders below with those details. Use the deployment's region if provided; otherwise keep `us-east-1`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("db://your-database") .api_key("your-api-key") .region("us-east-1") .host_override("https://your-endpoint") .execute() .await?; ``` > [!NOTE] > > In application code, load credentials from environment variables or a secrets manager. See [connection settings](/enterprise/v1-12-0/basics/catalog#enterprise) for an example. Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/enterprise/v1-12-0/index#architecture). ## 3. Create a table and add data Each row describes a frame from a robot video clip and stores an embedding alongside its video, caption, and quality stats. > [!NOTE] > > These embeddings are made up for this example. In your application, use an embedding model to generate them from your data. > [accordion] Frame records > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > data = [ > { > "frame_id": "1", > "video_id": "clip-1", > "caption": "a robot arm reaching toward a cup", > "stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3}, > "embedding": [0.7, 0.1, 0.9, 0.7], > }, > { > "frame_id": "2", > "video_id": "clip-1", > "caption": "a two-finger gripper closing on a cup", > "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, > "embedding": [0.2, 0.9, 0.4, 0.9], > }, > { > "frame_id": "3", > "video_id": "clip-2", > "caption": "a robot arm holding a cup steady", > "stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4}, > "embedding": [0.9, 0.1, 0.5, 0.4], > }, > ] > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const data = [ > { > frame_id: "1", > video_id: "clip-1", > caption: "a robot arm reaching toward a cup", > stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 }, > embedding: [0.7, 0.1, 0.9, 0.7], > }, > { > frame_id: "2", > video_id: "clip-1", > caption: "a two-finger gripper closing on a cup", > stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 }, > embedding: [0.2, 0.9, 0.4, 0.9], > }, > { > frame_id: "3", > video_id: "clip-2", > caption: "a robot arm holding a cup steady", > stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 }, > embedding: [0.9, 0.1, 0.5, 0.4], > }, > ]; > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use lancedb::arrow::arrow_array::types::Float32Type; > use lancedb::arrow::arrow_array::{ > FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator, > RecordBatchReader, StructArray, > }; > use lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; > > // Define structs representing the data schema > #[derive(Debug, Clone)] > struct Stats { > motion: i8, > sharpness: i8, > exposure: i8, > framing: i8, > } > > #[derive(Debug, Clone)] > struct Frame { > frame_id: String, > video_id: String, > caption: String, > stats: Stats, > embedding: [f32; 4], > } > > fn frames_schema() -> Arc<Schema> { > Arc::new(Schema::new(vec![ > Field::new("frame_id", DataType::LargeUtf8, false), > Field::new("video_id", DataType::LargeUtf8, false), > Field::new("caption", DataType::LargeUtf8, false), > Field::new( > "stats", > DataType::Struct(Fields::from(vec![ > Arc::new(Field::new("motion", DataType::Int8, false)), > Arc::new(Field::new("sharpness", DataType::Int8, false)), > Arc::new(Field::new("exposure", DataType::Int8, false)), > Arc::new(Field::new("framing", DataType::Int8, false)), > ])), > false, > ), > Field::new( > "embedding", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), > false, > ), > ])) > } > > fn frames_to_reader(schema: Arc<Schema>, rows: &[Frame]) -> Box<dyn RecordBatchReader + Send> { > let frame_ids = > LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str())); > let video_ids = > LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str())); > let captions = LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str())); > > let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion)); > let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness)); > let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure)); > let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing)); > let stats_fields: Vec<FieldRef> = vec![ > Arc::new(Field::new("motion", DataType::Int8, false)), > Arc::new(Field::new("sharpness", DataType::Int8, false)), > Arc::new(Field::new("exposure", DataType::Int8, false)), > Arc::new(Field::new("framing", DataType::Int8, false)), > ]; > let stats = StructArray::new( > stats_fields.into(), > vec![ > Arc::new(motion), > Arc::new(sharpness), > Arc::new(exposure), > Arc::new(framing), > ], > None, > ); > > let embeddings = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > rows.iter() > .map(|row| Some(row.embedding.iter().copied().map(Some).collect::<Vec<_>>())), > 4, > ); > > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(frame_ids), > Arc::new(video_ids), > Arc::new(captions), > Arc::new(stats), > Arc::new(embeddings), > ], > ) > .unwrap(); > > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > let data = vec![ > Frame { > frame_id: "1".to_string(), > video_id: "clip-1".to_string(), > caption: "a robot arm reaching toward a cup".to_string(), > stats: Stats { > motion: 3, > sharpness: 4, > exposure: 4, > framing: 3, > }, > embedding: [0.7, 0.1, 0.9, 0.7], > }, > Frame { > frame_id: "2".to_string(), > video_id: "clip-1".to_string(), > caption: "a two-finger gripper closing on a cup".to_string(), > stats: Stats { > motion: 5, > sharpness: 4, > exposure: 5, > framing: 2, > }, > embedding: [0.2, 0.9, 0.4, 0.9], > }, > Frame { > frame_id: "3".to_string(), > video_id: "clip-2".to_string(), > caption: "a robot arm holding a cup steady".to_string(), > stats: Stats { > motion: 2, > sharpness: 3, > exposure: 3, > framing: 4, > }, > embedding: [0.9, 0.1, 0.5, 0.4], > }, > ]; > ``` Create a `frames` table from those records: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("frames", data=data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable("frames", data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::database::CreateTableMode; let schema = frames_schema(); let table = db .create_table("frames", frames_to_reader(schema.clone(), &data)) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` This example uses overwrite mode so you can run it again. It replaces any existing `frames` table in the database you connect to. Add one more frame: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add( [ { "frame_id": "4", "video_id": "clip-2", "caption": "a gripper lowering a cup onto the table", "stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2}, "embedding": [0.3, 0.9, 0.6, 0.8], } ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.add([ { frame_id: "4", video_id: "clip-2", caption: "a gripper lowering a cup onto the table", stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 }, embedding: [0.3, 0.9, 0.6, 0.8], }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let more_data = vec![Frame { frame_id: "4".to_string(), video_id: "clip-2".to_string(), caption: "a gripper lowering a cup onto the table".to_string(), stats: Stats { motion: 5, sharpness: 4, exposure: 4, framing: 2, }, embedding: [0.3, 0.9, 0.6, 0.8], }]; table .add(frames_to_reader(schema.clone(), &more_data)) .execute() .await .unwrap(); ``` ## 4. Search the table Find the two embeddings closest to the query embedding. This example uses a fixed embedding; it does not call an embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Search for frames similar to "a gripper closing on an object" query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install pandas` beforehand result = ( table.search(query_vector) .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .to_pandas() ) print(result) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Search for frames similar to "a gripper closing on an object" const queryVector = [0.2, 0.8, 0.4, 0.9]; const result = await table .search(queryVector) .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .toArray(); console.table(result); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::arrow::IntoPolars; use lancedb::query::{ExecutableQuery, QueryBase, Select}; // Search for frames similar to "a gripper closing on an object" let query_vector = [0.2, 0.8, 0.4, 0.9]; let result = table .query() .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ "frame_id".to_string(), "video_id".to_string(), "caption".to_string(), "_distance".to_string(), ])) .limit(2) .execute() .await .unwrap() .into_polars() .await .unwrap(); println!("{result:?}"); ``` Frames 2 and 4 come back first -- the gripper closing on the cup, then lowering it. Python displays a Pandas DataFrame, Rust displays a Polars DataFrame, and TypeScript displays an array of results. The `_distance` column measures how far each result is from your query embedding, with smaller values indicating a closer match. ## 5. Curate data with SQL > [!NOTE] > > Step 5 needs LanceDB Enterprise: SQL is an Enterprise feature. If you're > using LanceDB Embedded, skip ahead to > [Flatten nested fields](#flatten-nested-fields) below. LanceDB Enterprise accepts SQL over the same connection, for sampling, joins, and curation tasks that go beyond a single table scan. Draw a quick sample to look at the data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} sample = db.execute_query( "SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)" ).read_all() print(sample.to_pylist()) ``` See [SQL](/enterprise/v1-12-0/basics/sql) for the Flight SQL client and CLI alternatives to `execute_query()`. Now add a near-duplicate frame -- frame 5 is one video frame after frame 2, with an almost identical embedding -- and build the vector index that `dedupe` reads: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Frame 5 is a near-duplicate of frame 2: the gripper is still closing, # one video frame later, with an almost identical embedding. table.add( [ { "frame_id": "5", "video_id": "clip-1", "caption": "the two-finger gripper still closing on the cup", "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, "embedding": [0.2, 0.9, 0.4, 0.89], } ] ) from lancedb.index import IvfFlat table.create_index( "embedding", config=IvfFlat(num_partitions=1, distance_type="l2") ) table.wait_for_index(["embedding_idx"]) ``` Collapse near-duplicates into a materialized view that stays current as new frames arrive, then read it back: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'embedding', distance_threshold => 0.03 ) """) ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} deduped = db.execute_query( "SELECT frame_id FROM frames_deduped ORDER BY frame_id" ).read_all() print(deduped.to_pylist()) ``` Frames 2 and 5 collapse into one representative -- five rows become four. Which of the two ids survives is not guaranteed to stay the same across appends, so don't treat it as a stable identifier for the cluster. See [Deduplicate near-duplicate records](/enterprise/v1-12-0/curation/dedupe) for `duplicate_pairs`, resolution strategies, and tuning `distance_threshold`, and [Statistical Sampling](/enterprise/v1-12-0/curation/statistical-sampling) for percentage samples, repeatable draws, and sampling across a join. ## 6. Add a derived feature ### Flatten nested fields A UDF binds to top-level columns, so flatten the fields inside `stats` first. This is a plain eager `add_columns` call, so it works the same on LanceDB Embedded and LanceDB Enterprise -- [step 8](#8-train) needs these columns either way: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns( { "motion": "cast(stats.motion as float)", "sharpness": "cast(stats.sharpness as float)", "exposure": "cast(stats.exposure as float)", "framing": "cast(stats.framing as float)", } ) ``` > [!NOTE] > > The rest of this step needs LanceDB Enterprise -- Functions are an > Enterprise feature. If you're using LanceDB Embedded, skip ahead to > [step 7](#7-store-multimodal-data). Register a UDF as a Function, then call it to fill a column computed from those flattened fields. This fills every existing row once, immediately: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col, udf @udf def quality_score( motion: float, sharpness: float, exposure: float, framing: float ) -> float: return (motion + sharpness + exposure + framing) / 4.0 version = db.create_function_async(quality_score).wait() table.add_columns( { "quality_score": version( motion=col("motion"), sharpness=col("sharpness"), exposure=col("exposure"), framing=col("framing"), ) } ) table.refresh_column("quality_score") ``` Read it back like any other column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} features = table.search().select(["frame_id", "video_id", "quality_score"]).limit(10).to_pandas() print(features) ``` `refresh_column` fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. Run the same refresh as a background job instead, so it doesn't block: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("quality_score") job.wait() ``` See [Create a Function](/enterprise/v1-12-0/curation/create-function) for UDFs that call external models or services, and [Computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) for the SQL-expression form that doesn't need a registered Function. ## 7. Store multimodal data Store images, audio, or other binary data alongside vectors and metadata, in a column of raw bytes. This creates a new table from one image file -- replace the path with one of your own: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pathlib import Path image_bytes = Path("data/sample-frame.jpg").read_bytes() multimodal_table = db.create_table( "frame_images", data=[ { "frame_id": "thumb-1", "caption": "Sample frame thumbnail", "image": image_bytes, "embedding": [0.9, 0.1, 0.5, 0.4], } ], mode="overwrite", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const arrow = await import("apache-arrow"); const { readFile } = await import("node:fs/promises"); const imageBytes = await readFile("data/sample-frame.jpg"); const imageSchema = new arrow.Schema([ new arrow.Field("frame_id", new arrow.Utf8()), new arrow.Field("caption", new arrow.Utf8()), new arrow.Field("image", new arrow.Binary()), new arrow.Field( "embedding", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), ]); const imageData = lancedb.makeArrowTable( [ { frame_id: "thumb-1", caption: "Sample frame thumbnail", image: imageBytes, embedding: [0.9, 0.1, 0.5, 0.4], }, ], { schema: imageSchema }, ); const multimodalTable = await db.createTable( "frame_images", imageData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::arrow::arrow_array::BinaryArray; let image_bytes = std::fs::read("data/sample-frame.jpg").unwrap(); let image_schema = Arc::new(Schema::new(vec![ Field::new("frame_id", DataType::LargeUtf8, false), Field::new("caption", DataType::LargeUtf8, false), Field::new("image", DataType::Binary, false), Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])); let image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]]; let image_batch = RecordBatch::try_new( image_schema.clone(), vec![ Arc::new(LargeStringArray::from_iter_values(["thumb-1"])), Arc::new(LargeStringArray::from_iter_values([ "Sample frame thumbnail", ])), Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( image_embeddings .iter() .map(|vector| Some(vector.iter().copied().map(Some).collect::<Vec<_>>())), 4, ), ), ], ) .unwrap(); let image_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(image_batch)].into_iter(), image_schema, )); let multimodal_table = db .create_table("frame_images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` See [Multimodal data types](/enterprise/v1-12-0/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. ## 8. Train on your data Read table data into PyTorch, projecting and shuffling only the columns a training step needs. This step needs PyTorch, which step 1 doesn't install: ```bash Python (pip) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install torch ``` ```bash Python (uv) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install torch ``` Then wrap the table in a data loader: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset dataset = StreamingDataset(table, columns=["motion", "sharpness"], shuffle_seed=42) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0) ``` `StreamingDataset` wraps a table for PyTorch training reads; `columns` projects before reading, so a training step touches only the columns it selects, not unused ones such as `caption` or `embedding`. It works the same way against LanceDB Embedded and LanceDB Enterprise. See [PyTorch Data Loader](/enterprise/v1-12-0/training/data-loading) for shuffling, transforms, resuming, and multi-worker loading, and [Permutation](/enterprise/v1-12-0/training/permutation) for the lower-level row-ordering primitive it's built on. ## Where to go next > [card] [Basic table operations](/enterprise/v1-12-0/management/table) > > Create, update, and manage your tables. > [card] [Build a RAG app](/enterprise/v1-12-0/tutorials/agents/contextual-rag) > > Use retrieved context in a language model application. > [card] [Indexing](/enterprise/v1-12-0/indexing/) > > Speed up queries on larger datasets. > [card] [Embedding models](/enterprise/v1-12-0/embedding/) > > Generate vectors from your own data. # Reranking Search Results Source: https://docs.lancedb.com/enterprise/v1-12-0/reranking/index Choose a reranker, apply it to search candidates and evaluate relevance and latency. **Applies to:** Embedded ✅, Enterprise ✅ Reranking changes the order of records returned by an initial search. It can combine several ranked lists or use a model to score each candidate against the query. It cannot recover records that the initial searches did not retrieve. ## Choose a reranker * **Rank fusion:** start with RRF for hybrid search. It combines vector and full-text rankings without a model or a provider API call. * **Model-based reranking:** try a cross encoder or hosted reranking model when you need a different relevance judgment over the retrieved text. Compare the relevance gain with added latency and provider cost. * **Custom ranking:** implement the reranker interface when your application needs its own scoring policy. > [accordion] Run a complete RRF example in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `rerank_search.py`, then run `python rerank_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `rerank_search.mts`, then run `node rerank_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > from lancedb.rerankers import RRFReranker > > table.create_index("text", config=FTS()) > rows = ( > table.search( > query_type="hybrid", vector_column_name="vector", fts_columns="text" > ) > .vector([1.0, 0.0]) > .text("puppy") > .rerank(RRFReranker()) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const reranker = await lancedb.rerankers.RRFReranker.create(); > const rows = await table > .vectorSearch([1.0, 0.0]) > .fullTextSearch("puppy", { columns: ["text"] }) > .rerank(reranker) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .rerank(Arc::new(lancedb::rerankers::rrf::RRFReranker::default())) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The result includes `_relevance_score` in descending order. RRF is already the > hybrid-search default; passing it explicitly shows where to substitute another > reranker. These scores express a ranking, not a probability of correctness. ## Supported rerankers Use rank fusion to combine search results without a model, or a model-based reranker to score each document against the query. Reranking runs in your application after retrieval, including when the table is in Enterprise. | Reranker | Method | SDK | | :- | :- | :- | | `RRFReranker` | Reciprocal rank fusion | Python, TypeScript, Rust | | `MRRReranker` | Weighted reciprocal rank fusion | Python | | `LinearCombinationReranker` (deprecated) | Blend normalized scores | Python | | `CrossEncoderReranker` | Score query-document pairs with a local cross encoder | Python | | `ColbertReranker`, `AnswerdotaiRerankers` | Local model reranking | Python | | Provider rerankers | Call a hosted model, such as Cohere, Jina or Voyage AI | Python | Local model rerankers need their model runtime packages. Hosted rerankers need provider credentials and make API calls. See [reranking integrations](/enterprise/v1-12-0/integrations/reranking) for provider setup and model selection; specify a model supported by your provider. Rerankers add `_relevance_score` and return rows ordered by descending relevance. Python rerankers accept a `return_score` option; use `"all"` where supported to keep the original vector distance or FTS score columns for debugging. Model-based rerankers read from `column="text"` by default, so either return that column in the search results or pass a different column. `refine_factor` expands the vector index's internal candidate pool and rescores those candidates using full vectors before keeping the requested limit. It can improve the candidates available for reranking, but it does not multiply the final result count. Compare retrieval recall and total query latency. > [!NOTE] > > **SDK coverage differs across languages** > > The provider-specific rerankers in the table above > (`CohereReranker`, `CrossEncoderReranker`, `ColbertReranker`, and others under `lancedb.rerankers`) > are currently **Python-only**. The TypeScript and Rust SDKs currently expose hybrid reranking through > the generic `Reranker` interface (`rerankHybrid` / `rerank_hybrid`) and the built-in `RRFReranker`. > In TypeScript, create the built-in RRF reranker with `await RRFReranker.create(k)`. To use a > model-based reranker from TypeScript or Rust, you must implement the hybrid reranker interface > yourself. ### Multi-vector reranking Use `rerank_multivector()` to combine result sets from several vector queries. The example below assumes `table` has three vector columns with embedding metadata and uses a cross encoder to rerank their candidates. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.rerankers import CrossEncoderReranker reranker = CrossEncoderReranker() query = "hello" # `deduplicate=True` requires `_rowid` on every input result set, # so call `.with_row_id(True)` on each search before passing it in. res1 = table.search(query, vector_column_name="vector").limit(3).with_row_id(True) res2 = table.search(query, vector_column_name="text_vector").limit(3).with_row_id(True) res3 = table.search(query, vector_column_name="meta_vector").limit(3).with_row_id(True) reranked = reranker.rerank_multivector([res1, res2, res3], deduplicate=True) ``` * Passing `deduplicate=True` to `rerank_multivector(...)` raises a `ValueError` if any of the input result sets is missing the `_rowid` column. Therefore, it's recommended to add `.with_row_id(True)` to every `table.search(...)` call before reranking, or omit `deduplicate=True` if you don't need it. * `RRFReranker.rerank_multivector(...)` always requires `_rowid` on its inputs, regardless of the `deduplicate` flag. ## Implement a custom ranking policy Python custom rerankers implement `rerank_hybrid()` and can optionally implement `rerank_vector()` and `rerank_fts()`. TypeScript and Rust expose hybrid reranking interfaces. See [the interface requirements](#custom) before implementing one. ## Algorithm options The following sections describe the Python constructor options and examples. Provider and local-model examples require their additional packages and model or credential setup. They are separate programs, not steps to concatenate. ## Reciprocal rank fusion > [accordion] RRF options and examples > > **Reciprocal Rank Fusion (RRF)** is a model-free way to merge several ranked result lists into a > single ordering. Rather than comparing raw similarity scores (which aren't directly comparable > across, say, a vector search and a full-text search), RRF looks only at each document's *rank > position* in each list. It scores every document with the formula `1 / (rank + K)`, sums those > contributions across the lists, and re-sorts by the total. Documents that rank highly in more than > one search rise to the top. Because there's no model to load or call, it's fast and cheap, which is > why it's the default reranker for LanceDB hybrid search. The implementation follows the > [Cormack et al. paper](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf). > > > **Supported query types:** hybrid search and [multi-vector reranking](/enterprise/v1-12-0/reranking#multi-vector-reranking). > > Because RRF fuses two or more ranked lists, it can't rerank a single vector or full-text result set > > on its own. Calling `rerank_vector` or `rerank_fts` on an `RRFReranker` raises `NotImplementedError`. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import RRFReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "rrf-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = RRFReranker() > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `K` | `int` | `60` | A constant used in the RRF formula (default is 60). Larger values reduce the difference in contribution between nearby rank positions. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score`. If "all", will return all scores from the vector and FTS search along with the relevance score. | > > `K` must be greater than `0`. In TypeScript, construct the built-in reranker with > `await RRFReranker.create(k)` before passing it to `.rerank(...)`. > > ### Multi-vector reranking > > `RRFReranker` can also fuse the results of several vector searches with `rerank_multivector`, applying > the same rank-fusion algorithm across more than two lists. Every input result set must include the > `_rowid` column, so add `.with_row_id(True)` to each `table.search(...)` call before reranking, > otherwise the call raises a `ValueError`. See [multi-vector reranking](/enterprise/v1-12-0/reranking#multi-vector-reranking) > for a full example. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` as the score column alongside the selected data columns. | > | `all` | ✅ Supported | Returned rows have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | ## Linear combination > [accordion] Linear combination options (deprecated) > > > **Note:** This reranker is deprecated. Use `RRFReranker` to combine vector and full-text rankings. > > The Linear Combination Reranker combines the results of semantic and full-text search using a linear combination of the scores. The weights for the linear combination can be specified, and defaults to 0.7, i.e, 70% weight for semantic search and 30% weight for full-text search. > > > **Note:** Supported query type: Hybrid search only. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import LinearCombinationReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "linear-combination-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = LinearCombinationReranker() > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `weight` | `float` | `0.7` | The weight to use for the semantic search score. The weight for the full-text search score is `1 - weight`. | > | `fill` | `float` | `1.0` | Score used when a result is missing from one side of the hybrid query. The default strongly penalizes missing vector or FTS matches. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", returns only `_relevance_score`. If "all", returns all scores from the vector and FTS search along with the relevance score. | > > `weight` must be between `0` and `1`. If either the vector or FTS side returns no rows, the reranker > returns the non-empty side with `_relevance_score` attached rather than failing. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns | > | `all` | ✅ Supported | Results have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`) | ## MRR > [accordion] MRR options and examples > > This reranker uses the Mean Reciprocal Rank (MRR) algorithm to combine and rerank search results from vector and full-text search. You can use this reranker by passing `MRRReranker()` to the `rerank()` method. The MRR algorithm calculates the average of reciprocal ranks across different search results, providing a balanced way to merge results from multiple ranking systems. > > > **Note:** Supported query types: Hybrid and Multivector search. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import MRRReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "mrr-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = MRRReranker(weight_vector=0.7, weight_fts=0.3) > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > > # Run multivector search across multiple vector columns > rs1 = tbl.search("hello").limit(10).with_row_id(True).to_arrow() > rs2 = tbl.search("greeting").limit(10).with_row_id(True).to_arrow() > combined = MRRReranker().rerank_multivector([rs1, rs2]) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `weight_vector` | `float` | `0.5` | Weight for vector search results (0.0 to 1.0). | > | `weight_fts` | `float` | `0.5` | Weight for FTS search results (0.0 to 1.0). | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score`. If "all", will return all scores from the vector and FTS search along with the relevance score. | > > **Note:** `weight_vector` + `weight_fts` must equal 1.0. > > For multivector reranking, input result sets need `_rowid` so LanceDB can identify the same row > across the ranked lists. Add `.with_row_id(True)` to each vector search before passing the results > to the reranker. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | > > #### Multivector Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector distances from all searches along with `_relevance_score`. | ## Cross encoder > [accordion] Cross-encoder options and examples > > This reranker uses Cross Encoder models from sentence-transformers to rerank the search results. You can use this reranker by passing `CrossEncoderReranker()` to the `rerank()` method. > > > **Note:** Supported query types: Hybrid, Vector, and FTS. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import CrossEncoderReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cross-encoder-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = CrossEncoderReranker() > > # Run vector search with a reranker > result = tbl.search("hello").rerank(reranker=reranker).to_list() > > # Build the full-text index before either FTS or hybrid search. > tbl.create_fts_index("text", replace=True) > > # Run FTS search with a reranker > result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() > > # Run hybrid search with a reranker > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `model_name` | `str` | `"cross-encoder/ms-marco-TinyBERT-L-6"` | The name of the reranker model to use. | > | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | > | `device` | `str` | `None` | The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu". | > | `trust_remote_code` | `bool` | `True` | Passed to Sentence Transformers model loading. Set this to `False` when you only want to load models that do not require custom repository code. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", returns only `_relevance_score`. If "all" is supported, returns relevance score along with the vector and/or FTS scores depending on query type. | > > The reranker loads the model locally through `sentence-transformers`, so install the local model > runtime dependencies you need, such as PyTorch and any device-specific acceleration packages. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Keeps `_distance`, `_score` and `_relevance_score` alongside the data columns. | > > #### Vector Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | > > #### FTS Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | ## Building a custom reranker You can build your own custom reranker in LanceDB by subclassing the base `Reranker` class. At a minimum, you need to implement `rerank_hybrid()`, which is the logic that combines vector and full-text search results. Beyond that, you can optionally implement `rerank_vector()` and `rerank_fts()` if you want your reranker to also handle pure vector or pure full-text searches. Implement the hooks your query paths call. The base class raises `NotImplementedError` for vector-only or FTS-only reranking unless you implement those methods. The Python base class exposes hybrid, vector-only, and FTS-only rerank hooks. TypeScript and Rust currently expose the custom reranker interface for hybrid reranking. In Rust, a custom reranker must also satisfy the trait bounds `Debug + Send + Sync`. ### Interface The `Reranker` base interface comes with a `merge_results()` method that can be used to combine the results of semantic and full-text search. This is a vanilla merging algorithm that simply concatenates the results and removes the duplicates without taking the scores into consideration. It only keeps the first copy of the row encountered. This works well in cases that don't require the scores of semantic and full-text search to combine the results. If you want to use the scores or want to support `return_score="all"`, you'll need to implement your own merging algorithm. The base `return_score` option accepts only `"relevance"` and `"all"`. Whichever methods you override, your reranker has one job on the way out: attach a `_relevance_score` column with the most relevant rows at the top. LanceDB will reject the result if that column is missing, and downstream `.limit(...)` calls trust the order you return, so sort descending before handing the table back. For vector-only reranking in Python, pass a text query to `.rerank(..., query_string="...")`. The vector query itself may be numeric, but `rerank_vector(query, vector_results)` still receives a string query so your reranker can score each candidate against the user's text intent. The method contract is: | Method | Input | Required output | | :- | :- | :- | | `rerank_hybrid` | Query text, vector results and FTS results | A merged Arrow table ordered by descending `_relevance_score` | | `rerank_vector` | Query text and vector results | An Arrow table ordered by descending `_relevance_score` | | `rerank_fts` | Query text and FTS results | An Arrow table ordered by descending `_relevance_score` | Implement only the single-search hooks your application uses. The base class raises `NotImplementedError` for those hooks until they are implemented. ### Extend an existing reranker This class definition extends `CohereReranker` to exclude text patterns after reranking. It requires the Cohere package and credentials when instantiated. It can return fewer results because exclusions happen after retrieval; use a query predicate instead when a metadata filter expresses the same restriction. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import List, Union import pyarrow as pa from lancedb.rerankers import CohereReranker class ModifiedCohereReranker(CohereReranker): def __init__(self, filters: Union[str, List[str]], **kwargs): super().__init__(**kwargs) filters = filters if isinstance(filters, list) else [filters] self.filters = filters def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table)-> pa.Table: combined_result = super().rerank_hybrid(query, vector_results, fts_results) df = combined_result.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) def rerank_vector(self, query: str, vector_results: pa.Table)-> pa.Table: vector_results = super().rerank_vector(query, vector_results) df = vector_results.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) def rerank_fts(self, query: str, fts_results: pa.Table)-> pa.Table: fts_results = super().rerank_fts(query, fts_results) df = fts_results.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) ``` The reranker receives and returns PyArrow tables. Use `to_pandas()` for a DataFrame transformation and `pa.Table.from_pandas()` to convert the result back, preserving `_relevance_score` and the desired row order. ## Evaluate relevance, latency and cost Compare rerankers on the same candidate inputs so you can distinguish ranking changes from retrieval changes. For hybrid retrieval, prepare the text index and query vectors before collecting those candidates. ### Reranking strategies Compare these approaches: * **Rank fusion:** RRF and MRR combine rank positions from multiple result lists. * **Score blending:** linear combination mixes normalized vector and text scores. * **Model-based reranking:** a model scores each query-document pair. Hybrid search uses RRF by default. You do not need to call `rerank()` to select it. Pass a reranker when you want a different algorithm or configuration. By default, rerankers return `_relevance_score`. Pass `return_score="all"` when a reranker supports it, and you also need the original vector or FTS scores for debugging. Evaluation code can rely on returned rows being ordered by descending `_relevance_score`. Empty reranked result sets still include the `_relevance_score` column. The synchronous Python hybrid `rerank(...)` method also accepts a `normalize` argument that controls how the raw vector and FTS scores are made comparable before reranking: * `normalize="score"` (the default); normalizes the raw vector and FTS scores directly. * `normalize="rank"`; converts each result list to ranks first, then normalizes. Normalization matters for algorithms that use raw scores, such as linear combination. RRF uses rank positions instead. Compare normalization settings only when the chosen reranker uses those scores. For score-based evaluation, the main built-in knobs are: * `RRFReranker(K=60)`: rank fusion with a positive smoothing constant. * `MRRReranker(weight_vector=0.5, weight_fts=0.5)`: weighted reciprocal rank fusion where the weights must sum to `1.0`. * `LinearCombinationReranker(weight=0.7, fill=1.0)`: blends vector and FTS scores directly; `fill` controls how strongly to penalize a result missing from one side. A result on one dataset does not establish which reranker will work best on another. Include representative queries and measure both retrieval quality and ranking quality. ### Historical evaluation example The tables below preserve an earlier experiment comparing multiple rerankers on \~800 hybrid search queries. This is a modified version of an evaluation script by [LlamaIndex](https://github.com/run-llama/finetune-embedding/blob/main/evaluate.ipynb) that measures hit-rate @ top-k. The recorded results do not establish performance for current models, SDK releases or your dataset; treat them as an example of an evaluation format. #### Using OpenAI `text-embedding-ada-002` Vector Search baseline: **0.64** | Reranker | Top-3 | Top-5 | Top-10 | | - | - | - | - | | Linear Combination | `0.73` | `0.74` | `0.85` | | Cross Encoder | `0.71` | `0.70` | `0.77` | | Cohere | `0.81` | `0.81` | `0.85` | | ColBERT | `0.68` | `0.68` | `0.73` | ![](https://github.com/AyushExel/assets/assets/15766192/d57b1780-ef27-414c-a5c3-73bee7808a45) #### Using OpenAI `text-embedding-3-small` Vector Search baseline: **0.59** | Reranker | Top-3 | Top-5 | Top-10 | | - | - | - | - | | Linear Combination | `0.68` | `0.70` | `0.84` | | Cross Encoder | `0.72` | `0.72` | `0.79` | | Cohere | `0.79` | `0.79` | `0.84` | | ColBERT | `0.70` | `0.70` | `0.76` | ![](https://github.com/AyushExel/assets/assets/15766192/259adfd2-6ec6-4df6-a77d-1456598970dd) ### Compare results on your workload Build a set of representative queries with known relevant records. Compare retrieval alone with each reranker using the same candidate inputs and result limit. Record a relevance metric such as recall or nDCG alongside latency and provider cost. Include queries with no useful matches and queries containing exact names or identifiers. If the relevant records never reach the reranker, adjust retrieval first. Then change one ranking setting at a time and retain the configuration that meets your application's quality and latency requirements. # Metadata Filtering in LanceDB Source: https://docs.lancedb.com/enterprise/v1-12-0/search/filtering Use predicates to select rows and control when filters apply to search. **Applies to:** Embedded ✅, Enterprise ✅ A filter restricts results to rows that satisfy a condition. Use it on its own to select records, or combine it with vector, full-text or hybrid search. For example, search for similar documents only within a particular category. > [accordion] Run a complete filtering example > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `filtered_search.py`, then run `python filtered_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `filtered_search.mts`, then run `node filtered_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([0.0, 1.0]) > .where("category = 'animals'", prefilter=True) > .select(["id", "text", "category", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([0.0, 1.0]) > .where("category = 'animals'") > .select(["id", "text", "category", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[0.0_f32, 1.0])? > .only_if("category = 'animals'") > .select(Select::columns(&["id", "text", "category", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The query vector is closest to the gardening record, but the filter excludes > that category. The results contain only the two animal records. ## Prefiltering and postfiltering * **Prefiltering**, the default, limits the rows eligible for retrieval before search chooses its candidates. * **Postfiltering** removes nonmatching rows after candidates are selected. It can return fewer than `limit` rows, including zero, even when matching records exist elsewhere in the table. Both modes exclude rows that fail the predicate. They differ in which matching rows the search can find. On hybrid queries, the filter applies to both the vector and full-text searches. SDK filters use SQL expressions without requiring a SQL connection. For Enterprise SQL queries, see [SELECT](/enterprise/v1-12-0/sql/dql/select#filtering). ## Filtering examples by language The following excerpts use a connected `db` handle. Create this sample table before running the queries beneath it; each query uses the same four records. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"vector": [3.1, 4.1], "item": "foo", "price": 10.0}, {"vector": [5.9, 26.5], "item": "bar", "price": 20.0}, {"vector": [10.2, 100.8], "item": "baz", "price": 30.0}, {"vector": [1.4, 9.5], "item": "fred", "price": 40.0}, ] table = db.create_table("metadata_filter_example", data=data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const data = [ { vector: [3.1, 4.1], item: "foo", price: 10.0 }, { vector: [5.9, 26.5], item: "bar", price: 20.0 }, { vector: [10.2, 100.8], item: "baz", price: 30.0 }, { vector: [1.4, 9.5], item: "fred", price: 40.0 }, ]; const tableName = "metadata_filter_example"; const table = await db.createTable(tableName, data, { mode: "overwrite", }); ``` ## Combine predicates Repeated filter calls combine predicates with logical `AND`. For example, `where("a > 0").where("b < 10")` is equivalent to `where("(a > 0) AND (b < 10)")`. Use a single expression for a fixed filter. Chain calls when your application builds the filter incrementally. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Both filters apply: item is in the list AND price is above 15. result = ( table.search([100, 102]) .where("item IN ('foo', 'bar', 'baz')") .where("price > 15.0") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Both filters apply: item is in the list AND price is above 15. const result = await table .search([100, 102]) .where("item IN ('foo', 'bar', 'baz')") .where("price > 15.0") .limit(3) .toArray(); ``` > [!WARNING] > > In Python SDK versions before `0.34.0` and Rust/TypeScript SDK versions before `0.31.0`, a second `where(...)` or `only_if(...)` call replaced the first filter, so only the last predicate was applied. If your code needs to run on those older versions, write a single predicate with `AND` instead of chaining calls. When upgrading to the latest SDKs, review any existing chained filters and drop earlier calls you no longer want to apply. ### Filtering Without Vector Search You can always filter your data without search. This is useful when you need to query based on metadata: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered_no_search_result = ( table.search() .where("(item IN ('foo', 'bar', 'baz')) AND (price > 15.0)") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const filteredResult = await table .query() .where("(item IN ('foo', 'bar', 'baz')) AND (price > 15.0)") .limit(3) .toArray(); ``` Set `limit()` explicitly to control how many matching records your application receives. ### Pre-Filtering with Vector Search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered_result = ( table.search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .limit(3) .toArray(); ``` ### Post-Filtering with Vector Search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} post_filtered_result = ( table.search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)", prefilter=False) .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const postFilteredResult = await table.vectorSearch([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .postfilter() .limit(3) .toArray(); ``` Postfiltering can return fewer than the requested number of records because the predicate removes candidates after search. ## Write SQL predicates Pass a SQL expression as the filter string. These expressions also select rows for SDK update and delete operations; they are not standalone SQL statements. LanceDB supports a growing list of SQL expressions: | SQL Expression | Description | | :- | :- | | `>, >=, <, <=, =` | Comparison operators | | `AND`, `OR`, `NOT` | Logical operators | | `IS NULL`, `IS NOT NULL` | Null checks | | `IS TRUE`, `IS NOT TRUE`, `IS FALSE`, `IS NOT FALSE` | Boolean checks | | `IN` | Value matching from a set | | `LIKE`, `NOT LIKE` | Pattern matching | | `CAST` | Type conversion | | `regexp_match(column, pattern)` | Regular expression matching | | [DataFusion Functions](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) | Additional SQL functions | ### Simple SQL Filters For example, the following filter string is acceptable: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search([100, 102]).where( "(item IN ('foo', 'baz')) AND (price > 20.0)" ).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .search([100, 102]) .where("(item IN ('foo', 'baz')) AND (price > 20.0)") .toArray(); ``` ### Advanced SQL Filters If your column name contains special characters, upper-case characters, or is a [SQL Keyword](https://docs.rs/sqlparser/latest/sqlparser/keywords/index.html), you can use backtick (`` ` ``) to escape it. For nested fields, each segment of the path must be wrapped in backticks. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} `CUBE` = 10 AND `UpperCaseName` = '3' AND `column name with space` IS NOT NULL AND `nested with space`.`inner with space` < 2 ``` > [!NOTE] > > Periods separate nested fields. LanceDB does not allow a literal period in a > top-level column name; backticks do not remove that restriction. ### Dates, Timestamps, Decimals Literals for dates, timestamps, and decimals can be written by writing the string value after the type name. For example: ```sql SQL icon="SQL" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} date_col = date '2021-01-01' and timestamp_col = timestamp '2021-01-01 00:00:00' and decimal_col = decimal(8,3) '1.000' ``` For timestamp columns, the precision can be specified as a number in the type parameter. Microsecond precision (6) is the default. | SQL | Time unit | | :- | :- | | `timestamp(0)` | Seconds | | `timestamp(3)` | Milliseconds | | `timestamp(6)` | Microseconds | | `timestamp(9)` | Nanoseconds | ## Apache Arrow Mapping LanceDB uses Arrow types for schemas and in-memory data. On disk, tables use the [Lance format](/enterprise/v1-12-0/basics/lance). The mapping from SQL types to Arrow types is: | SQL type | Arrow type | | :- | :- | | `boolean` | `Boolean` | | `tinyint` / `tinyint unsigned` | `Int8` / `UInt8` | | `smallint` / `smallint unsigned` | `Int16` / `UInt16` | | `int` or `integer` / `int unsigned` or `integer unsigned` | `Int32` / `UInt32` | | `bigint` / `bigint unsigned` | `Int64` / `UInt64` | | `float` | `Float32` | | `double` | `Float64` | | `decimal(precision, scale)` | `Decimal128` | | `date` | `Date32` | | `timestamp` | `Timestamp` | | `string` | `Utf8` | | `binary` | `Binary` | ## Speed up frequently used filters Consider a [scalar index](/enterprise/v1-12-0/indexing/scalar-index) on frequently filtered columns. Use the query plan to check whether a predicate uses that index. Functions or casts applied to a column can change which optimizations are available. For list columns, a label-list index supports membership filters such as `array_has_any` and `array_has_all`. ## Understand missing matches A restrictive predicate can legitimately leave fewer rows than the requested limit. Approximate vector search can also miss qualifying neighbors, and postfiltering can discard candidates without retrieving replacements. For a recall comparison, run the same query and predicate while bypassing the vector index on a suitably sized test table. Then compare the indexed query's results and latency while changing probe or refinement settings. Increasing those settings does not guarantee a full result set. See [vector search](/enterprise/v1-12-0/search/vector-search) and [query plans](/enterprise/v1-12-0/basics/sql#query-plans). # Full-Text Search (FTS) Source: https://docs.lancedb.com/enterprise/v1-12-0/search/full-text-search Find records by words, phrases or partial matches using a full-text index. **Applies to:** Embedded ✅, Enterprise ✅ Full-text search finds documents by matching words and ranks them with BM25. Use it to search for names, product codes, technical terms or phrases in your text columns. Create an FTS index on the column before running a query. You can also combine keyword matches with vector similarity using [hybrid search](/enterprise/v1-12-0/search/hybrid-search). > [accordion] Run a complete full-text search example > > Each example creates a temporary local table, runs the query and removes the > table when finished. No embedding model is needed for a text query. > > * **Python:** Install with `pip install lancedb`, save as `text_search.py`, then run `python text_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `text_search.mts`, then run `node text_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > }, > ], > ) > table.create_index("text", config=FTS()) > rows = ( > table.search("puppy", query_type="fts", fts_columns="text") > .select(["id", "text", "_score"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { id: 1, text: "A puppy playing in the park", category: "animals" }, > { id: 2, text: "A dog resting at home", category: "animals" }, > { id: 3, text: "A guide to growing tomatoes", category: "gardening" }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const rows = await table > .query() > .fullTextSearch("puppy", { columns: ["text"] }) > .select(["id", "text", "_score"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .query() > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .select(Select::columns(&["id", "text", "_score"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > Each example searches the indexed `text` column and returns the puppy record. > Higher `_score` values rank first; they are relevance scores, not probabilities. ## Basic usage The steps below create a table, index its `text` column and search for a word. For a standalone program with imports and sample data, expand the complete example above. ### Create the sample table First, open or create the table you want to search: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS uri = "data/sample-lancedb" db = lancedb.connect(uri) table = db.create_table( "my_table_fts", data=[ {"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}, {"vector": [5.9, 26.5], "text": "There are several kittens playing"}, ], ) ``` ```ts TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "data/sample-lancedb" const db = await lancedb.connect(uri); const data = [ { vector: [3.1, 4.1], text: "Frodo was a happy puppy" }, { vector: [5.9, 26.5], text: "There are several kittens playing" }, ]; const tbl = await db.createTable("my_table", data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let uri = "data/sample-lancedb"; let db = connect(uri).execute().await?; let initial_data: Box<dyn RecordBatchReader + Send> = create_some_records()?; let tbl = db .create_table("my_table", initial_data) .execute() .await?; ``` ### Build the text index Create a full-text search index on your text column: For asynchronous Python index creation, use `await table.create_index("text", config=FTS())`. See [FTS index](/enterprise/v1-12-0/indexing/fts-index). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index("text", config=FTS()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.createIndex("text", { config: lancedb.Index.fts(), }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) .execute() .await?; ``` LanceDB Embedded builds the index before the call returns. Enterprise builds it in the background. Wait for completion with Python’s `table.wait_for_index(["text_idx"])` or TypeScript’s `await tbl.waitForIndex(["text_idx"], 300)` before querying it. Use your actual index name if you chose a different one. ### Run the query Perform full-text search and retrieve results: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("puppy", query_type="fts", fts_columns="text") .limit(10) .select(["text", "_score"]) .to_list() ) # Returns the puppy record with its BM25 score. ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await tbl .search("puppy", "fts") .select(["text"]) .limit(10) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let results = tbl .query() .full_text_search(FullTextSearchQuery::new("puppy".to_owned())) .select(lancedb::query::Select::Columns(vec!["text".to_owned()])) .limit(10) .execute() .await?; ``` Specify the text column with `fts_columns="text"` in synchronous Python, especially when the table contains multiple text indexes. > [!NOTE] > > A string query can also invoke an embedding function when the table has > embedding metadata. Use `query_type="fts"` in Python when you specifically > want full-text search. If a table has more than one FTS index, specify the indexed text column in the query. In Python you can use `fts_columns` or the query builder's `nearest_to_text(..., columns=...)`; in TypeScript, use `query().nearestToText(..., columns)`. The newer Lance-native FTS does not accept legacy Tantivy-only index parameters. BM25 scores depend on the indexed corpus and its term statistics. Compare rankings on the dataset you will search; treat scores as relative relevance values rather than probabilities. ### Keeping the index up to date In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. Search includes those rows by scanning them, but that work can increase query latency. Call `optimize()` to update the index: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add([{"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}]) table.optimize() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.add([{ vector: [3.1, 4.1], text: "Frodo was a happy puppy" }]); await tbl.optimize(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.add(new_data).execute().await?; tbl.optimize(OptimizeAction::All).await?; ``` Choose a LanceDB Embedded maintenance schedule based on write volume and query latency. Inspect index coverage with `table.index_stats(...)` and optimize when the unindexed data adds too much work. `.fast_search()` skips unindexed rows, so use it only when omitting recent records is acceptable. Enterprise manages index updates automatically. You do not call `optimize()` on an Enterprise table. ## Choose the matching behavior | You need | Use | | :- | :- | | Words in any order | A terms query | | Words in a particular sequence | A [phrase query](#phrase-vs-terms-queries) and an index with token positions | | Tolerance for typing errors | [Fuzzy search](#fuzzy-search) | | Parts of words | An [n-gram index](#search-for-substring) | | Required, optional or excluded terms | [Boolean queries](#boolean-queries) | Use a metadata predicate to restrict qualifying records. See [filtering options](#filtering-options) for prefiltering and postfiltering. Enterprise SQL provides [`fts()`](/enterprise/v1-12-0/sql/dql/fts) for scored text retrieval. ## Configure tokenization and matching ### Tokenize Table Data The default tokenizer splits text at whitespace and punctuation, lowercases tokens and removes tokens longer than 40 characters. Stemming, stop-word removal and accent folding are also enabled by default. Stemming is useful for improving search results by reducing words to their root form, e.g. "running" to "run". LanceDB supports stemming for Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. You should set the `base_tokenizer` parameter rather than `tokenizer_name` because you cannot customize the tokenizer if `tokenizer_name` is specified. Tokenization and language filters are separate settings. `base_tokenizer` controls how text is split into searchable tokens. `language` controls stemming and stop-word removal when `stem=True` or `remove_stop_words=True`; choose the tokenizer for CJK or mixed-language segmentation. For example, to enable stemming for English: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index("text", language="English", replace=True) ``` Configure tokenization when you create the index. Rebuild the index to change how existing text is tokenized. **Default index parameters:** * `base_tokenizer`: `"simple"` * `language`: English * `with_position`: false * `max_token_length`: 40 * `lower_case`: true * `stem`: true * `remove_stop_words`: true * `ascii_folding`: true * `custom_stop_words`: `None`; pass a `list[str]` to drop additional words beyond the language defaults. Requires `remove_stop_words=True`. For multilingual use cases, use `base_tokenizer="icu"` for unicode-aware word segmentation on mixed-language text. ICU stands for [International Components for Unicode](https://icu.unicode.org/). The ICU tokenizer uses bundled ICU4X segmenter data, so it does not require external tokenizer model files. It is a good default when documents mix languages or include scripts where the simple tokenizer would keep an unspaced span as one large token. The Python API also supports tokenizer implementations that load language model files. Use `base_tokenizer="jieba/default"` for Jieba tokenization, which segments Chinese text into searchable word tokens when the text is written without spaces between words. Use Lindera-backed tokenizers for dictionary-based East Asian morphological segmentation, such as `base_tokenizer="lindera/ipadic"` for Japanese or `base_tokenizer="lindera/ko-dic"` for Korean when you have installed and compiled that Lindera model. These are language-specific tokenizers; ICU is the broader mixed-language option. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index( "text", base_tokenizer="jieba/default", stem=False, remove_stop_words=False, ascii_folding=False, replace=True, ) ``` Model-backed tokenizers require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to a different model root: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCE_LANGUAGE_MODEL_HOME=/path/to/lance/language_models ``` For example, `jieba/default` is resolved under `<model-home>/jieba/default/...`, `lindera/ipadic` under `<model-home>/lindera/ipadic/...`, and `lindera/ko-dic` under `<model-home>/lindera/ko-dic/...`. Model files must be installed where indexing and queries run: on your machine for LanceDB Embedded, or on the Enterprise cluster for an Enterprise table. > [!NOTE] > > Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. If you use another stemming language, such as Arabic, Greek, Romanian, Tamil, or Turkish, set `remove_stop_words=False` or pass `custom_stop_words`. Use `ascii_folding=True` to match accented and unaccented forms, such as “é” and “e”: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index( "text", language="French", stem=True, ascii_folding=True, replace=True, ) ``` ### Filtering Options Use `where(...)` to restrict text results to rows that match a predicate. Prefiltering applies the restriction before retrieval; postfiltering removes nonmatching candidates afterward and can leave fewer results. With pre-filtering: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search("puppy").limit(10).where("text='foo'", prefilter=True).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl .search("puppy") .select(["id", "doc"]) .limit(10) .where("meta='foo'") .prefilter(true) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .query() .full_text_search(FullTextSearchQuery::new("puppy".to_owned())) .select(lancedb::query::Select::Columns(vec!["doc".to_owned()])) .limit(10) .only_if("meta='foo'") .execute() .await?; ``` With post-filtering: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search("puppy").limit(10).where("text='foo'", prefilter=False).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl .search("apple") .select(["id", "doc"]) .limit(10) .where("meta='foo'") .prefilter(false) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .query() .full_text_search(FullTextSearchQuery::new(words[0].to_owned())) .select(lancedb::query::Select::Columns(vec!["doc".to_owned()])) .postfilter() .limit(10) .only_if("meta='foo'") .execute() .await?; ``` ### Phrase vs. Terms Queries > [!WARNING] > > Lance-based FTS doesn't support queries using boolean operators `OR`, `AND` in the search string. For full-text search you can specify either a **phrase** query like `"the old man and the sea"`, or a **terms** search query like `old man sea`. Enable token positions to search for phrases. Set `remove_stop_words=False` if you also need to match common words such as “the” and “and”: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS table.create_index("text", config=FTS(with_position=True, remove_stop_words=False), replace=True) ``` Storing token positions increases the index size and adds indexing work. ### Fuzzy Search Fuzzy search allows you to find matches even when the search terms contain typos or slight variations. LanceDB uses the classic [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) to find similar terms within a specified edit distance. | Parameter | Type | Default | Description | | - | - | - | - | | fuzziness | int | 0 | Maximum edit distance allowed for each term. The default, `0`, requires an exact match; set `1` or `2` to allow typos. | | max_expansions | int | 50 | Maximum number of terms to consider for fuzzy matching. Higher values may improve recall but increase search time | For a complete walkthrough that creates a sample table and demonstrates fuzzy search and relevance boosting, see [the worked example below](#fuzzy-search-and-boosting-example). ### Search for Substring LanceDB supports searching for substrings in the text column, you can set the `base_tokenizer` parameter to `"ngram"` to enable this feature, and use the parameters `ngram_min_length` and `ngram_max_length` to control the length of the substrings: | Parameter | Type | Default | Description | | - | - | - | - | | ngram_min_length | int | 3 | Minimum length of the n-grams to search for | | ngram_max_length | int | 3 | Maximum length of the n-grams to search for | | prefix_only | bool | false | Whether to only search for prefixes of the n-grams | ## Expected performance at scale Enterprise At 1 billion rows, LanceDB Enterprise reaches p50 62 ms and p99 274 ms on fully cached data with no custom tuning -- a representative floor to plan around, not a ceiling. Measured under a mixed workload of phrase, match-any and match-all queries, with an ICU-tokenized FTS v3 index (positions and lowercasing enabled, stemming disabled). The exact numbers depend on your deployment's shape (cluster size, storage class, dataset); for higher performance, talk to the sales team. ## Fuzzy Search and Boosting Example > [accordion] Worked examples: fuzzy, phrase, boosted and Boolean queries > > ### Generate Data > > Run the following steps in order. They use a temporary local database with four records, so the same data is available for each query. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import pandas as pd > from lancedb.index import FTS > from lancedb.query import MatchQuery, PhraseQuery, BoostQuery, MultiMatchQuery > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > table_name = "fts_examples" > text = ["puppy runs merrily", "car drives crazily", "puppy jumps crazily", "car runs slowly"] > text2 = ["rabbit jumps crazily", "girl runs merrily", "monkey jumps slowly", "rabbit runs merrily"] > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import * as lancedb from "@lancedb/lancedb"; > import { Index, MatchQuery, PhraseQuery, BoostQuery, MultiMatchQuery, BooleanQuery, Occur } from "@lancedb/lancedb"; > import { mkdtemp, rm } from "node:fs/promises"; > import { tmpdir } from "node:os"; > import { join } from "node:path"; > > const directory = await mkdtemp(join(tmpdir(), "lancedb-fts-")); > const db = await lancedb.connect(directory); > const tableName = "fts_examples"; > const text = ["puppy runs merrily", "car drives crazily", "puppy jumps crazily", "car runs slowly"]; > const text2 = ["rabbit jumps crazily", "girl runs merrily", "monkey jumps slowly", "rabbit runs merrily"]; > ``` > > ### Create Table > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create table with sample data > table = db.create_table( > table_name, > data=pd.DataFrame({ > "id": range(len(text)), > "text": text, > "text2": text2, > }), > mode="overwrite" > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create table with sample data > const data = text.map((value, i) => ({ id: i, text: value, text2: text2[i] })); > > const table = await db.createTable(tableName, data, { mode: "overwrite" }); > ``` > > ### Construct the index for these examples > > Create a full-text search index on the first text column: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index on first text column > table.create_index("text", config=FTS(with_position=True, remove_stop_words=False)) > table.wait_for_index(["text_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index on first text column > await table.createIndex("text", { config: Index.fts({ withPosition: true, removeStopWords: false }) }); > await table.waitForIndex(["text_idx"], 300); > ``` > > Then, create an index on the second text column: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index on second text column > table.create_index("text2", config=FTS(with_position=True, remove_stop_words=False)) > table.wait_for_index(["text2_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index on second text column > await table.createIndex("text2", { config: Index.fts({ withPosition: true, removeStopWords: false }) }); > await table.waitForIndex(["text2_idx"], 300); > ``` > > ### Basic and Fuzzy Search > > Now we can perform basic, fuzzy, and prefix match searches: > > #### Basic Exact Search > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > # Basic match (exact search) > basic_match_results = ( > table.search(MatchQuery("crazily", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Basic match (exact search) > const basicMatchResults = await table.query() > .fullTextSearch(new MatchQuery("crazily", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Fuzzy Search with Typos > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Fuzzy match (allows typos) > fuzzy_results = ( > table.search(MatchQuery("craziou", "text", fuzziness=2)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Fuzzy match (allows typos) > const fuzzyResults = await table.query() > .fullTextSearch(new MatchQuery("craziou", "text", { > fuzziness: 2, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Require an exact prefix in fuzzy matching > > `prefix_length` keeps the first characters unchanged when matching a misspelled term. It does not turn a short query into a prefix-completion search. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Fuzzy match (allows typos) > prefix_results = ( > table.search(MatchQuery("craziou", "text", fuzziness=2, prefix_length=3)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Fuzzy match (allows typos) > const prefixResults = await table.query() > .fullTextSearch(new MatchQuery("craziou", "text", { > fuzziness: 2, > prefixLength: 3, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Phrase Match > > Phrase matching enables you to search for exact sequences of words. Unlike regular text search > which matches individual terms independently, phrase matching requires words to appear in the > specified order with no intervening terms. > > > [!NOTE] > > > > Phrase queries are supported but only for a single column; providing multiple columns with a quoted phrase raises an error. > > Phrase matching is particularly useful for: > > * Searching for specific multi-word expressions > * Matching exact titles or quotes > * Finding precise word combinations in a specific order > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Exact phrase match > from lancedb.query import PhraseQuery > > phrase_results = ( > table.search(PhraseQuery("puppy runs", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Exact phrase match > const phraseResults = await table.query() > .fullTextSearch(new PhraseQuery("puppy runs", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Flexible Phrase Match > > To provide more flexible phrase matching, LanceDB supports the `slop` parameter. This allows you to match phrases where the terms appear close to each other, with gaps between them. The `slop` value limits the extra positions allowed in the phrase. > > For example, the phrase query "puppy merrily" would not return any results by default. However, if you set `slop=1`, it will match phrases like "puppy jumps merrily", "puppy runs merrily", and similar variations where one word appears between "puppy" and "merrily". > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Flexible phrase match with slop=1 for 'puppy merrily' > from lancedb.query import PhraseQuery > > slop_results = ( > table.search(PhraseQuery("puppy merrily", "text", slop=1)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Flexible phrase match with slop=1 for 'puppy merrily' > const slopResults = await table.query() > .fullTextSearch(new PhraseQuery("puppy merrily", "text", { slop: 1 })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Search with Boosting > > Boosting allows you to control the relative importance of different search terms or fields > in your queries. This feature is particularly useful when you need to: > > * Prioritize matches in certain columns > * Promote specific terms while demoting others > * Fine-tune relevance scoring for better search results > > | Parameter | Type | Default | Description | > | - | - | - | - | > | positive | Query | required | The primary query terms to match and promote in results | > | negative | Query | required | Terms to demote in the search results | > | negative_boost | float | 0.5 | Multiplier for negative matches (lower values = stronger demotion) | > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery, BoostQuery, MultiMatchQuery > > # Boost data with 'runs' in text more than 'puppy' in text > boosting_results = ( > table.search( > BoostQuery( > MatchQuery("runs", "text"), > MatchQuery("puppy", "text"), > negative_boost=0.2, > ), > ) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Search across both text and text2 > multi_match_results = ( > table.search(MultiMatchQuery("crazily", ["text", "text2"])) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Search with field boosting > multi_match_boosting_results = ( > table.search( > MultiMatchQuery("crazily", ["text", "text2"], boosts=[1.0, 2.0]), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Boosting Example > const boostingResults = await table.query() > .fullTextSearch(new BoostQuery(new MatchQuery("runs", "text"), new MatchQuery("puppy", "text"), { > negativeBoost: 0.2, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > > // Search across both text fields > const multiMatchResults = await table.query() > .fullTextSearch(new MultiMatchQuery("crazily", ["text", "text2"])) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .toArray(); > > // Search with field boosting > const multiMatchBoostingResults = await table.query() > .fullTextSearch(new MultiMatchQuery("crazily", ["text", "text2"], { > boosts: [1.0, 2.0], > })) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Search Columns as One Field > > > [!NOTE] > > > > `CombinedFieldsQuery` is not available in Python 0.41.0. This example uses the > > [0.42.0b8 client](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). `MultiMatchQuery` > > is available in 0.41.0, but does not have the same cross-field AND semantics. > > `MultiMatchQuery` scores each column on its own and keeps the best match. > `CombinedFieldsQuery` treats the columns as one field (BM25F), so with the `AND` > operator a row matches when every term appears in at least one of the columns. > The query below finds `car` in `text` and `merrily` in `text2`, returning rows 1 > and 3. The same query with `MultiMatchQuery` returns no rows, because neither > column contains both words on its own. > > Every column must use the same tokenizer configuration. The two indexes in this > example are built with the same `FTS` settings. Boosts work as they do for > `MultiMatchQuery`: one weight per column, each at least 1. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import CombinedFieldsQuery, FullTextOperator > > # Every term must appear in at least one of the two columns > combined_results = ( > table.search( > CombinedFieldsQuery("car merrily", ["text", "text2"], operator=FullTextOperator.AND), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Weight matches in text2 twice as much as matches in text > combined_boosting_results = ( > table.search( > CombinedFieldsQuery("car merrily", ["text", "text2"], boosts=[1.0, 2.0]), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > The typed `CombinedFieldsQuery` convenience class and this example are specific > to the Python SDK. Rust applications can construct the core query type exposed > by `lancedb::index::scalar`. TypeScript and Java do not yet provide typed > convenience entry points for this query. > > ### Boolean Queries > > LanceDB supports boolean logic in full-text search, allowing you to combine multiple queries using `and` and `or` operators. This is useful when you want to match documents that satisfy multiple conditions (intersection) or at least one of several conditions (union). > > #### Combining Two Match Queries > > In Python, combine two `MatchQuery` objects with `&` for intersection or `|` for union. Python's `and` and `or` operators return one operand and do not construct a boolean query. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > intersection = MatchQuery("puppy", "text") & MatchQuery("merrily", "text") > union = MatchQuery("puppy", "text") | MatchQuery("merrily", "text") > ``` > > In TypeScript, pass `[Occur, subquery]` pairs to `BooleanQuery`. Use `Must` for required matches, `Should` for alternatives, and `MustNot` to exclude matches. > > > [!NOTE] > > > > **Which queries are allowed?** > > > > A boolean query must include at least one `SHOULD` or `MUST` clause. Queries that contain only a `MUST_NOT` clause are not allowed. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > # Example: Find documents containing both "puppy" and "merrily" > and_query = MatchQuery("puppy", "text") & MatchQuery("merrily", "text") > and_results = ( > table.search(and_query) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Example: Find documents containing either "puppy" or "merrily" > or_query = MatchQuery("puppy", "text") | MatchQuery("merrily", "text") > or_results = ( > table.search(or_query) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Flexible boolean queries with MatchQuery > > // Find documents containing both "puppy" and "merrily" > const mustResults = await table > .search( > new BooleanQuery([ > [Occur.Must, new MatchQuery("puppy", "text")], > [Occur.Must, new MatchQuery("merrily", "text")], > ]), > ) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > > // Find documents containing either "puppy" or "merrily" > const shouldResults = await table > .search( > new BooleanQuery([ > [Occur.Should, new MatchQuery("puppy", "text")], > [Occur.Should, new MatchQuery("merrily", "text")], > ]), > ) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > > [!NOTE] > > > > **How to use booleans?** > > > > * Use `&` (Python), `Occur.Must` (TypeScript) for intersection (documents must match all queries). > > * Use `|` (Python), `Occur.Should` (TypeScript) for union (documents must match at least one query). > > ### Clean up the example > > Remove the temporary database when you have finished running the queries. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.close(); > db.close(); > await rm(directory, { recursive: true, force: true }); > ``` ## Substring Search Example > [accordion] Worked examples: substring search > > LanceDB supports searching for substrings in text columns using n-gram tokenization. This is useful for finding partial matches within text content. > > ### Setting Up the Table > > First, create a table with sample text data and configure n-gram tokenization: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import pyarrow as pa > from tempfile import TemporaryDirectory > from lancedb.index import FTS > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > > data = pa.table({"text": ["hello world", "lance database", "lance is cool"]}) > table = db.create_table("test", data=data) > table.create_index("text", config=FTS(base_tokenizer="ngram")) > ``` > > ### Basic Substring Search > > With the default n-gram settings (minimum length of 3), you can search for substrings of length 3 or more: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("lan", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > > results = ( > table.search("nce", query_type="fts").limit(10).to_list() > ) # spellchecker:disable-line > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > ``` > > ### Handling Short Substrings > > By default, the minimum n-gram length is 3, so shorter substrings like "la" won't match: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("la", query_type="fts").limit(10).to_list() > assert len(results) == 0 > ``` > > ### Customizing N-gram Parameters > > You can customize the n-gram behavior by adjusting the minimum length and using prefix-only matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.create_index( > "text", > config=FTS(base_tokenizer="ngram", ngram_min_length=2, prefix_only=True), > replace=True, > ) > ``` > > ### Testing Custom N-gram Settings > > With the new settings, you can now search for shorter substrings and use prefix-only matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("lan", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > > results = ( > table.search("nce", query_type="fts").limit(10).to_list() > ) # spellchecker:disable-line > assert len(results) == 0 > > results = table.search("la", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > ``` > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` ## Full-Text Search on Array Fields > [accordion] Worked examples: searching string arrays > > LanceDB supports full-text search on string array columns, enabling efficient keyword-based search across multiple values within a single field (e.g., tags, keywords). > > ### Setting Up the Connection > > This example uses a temporary local database. Run the steps in order. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import pyarrow as pa > from lancedb.index import FTS > from lancedb.query import MatchQuery, PhraseQuery > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import * as lancedb from "@lancedb/lancedb"; > import { Index, MatchQuery, PhraseQuery, makeArrowTable } from "@lancedb/lancedb"; > import { Schema, Field, List, Utf8 } from "apache-arrow"; > import { mkdtemp, rm } from "node:fs/promises"; > import { tmpdir } from "node:os"; > import { join } from "node:path"; > > const directory = await mkdtemp(join(tmpdir(), "lancedb-array-fts-")); > const db = await lancedb.connect(directory); > ``` > > ### Defining the Schema > > Create a schema that includes an array field for tags: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table_name = "fts-array-field-test" > schema = pa.schema([ > pa.field("id", pa.string()), > pa.field("tags", pa.list_(pa.string())), > pa.field("description", pa.string()) > ]) > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const tableName = "fts-array-field-test-ts"; > > // Create schema > const schema = new Schema([ > new Field("id", new Utf8(), false), > new Field("tags", new List(new Field("item", new Utf8()))), > new Field("description", new Utf8(), false) > ]); > ``` > > ### Creating Sample Data > > Generate sample data with array fields containing tags: > > ```python Python icon="python" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Generate sample data > data = { > "id": [f"doc_{i}" for i in range(10)], > "tags": [ > ["python", "machine learning", "data science"], > ["deep learning", "neural networks", "AI"], > ["database", "indexing", "search"], > ["vector search", "embeddings", "AI"], > ["full text search", "indexing", "database"], > ["python", "web development", "flask"], > ["machine learning", "deep learning", "pytorch"], > ["database", "SQL", "postgresql"], > ["search engine", "elasticsearch", "indexing"], > ["AI", "transformers", "NLP"] > ], > "description": [ > "Python for data science projects", > "Deep learning fundamentals", > "Database indexing techniques", > "Vector search implementations", > "Full-text search guide", > "Web development with Python", > "Machine learning with PyTorch", > "Database management systems", > "Search engine optimization", > "AI and NLP applications" > ] > } > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Generate sample data > const data = makeArrowTable( > Array(10).fill(0).map((_, i) => ({ > id: `doc_${i}`, > tags: [ > ["python", "machine learning", "data science"], > ["deep learning", "neural networks", "AI"], > ["database", "indexing", "search"], > ["vector search", "embeddings", "AI"], > ["full text search", "indexing", "database"], > ["python", "web development", "flask"], > ["machine learning", "deep learning", "pytorch"], > ["database", "SQL", "postgresql"], > ["search engine", "elasticsearch", "indexing"], > ["AI", "transformers", "NLP"] > ][i], > description: [ > "Python for data science projects", > "Deep learning fundamentals", > "Database indexing techniques", > "Vector search implementations", > "Full-text search guide", > "Web development with Python", > "Machine learning with PyTorch", > "Database management systems", > "Search engine optimization", > "AI and NLP applications" > ][i] > })), > { schema } > ); > ``` > > ### Creating the Table and Adding Data > > Create the table and populate it with the sample data: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create table and add data > table = db.create_table(table_name, schema=schema, mode="overwrite") > table_data = pa.Table.from_pydict(data, schema=schema) > table.add(table_data) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create table > const table = await db.createTable(tableName, data, { mode: "overwrite" }); > console.log(`Created table: ${tableName}`); > ``` > > ### Building the Full-Text Search Index > > Store token positions for phrase queries. This example disables stemming so fuzzy matching compares the original word forms: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index > table.create_index("tags", config=FTS(with_position=True, stem=False)) > table.wait_for_index(["tags_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index > console.log("Creating FTS index on 'tags' column..."); > await table.createIndex("tags", { > config: Index.fts({ withPosition: true, stem: false }) > }); > > // Wait for index > const ftsIndexName = "tags_idx"; > await table.waitForIndex([ftsIndexName], 300); > ``` > > ### Performing Fuzzy Search > > Search for terms with typos using fuzzy matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Search examples > print("\nSearching for 'learning' in tags with a typo:") > result = ( > table.search(MatchQuery("learnin", column="tags", fuzziness=1)) > .select(["id", "tags", "description", "_score"]) > .to_arrow() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Search examples > console.log("\nSearching for 'learning' in tags with a typo:"); > const fuzzyResults = await table.query() > .fullTextSearch(new MatchQuery("learnin", "tags", { > fuzziness: 1, > })) > .select(["id", "tags", "description", "_score"]) > .toArray(); > console.log(fuzzyResults); > ``` > > A string-array query can return a row more than once when several elements match. > Deduplicate by your record ID if your application needs one result per row. > > ### Performing Phrase Search > > Search for exact phrases within the array fields: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > print("\nSearching for 'machine learning' in tags:") > result = ( > table.search(PhraseQuery("machine learning", column="tags")) > .select(["id", "tags", "description", "_score"]) > .to_arrow() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > console.log("\nSearching for 'machine learning' in tags:"); > const phraseResults = await table.query() > .fullTextSearch(new PhraseQuery("machine learning", "tags")) > .select(["id", "tags", "description", "_score"]) > .toArray(); > console.log(phraseResults); > ``` > > ### Clean up the array example > > Remove the temporary database when you have finished running the queries. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.close(); > db.close(); > await rm(directory, { recursive: true, force: true }); > ``` # Hybrid Search Source: https://docs.lancedb.com/enterprise/v1-12-0/search/hybrid-search Combine vector similarity and keyword matches in a single ranked result set. **Applies to:** Embedded ✅, Enterprise ✅ Hybrid search combines vector similarity with keyword matching. It is useful when a query needs both: for example, finding products with a particular model number whose descriptions match what the customer is looking for. LanceDB runs a vector search and a full-text search, then merges their results with a reranker. Reciprocal Rank Fusion (RRF) is the default. It combines the positions of records in the two ranked lists. Before you query, store vectors and create an FTS index on the text column. > [accordion] Run a complete hybrid search example > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `hybrid_search.py`, then run `python hybrid_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `hybrid_search.mts`, then run `node hybrid_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > from lancedb.rerankers import RRFReranker > > table.create_index("text", config=FTS()) > rows = ( > table.search( > query_type="hybrid", vector_column_name="vector", fts_columns="text" > ) > .vector([1.0, 0.0]) > .text("puppy") > .rerank(RRFReranker()) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const reranker = await lancedb.rerankers.RRFReranker.create(); > const rows = await table > .vectorSearch([1.0, 0.0]) > .fullTextSearch("puppy", { columns: ["text"] }) > .rerank(reranker) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .rerank(Arc::new(lancedb::rerankers::rrf::RRFReranker::default())) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The puppy record ranks first because both searches place it first. The query > returns `_relevance_score`, with higher values first. This small example shows > the mechanics; evaluate retrieval quality with embeddings and queries from > your own application. ## Generate query embeddings automatically ### 1. Setup The following walkthrough uses Sentence Transformers in Python and OpenAI in TypeScript. Install the corresponding provider packages before starting. Python downloads a local model; TypeScript calls OpenAI. Install `lancedb sentence-transformers pandas` for Python, or `@lancedb/lancedb apache-arrow openai` for TypeScript. Set your OpenAI API key as described in the [OpenAI embedding setup](/enterprise/v1-12-0/integrations/embedding/openai). Run the steps for your chosen language in order, choosing one connection option. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS from lancedb.rerankers import RRFReranker from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/openai"; import { Utf8 } from "apache-arrow"; ``` ### 2. Connect to LanceDB Choose a LanceDB Embedded connection or use your Enterprise connection details. Embedded ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uri = "data/sample-lancedb" db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const databaseDir = "data/sample-lancedb"; const db = await lancedb.connect(databaseDir); ``` Enterprise Replace the placeholders with your Enterprise database URI, API key, region and endpoint. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` ### 3. Configure Embedding Model Configure the model used for both document and query embeddings. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} embeddings = get_registry().get("sentence-transformers").create() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const embedFunc = lancedb.embedding.getRegistry().get("openai")?.create({ model: "text-embedding-ada-002", }) as lancedb.embedding.EmbeddingFunction; ``` ### 4. Create Table and Schema Define the data structure for your documents, including both the text content and its vector representation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Documents(LanceModel): category: str text: str = embeddings.SourceField() vector: Vector(embeddings.ndims()) = embeddings.VectorField() table_name = "hybrid_search_example" table = db.create_table(table_name, schema=Documents, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const documentSchema = lancedb.embedding.LanceSchema({ category: new Utf8(), text: embedFunc.sourceField(new Utf8()), vector: embedFunc.vectorField(), }); const tableName = "hybrid_search_example"; const table = await db.createEmptyTable(tableName, documentSchema, { mode: "overwrite", }); ``` ### 5. Add Data Insert sample documents into your table, which will be used for both semantic and keyword search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"text": "rebel spaceships striking from a hidden base", "category": "film"}, {"text": "have won their first victory against the evil Galactic Empire", "category": "film"}, {"text": "during the battle rebel spies managed to steal secret plans", "category": "film"}, {"text": "to the Empire's ultimate weapon the Death Star", "category": "film"}, ] table.add(data=data) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const data = [ { text: "rebel spaceships striking from a hidden base", category: "film" }, { text: "have won their first victory against the evil Galactic Empire", category: "film" }, { text: "during the battle rebel spies managed to steal secret plans", category: "film" }, { text: "to the Empire's ultimate weapon the Death Star", category: "film" }, ]; await table.add(data); console.log(`Created table: ${tableName} with ${data.length} rows`); ``` ### 6. Build Full Text Index Create a full-text search index on the text column to enable keyword-based search capabilities. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index("text", config=FTS()) table.wait_for_index(["text_idx"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} console.log("Creating full-text search index..."); await table.createIndex("text", { config: lancedb.Index.fts(), }); await table.waitForIndex(["text_idx"], 300); ``` ### 7. Set Reranker \[Optional] RRF is the default. The examples below configure it explicitly. Other rerankers and their language support are described in [Reranking](/enterprise/v1-12-0/reranking). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reranker = RRFReranker() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const reranker = await lancedb.rerankers.RRFReranker.create(); ``` ### 8. Hybrid Search Perform a hybrid search query that combines semantic similarity with keyword matching, using the specified reranker to merge and rank the results. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search( "rebel spaceships", query_type="hybrid", vector_column_name="vector", fts_columns="text", ) .rerank(reranker) .limit(10) .to_pandas() ) print("Hybrid search results:") print(results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} console.log("Performing hybrid search..."); const queryVector = await embedFunc.computeQueryEmbeddings("rebel spaceships"); const hybridResults = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .rerank(reranker) .select(["text"]) .limit(10) .toArray(); console.log("Hybrid search results:"); console.log(hybridResults); ``` ### 9. Supply a vector and text separately You can supply the vector and text separately. The vector must use the same model and dimensions as the stored embeddings. This example reuses the model configured above; the complete example at the top also demonstrates this pattern in TypeScript and Rust. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} text_query = "rebel spaceships" vector_query = embeddings.compute_query_embeddings(text_query)[0] ( table.search(query_type="hybrid") .vector(vector_query) .text(text_query) .limit(5) .to_pandas() ) ``` ## Control the candidate results Use a result limit, metadata filters and vector distance bounds to control which candidates are available to the reranker. The examples below show each option on the query builder. > [!NOTE] > > Set `limit()` to the number of results your application needs. The default is 10. > A larger candidate set can help a reranker find relevant records, but adds work. ### Returning row IDs Pass `with_row_id(True)` (Python) or `withRowId()` (TypeScript) to include the internal `_rowid` column in the results. This is useful for joining hybrid results back to a primary table, or for deduping across multiple queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("rebel spaceships", query_type="hybrid") .with_row_id(True) .limit(10) .to_pandas() ) # results now contains a `_rowid` column alongside `_relevance_score` ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .withRowId() .limit(10) .toArray(); ``` ### Bounding vector distance `distance_range(lower, upper)` (Python) and `distanceRange(lower, upper)` (TypeScript) constrain the vector half of the hybrid query to the half-open interval `[lower, upper)`. This is helpful when you want to cap how far semantic candidates can drift from the query vector before reranking: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("rebel spaceships", query_type="hybrid") .distance_range(lower_bound=0.0, upper_bound=0.4) .limit(10) .to_pandas() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .distanceRange(0.0, 0.4) .limit(10) .toArray(); ``` Either bound can be omitted to leave that side unbounded. ### Prefilter vs. postfilter A hybrid query applies its metadata filter to both the vector and full-text searches. Prefiltering, the default, restricts eligible rows before retrieval. Postfiltering removes candidates after retrieval and can leave fewer results than requested. See [Filtering](/enterprise/v1-12-0/search/filtering). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Prefilter (default): filter applied before scoring table.search("rebel spaceships", query_type="hybrid") \ .where("category = 'film'", prefilter=True) \ .limit(10) \ .to_pandas() # Postfilter: filter applied after the sub-queries return top-k table.search("rebel spaceships", query_type="hybrid") \ .where("category = 'film'", prefilter=False) \ .limit(10) \ .to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Prefilter (default): just call .where(...) await table.query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .where("category = 'film'") .limit(10) .toArray(); // Postfilter: chain .postfilter() after .where(...) await table.query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .where("category = 'film'") .postfilter() .limit(10) .toArray(); ``` In Python, use [`explain_plan`](/enterprise/v1-12-0/basics/sql#analyzing-non-vector-queries) on a hybrid query to see whether the filter pushed into the scan or ran as a separate `FilterExec` step. ## Choose and evaluate a reranker Start with RRF, then compare alternatives on representative queries. Review which relevant rows reach the candidate set before evaluating how a reranker orders them. Record latency as well as relevance: increasing candidate counts or applying a model-based reranker adds work. Reranking runs in the application for both Embedded and Enterprise connections. See [Reranking](/enterprise/v1-12-0/reranking) for model-free fusion, model-based rerankers, custom implementations and score interpretation. In synchronous Python, `.rerank(...)` accepts a reranker and a `normalize` option (`"score"` or `"rank"`). Normalization matters for methods that blend raw scores; RRF uses rank positions. These are Python query options, not a shared signature across every SDK. # Search Source: https://docs.lancedb.com/enterprise/v1-12-0/search/index Choose vector, full-text or hybrid search and return the records your application needs. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB supports vector, full-text and hybrid search. Use vector search to find similar content, full-text search to match words, or hybrid search to combine both. Filters narrow the results to records that match your criteria. ## Choose a search method | You want to find | Use | Prepare | | :- | :- | :- | | Items similar to a query, such as related passages or images | [Vector search](/enterprise/v1-12-0/search/vector-search) | Stored vectors and a compatible query vector | | Documents represented by several embeddings | [Multivector search](/enterprise/v1-12-0/search/vector-search#multivector) | A multivector column and compatible query vectors | | Records containing particular words or phrases | [Full-text search](/enterprise/v1-12-0/search/full-text-search) | An FTS index on the text column | | Relevant meaning alongside keyword matches | [Hybrid search](/enterprise/v1-12-0/search/hybrid-search) | Vectors and an FTS index | | Rows matching a condition, without similarity ranking | [Filtering](/enterprise/v1-12-0/search/filtering) | A predicate over table columns | Vector search can run without an index. An approximate nearest-neighbor index reduces the work needed for larger tables, with a tradeoff between recall and latency. Full-text search needs an FTS index before you query it. ## Before you search For vector search, generate stored and query vectors with the same embedding model and compatible settings. Their dimensions must match. Keep the fields you want to return, such as document text or an item ID, in the same table. For full-text search, choose the text column and build its index. Enterprise builds indexes in the background, so wait for the index to be ready before querying it. Phrase queries also need token positions in the index. See [FTS indexes](/enterprise/v1-12-0/indexing/fts-index). > [accordion] Run a complete search example in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `search.py`, then run `python search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `search.mts`, then run `node search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([1.0, 0.0]) > .distance_type("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([1.0, 0.0]) > .distanceType("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .distance_type(lancedb::DistanceType::L2) > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > This query returns the puppy and dog records, ordered by vector distance. > It searches the three-row table directly, without an ANN index or an embedding > service. For connection options, see [Connect](/enterprise/v1-12-0/basics/catalog). ## Read the results Use `select()` to choose the columns your application needs and `limit()` to set the maximum number of results. The search also returns a ranking value: | Search method | Ranking column | Order | | :- | :- | :- | | Vector | `_distance` | Smaller distance first | | Full-text | `_score` | Higher text relevance first | | Hybrid | `_relevance_score` | Higher combined relevance first | These values have different meanings. Do not compare a vector distance directly with a full-text score or treat a reranker score as a probability. ## Add filters and reranking [Filters](/enterprise/v1-12-0/search/filtering) restrict which rows qualify, such as documents from a particular collection. Prefiltering searches within those rows. Postfiltering removes nonmatching rows from the candidates already retrieved, so it can leave fewer results than requested. [Reranking](/enterprise/v1-12-0/reranking) reorders the candidates returned by retrieval. Start with representative queries and expected results, then compare changes to relevance and latency. A reranker cannot recover a relevant row that retrieval never returned. ## Read large result sets in batches Materializing all rows at once can exhaust application memory. For exports and training reads, use bounded queries or the batch-reading interfaces described in [Data loading](/enterprise/v1-12-0/training/data-loading). The SDK buffers Enterprise query responses before exposing batches. Set a query limit rather than relying on batch iteration alone to bound memory. Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB Embedded interface. Use the SDK query builders for reads that need to work with both LanceDB Embedded and LanceDB Enterprise. ## Investigate a slow query Use [query plans](/enterprise/v1-12-0/basics/sql#query-plans) to see the scans, filters and indexes selected for a query. `explain_plan()` inspects the plan; `analyze_plan()` executes the query and reports measurements. Compare one change at a time, such as adding an index, returning fewer columns, or adjusting search parameters. # RTE reads Source: https://docs.lancedb.com/enterprise/v1-12-0/search/realtime-read Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table. **Applies to:** Embedded ✅, Enterprise ✅ A table with the [real time engine](/enterprise/v1-12-0/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL changes. This page covers what you get back; for enabling RTE and writing to a table, see [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write). For how Enterprise combines these results across machines, see [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read). ## Query a real time table Every query runs against the base table and the fresh tier (unflushed memtables and SSTables) in parallel, and the two are merged into one result. Fresh rows supersede base rows with the same primary key, so a row written a moment ago is already reflected: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # continuing the `frames` table connected and written to in RTE writes import numpy as np query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") frames.search(query_vector, vector_column_name="embedding").limit(10).to_list() frames.search("gripper closing on a cup", fts_columns="caption").limit(10).to_list() ``` By default every index on the table is RTE-maintained, re-read as the table changes, so a new index is picked up automatically; pin a smaller set with `RTEWriteSpec.with_maintained_indexes`. For full-text and scalar (BTree, bitmap) indexes, a maintained index covers every tier -- base table, SSTables, and the active memtable -- so a query rejects outright rather than silently skipping un-compacted rows if a resident memtable predates the index. Vector (ANN) search is maintained on the base table and SSTables the same way, and the active memtable builds its own in-memory HNSW graph as rows land, so writes stay vector-searchable within milliseconds too, without waiting on a freeze into an SSTable. That graph search steps aside for a full scan of the memtable only when it can't honor the query through a graph -- a prefilter, a primary-key override, a distance lower bound, or before the memtable has any index yet on a cold start. ## Embedded: one process, one dataset LanceDB Embedded runs this same LSM scanner directly against the local Lance dataset, in-process -- the identical merge-by-primary-key logic, the same maintained-index rules for vector, full-text, and scalar search, just with no network hop to a separate serving tier. There is no WAL node to route to and nothing to combine across machines: a query against an RTE-enabled Embedded table already reads the fresh tier together with the base table in one call. See [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read) for what Enterprise adds on top when that fresh tier is served by a separate machine from the one answering the rest of the query. Not every query shape runs through the LSM scanner -- a query that asks for `with_row_id`, time travel, multiple query vectors, hybrid search, or a handful of other combinations is rejected with a clear error asking you to set `use_rte(False)` and read the base table only, rather than silently returning a result that omits un-compacted rows. ## Limitations > [!NOTE] > > Support for all table operations on RTE tables is coming soon. Time travel, > `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet > available. ## Next steps * [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write) — enable RTE and write to a table * [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read) — combining results across machines in Enterprise * [How the real time engine works](/enterprise/v1-12-0/tables/realtime-engine#memwal-format) * [Hybrid search](/enterprise/v1-12-0/search/hybrid-search) * [Vector search](/enterprise/v1-12-0/search/vector-search) # Vector Search Source: https://docs.lancedb.com/enterprise/v1-12-0/search/vector-search Search by vector similarity, choose a distance metric and tune your queries. **Applies to:** Embedded ✅, Enterprise ✅ Vector search finds similar items by comparing their embeddings: numerical representations of text, images, audio or other data. An embedding model maps related items to nearby points in vector space, so you can search by meaning or similarity instead of matching exact words. ![An embedding model maps data into vectors for similarity search.](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/vector-db-basics.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=7fdcd20e077f4dbb6ab51e4bc3fdbacb) To run a search, pass a query vector to LanceDB and specify how many matches to return. Generate the query vector with the same model and settings used for your stored embeddings. LanceDB ranks the results by distance from the query. For small tables, you can search the vectors directly. A [vector index](/enterprise/v1-12-0/indexing/vector-index) speeds up searches on larger tables by narrowing the candidates to examine. > [accordion] Run a complete example in Python, TypeScript or Rust > > These examples create a three-row table and find the two closest matches to a > query vector. They use hand-written vectors, so you can try the query without > an embedding model. The temporary table is removed when the program finishes. > > * **Python:** Install with `pip install lancedb`, save as `vector_search.py`, then run `python vector_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `vector_search.mts`, then run `node vector_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([1.0, 0.0]) > .distance_type("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([1.0, 0.0]) > .distanceType("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .distance_type(lancedb::DistanceType::L2) > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The first result is the puppy record, whose vector exactly matches the query. > The dog record is next. `_distance` is smaller for closer matches. This example > uses an exhaustive scan; the indexing section explains how to search larger tables. ## Supported distance metrics A distance metric determines how LanceDB compares vectors. Choose the metric recommended by your embedding model. Use the same metric when building an index and querying it. LanceDB supports `l2`, `cosine`, `dot` and `hamming`. An unindexed search uses `l2` by default; Hamming distance is for binary vectors. The table below shows the value returned in the `_distance` column. Smaller values rank first. | Distance metric | Mathematical form | Notes | | - | - | - | | `l2` | $\sum_i (x_i-y_i)^2$ | Squared Euclidean distance returned in `_distance`. | | `cosine` | $1-\frac{x\cdot y}{\|x\|_2\|y\|_2}$ | Measures directional difference between vectors. Insensitive to nonzero scaling of vectors. | | `dot` | $1-\sum_i x_i y_i$ | Dot-product distance. For unit-normalized vectors, this equals cosine distance. | | `hamming` | $\underset{i}{\sum} \,\: \mathbf{1}_{\, [x_i\neq y_i]}$ | Counts the number of bitwise-differing bits between binary vectors. | For indexed search, supported distance metrics vary by index type: | Index type | Supported distance metrics | | - | - | | `IVF_FLAT` | `["l2", "cosine", "dot", "hamming"]` | | `IVF_PQ` | `["l2", "cosine", "dot"]` | | `IVF_SQ` | `["l2", "cosine", "dot"]` | | `IVF_RQ` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_FLAT` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_PQ` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_SQ` | `["l2", "cosine", "dot"]` | ### Configure Distance Metric Without a vector index, searches use `l2` by default. You can specify `cosine` or `dot` instead (`hamming` is supported for `IVF_FLAT` indexes only). When a vector index exists, the search metric must match the metric used to build the index. If you explicitly request a different metric, LanceDB cannot use that index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. LanceDB Enterprise doesn't have the limit. If you omit the search metric, current SDKs use the index metric when an index is available. Some older SDK versions sent `l2` when the metric was omitted; with a non-`l2` index, explicitly set the matching metric or upgrade the SDK. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search(np.random.random((1536))).distance_type("cosine").limit(10).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results2 = await ( tbl.search(Array(128).fill(1.2)) as lancedb.VectorQuery ) .distanceType("cosine") .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Use the same distance metric the index was trained with. let mut results = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` These examples use cosine distance and return up to ten matches. If the table has a vector index, build it with the same metric. Set `.limit(...)` on vector searches you run in applications. You can page through results with `.offset(...)` and include LanceDB's internal row id with `.with_row_id()` / `.withRowId()` when an operation requires internal row IDs. Use your own ID column for application identifiers. ## Selecting the vector column If your table has exactly one vector column, you can omit the column name and LanceDB will pick it for you. This works for both top-level columns (such as `vector`) and vector fields nested inside a struct (such as `image.embedding`). When LanceDB can't infer a single column, it raises a `ValueError` (Python) or rejects the query (Node/Rust). Two cases trigger this: * No vector column: the schema has no `fixed_size_list` or `list` of floats. * Multiple candidates: more than one column matches the query's dimension. The error lists every candidate path so you can pick one explicitly. To disambiguate, pass the field path with dot notation. Wrap any segment that contains characters outside `[A-Za-z0-9_]` in backticks (for example, `` `image-meta`.`embedding.v1` ``). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema([ pa.field("id", pa.int32()), pa.field( "image", pa.struct([pa.field("embedding", pa.list_(pa.float32(), 2))]), ), ]) table = db.create_table( "nested", data=[{"id": 0, "image": {"embedding": [0.0, 1.0]}}], schema=schema, ) # Inferred: the only vector leaf is `image.embedding`. table.search([0.0, 1.0]).limit(1).to_list() # Explicit: required when more than one vector column matches. table.search([0.0, 1.0], vector_column_name="image.embedding").limit(1).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.openTable("nested"); // Inferred: LanceDB finds the single nested vector leaf automatically. await table.query().nearestTo([0.0, 1.0]).limit(1).toArray(); // Explicit: required when more than one vector column matches. await table .query() .nearestTo([0.0, 1.0]) .column("image.embedding") .limit(1) .toArray(); ``` The same field-path syntax works when creating an index on a nested vector column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index(vector_column_name="image.embedding") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.createIndex("image.embedding"); ``` When several columns share a name across structs (for example, `image.embedding` and `text.embedding`), LanceDB still picks the one whose dimension matches your query vector. If two candidates have the same dimension, you must pass the column name explicitly. ## Search with a vector index An approximate nearest-neighbor (ANN) index narrows the set of vectors examined for a query. It can reduce query latency, but may miss neighbors that an exhaustive search would find. Compare recall and latency on queries that represent your application before choosing an index and its search settings. > [!WARNING] > > When a vector index is used, `_distance` is not always the true distance between full vectors. On quantized ANN indexes, LanceDB may compute `_distance` from the compressed representation for speed. Use `refine_factor` when you want reranking on full vectors. ### Exact vs Approximate Distances When doing vector search, the meaning of "distance" depends on whether you are using an index and whether `refine_factor` is specified as part of your query. `nprobes` controls how many partitions are searched to find candidates, `approx_mode` controls the query-time speed/recall trade-off for RQ-quantized and filtered HNSW indexes, and `refine_factor` controls how many candidates are rescored on full vectors for better distance fidelity and reranking quality. The table below summarizes the behavior of `_distance` in search results based on your query configuration: | Query mode | Neighbor quality | `_distance` in results | | :- | :- | :- | | No index or `.bypass_vector_index()` | Exact kNN (100% recall) | True distance on full vectors | | Indexed ANN, no `refine_factor` | Approximate neighbors | Distance on the index representation: exact for flat indexes, approximate for quantized indexes | | Indexed ANN + `refine_factor(1)` | Approximate neighbors (same candidate set) | Distances recomputed on full vectors for reranked candidates | | Indexed ANN + `refine_factor(>1)` | Better recall than no refine (usually) | Distances recomputed on full vectors for reranked candidates | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Indexed ANN search without refinement (fast, approximate `_distance`) fast_results = ( table.search(embedding) .limit(10) .to_pandas() ) # Recompute distances on full vectors for reranked candidates exact_distance_results = ( table.search(embedding) .limit(10) .refine_factor(1) .to_pandas() ) # Rerank a larger candidate set for better recall (higher latency) higher_recall_results = ( table.search(embedding) .limit(10) .refine_factor(20) .to_pandas() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Indexed ANN search without refinement (fast, approximate `_distance`) const fastResults = await (table.search(embedding) as lancedb.VectorQuery) .limit(10) .toArray(); // Recompute distances on full vectors for reranked candidates const exactDistanceResults = await ( table.search(embedding) as lancedb.VectorQuery ) .limit(10) .refineFactor(1) .toArray(); // Rerank a larger candidate set for better recall (higher latency) const higherRecallResults = await ( table.search(embedding) as lancedb.VectorQuery ) .limit(10) .refineFactor(20) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Approximate ANN search (fast, distances may come from the index representation) let mut fast_results = table.vector_search(&query_vector)?.limit(10).execute().await?; while let Some(batch) = fast_results.try_next().await? { println!("{:?}", batch); } // Rerank a larger candidate set on full vectors for better recall let mut refined_results = table .vector_search(&query_vector)? .limit(10) .refine_factor(20) .execute() .await?; while let Some(batch) = refined_results.try_next().await? { println!("{:?}", batch); } ``` See [vector indexes](/enterprise/v1-12-0/indexing/vector-index) for index configuration. The following sections cover query-time settings. ### Tuning `approx_mode` > [!NOTE] > > Python 0.41.0 and TypeScript 0.41.0 do not expose this setting. The Python > example baseline is 0.42.0b8; TypeScript exposes `approxMode` starting with > 0.42.0-beta.1. Rust 0.41.0 already exposes `approx_mode`. See the > [client versions](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). Use `approx_mode` when you want to adjust the speed/recall trade-off for approximate vector search at query time. It applies to RQ-quantized indexes, such as `IVF_RQ`, and to filtered searches on HNSW indexes. Other index types, and queries that bypass the index, ignore it. The supported values are: | Value | Behavior | | :- | :- | | `fast` | Prefer lower query latency, which can reduce recall. | | `normal` | Use the default balance between query latency and recall. For RQ indexes built with `num_bits=1`, this uses the same one-bit scoring path as `fast`. | | `accurate` | Prefer higher recall, which can increase query latency. | `approx_mode` defaults to `normal` and can change per query without rebuilding the index. The Python and Rust APIs call it `approx_mode`, and the TypeScript API calls it `approxMode`. On HNSW, `fast` enables ACORN traversal only when a filter leaves a non-trivial subset of rows; unfiltered or all-row searches use the regular traversal, and very selective filters may use an exact scan instead. If you also set `refine_factor`, LanceDB first uses `approx_mode` while finding candidates, then reranks the selected candidates on full vectors. ### Tuning `nprobes` For IVF vector indices, start with **Auto** by leaving the probe settings unset. LanceDB chooses how many partitions to search to balance recall and latency. It can search further if a filter leaves too few results, within any limits you set. The examples below assume `table` has an IVF index and `query_vector` uses the same embedding model and dimension as its vectors. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Start with Auto. auto = table.search(query_vector).limit(10).to_arrow() ``` #### Adjust speed and recall Use `search_effort` to tune how much work a search does. It accepts values from `0` to `1`; `0.5` uses Auto. Increase it to search more partitions when recall is too low, or decrease it when you can trade some recall for lower latency. `search_effort(0.95)` does **not** mean 95% recall. SDK builds using Lance 15.0.0-beta.11 or later provide these calibrated tiers: | Effort | Empirical mean partition-routing target | | :- | :- | | `0.1` | 80% | | `0.25` | 90% | | `0.5` (default) | Approximately 95%; existing Auto behavior | The probe budget adapts to the distance metric and requested `k`, so you can keep the same effort when changing the result count. The lower tiers were calibrated for `l2`, `cosine` and `dot` through `k=100000`. This is the tested range, not a limit on `k`; Hamming and larger requests remain uncalibrated. These are average routing objectives, not guarantees for each query or final Recall\@k. Quantization, filtering and explicit probe bounds can lower final recall. Remote queries require a server with the corresponding Lance version; upgrading only the client does not change server-side routing. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Search more partitions to try to improve recall. higher_effort = table.search(query_vector).search_effort(0.75).limit(10).to_arrow() ``` Measure the effect on your queries. Higher effort may add latency without improving recall. With no maximum set, `search_effort(1)` searches all partitions and can be expensive. In TypeScript, the method is named `searchEffort`. #### Set probe limits Use explicit probe counts when you have measured a suitable range for your workload: | Parameter | When to use it | | :- | :- | | `minimum_nprobes` | Set a lower bound on how many partitions to search. Auto may search more from the start. | | `maximum_nprobes` | Cap the number of partitions searched, including additional searches needed to fill the result count. A low cap can reduce recall or return fewer results than requested. | | `nprobes` | Search a fixed number of partitions instead of using Auto. Useful for comparing settings in a benchmark. | Counts apply **per index segment**, not to the entire query. With many segments, more probes can mean substantially more data reads and cache-fill writes. A probe cap is not a limit on total latency or I/O. Use positive counts and keep the minimum no larger than the maximum. Leave the maximum unset to allow further searching as needed. If filtered queries return too few results, raise or remove that cap; see the [bounded-search example](/enterprise/v1-12-0/indexing/vector-index#probe-limits-example). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Use a fixed probe count. fixed = table.search(query_vector).nprobes(20).limit(10).to_arrow() ``` Prefer choosing either effort or a fixed count. If both are set, explicit `search_effort` overrides `nprobes`. Explicit min/max bounds still apply; setting them equal fixes the count. #### Check result quality Auto was tuned toward roughly **95% average recall** in benchmark tests. That is a starting point, not a guarantee for your data or every query. Returning `k` results also does not mean they are the true nearest `k` neighbors. [Measure recall](/enterprise/v1-12-0/indexing/vector-index#measuring-vector-recall) on representative queries against an exact search with the same metric and filter. Test the settings you intend to use: an Auto search capped at 50 probes can search fewer partitions than fixed `nprobes(50)`, so the two can have different recall. If more probes stop improving quality, try increasing `refine_factor` or using a higher-precision index. More probes do not remove quantization error, and refinement can only rerank the candidates the search finds. > [!NOTE] > > The Python examples use APIs available in LanceDB 0.41.0. Remote queries need > server support too. Older clients may send fixed probe settings by default; > upgrading the server alone does not switch those requests to Auto. > > Auto's calibration covers `l2`, `cosine` and `dot` searches up to `k=100000`. > For Hamming or larger requests, measure quality and latency on your workload > before relying on the defaults. ### Vector Search with Prefiltering This is the default vector search setting. You can use prefiltering to boost query performance by reducing the search space before vector calculations begin. The system first applies your filter criteria to the dataset, then conducts vector search operations only on the remaining relevant subset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datasets import load_dataset # Load query vector from dataset query_dataset = load_dataset("sunhaozhepy/ag_news_sbert_keywords_embeddings", split="test[5000:5001]") print(f"Query keywords: {query_dataset[0]['keywords']}") query_embed = query_dataset["keywords_embeddings"][0] # Open table and perform search table_name = "lancedb-enterprise-quickstart" table = db.open_table(table_name) # Vector search with filters (pre-filtering is the default) search_results = ( table.search(query_embed) .where("label > 2") .select(["text", "keywords", "label"]) .limit(5) .to_pandas() ) print("Search results (with pre-filtering):") print(search_results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Generate a sample 768-dimension embedding vector (typical for BERT-based models) // In real applications, you would get this from an embedding model const dimensions = 768; const queryEmbed = Array.from( { length: dimensions }, () => Math.random() * 2 - 1, ); // Open table and perform search const tableName = "lancedb-enterprise-quickstart"; const table = await db.openTable(tableName); // Vector search with filters (pre-filtering is the default) const vectorResults = await table .search(queryEmbed) .where("label > 2") .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Search results (with pre-filtering):"); console.log(vectorResults); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Prefiltering is the default: the filter is applied before vector search. let mut results = table .vector_search(&query_vector)? .only_if("id > 100") .select(Select::columns(&["id"])) .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` The filter limits which rows can match. Use `select()` to choose the returned columns and `limit()` to set the maximum number of results. ### Vector Search with Postfiltering Postfiltering selects vector-search candidates before applying the metadata predicate. It can return fewer matches than requested, even when other rows in the table satisfy the predicate. Use prefiltering when you want the nearest records within the matching subset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results_post_filtered = ( table.search(query_embed) .where("label > 1", prefilter=False) .select(["text", "keywords", "label"]) .limit(5) .to_pandas() ) print("Vector search results with post-filter:") print(results_post_filtered) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const vectorResultsWithPostFilter = await ( table.search(queryEmbed) as lancedb.VectorQuery ) .where("label > 2") .postfilter() .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Vector search results with post-filter:"); console.log(vectorResultsWithPostFilter); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Apply the filter after vector search by calling postfilter(). let mut results = table .vector_search(&query_vector)? .only_if("id > 100") .postfilter() .select(Select::columns(&["id"])) .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Only retrieved candidates that satisfy the predicate remain in the result. Increase the candidate limit or use prefiltering if too few records are returned. > [card] > > [Post-filtering](/enterprise/v1-12-0/search/filtering/#post-filtering-with-vector-search) in LanceDB applies > the filter condition after obtaining the nearest neighbors based on vector similarity. ## Multivector Search Use multivector search when your documents contain multiple embeddings and you need sophisticated matching between query and document vector pairs. The late interaction approach finds the most relevant combinations across all available embeddings and provides nuanced similarity scoring. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_multi = np.random.random(size=(2, 256)) results_multi = tbl.search(query_multi).limit(5).to_pandas() ``` Here you can see how to take 2 query vectors and find the best matching pairs between them and document vectors using late interaction. The `np.random.random(size=(2, 256))` creates a 2×256 array with two random query vectors, `.limit(5)` returns the top 5 best document-query combinations, and `.to_pandas()` provides results in a DataFrame format. For the supported metric, how scoring works and a complete example, see the [multivector search walkthrough](#multivector). ## Advanced Search Scenarios ### Search With Distance Range Use `distance_range` search when you need vectors within particular similarity bounds rather than just the closest neighbors. The system filters results to only include vectors that fall within your specified distance thresholds from the query. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(256) # Search for the vectors within the range of [0.1, 0.5) tbl.search(query).distance_range(0.1, 0.5).to_arrow() # Search for the vectors with the distance less than 0.5 tbl.search(query).distance_range(upper_bound=0.5).to_arrow() # Search for the vectors with the distance greater or equal to 0.1 tbl.search(query).distance_range(lower_bound=0.1).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results3 = await ( tbl.search(Array(128).fill(1.2)) as lancedb.VectorQuery ) .distanceType("cosine") .distanceRange(0.1, 0.2) .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Only return rows whose distance falls within [0.1, 0.5). let mut results = table .vector_search(&query_vector)? .distance_range(Some(0.1), Some(0.5)) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` This shows three ways to search within distance ranges: bounded, upper bound only, and lower bound only. The `distance_range()` method filters results by similarity thresholds - the first example finds vectors with distance between `0.1` and `0.5`, the second finds vectors closer than `0.5`, and the third finds vectors farther than `0.1`. Each approach returns Arrow tables with vectors that fall within your specified distance thresholds. ### Search With Binary Vectors Use binary vector search for scenarios involving binary embeddings, such as those produced by hashing algorithms. The system stores these efficiently as packed uint8 arrays and uses Hamming distance calculations to determine vector similarity. > [!TIP] > > The number of dimensions of the binary vector must be a multiple of 8. A vector of dimensionality 128 will be stored as a `uint8` array of size 16. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa schema = pa.schema( [ pa.field("id", pa.int64()), # for dim=256, lance stores every 8 bits in a byte # so the vector field should be a list of 256 / 8 = 32 bytes pa.field("vector", pa.list_(pa.uint8(), 32)), ] ) tbl = db.create_table("my_binary_vectors", schema=schema) data = [] for i in range(1024): vector = np.random.randint(0, 2, size=256) # pack the binary vector into bytes to save space packed_vector = np.packbits(vector) data.append( { "id": i, "vector": packed_vector, } ) tbl.add(data) query = np.random.randint(0, 2, size=256) packed_query = np.packbits(query) tbl.search(packed_query).distance_type("hamming").to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.createTable("binary_vectors", data, { mode: "overwrite", }); await tbl.createIndex("vector", { config: lancedb.Index.ivfFlat({ numPartitions: 10, distanceType: "hamming", }), }); const query = Array(32) .fill(1) .map(() => Math.floor(Math.random() * 255)); const results = await tbl.query().nearestTo(query).limit(10).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Binary vectors use `hamming` distance over the packed uint8 bytes. let query: Arc<dyn Array> = Arc::new(UInt8Array::from(vec![1u8; NUM_BYTES as usize])); let mut results = tbl .vector_search(query)? .distance_type(DistanceType::Hamming) .limit(10) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Here you can see how to set up a table for binary vectors, pack them efficiently into bytes, and search using Hamming distance. The schema defines a 32-byte vector field (256 bits ÷ 8), `np.random.randint(0, 2, size=256)` creates binary vectors, `np.packbits()` compresses them to bytes, and `.distance_type("hamming")` specifies `hamming` distance for similarity calculation. The search produces an Arrow table with binary vectors ranked by how many bits differ from the query. ## Scaling Vector Search ### Query multiple vectors in a batch Batch search accepts multiple query vectors in one request. The `query_index` column identifies which query produced each result. Measure throughput and latency with your workload when choosing a batch size. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Load a batch of query embeddings query_dataset = load_dataset( "sunhaozhepy/ag_news_sbert_keywords_embeddings", split="test[5000:5005]" ) query_embeds = query_dataset["keywords_embeddings"] batch_results = table.search(query_embeds).limit(5).to_pandas() print(batch_results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Batch query console.log("Performing batch vector search..."); const batchSize = 5; const queryVectors = Array.from({ length: batchSize }, () => Array.from({ length: dimensions }, () => Math.random() * 2 - 1), ); let batchQuery = table.search(queryVectors[0]) as lancedb.VectorQuery; for (let i = 1; i < batchSize; i++) { batchQuery = batchQuery.addQueryVector(queryVectors[i]); } const batchResults = await batchQuery .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Batch vector search results:"); console.log(batchResults); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Search multiple query vectors in one call. Each result row carries a // `query_index` mapping it back to the query it matched. let mut results = table .vector_search(&query_1)? .add_query_vector(&query_2)? .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Each input vector has its own nearest-neighbor results. Use `query_index` to associate each row with the corresponding input vector. ### Include or skip unindexed rows To optimize for speed over completeness, enable the `fast_search` flag in your query to skip searching unindexed data. By default, search includes both indexed vectors and unindexed rows visible to the query. LanceDB scans the unindexed rows directly. `fast_search` skips that scan, which can reduce query time but omit recent records. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search(embedding, fast_search=True).limit(5).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .query() .nearestTo(embedding) .fastSearch() .limit(5) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Skip unindexed data for lower latency. let mut results = table .vector_search(&query_vector)? .fast_search() .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Use this option only when results from indexed data are sufficient. ### Expected performance at scale Enterprise At 1 billion rows, LanceDB Enterprise reaches p50 28 ms and p99 58 ms on fully cached data with no custom tuning -- a representative floor to plan around, not a ceiling. Measured with 1,536-dimensional embeddings, an IVF-RQ index, `nprobe=8`, `k=100`, on the best-performing configuration tested at that scale. The exact numbers depend on your deployment's shape (cluster size, storage class, dataset); for higher performance, talk to the sales team. ## Search without a vector index ### Search With No Index The simplest way to perform vector search is to perform a brute force search, without an index, where the distance between the query vector and all the vectors in the database are computed, with the top-k closest vectors returned. This is equivalent to a k-nearest neighbours (kNN) search in vector space. Choose brute force search when you need guaranteed 100% recall, typically with smaller datasets where query speed isn't the primary concern. The system scans every vector in the table and calculates precise distances to find the exact nearest neighbors. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search(np.random.random((1536))).limit(3).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.openTable("my_vectors"); const results1 = await tbl.search(Array(128).fill(1.2)).limit(3).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // A plain vector search returns the top-k closest rows. let mut results = table.vector_search(&query_vector)?.limit(3).execute().await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` These queries return the three nearest matches. Without a vector index, LanceDB calculates distances directly from the stored vectors. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/knn_search.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=4955d72d7e418a7561be2f20baf16b44) Exhaustive search does more work as the table grows. When query latency becomes too high, add an ANN index and compare its results with the exhaustive baseline. ### Bypass the Vector Index Use `bypass_vector_index` to get exact, ground-truth results by performing exhaustive searches across all vectors. Instead of relying on approximate methods, the system directly compares your query against every vector in the table, ensuring 100% recall at the cost of increased query time. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search(embedding).bypass_vector_index().limit(5).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .query() .nearestTo(embedding) .bypassVectorIndex() .limit(5) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Force an exhaustive (flat) scan for exact, ground-truth results. let mut results = table .vector_search(&query_vector)? .bypass_vector_index() .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` This skips the approximate index and checks every single vector for exact, ground-truth results. The `.bypass_vector_index()` method forces LanceDB to perform an exhaustive search through all vectors instead of using the approximate nearest neighbor index, ensuring exact results but at the cost of slower performance. The query returns the nearest five rows within its filters and distance bounds. Use an exhaustive scan as a baseline when measuring ANN recall. This approach is particularly useful when: * Evaluating ANN index quality * Calculating recall metrics to tune index parameters * Ensuring exact results for critical applications ## Multivector search walkthrough LanceDB's multivector support enables you to store and search multiple vector embeddings for a single item. This capability is particularly valuable when working with late-interaction models like ColBERT and ColPaLi, which generate multiple embeddings per document. In this tutorial, you'll create a table with multiple vector embeddings per document and learn how to perform multivector search. For more end-to-end examples, see the [VectorDB recipes repository](https://github.com/lancedb/vectordb-recipes/tree/main/examples). ### Multivector Support Each item in your dataset can have a column containing multiple vectors, which LanceDB can efficiently index and search. When performing a search, you can query with either a single vector embedding or multiple vector embeddings. > [!WARNING] > > Currently, only the `cosine` metric is supported for multivector search. The vector value type can be `float16`, `float32`, or `float64`. Each query vector must match the inner vector dimension in the multivector column. This applies to both single-vector queries and multi-vector query matrices. ### Computing Similarity MaxSim (Maximum Similarity) is a key concept in late-interaction models that: * Computes the maximum similarity between each query embedding and all document embeddings * Sums these maximum similarities to get the final relevance score * Effectively captures fine-grained semantic matches between query and document tokens The MaxSim calculation can be expressed as: $$ \text{MaxSim}(Q, D) = \sum_{i=1}^{|Q|} \max_{j=1}^{|D|} \text{sim}(q_i, d_j) $$ Where $sim$ is the similarity function (e.g., cosine similarity). $$ Q = \{q_1, q_2, ..., q_{|Q|}\} $$ $Q$ represents the query embeddings, and $D = \{d_1, d_2, ..., d_{|D|}\}$ represents the document embeddings. ### Using Multivector Search #### 1. Setup Connect to a local LanceDB database and import the required libraries. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa db = lancedb.connect("data/multivector_demo") ``` > [!NOTE] > > To run this walkthrough on LanceDB Enterprise, connect with > `lancedb.connect(uri="db://your-database", api_key="your-api-key", region="your-region")` > instead. The remaining steps are the same. #### 2. Define Schema Define a schema that specifies a multivector field. A multivector field is a nested list structure in which each document contains multiple vectors. In this case, we'll create a schema with: 1. An ID field as an integer (int64) 2. A vector field that is a list of lists of float32 values * The outer list represents multiple vectors per document * Each inner list is a 256-dimensional vector * Using float32 for memory efficiency while maintaining precision ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} schema = pa.schema( [ pa.field("id", pa.int64()), # float16, float32, and float64 are supported pa.field("vector", pa.list_(pa.list_(pa.float32(), 256))), ] ) ``` #### 3. Generate Multivectors Generate sample data where each document contains multiple vector embeddings, which can represent different aspects or views of the same document. In this example, we create **1024 documents** where each document has **2 random vectors** of **dimension 256**, simulating a real-world scenario where you might have multiple embeddings per item. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ { "id": i, "vector": np.random.random(size=(2, 256)).tolist(), # Each document has 2 vectors } for i in range(1024) ] ``` #### 4. Create a Table Create a table with the defined schema and sample data, which will store multiple vectors per document for similarity search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("multivector_example", data=data, schema=schema) ``` #### 5. Build an Index Only cosine similarity is supported for multivector search operations. For faster search, build the standard `IVF_PQ` index over your vectors: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.create_index(metric="cosine", vector_column_name="vector") ``` > [!NOTE] > > **Indexing matters more for multivector tables than for single-vector ones.** > > A brute-force scan over a multivector column has to compare every query vector to every document vector in every row, so the cost grows with both the row count and the number of vectors per row. > In LanceDB Embedded, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. > > On LanceDB Cloud, the brute-force KNN safety check applies a stricter row threshold to multivector columns; roughly 10× lower than for single-vector columns. So an unindexed multivector table can be rejected with a "vector search would use brute-force KNN" error well before a comparable single-vector table would. LanceDB Enterprise doesn't have the limit. Build the index before you start hitting it from production traffic, even if the dataset is small enough that you'd skip indexing for a single-vector workload. #### 6. Query a Single Vector When searching with a single query vector, it will be compared against all vectors in each document, and the similarity scores will be aggregated to find the most relevant documents. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(256) results_single = tbl.search(query).limit(5).to_pandas() ``` #### 7. Query Multiple Vectors With multiple query vectors, LanceDB calculates similarity using late interaction, a late-interaction technique that computes relevance by finding the best-matching pairs between query and document vectors. This approach provides more nuanced matching while maintaining fast retrieval speeds. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_multi = np.random.random(size=(2, 256)) results_multi = tbl.search(query_multi).limit(5).to_pandas() ``` Visit the [HuggingFace embedding integration](/enterprise/v1-12-0/integrations/embedding/huggingface/) page for information on embedding models. ### Simple Example: ColBERT Embeddings [ColBERT](https://arxiv.org/abs/2004.12832) is the most well-known late-interaction retrieval model that represents each document and query as multiple token embeddings and scores matches by taking the best token-to-token similarities (MaxSim) across them. Install the dependencies before running this example: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install pylate lancedb pandas ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa from pylate import models ## 1) Load a late-interaction model via PyLate ## PyLate docs show ColBERT() + encode(..., is_query=...) model = models.ColBERT(model_name_or_path="lightonai/GTE-ModernColBERT-v1") ## You can discover dim from one embedding (avoid guessing) dim = model.encode(["hello"], is_query=True)[0].shape[1] ## 2) Create a LanceDB table with a multivector column db = lancedb.connect("./pylate_lancedb") schema = pa.schema([ pa.field("doc_id", pa.string()), pa.field("text", pa.string()), # multivector: list<list<float32, dim>> pa.field("mv", pa.list_(pa.list_(pa.float32(), dim))), ]) docs = [ {"doc_id": "1", "text": "The train to Tokyo leaves at 5pm."}, {"doc_id": "2", "text": "That Pho restaurant in Hanoi is highly rated."}, {"doc_id": "3", "text": "This is a noodle bar in Osaka, Japan."}, ] ## 3) Encode documents with PyLate (token vectors per doc) doc_texts = [d["text"] for d in docs] doc_embs = model.encode(doc_texts, is_query=False) # list/array of (T, dim) per doc rows = [] for d, emb in zip(docs, doc_embs): emb = np.asarray(emb, dtype=np.float32) rows.append({**d, "mv": emb.tolist()}) tbl = db.create_table("docs", data=rows, schema=schema, mode="overwrite") ## 4) Build an index + query using a query matrix. ## Multivector brute-force scales with rows × vectors-per-row, so build the index ## at much smaller dataset sizes than you would for single-vector search; and ## always before exposing the table to remote traffic. tbl.create_index(vector_column_name="mv", metric="cosine") query = "Tell me about ramen in Japan" q_emb = np.asarray(model.encode([query], is_query=True)[0], dtype=np.float32) # (Tq, dim) out = tbl.search(q_emb).limit(5).to_pandas() # multivector search accepts a matrix print(out[["doc_id", "text"]]) ``` Late-interaction model implementations evolve rapidly, so it's a good idea to check the latest popular models when trying multivector search. ### Advanced Example: XTR Embeddings [ConteXtualized Token Retriever (XTR)](https://arxiv.org/abs/2304.01982) is a late-interaction retrieval model that represents text as token-level vectors instead of a single embedding. This lets search score token-to-token matches (MaxSim), which can improve fine-grained relevance. The notebook linked below shows how to integrate XTR, which prioritizes critical document tokens during the initial retrieval stage and removes the gathering stage to improve performance significantly. By focusing on the most semantically salient tokens early in the process, XTR reduces computational complexity while improving recall and ensuring rapid identification of candidate documents. > [card] [Multivector search with ColPali + XTR embeddings and LanceDB](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/multivector_xtr/main.ipynb) # Consistency Source: https://docs.lancedb.com/enterprise/v1-12-0/tables/consistency Understand when readers see changes and choose the freshness your application needs. **Applies to:** Embedded ✅, Enterprise ✅ ## Table snapshots and freshness Each table read uses one committed version of the data. **Freshness** describes whether that version includes recent writes. For example, after another application appends records, an already-open table handle can still read the version from before the append. For example, a dashboard may need the latest updates, while an experiment may need to keep reading a specific table version. Use read freshness settings for the dashboard and an explicit table version for the experiment. ## Visibility of writes In **LanceDB Embedded**, a table handle sees its own committed writes. By default, it does not automatically check for changes made through other handles or processes. Use a read consistency interval or `checkout_latest()` to pick up those changes. In **LanceDB Enterprise**, readers use the service's configured freshness policy. A connection can request fresher data. When a read must include a completed write, use a zero interval or call `checkout_latest()` after the write, with a client and server that support these freshness controls. ## Configure read freshness Set `read_consistency_interval` when connecting. This controls when reads pick up newer table versions; it does not change how writes commit. | Setting | Embedded | Enterprise | | - | - | - | | **Unset** | Keep the open table version until explicitly refreshed or changed by that handle. | Use the service's configured freshness policy. | | **Zero** | Check for the latest committed version on every read. | Request the latest committed version on every read. | | **Non-zero interval** | Check for updates on a read once the interval since the last check has elapsed. | Request data no older than the interval allows; the service may return fresher data. | `checkout_latest()` explicitly refreshes an Embedded table handle. On Enterprise it asks subsequent reads on that handle to reflect data at least as recent as the refresh request. To read a fixed historical version instead, use [table versioning](/enterprise/v1-12-0/management/table#versioning). > [accordion] Complete Python example: compare two readers > > Install the Python SDK with `pip install lancedb`, then save this as > `consistency.py` and run `python consistency.py`. It creates a temporary local > database and removes it when finished. No Enterprise connection is needed. > > ```python consistency.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from datetime import timedelta > > import lancedb > > writer = lancedb.connect(uri) > table = writer.create_table("documents", [{"id": 1, "text": "first"}]) > > default_reader = lancedb.connect(uri).open_table("documents") > latest_reader = lancedb.connect( > uri, read_consistency_interval=timedelta(0) > ).open_table("documents") > > table.add([{"id": 2, "text": "second"}]) > > default_count = default_reader.count_rows() > latest_count = latest_reader.count_rows() > print(f"Default reader: {default_count} rows") # 1 > print(f"Zero-interval reader: {latest_count} rows") # 2 > > default_reader.checkout_latest() > refreshed_count = default_reader.count_rows() > print(f"After explicit refresh: {refreshed_count} rows") # 2 > ``` > > The default reader sees one row until refreshed. The reader with a zero > interval sees the new row on its next read. ## Choose a freshness interval * **Reads that must include recent writes:** use a zero interval. Checking more frequently can increase read latency and storage requests. * **Dashboards with an acceptable delay:** choose an interval within that delay budget, then measure the effect on latency and cost. * **Reproducible experiments:** read an explicit table version and retain it for as long as the experiment needs it. Choose the interval based on the delay your application can tolerate between a write completing and a reader seeing it. ## Learn more * [Connect](/enterprise/v1-12-0/basics/catalog): configure your client. * [Table versioning](/enterprise/v1-12-0/management/table#versioning): read and restore retained versions. * [Guarantees](/enterprise/v1-12-0/basics/guarantees): understand commit and failure boundaries. For invalid vector handling during ingestion, see [Create a table](/enterprise/v1-12-0/ingestion/create-table#from-a-custom-schema). # Real Time engine (RTE) Source: https://docs.lancedb.com/enterprise/v1-12-0/tables/realtime-engine Absorb small, frequent writes cheaply and make them queryable within milliseconds. **Applies to:** Embedded ✅, Enterprise ✅ ## What is the real time engine? Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. The real time engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. ## The Lance MemWAL format RTE is built on **MemWAL**, a log-structured-merge (LSM) format that Lance itself defines -- the structure Enterprise serves is part of the open Lance format, not a layer bolted on beside it. A table with RTE enabled is divided into one or more **shards** (see [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write#primary-key) for enabling and sizing them), and each shard holds: * A **memtable**: the active, in-memory table for that shard's newest rows, queryable as soon as a write lands in it. * A **WAL buffer**: the same writes, batched and flushed to object storage before a write is acknowledged, so an unflushed memtable is never the only copy of a row. * Its own **in-memory indexes** (vector, full-text, BTree, and other scalar types), kept current as rows land, independently of the base table's indexes. A write commits in two stages, both before it is acknowledged: the WAL buffer append makes it durable, then it lands in the shard's memtable. When a memtable crosses a size or row-count threshold, it freezes and flushes as an immutable **SSTable** -- an ordinary Lance data file -- and a fresh memtable takes over. [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction) later folds SSTables into the base table, catching its indexes up as it goes. ## WAL nodes serve MemWAL shards This section describes LanceDB Enterprise's serving layer. LanceDB Embedded runs the same MemWAL mechanics directly against the local dataset, in one process -- there is no separate node to route to or scale; see [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write#getting-started) and [RTE reads](/enterprise/v1-12-0/search/realtime-read#embedded) for what that looks like. RTE's Enterprise serving layer is a dedicated component, separate from the [query nodes and plan executors](/enterprise/v1-12-0/enterprise/distributed-search) that serve ordinary queries: | Component | Responsibility | | - | - | | WAL node | Own one or more tables' shards; append their WAL, maintain their memtables and in-memory indexes, and serve reads and writes against them. | A query node routes every request for an RTE-enabled table -- reads and writes alike -- to the WAL node that owns that table, by a consistent hash of the database and table name. WAL node pods share nothing but the underlying object storage; no pod talks to another one directly. One WAL node owns every shard of a given table. Splitting a table into more shards parallelizes that table's own writes into more independent append streams on the node that already owns it; adding more WAL node replicas instead spreads ownership of more *tables* across more pods. Shard a large table to raise its own ingest ceiling, and add WAL node replicas to raise the cluster's overall capacity. If a WAL node pod is replaced, its successor must claim ownership of a shard, by a version number that only ever increases, before writing to it -- so two pods are never both appending to the same shard's WAL at once. ## Reading a real time table Every query runs against the base table and the fresh tier -- every shard's memtable and not-yet-compacted SSTables -- in parallel. Fresh rows supersede base rows with the same primary key, and the two are merged into one result. See [RTE reads](/enterprise/v1-12-0/search/realtime-read) for what this means for query results. ## Next steps * [RTE writes](/enterprise/v1-12-0/ingestion/realtime-write) — enable RTE and write to a table * [RTE reads](/enterprise/v1-12-0/search/realtime-read) — query an RTE table * [Distributed RTE Write](/enterprise/v1-12-0/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes * [Distributed RTE Read](/enterprise/v1-12-0/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines * [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction) — how Enterprise folds shards into the base table # Multicloud Source: https://docs.lancedb.com/enterprise/v1-12-0/deployment/multicloud Keep deployment orchestration in your cloud while dispatching compute-heavy work, like GPU UDF execution, to run in a different cloud. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB Enterprise deployment doesn't have to keep all of its compute in one cloud. Orchestration -- query nodes, job coordination, the catalog -- stays with your deployment in its own cloud account and region. Specific, compute-heavy work, such as a GPU-bound Function's execution during a refresh, can instead dispatch to run in a **different** cloud account, region, or provider entirely, and send its results back to complete the job. ## How it fits together Your deployment's job orchestration plans the work and tracks it to completion the same way it would locally. The part that actually needs the remote capacity -- a GPU UDF call, for example -- runs across a network boundary instead of on a worker in your own cloud, and reports its result back the same way a local worker would. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph P["Your cloud"] direction TB QN["Query node"] Job["Job orchestration"] end subgraph R["Remote cloud"] direction TB Exec["Compute execution<br/>(e.g. GPU UDFs)"] end QN --> Job Job -- "dispatches work" --> Exec Exec -- "results" --> Job classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Exec accent ``` ## Why it matters The cloud that's right for your primary deployment -- where your data and other infrastructure already live -- isn't always the cloud with the best GPU availability or pricing. Splitting orchestration from execution means you don't have to choose: keep your deployment where it already makes sense, and reach compute capacity elsewhere only for the work that actually needs it, without migrating the deployment or operating that remote capacity yourself. [Contact us](https://www.lancedb.com/contact) to learn more about setting up cross-cloud execution for your deployment. ## What to read next > [card] [Slurm](/enterprise/v1-12-0/deployment/slurm) > > A common way the remote cloud's compute gets scheduled: as Slurm jobs. > [card] [Adaptive Execution](/enterprise/v1-12-0/enterprise/adaptive-execution) > > How a refresh's resource class, part size and worker count adjust themselves. # Monitor LanceDB with OpenTelemetry Source: https://docs.lancedb.com/enterprise/v1-12-0/deployment/opentelemetry Export LanceDB object store request counts, bytes, latency, errors, and throttles to any OpenTelemetry backend. LanceDB emits internal metrics (currently object store request counts, bytes transferred, request latency, retryable errors, and throttles) and can bridge them into any [OpenTelemetry](https://opentelemetry.io/) backend. Use this to watch how your application interacts with S3, GCS, Azure Blob, or the local filesystem in production: spot latency regressions, catch retry storms, and size your storage tier from real workload data. The bridge is available in the Python and TypeScript SDKs. It is a thin wrapper over LanceDB's `metrics` recorder; your application supplies and configures the OpenTelemetry SDK. > [!NOTE] > > This page covers LanceDB Embedded instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. ## Available metrics Once instrumented, LanceDB registers one observable instrument per metric on your `MeterProvider`. The current catalog covers the object store layer: | Metric | Kind | Description | | - | - | - | | `lance_object_store_requests_total` | Counter | Total object store requests, labelled by `operation` and `base` (store scheme). | | `lance_object_store_request_duration_seconds` | Histogram | Request latency in seconds. | | `lance_object_store_request_bytes_total` | Counter | Bytes read from or written to the store. | | `lance_object_store_errors_total` | Counter | Object store requests that failed. | | `lance_object_store_retryable_responses_total` | Counter | Retryable HTTP responses (5xx, 429 and 408) from a store reached over HTTP. | | `lance_object_store_throttle_total` | Counter | Throttle responses (429 and 503) from a store reached over HTTP. | | `lance_object_store_in_flight_requests` | Gauge | Currently outstanding object store requests. | The recorder is process-global and pull-based: your configured `MetricReader` collects on its own schedule, so there is no hot-path overhead beyond the atomic aggregation that LanceDB does anyway. > [!NOTE] > > **Histograms are exported Prometheus-style.** OpenTelemetry has no asynchronous histogram instrument, so each histogram surfaces as three observable counters: `<name>_bucket` (with an `le` attribute per bucket boundary, including `+Inf`), `<name>_count`, and `<name>_sum`. Only `_sum` carries the histogram's unit; `_bucket` and `_count` are cumulative sample counts. ## Python Install LanceDB with the `otel` extra to pull in the OpenTelemetry API, plus an OpenTelemetry SDK of your choice. The SDK is intentionally not bundled, so you configure it and its readers and exporters however your platform expects. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lancedb[otel]" opentelemetry-sdk opentelemetry-exporter-otlp-proto-grpc ``` Call `instrument_lancedb_metrics()` once at startup, before opening any tables. It returns `True` when the recorder is installed and instruments are registered. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.otel import instrument_lancedb_metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import ( PeriodicExportingMetricReader, ) from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import ( OTLPMetricExporter, ) reader = PeriodicExportingMetricReader(OTLPMetricExporter()) provider = MeterProvider(metric_readers=[reader]) instrument_lancedb_metrics(provider) # Any object store activity from this point on is now recorded. db = lancedb.connect("s3://my-bucket/lancedb") ``` If you omit `meter_provider`, LanceDB uses the global provider returned by `opentelemetry.metrics.get_meter_provider()`. > [!WARNING] > > `instrument_lancedb_metrics()` returns `False` and emits a warning if another `metrics`-crate recorder is already installed in the process. Only one global recorder is permitted, so instrument LanceDB before any other library that installs its own recorder. ## TypeScript Install the OpenTelemetry SDK and exporter in your application: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @opentelemetry/sdk-metrics @opentelemetry/exporter-metrics-otlp-grpc ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { connect, instrumentLanceDbMetrics } from "@lancedb/lancedb"; import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-grpc"; const reader = new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(), }); const provider = new MeterProvider({ readers: [reader] }); instrumentLanceDbMetrics(provider); const db = await connect("s3://my-bucket/lancedb"); ``` `instrumentLanceDbMetrics()` also accepts no arguments, in which case it uses the global provider from `@opentelemetry/api`. Calling it more than once is safe: instruments are created only on the first successful call. ## Build dashboards and alerts A few starting points for dashboards and alerts: * **Request rate by operation:** `rate(lance_object_store_requests_total[1m])` broken down by `operation` shows read vs. write pressure and helps size ingestion and serving traffic separately. * **Tail latency:** histogram quantiles over `lance_object_store_request_duration_seconds_bucket` catch object store slowdowns before they surface as query timeouts. * **Retryable responses:** a rising `lance_object_store_retryable_responses_total` typically means you are being throttled and should back off or shard writes. * **In-flight requests:** a growing `lance_object_store_in_flight_requests` gauge without a matching rise in throughput indicates queueing. ## Enterprise monitoring Enterprise A deployment emits its own metrics from the server side, using Prometheus for collection and OpenTelemetry (OTel) to export them with data enrichment. No client-side instrumentation is needed. | Component | Metrics | | - | - | | Query node | RPS, query latency, error codes, slow-query count, CPU/memory utilization | | Executor | SSD cache hit/miss rate, CPU/memory utilization | [Contact support](/enterprise/v1-12-0/deployment/support) for the comprehensive metric list and help integrating them with your monitoring dashboard. ## Related guides > [card] [Performance tips](/enterprise/v1-12-0/search#performance) > > Tune ingestion, indexing, and query patterns once metrics highlight a hot spot. > [card] [Object storage](/enterprise/v1-12-0/basics/catalog#object-storage) > > Configure the object store backends whose requests these metrics measure. # Slurm Source: https://docs.lancedb.com/enterprise/v1-12-0/deployment/slurm Run LanceDB Enterprise's own pods as Slurm-scheduled jobs, and reach a Neocloud's GPU capacity through Slurm in the multicloud case. **Applies to:** Embedded ❌, Enterprise ✅ [Slurm](https://slurm.schedmd.com/) is the workload manager most GPU clusters run to schedule and account for jobs -- queueing work across shared nodes, enforcing fair-share and priority policies between teams, and tracking GPU-hour usage per job. That makes it the de facto standard in AI training infrastructure, where expensive GPU nodes are shared across many training and data jobs instead of dedicated to one team. GPU-focused cloud providers ("Neoclouds") such as CoreWeave and Nebius run Slurm-based scheduling across their Kubernetes clusters for exactly this reason. Slurm shows up for LanceDB Enterprise in two related ways. Its own pods -- query nodes, plan executors, and background job workers alike -- can run as Slurm-scheduled jobs rather than plain Kubernetes pods, under the same scheduling and accounting as everything else on the cluster. And in the [multicloud](/enterprise/v1-12-0/deployment/multicloud) case, when the remote cloud is a Neocloud, Slurm is commonly how the dispatched GPU work actually gets scheduled there. ## How it fits together Scheduling LanceDB's pods through Slurm puts them under the same scheduler as GPU training jobs, so the cluster's capacity is accounted for consistently regardless of which one is using it -- Slurm's fair-share and priority policies apply to LanceDB the same way they apply to a training job, including preemption when training needs the capacity back. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph P["Your cloud"] direction TB Job["Job orchestration"] end subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] direction TB Slurm["Slurm scheduler"] Train["GPU training jobs"] LDB["LanceDB Enterprise pods"] Slurm --> Train Slurm --> LDB Train -.->|"can preempt"| LDB end Job -- "dispatches GPU work" --> Slurm LDB -- "results" --> Job classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Slurm accent ``` ## Why it matters Most GPU infrastructure already runs Slurm for training. Deploying LanceDB Enterprise into that same infrastructure, under the same scheduler, means it can share capacity with training workloads safely -- queued, accounted, and preemptible like everything else -- instead of requiring a separate, dedicated pool of nodes carved out just for LanceDB. Combined with [multicloud](/enterprise/v1-12-0/deployment/multicloud) dispatch, that makes it practical to keep your primary deployment wherever it already lives and still reach GPU capacity on a Neocloud built around Slurm, only for the work that needs it. [Contact us](https://www.lancedb.com/contact) to learn more about running LanceDB Enterprise on a Slurm-scheduled cluster. ## What to read next > [card] [Multicloud](/enterprise/v1-12-0/deployment/multicloud) > > The cross-cloud dispatch model this page's Neocloud case builds on. > [card] [Architecture](/enterprise/v1-12-0/index#architecture) > > The query, executor, cache and jobs fleets this scheduling applies to. # Managing Embeddings Source: https://docs.lancedb.com/enterprise/v1-12-0/embedding/index Use the embedding API in LanceDB: registry, functions, schemas, and multi-language SDK support. **Applies to:** Embedded ✅, Enterprise ✅ Modern machine learning models can be trained to convert raw data into embeddings, which are vectors of floating point numbers. The position of an embedding in vector space captures the semantics of the data, so vectors that are close to each other are considered similar. LanceDB provides an embedding function registry in LanceDB Embedded as well as LanceDB Enterprise ([see below](#embeddings-in-lancedb-enterprise)) that automatically generates vector embeddings during data ingestion. Query text is embedded automatically too, in the client, for local and Enterprise tables alike, with SDK-specific query ergonomics. The API abstracts embedding generation, allowing you to focus on your application logic. ## Embedding Registry You can get a supported embedding function from the registry, and then use it in your table schema. Once configured, the embedding function will automatically generate embeddings when you insert data into the table. Query-time behavior depends on SDK: Python/TypeScript can query with text directly, while Rust examples typically compute query embeddings explicitly before vector search. In the Rust examples, replace `your-openai-api-key` with your OpenAI API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create(name="text-embedding-ada-002") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add([{"text": "hello world"}, {"text": "goodbye world"}]) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect(databaseDir); const func = getRegistry() .get("openai") ?.create({ model: "text-embedding-ada-002" }) as EmbeddingFunction; const wordsSchema = LanceSchema({ text: func.sourceField(new Utf8()), vector: func.vectorField(), }); const tbl = await db.createEmptyTable("words", wordsSchema, { mode: "overwrite", }); await tbl.add([{ text: "hello world" }, { text: "goodbye world" }]); const query = "greetings"; const actual = (await tbl.search(query).limit(1).toArray())[0]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::{iter::once, sync::Arc}; use arrow_array::{record_batch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::StreamExt; use lancedb::{ connect, embeddings::{openai::OpenAIEmbeddingFunction, EmbeddingDefinition, EmbeddingFunction}, query::{ExecutableQuery, QueryBase}, Result, }; #[tokio::main] async fn main() -> Result<()> { let db = connect("./mydb").execute().await?; let api_key = "your-openai-api-key".to_string(); let embedding = Arc::new(OpenAIEmbeddingFunction::new_with_model( api_key, "text-embedding-3-large", )?); db.embedding_registry().register("openai", embedding.clone())?; let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); let table = db .create_empty_table("mytable", schema) .add_embedding(EmbeddingDefinition::new("text", "openai", Some("vector")))? .execute() .await?; table .add(record_batch!(("text", Utf8, ["This is a test.", "Another example."]))?) .execute() .await?; let query = Arc::new(StringArray::from_iter_values(once("test example"))); let query_vector = embedding.compute_query_embeddings(query)?; let mut results = table.vector_search(query_vector)?.limit(5).execute().await?; while let Some(batch) = results.next().await { println!("{:?}", batch?); } Ok(()) } ``` ### Using an embedding function Create an embedding function before you attach it to table or schema metadata. Python and TypeScript fetch provider implementations from the embedding registry, while Rust constructs the provider embedding function directly and registers it on the connection before using it in an `EmbeddingDefinition`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} func = get_registry().get("openai").create( name="text-embedding-3-small", max_retries=7, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const func = getRegistry().get("openai")!.create({ model: "text-embedding-3-small", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use lancedb::embeddings::openai::OpenAIEmbeddingFunction; let api_key = "your-openai-api-key".to_string(); let embedding = Arc::new( OpenAIEmbeddingFunction::new_with_model(api_key, "text-embedding-3-small") .expect("failed to create OpenAI embedding function"), ); ``` Provider configuration is SDK-specific, so copy the option names from the provider page for the SDK you use. For example, the OpenAI model is selected with `name` in Python, `model` in TypeScript, and the model argument to `OpenAIEmbeddingFunction::new_with_model` in Rust. | Concept | Python | TypeScript | Rust | | - | - | - | - | | Model | `name="text-embedding-3-small"` | `{ model: "text-embedding-3-small" }` | `new_with_model(api_key, "text-embedding-3-small")` | | Retry count | `max_retries=7` | Provider/client-specific | Provider/client-specific | | API key | `api_key="..."`, environment variables, or `$var:` | `apiKey: "..."`, environment variables, or `$var:` | Constructor argument or environment variable | | Device | Provider-specific, for example `device="cuda"` | Provider-specific | Provider-specific | When ingesting data with an embedding definition, LanceDB only computes the vector column if that column is missing from the incoming batch or present but entirely null. If you provide any non-null values in the vector column, LanceDB treats the column as user-supplied and does not backfill the remaining rows in that batch. For reusable runtime configuration, the registry also supports `$var:` placeholders in embedding-function config. This is useful for provider secrets and environment-specific settings in Python and TypeScript. * Python uses `registry.set_var(...)`. * TypeScript uses `registry.setVar(...)`. * You can provide a fallback with `$var:name:default`. * Sensitive values such as API keys should be passed through registry variables instead of hardcoding them in config. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} registry = get_registry() registry.set_var("api_key", "sk-...") func = registry.get("openai").create(api_key="$var:api_key") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const registry = getRegistry(); registry.setVar("api_key", "sk-..."); const func = registry.get("openai")!.create({ apiKey: "$var:api_key", }); ``` For non-sensitive settings such as inference device selection, you can also use a default fallback: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch registry = get_registry() if torch.cuda.is_available(): registry.set_var("device", "cuda") func = registry.get("huggingface").create(device="$var:device:cpu") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const registry = getRegistry(); registry.setVar("openai_model", "text-embedding-3-large"); const func = registry.get("openai")!.create({ model: "$var:openai_model:text-embedding-3-small", }); ``` Find the full list of arguments for each provider in the [integrations](/enterprise/v1-12-0/integrations/embedding) section. ### Trusting remote code and custom endpoints In Python, the embedding definition is stored in the table, so anyone who can write to the table can change it. To keep a table from running code or sending data where you didn't intend, two kinds of settings are only honored when this process has approved them: * `trust_remote_code=True`, which runs code from the model's HuggingFace repository. * Custom endpoints such as OpenAI `base_url`, Ollama `host`, or watsonx `url`, which receive your data and API keys. Embedding functions you create in the current process are approved automatically. When you open a table in a new process, approve these settings explicitly before computing embeddings: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.embeddings import get_registry registry = get_registry() # Pinning a commit hash is recommended, since the code at a branch can change. registry.allow_remote_code("nomic-ai/nomic-embed-text-v1.5", revision="<commit-hash>") registry.allow_endpoint("http://my-ollama-host:11434") ``` Until then, computing embeddings raises `UntrustedEmbeddingConfigError`. Other operations on the table still work. ## Multiple embedding columns A single table can include more than one embedding definition when you want to store multiple semantic views of the same data, or generate embeddings from different source columns. In practice, each embedding definition maps one source column to one vector column, and the table schema can contain multiple such pairs. The exact setup differs by SDK, but the underlying pattern is the same: define a distinct source/vector pair for each embedding function you want applied during ingest. In TypeScript, automatic query embedding currently uses the first embedding function stored in the table metadata. If a table has multiple embedding definitions and you need to query a specific vector column, compute the query embedding explicitly and pass the vector to the search builder. ## Embedding model providers LanceDB supports most popular embedding providers. ### Text embeddings | Provider | Model ID | Default Model | | - | - | - | | OpenAI | `openai` | `text-embedding-ada-002` | | Sentence Transformers | `sentence-transformers` | `all-MiniLM-L6-v2` | | HuggingFace | `huggingface` | `colbert-ir/colbertv2.0` | | Cohere | `cohere` | `embed-multilingual-v3.0` | | ... | ... | ... | ### Multimodal embedding | Provider | Model ID | Supported Inputs | | - | - | - | | OpenCLIP | `open-clip` | Text, Images | | ImageBind | `imagebind` | Text, Images, Audio, Video | | ... | ... | ... | You can find all supported embedding models in the [integrations](/enterprise/v1-12-0/integrations/embedding) section. ## Embeddings in LanceDB Enterprise Enterprise In LanceDB Enterprise, embedding generation during data ingestion is client-side and the resulting vectors are stored in the Enterprise table. > [!NOTE] > > The Enterprise server does not currently generate embeddings from query text on its own. Any automatic > query-time embedding happens on the client side. ### How string queries are interpreted When the Python SDK connects to Enterprise, `table.search("hello")` can take two different paths: * If the selected vector column has embedding metadata (i.e., the table schema stores the source-column, vector-column, and embedding-function mapping created from fields like `SourceField()` and `VectorField()` during table creation), then the embeddings are computed in the Python client process. The client uses the same local LanceDB embedding registry used by LanceDB Embedded tables to reconstruct the embedding function from schema metadata, compute the query vector in the client process, and send that vector to Enterprise for search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = table.search("hello").limit(1).to_list() # The Python client computes the query embedding locally, then sends a vector search. ``` * If the table does not have embedding metadata for that search, `table.search("hello")` in `auto` mode is treated as an FTS query instead. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = table.search("hello").limit(5).to_list() # In auto mode this is treated as an FTS query, not a vector query. ``` If you want explicit vector or hybrid behavior and the client cannot resolve an embedding function from the table metadata, generate the query embedding yourself and pass the vector directly. TypeScript has a similar string-query distinction in `auto` mode: if no embedding providers have been registered in the process, `search("text")` falls back to FTS. Once an embedding provider has been imported and registered, the client expects table embedding metadata for automatic vector search and raises an error if the table has none. The manual query-embedding flow below works across Enterprise SDKs and is an explicit path you can use when you want full control over query-time behavior. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # query_vector is assumed to already be generated by your embedding function actual = table.search(query_vector).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // queryVector is assumed to already be generated by your embedding function const actual = (await tbl.search(queryVector).limit(1).toArray())[0]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // query_vector is assumed to already be generated by your embedding function let mut results = table.vector_search(query_vector)?.limit(5).execute().await?; while let Some(batch) = results.next().await { println!("{:?}", batch?); } ``` ## Custom Embedding Functions You can always implement your own embedding function: * Python/TypeScript: subclass `TextEmbeddingFunction` (text) or `EmbeddingFunction` (multimodal). * Rust: implement the `EmbeddingFunction` trait. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from functools import cached_property from lancedb.embeddings import TextEmbeddingFunction, register class MyEmbeddingModel: def __init__(self, model_name: str): self.model_name = model_name def encode(self, texts: list[str]) -> list[list[float]]: return [[1.0, 2.0, 3.0] for _ in texts] @register("my-embedder") class MyTextEmbedder(TextEmbeddingFunction): model_name: str = "my-model" def generate_embeddings(self, texts: list[str]) -> list[list[float]]: # Your embedding logic here return self._model.encode(texts) def ndims(self) -> int: # Return the dimensionality of the embeddings return len(self.generate_embeddings(["test"])[0]) @cached_property def _model(self) -> MyEmbeddingModel: # Initialize your model once return MyEmbeddingModel(self.model_name) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect(databaseDir); @register("my_embedding") class MyEmbeddingFunction extends EmbeddingFunction<string> { constructor(optionsRaw = {}) { super(); const options = this.resolveVariables(optionsRaw); // Initialize using options } ndims() { return 3; } protected getSensitiveKeys(): string[] { return []; } embeddingDataType(): Float { return new Float32(); } async computeQueryEmbeddings(_data: string) { // This is a placeholder for a real embedding function return [1, 2, 3]; } async computeSourceEmbeddings(data: string[]) { // This is a placeholder for a real embedding function return Array.from({ length: data.length }).fill([ 1, 2, 3, ]) as number[][]; } } const func = new MyEmbeddingFunction(); const data = [{ text: "pepperoni" }, { text: "pineapple" }]; // Option 1: manually specify the embedding function const table = await db.createTable("vectors", data, { embeddingFunction: { function: func, sourceColumn: "text", vectorColumn: "vector", }, mode: "overwrite", }); // Option 2: provide the embedding function through a schema const schema = LanceSchema({ text: func.sourceField(new Utf8()), vector: func.vectorField(), }); const table2 = await db.createTable("vectors2", data, { schema, mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::{borrow::Cow, sync::Arc}; use arrow_array::{Array, FixedSizeListArray, Float32Array}; use arrow_schema::{DataType, Field, Schema}; use lancedb::{ connect, embeddings::{EmbeddingDefinition, EmbeddingFunction}, Result, }; #[derive(Debug, Clone)] struct MyTextEmbedder { dim: usize, } impl EmbeddingFunction for MyTextEmbedder { fn name(&self) -> &str { "my-embedder" } fn source_type(&self) -> Result<Cow<'_, DataType>> { Ok(Cow::Owned(DataType::Utf8)) } fn dest_type(&self) -> Result<Cow<'_, DataType>> { Ok(Cow::Owned(DataType::new_fixed_size_list( DataType::Float32, self.dim as i32, true, ))) } fn compute_source_embeddings(&self, source: Arc<dyn Array>) -> Result<Arc<dyn Array>> { let values = Arc::new(Float32Array::from(vec![1.0f32; source.len() * self.dim])); let field = Arc::new(Field::new("item", DataType::Float32, true)); Ok(Arc::new(FixedSizeListArray::new( field, self.dim as i32, values, None, ))) } fn compute_query_embeddings(&self, _input: Arc<dyn Array>) -> Result<Arc<dyn Array>> { unimplemented!() } } #[tokio::main] async fn main() -> Result<()> { let db = connect("./mydb").execute().await?; db.embedding_registry() .register("my-embedder", Arc::new(MyTextEmbedder { dim: 3 }))?; let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); db.create_empty_table("mytable", schema) .add_embedding(EmbeddingDefinition::new( "text", "my-embedder", Some("vector"), ))? .execute() .await?; Ok(()) } ``` # Embeddings: Quickstart Source: https://docs.lancedb.com/enterprise/v1-12-0/embedding/quickstart Quickstart guide for generating and working with embeddings. LanceDB will automatically vectorize the data both at ingestion and query time. All you need to do is specify which model to use. Popular embedding models like OpenAI, HuggingFace, Sentence Transformers, CLIP, and more, are supported. ## Step 1: Import Required Libraries First, import the necessary LanceDB components: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector from lancedb.embeddings import get_registry ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/transformers"; import { Utf8 } from "apache-arrow"; ``` * `lancedb`: The main database connection and operations * `LanceModel`: Pydantic model for defining table schemas * `Vector`: Field type for storing vector embeddings * `get_registry()`: Access to the embedding function registry. It has all the supported as well as custom embedding functions registered by the user * TypeScript uses `lancedb.embedding.getRegistry()` and `lancedb.embedding.LanceSchema()` for the same registry/schema workflow * In TypeScript, import the provider module before calling `getRegistry().get(...)`; the provider import is what registers names such as `"huggingface"` or `"openai"` ## Step 2: Connect to LanceDB Establish a connection to your LanceDB Embedded directory or Enterprise cluster: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Enter your LanceDB connection URI for LanceDB Embedded or Enterprise here db = lancedb.connect(...) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect("data/sample-lancedb"); ``` ## Step 3: Initialize the Embedding Function Choose and configure your embedding model: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} model = get_registry().get("sentence-transformers").create(name="BAAI/bge-small-en-v1.5", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const model = (await lancedb.embedding .getRegistry() .get("huggingface") ?.create()) as lancedb.embedding.EmbeddingFunction; ``` This creates an embedding function from the local embedding registry. The Python snippet uses the `sentence-transformers` provider with the BGE model; the TypeScript snippet uses the Transformers-backed `huggingface` provider. You can: * Change `"sentence-transformers"` to other providers like `"openai"`, `"cohere"`, etc. * Modify the model name for different embedding models * Set `device="cuda"` for GPU acceleration if available ## Step 4: Define Your Schema Create a Pydantic model that defines your table structure: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Words(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const wordsSchema = lancedb.embedding.LanceSchema({ text: model.sourceField(new Utf8()), vector: model.vectorField(), }); ``` * `SourceField()`: This field will be embedded * `VectorField()`: This stores the embeddings * `model.ndims()`: Sets vector dimensions for your model * In TypeScript, use `model.sourceField(...)` and `model.vectorField()` inside `LanceSchema(...)` ## Step 5: Create Table and Ingest Data Create a table with your schema and add data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("words", schema=Words) table.add([ {"text": "hello world"}, {"text": "goodbye world"} ]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createEmptyTable("words", wordsSchema, { mode: "overwrite", }); await table.add([{ text: "hello world" }, { text: "goodbye world" }]); ``` The `table.add()` call automatically: * Takes the text from each document * Generates embeddings using your chosen model * Stores both the original text and the vector embeddings If your input already includes the vector column, automatic embedding only runs when that column is absent or entirely null for the batch. Partially supplied vectors are treated as manual data, so LanceDB preserves them instead of filling only the missing rows. ## Step 6: Query with Automatic Embedding Note: On LanceDB Enterprise, the server does not generate embeddings from query text. When the Python SDK connects to Enterprise, `table.search("greetings")` can still work when the table schema includes embedding metadata, because the client computes the query embedding before sending the vector search. If there is no embedding metadata for that search, `search("greetings")` in `auto` mode is treated as FTS instead. Search your data using natural language queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const query = "greetings"; const actual = (await table.search(query).limit(1).toArray())[0]; console.log(actual.text); ``` The search process: 1. Automatically converts your query text to embeddings 2. Finds the most similar vectors in your table 3. Returns the matching documents Automatic text search depends on the table's embedding metadata. If the client cannot reconstruct an embedding function from that metadata, compute the query embedding yourself and search with the vector directly. # Advanced Conflict Resolution Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/advanced-conflict-resolution How compaction and indexing stay safe to run concurrently, using Lance's fragment reuse index. **Applies to:** Embedded ❌, Enterprise ✅ [Compaction](/enterprise/v1-12-0/maintenance/compaction) rewrites fragments into fewer, larger files, which changes the physical row address -- file and offset -- of every row it moves. An index built against the old layout stores exactly those addresses, so a naive compaction would leave any index covering the rewritten fragments pointing at rows that have moved or no longer exist there. LanceDB Embedded avoids this by default by never letting the two run independently: `optimize()` compacts and remaps affected indexes in the same call, before returning. Compaction's `defer_index_remap` option opts out of that -- the call returns once compaction itself commits, leaving the remap for later -- which is what lets a custom remapper or a stable-row-ID table skip the synchronous step. LanceDB Enterprise runs compaction and indexing as separate, independently scheduled background jobs -- a table can compact while an index build is still catching up from an earlier compaction -- so it needs a way to keep an index correct without forcing every compaction to wait for a synchronous remap. ## The fragment reuse index The **fragment reuse index** (FRI) is a Lance format-level mechanism, not an Enterprise add-on: a system index that records every fragment rewrite as a **transition** -- the source fragments' digests, the destination fragments' digests, and a row-address mapping between them (`Transition` and `Mapping` in `lance-table`'s `system_index::frag_reuse::ledger`). An index that covers a rewritten fragment does not need to be rebuilt before the rewrite commits; it can instead translate the row addresses it already stores forward through the chain of recorded transitions at read time. Only a compaction run with `defer_index_remap` ever touches the FRI; a synchronous-remap rewrite -- the Embedded default -- never tags a table or appends anything. Every `defer_index_remap` commit is classified before it is admitted; that classifier is Lance's own commit protocol (`lance-table`'s `frag_reuse::gate::classify`), the same one every write funnels through -- not a lock or a sequencing rule Enterprise imposes from outside. A table starts **untagged**: its deferred rewrites are admitted as ordinary business with nothing appended, unless the rewrite has stable row IDs to translate or touches a fragment an index covers -- either one makes that commit record a legacy, untagged ("v0") FRI entry, which does **not** tag the table. Tagging is a separate, one-way transition (a sticky manifest flag that a later trim never clears) that publishes the FRI's first real transition; this page does not cover what triggers it. Once a table is tagged, its commits are classified against which indexes cover the rewritten fragments the way the rest of this page describes, and every entry it records from then on is a tagged transition, never v0 again. A table with stable row IDs is permanently confined to the untagged, v0 form -- Lance refuses to tag it at all -- so its deferred compactions keep recording v0 entries indefinitely, for every rewrite that moves row addresses, not only ones that touch an indexed fragment: the address translation itself depends on that record, independent of indexing. Once a table is tagged, Lance refuses a compaction that does not set `defer_index_remap`, including a plain Embedded `optimize()` call: an Enterprise-tagged table has to keep deferring the remap, or be compacted by a writer that can remap the tagged history eagerly. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Commit["Compaction commit<br/>(defer_index_remap only)"] --> Tagged{"Table already<br/>tagged with an FRI?"} Tagged -->|no| First{"Stable row IDs, or does<br/>any index cover the<br/>rewritten fragments?"} First -->|no| Admit["Admitted as<br/>ordinary business --<br/>nothing appended"] First -->|yes| V0["Records a legacy v0 entry --<br/>table stays untagged"] Tagged -->|yes| Classify{"Does any index<br/>cover the rewritten<br/>fragments?"} Classify -->|no| Admit Classify -->|yes| Append["Must append a tagged<br/>transition before the<br/>commit is admitted"] V0 --> FRI[("Fragment reuse index")] Append --> FRI classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class FRI accent ``` ## Enterprise defers and batches the catch-up Translating addresses through a long chain of transitions at every read adds up, so Enterprise does not let the FRI grow without bound. Its job planner tracks how many transitions have accumulated for a table and schedules a dedicated **remap catch-up** job -- which applies the accumulated transitions to the indexes that need them, physically, in one pass -- once either: * the FRI reaches **5 pending transitions** (`remap_fri_version_threshold`, tunable), or * the oldest pending transition is **1 day old** (`remap_fri_max_age_secs`, tunable), whichever comes first. The version count only climbs while a table keeps compacting, so the age threshold exists to clear a lingering FRI -- and the per-read remap cost that comes with it -- on a table that stops compacting before reaching the count threshold, without scheduling a catch-up job on every table that is still actively compacting. This is what lets compaction and index maintenance run as separate background jobs (see [Index maintenance jobs](/enterprise/v1-12-0/indexing/incremental-indexing#index)) rather than one blocking on the other: a handful of compactions can land before their indexes are physically remapped, and the catch-up job amortizes that remap across all of them in one job instead of one per compaction. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index<br/>(ledger of transitions)"] C2["Compaction job"] -->|appends transition| FRI C3["Compaction job"] -->|appends transition| FRI FRI -->|5 transitions or<br/>1 day old| R["Remap catch-up job"] R -->|applies accumulated<br/>transitions| IDX["Affected indexes,<br/>physically remapped"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class FRI,R accent ``` ## What to read next > [card] [Compaction and cleanup](/enterprise/v1-12-0/maintenance/compaction) > > What compaction merges, and how the embedded library runs it in one call. > [card] [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing#index) > > The `index_remap` job type, and keeping an index current as the table changes. > [card] [Distributed Compaction](/enterprise/v1-12-0/enterprise/distributed-compaction) > > How compaction itself scales across the jobs fleet. > [card] [Distributed Indexing](/enterprise/v1-12-0/enterprise/distributed-indexing) > > How an index build scales across the jobs fleet. # Authentication Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/authentication Authentication modes for LanceDB Enterprise: API keys and OAuth credentials. **Applies to:** Embedded ❌, Enterprise ✅ A deployment authenticates each request over a `db://` connection before [authorization](/enterprise/v1-12-0/governance/authorization) decides what it may do. Choose one of these methods: * **API keys**: a long-lived shared secret passed as `api_key` on connect. Works in every SDK. * **OAuth 2.0**: short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. OAuth is the recommended option when you want to rotate credentials centrally, plug into an existing identity provider, or run on Azure with managed identities so no secret material lives on the client. ## API key Pass the API key from your Enterprise tenant on `connect`. This works with both the synchronous and asynchronous Python clients, as well as TypeScript and Rust. Load the key from an environment variable or secret manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os db = lancedb.connect( uri="db://your-database-uri", api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-enterprise-endpoint.com", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const apiKey = process.env.LANCEDB_API_KEY; if (!apiKey) throw new Error("LANCEDB_API_KEY is required"); const db = await lancedb.connect("db://your-database-uri", { apiKey, region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let api_key = std::env::var("LANCEDB_API_KEY")?; let db = lancedb::connect("db://your-database-uri") .api_key(&api_key) .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .execute() .await?; ``` For Rust, enable the `remote` feature on the `lancedb` dependency to use API key or OAuth authentication. See [Database](/enterprise/v1-12-0/management/database#deployment) for the connection options. ## OAuth The async Python, TypeScript, and Rust clients can obtain bearer tokens from an OIDC issuer and attach them to every request. Token acquisition, caching, and refresh are handled inside the client. Your application code only provides the configuration. A deployment accepts these tokens only when its administrator has configured it with your identity provider. Ask them for the issuer URL, client ID, scopes, and any resource or audience required by the provider. For Authorization Code, register the loopback redirect URI with the provider. For Device Code, enable the provider's device authorization grant for your application. > [!NOTE] > > In Python, OAuth is supported through `lancedb.connect_async`. The synchronous > `connect` entry point continues to use API key authentication for `db://` > URIs. In TypeScript, `lancedb.connect` accepts `oauthConfig` directly. > In Rust, use `.oauth_config(config)` on the connection builder. ### Supported flows `OAuthFlowType` (Python and TypeScript) or `OAuthFlow` (Rust) selects how the client acquires tokens: | Flow | Python value | TypeScript value | Rust value | When to use | | - | - | - | - | - | | Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | `OAuthFlow::ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | | Authorization Code | `OAuthFlowType.AUTHORIZATION_CODE` | `OAuthFlowType.AuthorizationCode` | `OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new())` | Interactive user sign-in through a browser and local callback server. Uses S256 PKCE by default. | | Device Code | `OAuthFlowType.DEVICE_CODE` | `OAuthFlowType.DeviceCode` | `OAuthFlow::DeviceCode(DeviceCodeOptions::new())` | CLI or headless sign-in. The client displays a verification URL and user code for the user to enter on another device. | | Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | `OAuthFlow::AzureManagedIdentity { client_id: None }` | Azure workloads with access to the IMDS endpoint. Tokens are fetched from IMDS, so no client secret is stored on the client. | ### Configure OAuth Build an OAuth config and pass it on connect. Use `oauth_config` in Python and Rust, and `oauthConfig` in TypeScript. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb.remote import OAuthConfig, OAuthFlowType # Client Credentials (service-to-service) oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", client_secret=os.environ["LANCEDB_OAUTH_CLIENT_SECRET"], scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.CLIENT_CREDENTIALS, ) db = await lancedb.connect_async( uri="db://your-database-uri", region="us-east-1", host_override="https://your-enterprise-endpoint.com", oauth_config=oauth_config, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; const clientSecret = process.env.LANCEDB_OAUTH_CLIENT_SECRET; if (!clientSecret) throw new Error("LANCEDB_OAUTH_CLIENT_SECRET is required"); // Client Credentials (service-to-service) const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", clientSecret, scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.ClientCredentials, }; const db = await lancedb.connect("db://your-database-uri", { region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", oauthConfig, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{OAuthConfig, OAuthFlow}; // Client Credentials (service-to-service) let oauth_config = OAuthConfig { issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), client_id: "your-application-client-id".into(), client_secret: Some(std::env::var("LANCEDB_OAUTH_CLIENT_SECRET")?), scopes: vec!["api://lancedb-api/.default".into()], flow: OAuthFlow::ClientCredentials, client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: None, }; let db = lancedb::connect("db://your-database-uri") .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .oauth_config(oauth_config) .execute() .await?; ``` For Azure workloads with access to IMDS, use a managed identity instead of a client secret: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthConfig, OAuthFlowType oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.AZURE_MANAGED_IDENTITY, # Set only for a user-assigned managed identity: # managed_identity_client_id="your-user-assigned-identity-client-id", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.AzureManagedIdentity, // Set only for a user-assigned managed identity: // managedIdentityClientId: "your-user-assigned-identity-client-id", }; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{OAuthConfig, OAuthFlow}; let oauth_config = OAuthConfig { issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), client_id: "your-application-client-id".into(), client_secret: None, scopes: vec!["api://lancedb-api/.default".into()], flow: OAuthFlow::AzureManagedIdentity { // Set to Some("your-user-assigned-identity-client-id".into()) // only for a user-assigned managed identity. client_id: None, }, client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: None, }; ``` `managed_identity_client_id` / `managedIdentityClientId` selects a user-assigned identity. Omit it for a system-assigned identity. The required `client_id` / `clientId` field does not select the Azure managed identity. In Rust, set the `client_id` inside `OAuthFlow::AzureManagedIdentity` to `Some(...)` for a user-assigned identity, or `None` for a system-assigned identity. The top-level `OAuthConfig::client_id` is the application client ID. For interactive sign-in, configure Authorization Code or Device Code. The authorization URL or device verification instructions are written to standard error. Authorization Code also tries to open a browser and listens for the callback at `http://127.0.0.1:8400/callback` by default. Register that redirect URI with your identity provider. Public clients can omit `client_secret`; request a refresh token from your provider (often by including `offline_access`) if you want to reuse the session. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthConfig, OAuthFlowType, TokenCacheOptions # Use DEVICE_CODE for a CLI without a local browser or callback server. oauth_config = OAuthConfig( issuer_url="https://your-issuer.example.com", client_id="your-public-client-id", scopes=["openid", "offline_access", "lancedb.read"], flow=OAuthFlowType.AUTHORIZATION_CODE, token_cache=TokenCacheOptions(), ) db = await lancedb.connect_async( uri="db://your-database-uri", region="us-east-1", host_override="https://your-enterprise-endpoint.com", oauth_config=oauth_config, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { OAuthFlowType, type OAuthConfig } from "@lancedb/lancedb"; // Use OAuthFlowType.DeviceCode for a CLI without a local browser or callback server. const oauthConfig: OAuthConfig = { issuerUrl: "https://your-issuer.example.com", clientId: "your-public-client-id", scopes: ["openid", "offline_access", "lancedb.read"], flow: OAuthFlowType.AuthorizationCode, tokenCache: {}, }; const db = await lancedb.connect("db://your-database-uri", { region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", oauthConfig, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{AuthorizationCodeOptions, OAuthConfig, OAuthFlow, TokenCacheOptions}; // Use OAuthFlow::DeviceCode(Default::default()) for a CLI without a local browser or callback server. let oauth_config = OAuthConfig { issuer_url: "https://your-issuer.example.com".into(), client_id: "your-public-client-id".into(), client_secret: None, scopes: vec![ "openid".into(), "offline_access".into(), "lancedb.read".into(), ], flow: OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new()), client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: Some(TokenCacheOptions::new()), }; let db = lancedb::connect("db://your-database-uri") .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .oauth_config(oauth_config.clone()) .execute() .await?; ``` With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode(DeviceCodeOptions::new())`, the same configuration and connection calls apply; only the `flow` value changes. Device Code sends no PKCE parameters by default. For a provider that requires S256 PKCE on device grants, Rust callers can select `OAuthFlow::DeviceCode(DeviceCodeOptions::new().use_pkce(true))` (import `DeviceCodeOptions` from `lancedb::remote`). This option is currently Rust-only. Enable it only when the provider supports the extension; a failed PKCE request is not retried without PKCE. ### Reuse an interactive session By default, tokens stay in process memory. Set `token_cache` / `tokenCache` for Authorization Code or Device Code to keep refresh tokens across process restarts. Only refresh tokens are persisted; access tokens and client secrets are not written to the cache. Set `cache_dir` / `cacheDir` to choose the directory, or leave it unset to use the platform cache directory. Your identity provider must issue a refresh token for a later process to sign in without prompting again. Use `OAuthSession` with the same config to log in before connecting, inspect whether a refresh token is cached, or remove the local cached credential: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthSession session = OAuthSession(oauth_config) status = await session.login() print(status.refreshable) status = await session.status() # Does not contact the provider. print(status.refreshable) logout = await session.logout() print(logout.removed) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { OAuthSession } from "@lancedb/lancedb"; const session = new OAuthSession(oauthConfig); const status = await session.login(); console.log(status.refreshable); const current = await session.status(); // Does not contact the provider. console.log(current.refreshable); const logout = await session.logout(); console.log(logout.removed); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::OAuthSession; let session = OAuthSession::new(oauth_config)?; let status = session.login().await?; println!("{}", status.refreshable); let status = session.status().await?; // Does not contact the provider. println!("{}", status.refreshable); let logout = session.logout().await?; println!("{}", logout.removed); ``` `login()` runs the interactive flow even when a session is cached. `logout()` removes the local cache entry; it does not revoke the provider's token or end a browser sign-in. `OAuthSession` requires a persistent cache and supports only Authorization Code and Device Code. A cache is unused for Client Credentials and rejected for Azure Managed Identity. ### Configuration reference The shared configuration below is available in all three SDKs; device-code PKCE is a Rust-only option through `DeviceCodeOptions`. Python and Rust use `snake_case` field names; TypeScript uses `camelCase`. In Rust, set optional `OAuthConfig` fields to `Some(value)` or `None`. Configure `redirect_uri`, `callback_port`, and `use_pkce` through the builder methods on `AuthorizationCodeOptions`, and select a managed identity through `OAuthFlow::AzureManagedIdentity { client_id: ... }`. | Python field / TypeScript field | Required | Description | | - | - | - | | `issuer_url` / `issuerUrl` | Yes | OIDC issuer URL or OAuth authority URL. For Azure, use `https://login.microsoftonline.com/{tenant_id}/v2.0`. | | `client_id` / `clientId` | Yes | Application / client ID registered with your identity provider. | | `scopes` | Yes | List of OAuth scopes to request. For Azure managed identity, provide exactly one scope or resource, for example `["api://your-app-id/.default"]`. | | `flow` | Yes in Rust; otherwise no | Selects the OAuth flow. Defaults to Client Credentials in Python and TypeScript; Rust requires an explicit `OAuthFlow`. | | `client_secret` / `clientSecret` | Conditional | Required for Client Credentials; only required for Authorization Code and Device Code when the provider registers a confidential client. Redacted from the config's `repr` (Python) and `Debug` output (Rust and TypeScript native binding). | | `client_auth_method` / `clientAuthMethod` | No | Token endpoint authentication: `ClientAuthMethod.NONE` / `ClientAuthMethod.None` for a public client, `ClientAuthMethod.CLIENT_SECRET_BASIC` / `ClientAuthMethod.ClientSecretBasic`, or `ClientAuthMethod.CLIENT_SECRET_POST` / `ClientAuthMethod.ClientSecretPost`. Defaults to Basic when a client secret is set and no client authentication otherwise. The secret methods require `client_secret` / `clientSecret`. Omit for Azure Managed Identity. | | `redirect_uri` / `redirectUri` | No | Authorization Code loopback callback URI. Defaults to `http://127.0.0.1:{callback_port}/callback`; register it with the provider. | | `callback_port` / `callbackPort` | No | Authorization Code callback server port (default 8400). If `redirect_uri` / `redirectUri` has an explicit port, the two ports must match. | | `use_pkce` / `usePkce` | No | Enable S256 PKCE for Authorization Code (default `true`). | | `managed_identity_client_id` / `managedIdentityClientId` | No | Client ID of a user-assigned managed identity. Only used with Azure Managed Identity; omit for system-assigned identities. | | `resource` | No | RFC 8707 resource indicator, an absolute URI without a fragment. Sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `audience` | No | Provider-specific audience sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL: setting it greater than or equal to the TTL forces a refresh on every request. | | `token_cache` / `tokenCache` | No | Opt in to a persistent refresh-token cache for Authorization Code or Device Code. Use `TokenCacheOptions()` in Python, `{}` in TypeScript, or `Some(TokenCacheOptions::new())` in Rust. Defaults to an in-memory session. | `TokenCacheOptions` also accepts `cache_dir` / `cacheDir` to select a cache directory and `lock_timeout_secs` / `lockTimeoutSecs` to set the wait for a cross-process refresh lock (default 30 seconds). In Rust, use the `TokenCacheOptions::cache_dir(...)` and `TokenCacheOptions::lock_timeout_secs(...)` builder methods. Token endpoint authentication uses `Some(ClientAuthMethod::None)`, `Some(ClientAuthMethod::ClientSecretBasic)`, or `Some(ClientAuthMethod::ClientSecretPost)`; `None` selects the default. > [!WARNING] > > Treat the client secret like any other production credential. Load it from a > secret manager or environment variable rather than committing it to source > control. All three SDKs deliberately omit the secret from their debug/repr output > so accidental log lines do not expose the value. LanceDB Embedded has nothing to authenticate to: your process opens the files directly, and the object store's own credentials are the only gate. # Kubernetes deployment guide Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/deployment/kubernetes Learn how LanceDB Enterprise deploys on Kubernetes with private networking, object storage, and workload identity. LanceDB Enterprise deploys on a Kubernetes cluster (AKS, EKS, GKE, or self-managed) with object storage for data persistence and your cloud's private networking for secure connectivity. The architecture below is the same shape on every cloud; the only cloud-specific part is how storage containers are organized, covered at the end of this page for Azure Blob Storage. ## General architecture overview ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TB subgraph "Client VPC" Client[Client Applications] end subgraph "Server VPC" PLS[Private Link Service] subgraph "Kubernetes Cluster" LDB[LanceDB Enterprise<br/>Query Nodes, Executors,<br/>Lance Agent, Indexer Pods] end EH[Message Queue<br/>for LanceDB internal<br/>message passing] BS[Object Storage] WI[Workload Identity] end Client ==>|Private Link| PLS PLS ==> LDB LDB <-->|Read/Write| BS LDB -->|Async Events| EH EH -->|Process| LDB WI -.->|RBAC| BS WI -.->|Assigned| LDB classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class LDB accent ``` ### Key components * **LanceDB architecture** is deployed in a Kubernetes cluster within its own VPC. * **Client applications** connect to the cluster securely using your cloud's private link service. * **The cluster** is granted object storage read/write permissions using cloud-native workload identity (Azure Workload Identity, IRSA on EKS, or Workload Identity Federation on GKE). * **A message queue** -- a managed service such as Azure EventHub, or a self-hosted Kafka cluster in Kubernetes -- carries LanceDB's internal message passing. ## Read path architecture ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph LR subgraph "Client Network" C[Client App] end subgraph "Kubernetes Cluster" PL[Private Link<br/>Service] QN[Query Nodes<br/>Query planning + routing fleet] PE[Executors<br/>Executor + cache fleet] end subgraph "Storage" BS[Object<br/>Storage] end C -->|Private<br/>Connection| PL PL --> QN QN -->|Query<br/>Request| PE PE -->|Cache Miss<br/>Read Data| BS classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class BS accent ``` ### Read path flow 1. **Client application** sends a query request through the private link. 2. **Query nodes** receive and process the request. 3. **Executors** execute the query using the distributed data cache to speed up read queries. 4. **Object storage** stores data and indices in Lance format, while executors maintain a distributed cache for performance. ## Write path architecture ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TD subgraph "Client Network" C[Client App] end subgraph "Kubernetes Cluster" PL[Private Link<br/>Service] QN[Query Nodes<br/>Query planning + routing fleet] LA[Lance Agent] IP[Indexer Pods<br/>On-Demand] end subgraph "Messaging" EH[Message Queue<br/>Write Events] end subgraph "Storage" BS[Object<br/>Storage] end C -->|Private Connection| PL PL --> QN QN -->|Sync Write| BS QN -->|Async Events| EH EH -->|Consume| LA LA -->|Launch| IP IP -->|Index & Optimize| BS classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class BS accent ``` ### Write path flow Query nodes write data and indices synchronously to object storage in Lance format while asynchronously sending data modification events to the message queue (a managed service such as Azure EventHub, or a self-hosted Kafka cluster). These write events are processed by the Lance Agent, which launches indexing pods or data optimization pods to optimize data for better read performance. ## Deployment models LanceDB Enterprise supports three deployment models, available on AWS, GCP, and Azure: ### 1. Fully managed service * **Infrastructure and storage** in LanceDB's cloud account. * **Complete management** by the LanceDB team. * **Simplest setup** for customers. ### 2. BYOC (bring your own cloud) * **Infrastructure and storage** in the customer's cloud account. * **Fully managed by LanceDB.** * **Full control** over data residency. ### 3. Hybrid -- bring your own container * **Infrastructure** in LanceDB's account. * **Storage containers** in the customer's account. > [!NOTE] > > For private deployments, high performance at extreme scale, or if you have strict security requirements, [contact us about LanceDB Enterprise](https://www.lancedb.com/contact). ## Azure-specific: storage containers The one part of this architecture that is genuinely cloud-specific is how object storage is organized. On Azure, data lives in **Blob Storage containers**, grouped under one or more **storage accounts** -- the same multi-tenant or multi-workload layout applies whether you use a single account with several containers, or split workloads across accounts: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TB subgraph "Multi-Account & Multi-Container Support" SA1[Storage Account 1] SA2[Storage Account 2] SA3[Storage Account N] SA1 --> C1A[Container A] SA1 --> C1B[Container B] SA1 --> C1C[Container C] SA2 --> C2A[Container X] SA2 --> C2B[Container Y] SA3 --> C3A[Container 1] SA3 --> C3B[Container 2] end classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` The equivalent on other clouds is an S3 bucket (AWS) or a Cloud Storage bucket (GCP); everything else on this page \-- the Kubernetes cluster layout, the read and write paths, and the deployment models -- applies unchanged. # Distributed Compaction Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-compaction How LanceDB Enterprise distributes compaction across a fleet of job workers. **Applies to:** Embedded ❌, Enterprise ✅ Distributed compaction splits a table's fragments into independent, fragment-disjoint tasks and fans them out across job workers in LanceDB Enterprise. Unlike an index build, a compaction plan needs no bin-packing: Lance's own planner already produces disjoint tasks, so workers claim and execute them directly, with no coordination needed to decide who does what. See [Architecture](/enterprise/v1-12-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR L["Lance's planner<br/>splits fragments into<br/>disjoint tasks"] L --> W1["Worker<br/>claims fragments 1-2"] L --> W2["Worker<br/>claims fragments 3-4"] L --> W3["Worker<br/>claims fragments 5-6"] W1 --> C["Fleet-wide eligibility gate:<br/>one worker claims the commit"] W2 --> C W3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class C accent ``` No task depends on another's result, so a worker that finishes early simply claims another task rather than waiting on its peers. Committing is where the fleet does coordinate: finished tasks go through a shared eligibility gate, and only the one worker that claims the commit actually writes it, rather than each worker committing its own task independently. Whether a failed task can still let the rest commit depends on the remap mode. Inline remap is all-or-nothing: one failed task fails the whole job, since the commit updates every affected index inline and can't skip a task's share of that. Deferred remap can commit a subset -- a failed task's fragments are abandoned and replanned in a later round, while the rest of the job's tasks commit without waiting on it. See [Advanced Conflict Resolution](/enterprise/v1-12-0/enterprise/advanced-conflict-resolution) for when compaction defers a remap at all. ## Compaction interfaces * [Compaction](/enterprise/v1-12-0/maintenance/compaction) for triggering and configuring a compaction. * [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup) for removing files compaction and other operations leave behind. * [Job Framework](/enterprise/v1-12-0/basics/jobs) for the job types a deployment runs on its own schedule. # Distributed Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/distributed-indexing How LanceDB Enterprise distributes a vector index build across a fleet of workers, stage by stage. **Applies to:** Embedded ❌, Enterprise ✅ A vector index build splits into stages, and the data in scope narrows at each one: training works from a small sample, shuffling touches every row once, and merging works entirely within one partition at a time. Full-text and scalar index builds skip training and shuffling -- they bin-pack directly into independent tasks workers claim and build in parallel, closer to how [distributed compaction](/enterprise/v1-12-0/enterprise/distributed-compaction) splits work. See [Architecture](/enterprise/v1-12-0/index#architecture). ## Stages of a vector index build 1. **Train.** A sample of the table's vectors -- not the full dataset -- trains the shared model every worker will use: IVF partition centroids, and for IVF-PQ, a PQ codebook on top of them. 2. **Shuffle.** Every row in the table gets assigned to its nearest trained partition and regrouped so that all of one partition's rows end up together, wherever in the table they originally lived. 3. **Merge.** Each partition is now self-contained, so workers build and merge partitions in parallel with no cross-partition coordination -- one worker's output never depends on another's. 4. **Commit.** The finished index is committed to the table. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Sample"] --> T["Train IVF centroids<br/>+ PQ codebook"] T --> Sh["Shuffle: assign every row<br/>to its nearest partition"] Sh --> M1["Merge<br/>partition A"] Sh --> M2["Merge<br/>partition B"] Sh --> M3["Merge<br/>partition C"] M1 --> C["Commit the<br/>finished index"] M2 --> C M3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Sh accent ``` ## Indexing interfaces The shared indexing guides describe how to build and maintain each index type: * [Vector indexes](/enterprise/v1-12-0/indexing/vector-index) and [vector search](/enterprise/v1-12-0/search/vector-search). * [Full-text indexes](/enterprise/v1-12-0/indexing/fts-index) and [full-text search](/enterprise/v1-12-0/search/full-text-search). * [Scalar indexes](/enterprise/v1-12-0/indexing/scalar-index) and [filtering](/enterprise/v1-12-0/search/filtering). * [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing) for triggering and tracking a build. # Compress Function output columns Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/function-column-compression Choose Lance storage compression before refreshing a Function output column. Use `update_field_metadata` to choose compression for a top-level column populated by a registered Function. Storage settings belong to the table column; keep compression metadata out of the Function's `output_schema`. To apply compression to the first backfill, disable automatic refresh while adding the column, set its compression, then start a refresh. For an existing table with a `blob_id` column and a registered Function `fetch_content` that returns text: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col table.add_columns( {"content": fetch_content(blob_id=col("blob_id"))}, auto_refresh_enabled=False, ) table.update_field_metadata( { "path": "content", "metadata": { "lance-encoding:compression": "zstd", "lance-encoding:compression-level": "22", }, } ) job = table.refresh_column_async("content") job.wait() ``` Higher compression levels trade write speed for smaller storage. The settings apply to subsequent writes; changing metadata does not rewrite existing files. Set a key's value to `None` to remove that setting. Use the default merge behavior of `update_field_metadata` to preserve the server-managed Function declaration. Compression updates are supported on Function outputs that no Function binding reads. If another Function will consume `content`, configure compression before binding that downstream Function: input contracts capture field metadata, so metadata changes on bound inputs remain rejected. Only `lance-encoding:compression` and `lance-encoding:compression-level` receive this exception; other metadata updates and metadata replacement remain rejected on Function-bound columns. # Horizontal Scaling Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/horizontal-scaling How LanceDB Enterprise spreads serving capacity for a table across replica groups, and replicates it within each one. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB Enterprise scales serving capacity by assigning a table to one or more **replica groups** -- numbered subsets of the plan-executor fleet -- and, within each group, by **replication factor** (RF): how many copies of the table's data that group holds. A table is served only from the groups it is explicitly assigned to; adding plan executors to the fleet, or adding a new group, never auto-includes existing tables. A pristine table that was never explicitly placed stays on one default group at the cluster's default RF. See [Architecture](/enterprise/v1-12-0/index#architecture). Placement is stored in the table's own manifest, not a separate configuration store, and takes effect for a table within its readers' read-consistency refresh interval after a change. An index can carry its own RF override within each of the table's groups instead of inheriting the table's RF. Reassigning a table's groups or RF is an operator action (through the admin API, not SQL); [contact support](https://www.lancedb.com/contact) to change a table's placement. Replica groups are numbered subsets of the fleet, not per-table resources -- different tables can share a group, use entirely different groups, or overlap partially, and each picks its own RF independently within every group it uses: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph G0["Replica group 0"] direction LR G0A["Plan executor"] G0B["Plan executor"] end subgraph G1["Replica group 1"] direction LR G1A["Plan executor"] end subgraph G2["Replica group 2"] direction LR G2A["Plan executor"] G2B["Plan executor"] G2C["Plan executor"] end TA["Table A<br/>groups 0, 1 · RF 2 in group 0, RF 1 in group 1"] -.-> G0 TA -.-> G1 TB["Table B<br/>group 2 only · RF 3"] -.-> G2 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class TA,TB accent ``` Table A is assigned to groups 0 and 1, at RF 2 and RF 1 respectively -- three plan executors total hold a copy of Table A. Table B never touches groups 0 or 1 at all; it is assigned only to group 2, at RF 3. Group 2's plan executors serve no part of Table A, and group 0's plan executors serve no part of Table B. Raising Table B's RF to 3 did not add a single plan executor to Table A's serving path, and vice versa -- each table's placement decision only changes which plan executors hold *that* table's data. ## Why this scales serving More replicas of a hot table's data, across more plan executors, means more of the fleet can serve that table's queries in parallel -- the same reasoning as adding query-serving capacity generally (see [Architecture](/enterprise/v1-12-0/index#architecture)), applied per table rather than cluster-wide. Replication also gives a table fault tolerance: losing one plan executor does not take its data offline if another replica still holds it. A single query that reads several tables routes every read to the same replica group -- the intersection of the tables' assigned groups, trying a lead group first and falling back through the rest of the order if it has no healthy plan executor. Keeping one query's reads co-located protects the locality of whichever group's cache is already warm for it, rather than letting each table's read drift to a different group. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>routes to the lead group"] subgraph G0["Replica group 0 (lead)"] direction LR A0["Plan executor<br/>copy 1"] A1["Plan executor<br/>copy 2"] end subgraph G1["Replica group 1 (fallback)"] direction LR B0["Plan executor<br/>copy 1"] B1["Plan executor<br/>copy 2"] end Q --> A0 Q --> A1 Q -. "only if group 0 has no healthy PE" .-> B0 Q -. "only if group 0 has no healthy PE" .-> B1 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Q accent ``` This table is assigned to two replica groups, each at replication factor 2: four plan executors in total, each holding a full copy of the table's data. Adding a third group, or raising RF within a group, adds more plan executors that can serve this table's reads in parallel -- scaling throughput for this one table without touching any other table's placement. ## Scaling interfaces * [Distributed Search](/enterprise/v1-12-0/enterprise/distributed-search) for how a query divides across query nodes and plan executors generally. * [Architecture](/enterprise/v1-12-0/index#architecture) for the components a replica group is made of. # Intelligent Auto-Maintenance Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/intelligent-auto-maintenance How Enterprise continuously tracks table activity in the background and decides what maintenance -- compaction, cleanup, indexing, remap catch-up -- a table needs next. **Applies to:** Embedded ❌, Enterprise ✅ Keeping a table in good condition takes several different kinds of work -- compacting files, catching indexes up, cleaning old versions, folding a RTE write tier into the base table -- each with its own trigger. In LanceDB Enterprise, a fleet of agent processes decides when each of these needs to run, continuously, per table, in the background across your cluster -- nothing to schedule, trigger, or monitor by hand unless you want to. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR E["Table event notifications"] --> P S["Periodic sweep<br/>every table, on a timer"] --> P P["Planner<br/>evaluates one table"] P --> W["Possible next step:<br/>WAL index catch-up"] P --> I["Possible next step:<br/>Index operations"] P --> C["Possible next step:<br/>Compaction"] P --> CL["Possible next step:<br/>Cleanup"] P --> R["Possible next step:<br/>Remap catch-up"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class P accent ``` ## Tracking activity An agent's long-running process watches two independent sources for a table: **table events** (Job Registry notifications, so it learns about a write, a schema change, or a new index almost immediately) and a **periodic sweep** that revisits every table it owns on a timer -- 600 seconds by default -- so a table that stops producing events still gets re-evaluated rather than going stale. A hot table producing a flood of events does not get to monopolize evaluation: notifications and the periodic sweep share a bounded per-tick budget, and reads for a given table run at most once at a time. Each evaluation reopens the table and reads its manifest, indexes and in-flight jobs fresh, rather than deciding from a cached guess. Those are separate reads rather than one atomic snapshot, so a concurrent write between them is possible; the next evaluation -- triggered by that same write's own event notification -- is what catches anything the current one missed. ## Deciding what to run A table is not reduced to one "next best action" -- each evaluation walks a fixed, priority-ordered sequence of independent decisions, launching whichever ones are due: 1. **WAL index catch-up.** Checked first and gated by nothing else, because it is correctness-driven rather than discretionary: while an index lags behind the compacted generation, the RTE write tier cannot trim its log. See [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction). 2. **Index operations.** Reindexing a column, unless a compaction that cannot defer its remap is about to run this same tick -- deferred-remap compaction lets index work proceed alongside it instead of waiting. See [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing). 3. **Compaction.** Whether enough small fragments or deleted rows have accumulated to merge. See [Compaction](/enterprise/v1-12-0/maintenance/compaction) and [Distributed Compaction](/enterprise/v1-12-0/enterprise/distributed-compaction). 4. **Cleanup.** Independent of the other four -- it can always run in parallel with them. [See below](#cleanup) for exactly when it's due. 5. **Deferred-remap catch-up.** The batched, amortized follow-up for index entries a deferred compaction didn't remap synchronously. See [Advanced Conflict Resolution](/enterprise/v1-12-0/enterprise/advanced-conflict-resolution). More than one of these can fire for the same table in the same evaluation -- a compaction and a cleanup are unrelated and can both launch together -- but some gate each other where running them at the same time would be unsafe, like index operations waiting on a compaction that can't defer its remap. ### When cleanup is due [Cleanup](/enterprise/v1-12-0/maintenance/cleanup) prunes old table versions and the files only they referenced. In LanceDB Embedded, that always happens because you asked for it -- a call to `optimize()`. LanceDB Enterprise does not support a manual `optimize()` call at all; cleanup there is entirely this planner's own decision, off by default unless the deployment sets a minimum version age -- with no minimum age configured, nothing is ever old enough to clean up automatically, and old versions simply accumulate until an operator enables it. A table can also disable it individually even when the deployment allows it, overriding the deployment-wide setting for just that table. Once enabled, a table becomes due for cleanup when any one of these is true: | Trigger | Condition | | - | - | | Enough new versions | The current version has advanced far enough past the version the last successful cleanup started from | | Enough time has passed | The last successful cleanup finished long enough ago -- the default is 24 hours -- so an idle table whose versions simply age past the retention window still gets revisited | | Version went backward | The current version is lower than the version the last successful cleanup recorded, which re-triggers a run immediately | A table that has never had a successful cleanup run is held to its own initial version threshold first, so a brand-new table is not claimed for cleanup before it has accumulated enough versions to be worth the pass. A failed attempt is retried, but not immediately -- a minimum delay (60 seconds by default) must pass after the failure before the table becomes eligible again, even if one of the triggers above would otherwise fire. ## Confirming it's actually running Rather than asking you to trust that evaluation is happening, the agent exposes coverage metrics scoped to *successful* evaluations specifically -- a failed or timed-out attempt does not count: | Metric (`lance_agent_` prefix) | What it tells you | | - | - | | `coverage_never_evaluated` | Tables this agent owns that have never completed an evaluation | | `coverage_oldest_success_age_seconds` | How long it's been since the longest-overdue table was last successfully evaluated | | `coverage_cycle_target` / `coverage_cycle_pending` | How much work the current full sweep has left | | `coverage_cycles_completed_total` | How many full sweeps have finished | A cycle freezes its target set of tables up front; new tables join the *next* cycle rather than resetting progress on the current one, and a table that disappears or changes ownership is dropped from the target rather than counted as covered. ## What to read next > [card] [Cleanup](/enterprise/v1-12-0/maintenance/cleanup) > > What a cleanup pass actually removes, and the retention window it respects. > [card] [Advanced Conflict Resolution](/enterprise/v1-12-0/enterprise/advanced-conflict-resolution) > > Why compaction and index maintenance need the deferred-remap decision at all. > [card] [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction) > > The WAL-tier compaction this page's Decision 1 depends on. > [card] [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing) > > What an index operation actually does once scheduled. > [card] [OpenTelemetry](/enterprise/v1-12-0/deployment/opentelemetry) > > Viewing the `lance_agent_*` coverage metrics above. # Real Time Engine compaction Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/realtime-engine-compaction How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up. **Applies to:** Embedded ❌, Enterprise ✅ [Distributed Compaction](/enterprise/v1-12-0/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/enterprise/v1-12-0/maintenance/compaction) describes for LanceDB Embedded. A table with the [real time engine](/enterprise/v1-12-0/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and `memwal_catchup_<type>`, already distinct from ordinary `compact` in `SHOW JOBS` and `list_jobs`. This page covers how Enterprise decides when to run them, not just what they do. ## What triggers a compaction pass A per-pod loop, ticking every `WAL_COMPACTION_INTERVAL_SECS` (5s by default), walks every table this pod owns and reads each shard's manifest. It dispatches a compaction job for a shard once any threshold crosses: | Trigger | Default | Checks | | - | - | - | | `WAL_COMPACT_TRIGGER_COUNT` | 4 | The shard's SSTable count | | `WAL_COMPACT_TRIGGER_BYTES` | 1 GiB | The shard's total flushed SSTable bytes | | Oldest generation's age | 7 days | How long the head SSTable generation has sat, whatever the file count -- a file that will never gather enough siblings to cross the count trigger still gets compacted eventually | Whichever crosses first wins. A shard under write pressure does not wait for the next tick either: the same thresholds are re-checked on every backpressure relief pass, so a hot shard that already qualifies compacts sooner than `WAL_COMPACTION_INTERVAL_SECS` would otherwise allow. Setting `WAL_COMPACTION_INTERVAL_SECS` to `0` disables the periodic walk; an operator can still force a pass with `POST /v1/compact`, and `Table::checkpoint_rte` drives the same flush-then-compact cycle from the client when you need a table to converge on demand rather than wait for the trigger. `checkpoint_rte` has no liveness bound of its own -- it is idempotent and abandonable at any point, but the caller owns the deadline for how long to wait on it. This trigger decision is internal to the WAL pod -- it is not the general job scheduler deciding to run `memwal_compaction`, the pod decides to enqueue one. Once enqueued, the work is still tracked as an ordinary job (`memwal_compaction`, then `memwal_catchup_<type>` once it lands), so `SHOW JOBS` and `list_jobs` surface it the same way they surface any other background job. ## What one pass does By default (`wal.remoteMaintenance` is on), a tick's passes are offloaded as ordinary Job Registry worker jobs instead of running in the WAL pod itself, up to `WAL_COMPACT_CONCURRENCY` at a time (32 by default). With remote maintenance off, the pod runs them itself, in a per-pod compactor pool shared across every table it owns, bounded to 2 concurrent passes instead. Either way, each pass: 1. Snapshots the shard's current list of SSTables. 2. Takes a bounded prefix of them, oldest first (`WAL_COMPACT_PREFIX_MAX`, 32 by default), further capped at `COMPACT_PASS_TARGET_BYTES` (2 GiB) \-- a budget every in-pod pass shares, but that an offloaded pass gets in full to itself. 3. Opens each as a Lance file and scans its rows. 4. Deduplicates across the prefix by primary key -- a later SSTable's row wins over an earlier one with the same key. 5. Merges the deduplicated rows into the base table with `merge_insert`. 6. Commits a manifest update that drops exactly the SSTables just folded in, identified individually rather than by position, so a retried commit against a newer manifest can't drop the wrong ones. 7. `memwal_catchup_<type>` then extends each of the base table's indexes \-- one job per index type (`memwal_catchup_btree`, `memwal_catchup_fts`, `memwal_catchup_ivfpq`, and so on) -- over the rows step 5 just added, and records how far that index has caught up. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR A["Shard crosses a trigger<br/>(count, bytes, or generation age)"] --> B["Per-pod trigger loop<br/>or backpressure relief pass"] B --> C["Compactor pool<br/>dedup by PK, merge_insert into base"] C --> D["Manifest drops<br/>the folded SSTables"] D --> E["memwal_catchup_<type><br/>extends each base index"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` Only one compaction pass runs against a given shard at a time. A second, concurrent pass against the same shard would corrupt it: a stale pass can overwrite rows a newer generation already replaced, or resurrect a row a newer generation deleted, since the merge step has no way to tell a late-arriving write from a value that was already superseded. A per-shard latch enforces this -- the periodic trigger skips a shard that's already compacting, a manual `POST /v1/compact` is refused outright (never queued) on the same collision, and node drain waits for the shard's current pass instead of skipping it, since a skipped table is exactly what drain exists to flush. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Shard["Shard's per-shard latch"] --> Held{"Already held by<br/>an in-progress pass?"} Held -->|no| Grant["Grant the latch,<br/>run the pass"] Held -->|yes, periodic trigger| Skip["Skip this tick --<br/>retried next tick"] Held -->|yes, manual POST /v1/compact| Refuse["Refused outright,<br/>never queued"] Held -->|yes, node drain| Wait["Wait for the current<br/>pass to finish, don't skip"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Shard accent ``` ## Reading while compaction runs A query against an RTE-enabled table always reads the shard's current memtable and SSTables unioned with the base table, regardless of where a compaction pass is in its cycle -- compaction only ever changes which side of that union a row's latest value lives on, never which value is current. There's no window where a row is visible in neither side: the manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. A table queried *without* the real time engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks whichever trigger fires -- wider either way than the real time engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough siblings or bytes instead waits on the age trigger, up to 7 days by default, before it's compacted at all. `WAL_MAX_DATA_AGE_SECS` bounds two independent stages -- the memtable freeze and this compaction age trigger \-- so a slow table's worst-case staleness without the live path is up to roughly twice that default, not one interval plus one job's runtime. Either way, the bound also assumes a free compaction slot when the shard becomes eligible; an eligible shard can wait in queue behind `WAL_COMPACT_CONCURRENCY` other passes already running, so the actual delay can run longer than the trigger alone suggests. See [RTE reads](/enterprise/v1-12-0/search/realtime-read) for what a live RTE read sees instead. ## What to read next > [card] [Real Time Engine](/enterprise/v1-12-0/tables/realtime-engine) > > The MemWAL format, shards, and WAL nodes this page assumes. > [card] [Distributed Compaction](/enterprise/v1-12-0/enterprise/distributed-compaction) > > The unrelated, ordinary compaction every table -- WAL-enabled or not -- gets. > [card] [Job Framework](/enterprise/v1-12-0/basics/jobs) > > Job handles, waiting, and inspecting jobs -- memwal_compaction included. # Compliance Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/security Learn about LanceDB Enterprise security features and best practices. LanceDB Enterprise maintains high security standards with SOC 2 Type II, HIPAA, and GDPR compliance. Our security framework is designed to provide enterprise-grade protection for your data and workloads across deployment models. ## Security Certifications * **SOC 2 Type II**: Independent audit confirming our security controls and operational effectiveness * **HIPAA Compliance**: Certified to handle protected health information (PHI) in healthcare applications * **GDPR Compliance**: Supports organizations with data privacy requirements under the General Data Protection Regulation * **Regular Audits**: Ongoing security assessments to maintain compliance standards ### Ongoing Compliance LanceDB maintains SOC 2 Type II, HIPAA, and GDPR compliance through ongoing audits and continuous improvement of our security practices as standards and risks evolve. > [!NOTE] > > Visit the [LanceDB Trust Center](https://trust.lancedb.com/) to learn more about LanceDB's security posture, data privacy practices, and to request access to security documentation. ## LanceDB Enterprise ### Data Security Customer data is strictly protected and remains within the confines of your account. We maintain rigorous data isolation and encryption protocols to ensure confidentiality. LanceDB Enterprise only receives telemetry data for monitoring system health. At LanceDB, customer data security is paramount. ### Encryption LanceDB Enterprise safeguards your data through encryption at rest, preventing unauthorized access. This comprehensive encryption covers all data stored within the object store and cache. # MinHash SQL functions Source: https://docs.lancedb.com/enterprise/v1-12-0/enterprise/sql-minhash Create lexical text signatures and probabilistic duplicate candidates. **Applies to:** Embedded ❌, Enterprise ✅ MinHash compares the sets of token shingles in two texts. Use it to find lexical near duplicates, such as copies with small edits. Embedding distance measures a different kind of similarity; use vector deduplication when semantic similarity is the desired criterion. Use exact hashes when only identical values count as duplicates. > [!NOTE] > > These experimental functions require an Enterprise server with native MinHash > SQL support. Check the server release you run; installing a newer client does > not add server capabilities. The shared SQL and Functions execution context uses the same implementation. Persisted signatures retain their version, tokenizer profile, hash count and shingle size. Recompute signatures when upgrading to an incompatible signature version. Raw index values do not carry the SQL field metadata required to establish a compatible tokenizer and shingle configuration. ## Create a signature ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash('the quick brown fox') AS signature; SELECT minhash(body) AS signature FROM documents; SELECT minhash(body, 256, 3) AS signature FROM documents; ``` `minhash(text[, num_hashes[, shingle_size]])` returns `FixedSizeList<UInt16>` with exactly `num_hashes` elements per signature. The defaults are 128 hashes and shingles of 3 consecutive tokens. `num_hashes` must be a constant integer from 1 through 4096; `shingle_size` must be a constant integer from 1 through 4294967295. More hashes increase storage and computation and reduce sampling error. The integer values occupy `2 * num_hashes` bytes per row before Arrow validity and storage encoding overhead; there is no per-row header. The fixed tokenizer splits text into alphanumeric tokens and lowercases them. It retains stop words, accents and long tokens, and does not stem words. A text with fewer tokens than `shingle_size` contributes a single shingle containing all its tokens. `NULL`, empty text and text with no tokens return `NULL`. The result field carries the logical-type marker and configuration. The configuration is also attached to its `UInt16` item field: Lance storage preserves the outer metadata, while worker function-type transport preserves the item metadata. Readers accept either and reject conflicts. Default metadata: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "field_metadata": { "lancedb:logical_type": "minhash_signature", "lancedb:minhash:signature_version": "0", "lancedb:minhash:tokenizer": "simple_lowercase_v1", "lancedb:minhash:shingle_size": "3" }, "item_metadata": { "lancedb:minhash:signature_version": "0", "lancedb:minhash:tokenizer": "simple_lowercase_v1", "lancedb:minhash:shingle_size": "3" } } ``` Aliases and `CREATE TABLE ... AS SELECT` preserve this marker, including for empty or all-null results. It identifies the output of `minhash`, regardless of the column's name. Distance and band-key results use their ordinary numeric and list types. Consumers require the configuration metadata and validate the list width and element type. Preserve both levels of field metadata when copying or exporting signatures; Python Arrow fields expose metadata keys and values as byte strings. An ordinary integer list is not automatically a MinHash signature. Earlier experimental `BINARY` signatures must be regenerated from their source text. ## Store signatures in a new table Use a fresh table name to materialize the source columns and their signatures: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents_with_signatures AS SELECT *, minhash(body) AS signature FROM documents; ``` Preserve the generated values and field metadata when storing signatures. Use `minhash_distance` to compare compatible signatures. Storing this column does not build a MinHash LSH index. ## Add a signature column with the Python SDK On an Enterprise server with native MinHash column-transform support, an eager column addition uses the same SQL expression as a query: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns({"signature": "minhash(body)"}) ``` This fills the new column for existing rows, using only the input columns the expressions reference. It supports the ordinary eager expression form of `add_columns`. Deferred `computed=` declarations and SQL `ALTER TABLE ... ADD COLUMN ... AS` use a separate planner and still require their own MinHash support. Earlier servers can accept `SELECT minhash(body)` while rejecting a column addition; use CTAS with an unused destination name on those versions. Verify the column-writing path on the deployed server version. ## Estimate Jaccard distance ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash_distance( minhash('the red fox jumps', 128, 1), minhash('the red fox runs', 128, 1) ) AS distance; ``` `minhash_distance(left, right)` returns `FLOAT`: one minus the fraction of hash positions that agree. Zero means identical signatures; one means no matching positions. This is an estimate of token-shingle Jaccard distance, with sampling error and possible hash collisions. A threshold on this value is not an exact Jaccard threshold. Exact token-shingle comparison is needed when exact threshold decisions are required. Both signatures must use the same version, tokenizer profile, hash count and shingle size. Missing or incompatible metadata is rejected, even for empty inputs. `UNION`, `CASE` and `COALESCE` reject incompatible signature configurations before execution. Individual hash elements must not be NULL. If either valid operand is `NULL`, the result is `NULL`. ## One entry point for text and vectors `dedupe` and `duplicate_pairs` select the algorithm from the column at the requested dataset snapshot. Top-level string columns use MinHash; supported vector columns retain the vector-index workflow and its metric. A text distance threshold is estimated Jaccard distance in `[0, 1]`; vector thresholds retain their metric's units. Options are validated by the selected implementation. `dedupe` and `duplicate_pairs` also accept stored `FixedSizeList<UInt16>` MinHash columns with the configuration metadata described above: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe('documents', 'signature', distance_threshold => 0.2); SELECT * FROM duplicate_pairs('documents', 'signature', distance_threshold => 0.2); ``` This path reads the saved hashes instead of tokenizing and hashing text again. Hash count and shingle size come from the column; conflicting explicit options are rejected. `num_bands` defaults to 16 and must divide the signature width. An ordinary integer list without MinHash metadata is not a signature column. `EXPLAIN ANALYZE` reports `column_signatures` and `computed_signatures` so the input path can be verified. Producing candidate pairs reads the signature column; returning retained rows still reads the original rows. Eager `add_columns` calculates existing rows once. Keep the saved signatures in sync when text changes. NULL signatures stay in deduplicated output. Compare the two paths on the same source data and with matching signature settings. `text_dedupe` and `text_duplicate_pairs` remain supported for raw-text queries. Use the shared names above for signature-column dispatch and configuration inference. ## Generate candidate keys ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash_lsh_keys(minhash(body), 16) AS band_keys FROM documents; ``` `minhash_lsh_keys(signature[, num_bands])` returns a list of `UINT64` keys. The default is 16 bands. The band count must be a constant integer from 1 through 256 and divide the signature's hash count. Each key includes its band number; matching keys identify potential duplicate pairs. A null signature returns a null list. Generate candidates only among signatures with the same configuration and band count. Deduplicate pairs that share several bands, then score the candidates with `minhash_distance`. LSH can miss pairs that meet the distance threshold; increasing the number of bands improves coverage but increases candidate work. For ideal independent MinHash values, similarity `s`, `b` bands and `r` hashes per band give candidate probability `1 - (1 - s^r)^b`. This is a tuning model, not a completeness guarantee for the implementation. Identical or heavily templated documents can produce quadratic numbers of candidate pairs. A SQL self-join over keys does not by itself impose a memory, pair-count or concurrency bound. A per-row nearest-neighbor query with a top-k limit also does not enumerate all batch duplicate pairs. ## Run complete batch text deduplication ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id_a, row_id_b, distance, dataset_version FROM duplicate_pairs( 'documents', 'body', distance_threshold => 0.2, num_hashes => 128, shingle_size => 3, num_bands => 16 ); CREATE MATERIALIZED VIEW documents_clean AS SELECT * FROM dedupe( 'documents', 'body', distance_threshold => 0.2 ); REFRESH MATERIALIZED VIEW documents_clean; ``` Both relations bind one immutable source snapshot, scan live rows across all fragments, generate LSH collisions and apply the estimated distance threshold. They require a native table without WAL and a threshold from zero through one. The top-level input column can contain strings or `FixedSizeList<UInt16>` MinHash signatures with valid configuration metadata. No MinHash or vector index is required. The source remains intact. These names preserve the vector meaning of the existing `duplicate_pairs` and `dedupe` relations. The optional `num_hashes`, `shingle_size` and `num_bands` arguments have the same limits as the scalar functions. Text-column queries use the scalar defaults; saved-signature queries infer omitted `num_hashes` and `shingle_size` from column metadata. All arguments must be literals. `dataset_version => 7` pins an explicit version; without it, each query or refresh binds the latest snapshot again. Keep that snapshot's files available throughout execution. Pair row IDs belong to the reported snapshot version; physical row IDs can change across compaction, while stable row IDs remain stable when that table feature is enabled. `duplicate_pairs` emits each unordered candidate pair at most once, with `row_id_a < row_id_b`. It does not silently limit a bucket or apply a per-row neighbor cap. Completeness means all collisions in the declared LSH configuration, not all pairs that meet an exact or estimated distance threshold. `dedupe` returns retained original rows and columns. The default `resolution => 'connected_components'` keeps the smallest snapshot row ID in each transitive component. A chain A–B–C can remove C even when A and C do not match directly. `resolution => 'direct_representative'` visits canonical edges in ascending row-ID order and removes only rows that directly match a retained representative; the same chain retains A and C. Neither policy recovers LSH misses. Rows with NULL or no-token text are retained as isolated rows. For connected components, equal signatures form a clique with identical neighbours. Execution connects each such group with a star and compares one representative per signature group. These edges preserve the same connected components and smallest original row IDs. The pair relation and direct-representative resolution enumerate all matching pairs. A refresh recomputes the complete result because an appended row can connect previously separate components. It does not append new representatives to an old result. Functions SQL jobs and distributed SQL use the ordinary result publication path; incomplete worker output is not a successful materialization. ## Resource limits The initial batch implementation assigns the complete candidate stage to one plan executor. A global stage preserves matches across source fragments. It uses the ordinary streaming transport with backpressure, not one worker per bucket. The executor fleet must advertise `streaming_datafusion` and the capability for the input type: `minhash_pairs_v1` for text-column queries, or `minhash_signature_pairs_v1` for saved-signature-column queries. Signatures and band membership spill to a temporary redb database with a 64 MiB cache. The stage reserves 192 MiB from the query memory pool for that cache and working buffers. Input batches target at most 128 rows and 8 MiB, with 16 MiB of storage I/O buffering and one batch/fragment read ahead. These are processing budgets, not a process RSS limit; storage readers, shared caches and decoding a single large value also use memory. A document larger than 4 MiB fails the operation explicitly. It is never shortened silently. Candidate output has batches of at most 1,024 pairs and a two-batch queue. The final retained-row scan also uses an 8 MiB byte target, 16 MiB of I/O buffering, and one batch/fragment read ahead. Temporary disk use is charged to the query's disk manager and exceeding its budget fails the operation. Representative selection can also spill; it reserves additional memory for the final row masks based on source cardinality, plus a 256 MiB sorting allowance for direct-representative resolution. An insufficient memory pool fails before representative processing. Cancellation closes the output queue and releases temporary state. Dense groups of different signatures can still require quadratic comparisons. Complete pair output is also quadratic for a duplicate clique. The operator reports input rows, signed rows, stored signatures, collapsed signature rows, band entries, band comparisons, output rows and peak staging file bytes. In connected-components mode, `candidate_signature_pairs` counts comparisons between signature groups; full-pair mode reports `unique_candidates` between source rows. Stage, scan-wait, signature and enumeration timers help locate costs; enumeration time includes output backpressure. Evaluate candidate recall and these costs on representative data before increasing workload size or band count. # Geneva Python SDK Source: https://docs.lancedb.com/enterprise/v1-12-0/geneva/reference LanceDB Feature Engineering Python SDK Reference > [card] [Geneva Python SDK Reference](https://lancedb.github.io/geneva/) > > Refer to the Geneva Python SDK reference documentation by clicking here. # Audit Log Source: https://docs.lancedb.com/enterprise/v1-12-0/governance/audit-log The durable record of access attempts in the cluster: its schema, how to query it, and how to grant access. **Applies to:** Embedded ❌, Enterprise ✅ Every authorization check in LanceDB Enterprise -- the principal, the privilege that was checked, and the object it was checked against -- can be recorded as a durable audit log entry. On a failed check, the first failure is logged; on success, the final successful check is logged. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Request arrives"] --> C["Authorization check"] C -->|denied| L1["Log the first failed check"] C -->|granted| L2["Log the final successful check"] L1 --> T[("__audit_log table<br/>system database")] L2 --> T T --> Q["SELECT ... FROM system.public.__audit_log"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class T accent ``` A deployment chooses how audit records are kept: discarded, written alongside ordinary application logs, or stored durably as rows in a Lance table. Only the durable Lance-backed sink produces something you can query with SQL -- the other two modes exist, but leave nothing in the table this page describes. ## Schema | Column | Type | Nullable | What it holds | | - | - | - | - | | `AccessId` | string | no | The record's own unique ID, a UUIDv4 in hyphenated text form | | `AccessTime` | timestamp (microsecond, UTC) | no | When the check happened | | `PrincipalId` | string | no | The checked principal's ID | | `PrincipalName` | string | yes | The principal's display name, where known | | `Object` | string | yes | The object checked against, when the operation maps to a single object | | `AccessType` | string | no | The privilege that was checked | | `Description` | string | no | A human-readable description of the check | | `RequestId` | string | yes | The query node's own request ID, for correlating with request logs | | `Granted` | boolean | no | Whether the check succeeded | `RequestId` ties an authorization decision back to the request that produced it -- both the REST and Flight SQL transports accept only UUID request IDs, generating one when a request arrives without a valid one, so this column is always a canonical UUID string when present. ## Accessing it The audit log is an ordinary table, not a special API -- it lives in the `system` database's `public` namespace under the name `__audit_log` by default (a deployment can configure a different suffix, producing `__audit_<suffix>` instead, but the `__audit_` prefix is fixed to keep every audit table in its own part of the system database's namespace). Query it the same way you would any other table, with its full three-part name: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT PrincipalName, AccessType, Object, Granted, AccessTime FROM system.public.__audit_log WHERE Granted = false ORDER BY AccessTime DESC LIMIT 100 ``` ## Durability The Lance-backed sink batches records in the background instead of writing on the request path: a batch flushes once it reaches a configured size or once its oldest record has waited a configured linger period, whichever comes first. Its queue holds a bounded number of pending records; once full, requests producing new records wait for the writer to drain it rather than having a record dropped, and a failed write is retried with growing backoff rather than abandoned -- so a sink that cannot keep up applies back pressure and, if sustained, eventually blocks request handling instead of silently losing entries. The audit table is opened at service startup rather than on first use, so a misconfigured or unreachable sink fails startup instead of surfacing the first time something needs to be logged. This page does not cover retention -- how long written records are kept, or whether anything prunes them -- which a deployment operator should confirm for your version and configuration. ## Granting access `system` is not a grantable database -- SQL refuses `GRANT ... ON DATABASE system`. Reaching into it instead requires `USAGE` on the `SYSTEM` authorization object, plus `SELECT` on the table itself. Only a superuser can run these grants. See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full `GRANT`/`REVOKE` syntax: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SYSTEM TO ROLE security_team GRANT SELECT ON TABLE system.public.__audit_log TO ROLE security_team ``` System `USAGE` is broad: beyond reaching the audit log, it also lets the grantee list every job and its events, look up identities, and run untargeted `SHOW GRANTS` / `SHOW ROLE BINDINGS`. Grant it deliberately, not as an incidental step toward audit-log access. The audit log itself still records who was granted access and who reads it -- granting and querying it are both authorization checks like any other, so they appear as rows in the table they govern. ## What to read next > [card] [Compliance](/enterprise/v1-12-0/enterprise/security) > > Certifications, data handling, and the controls a deployment provides. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > The full privilege model, and how creation privileges resolve upward. # Authorization Source: https://docs.lancedb.com/enterprise/v1-12-0/governance/authorization Who may do what: an overview of LanceDB Enterprise's access control model. **Applies to:** Embedded ❌, Enterprise ✅ [Authentication](/enterprise/v1-12-0/enterprise/authentication) establishes who is calling. Authorization decides what they may do. An access control entry grants **one privilege** on **one object** to **one subject**. Everything on the Principals and Privileges pages is a consequence of that shape. ## Granting a privilege `GRANT` and `REVOKE` cover every object in the catalog -- system, database, schema/namespace, table, view, materialized view, secret, function, and storage integration. A Secret, the one a day-to-day user shares most often, looks like this: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research REVOKE USAGE ON SECRET platform.`model-api-key` FROM ROLE research ``` The caller must already hold `OWNERSHIP` on the object being granted (`GRANT` additionally requires the object to already exist; `REVOKE` does not, so an entry left on a dropped object can still be removed). A role need not exist beforehand, but a `USER` or `GROUP` name must resolve to exactly one identity in your identity provider, or the statement fails. See [Privileges](/enterprise/v1-12-0/governance/privileges) for the full statement syntax and every privilege each operation needs. See [Principals](/enterprise/v1-12-0/governance/principals) for who a grant can name. ## What to read next > [card] [Principals](/enterprise/v1-12-0/governance/principals) > > Users, groups, and roles -- where each comes from, and how a grant names one. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > Every object's privileges, and the GRANT/REVOKE syntax that covers them. # Principals Source: https://docs.lancedb.com/enterprise/v1-12-0/governance/principals Users, groups, and roles: where each comes from, and how a GRANT or REVOKE statement names one. **Applies to:** Embedded ❌, Enterprise ✅ A grant names one of three kinds of subject: | Subject | Where it comes from | | - | - | | User (principal) | Your identity provider -- OIDC, Microsoft Entra, Okta, or Keycloak. LanceDB never creates one. | | Group | Also your identity provider. LanceDB never creates one. | | Role | LanceDB itself. There is no statement that creates a role -- naming one in a grant is what brings it into existence. | ## Naming a subject in SQL `GRANT` and `REVOKE` accept a role, user, or group name directly, with an optional keyword to disambiguate: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice GRANT USAGE ON SECRET platform.`model-api-key` TO GROUP `data-science` ``` A `USER` or `GROUP` name is resolved against your identity provider, but only after the caller's `OWNERSHIP` on the object is checked. A name that isn't found, or that matches more than one identity, is an error -- not a silent no-op. `ROLE` needs no such lookup, since a role is simply whatever name a grant has used. Name several subjects of the same kind in one statement by omitting the keyword after the first: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service ``` ## Role membership in SQL SQL manages which users or groups a role applies to -- its membership -- directly: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT ROLE analysts TO USER alice GRANT ROLE analysts TO GROUP `data-science` REVOKE ROLE analysts FROM USER alice SHOW ROLE BINDINGS ``` Changing membership (`GRANT`/`REVOKE ROLE`) needs system `OPERATE`; `SHOW ROLE BINDINGS` needs only system `USAGE`. A role binding accepts a `USER` or `GROUP` on the receiving side, never another `ROLE` -- granting a privilege to a role before anyone is a member of it is still valid; the role simply has no effect until it has members. ## What to read next > [card] [Authorization](/enterprise/v1-12-0/governance/authorization) > > The access-control model a grant is built from. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > Every object's privileges, and the GRANT/REVOKE syntax that covers them. # Privileges Source: https://docs.lancedb.com/enterprise/v1-12-0/governance/privileges Every privilege, which object it's granted on, and the GRANT/REVOKE syntax that covers each one. **Applies to:** Embedded ❌, Enterprise ✅ | Privilege | Granted on | Allows | | - | - | - | | `OWNERSHIP` | any object | full authority over it, including granting any other privilege | | `USAGE` | system | listing, describing and reading the events of jobs, and looking up other identities | | `USAGE` | database | accessing the namespaces inside | | `USAGE` | namespace | accessing the tables inside | | `USAGE` | secret | binding it to a Function, and resolving its value at evaluation time | | `USAGE` | function | binding it to a column, and refreshing a column it computes | | `USAGE` | storage integration | reading through it or importing with it | | `SELECT` | table, view | reading rows | | `INSERT` | table | appending rows | | `UPDATE` | table | modifying existing rows | | `UPDATE` | secret | rotating it, without the right to bind or read it | | `DELETE` | table | deleting rows | | `CREATE_DATABASE` | system | creating a database | | `CREATE_NAMESPACE` | database, namespace | creating immediate child namespaces | | `CREATE_TABLE` | namespace | creating a table in it | | `CREATE_MATERIALIZED_VIEW` | namespace | creating a materialized view in it | | `CREATE_VIEW` | namespace | creating a non-materialized view in it | | `CREATE_SECRET` | namespace | creating a Secret in it | | `CREATE_FUNCTION` | namespace | registering a Function in it | | `CREATE_STORAGE_INTEGRATION` | namespace | registering a storage integration in it | | `OPERATE` | system | controlling jobs (cancel, pause, resume), managing caches, reading server configuration, and managing role membership | `OWNERSHIP` is never revoked -- granting it again transfers it to a new owner instead, and a single `GRANT OWNERSHIP` statement names exactly one subject. The caller must already hold `OWNERSHIP` on an object to change any grant on it. > [!NOTE] > > `CREATE_MATERIALIZED_VIEW` and `CREATE_VIEW` are separate privileges because > [the two objects differ](/enterprise/v1-12-0/basics/catalog): one stores rows and is refreshed, > the other stores only a query. Granting the ability to create one does not > grant the other. ## Creating an object you don't own yet Creating a database or namespace checks its *parent*, not itself: one with no owner -- because it doesn't exist yet -- falls back to `CREATE_DATABASE` on the system, or `CREATE_NAMESPACE` on its parent namespace, and the creator becomes its owner. This is what makes creation possible at all, so holding `CREATE_DATABASE` is enough to create a table in a database that has not been created yet. ## Granting privileges from SQL `GRANT` and `REVOKE` reach every object in the table above -- `SYSTEM`, `DATABASE`, `SCHEMA`, `NAMESPACE <name> [IN <schema>]`, `TABLE`, `VIEW`, `MATERIALIZED VIEW`, `SECRET`, `STORAGE INTEGRATION`, and `FUNCTION` -- with the same statement shape. `SCHEMA` and `NAMESPACE` both target a namespace, but aren't interchangeable spellings: `SCHEMA` takes a namespace's complete path, while `NAMESPACE` takes one unqualified component, resolved under an explicit parent (`IN <schema>`) or the session's current namespace when `IN` is omitted: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT SELECT ON VIEW dashboard TO ROLE analysts GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins GRANT USAGE ON FUNCTION platform.embed TO ROLE etl GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` A materialized view is a table for authorization purposes: the same `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` privileges apply, and granting one does not reach the non-materialized `VIEW` beside it. | Target in the statement | Privileges it accepts | | - | - | | `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | | `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | | `SCHEMA` / `NAMESPACE` | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | | `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | | `VIEW` | `OWNERSHIP`, `SELECT` | | `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | | `FUNCTION` | `OWNERSHIP`, `USAGE` (bind it to a column) | | `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | See [GRANT and REVOKE](/enterprise/v1-12-0/sql/ddl/grant) for the full statement syntax, including every grantee form (`ROLE`, `USER`, `GROUP`, the `ID '<id>'` form) and every status a statement can return, shared by every target above. The REST ACL API covers the same objects and reaches further back: it works against deployments whose SQL surface does not yet expose a given target, and is the only option for a client that does not speak SQL. ### What each Secret operation requires | Operation | Requires | | - | - | | Create a Secret | `CREATE_SECRET` on the namespace. The creator owns the new Secret. | | Rotate (`alter`) | `UPDATE` on the Secret | | Describe | `USAGE` on the Secret | | List | `USAGE` on the database and the namespace | | Drop | `OWNERSHIP` on the Secret. Dropping also deletes its grants. | | Bind it to a Function | `USAGE` on the Secret | `UPDATE` is deliberately separate from `USAGE`, so a rotation service can replace a value without being able to bind the Secret to a Function of its own. ### Example: sharing one key * A **platform operator** owns the `platform` namespace. They create `platform$model-api-key`, then grant the `research` group `USAGE` on that one Secret. * A **researcher** in `research` registers a Function bound to `platform$model-api-key`. Binding any other Secret in `platform` is refused. * A **table owner** in `research` adds a column computed by that Function. They hold `USAGE` on the Secret through the group, but are refused until they also hold `USAGE` on the Function. * **Analysts** read the resulting column with table access alone -- no Function runs on the read path, so they need no grant on the Function or its Secret. ## What to read next > [card] [Authorization](/enterprise/v1-12-0/governance/authorization) > > The access-control model a grant is built from. > [card] [Principals](/enterprise/v1-12-0/governance/principals) > > Users, groups, and roles -- where each comes from, and how a grant names one. # Full-Text Search (FTS) Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/fts-index Create and tune BM25-based full-text search indexes in LanceDB. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB provides performant full-text search based on BM25, allowing you to incorporate keyword-based search in your retrieval solutions. This page shows examples on how to create and configure FTS indexes in LanceDB Embedded and LanceDB Enterprise, using the synchronous and asynchronous APIs. > [!NOTE] > > In LanceDB Enterprise, `create_fts_index` API returns immediately, but index building happens asynchronously. ## Creating FTS Indexes ### Synchronous API Use `create_fts_index` with synchronous LanceDB connections: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "fts-index-create" table = db.open_table(table_name) table.create_fts_index("text") ``` Check FTS index status using the API: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "fts-index-wait" table = db.open_table(table_name) table.create_fts_index("text") index_name = "text_idx" table.wait_for_index([index_name]) ``` `wait_for_index(...)` waits until the named FTS index exists and `index_stats(...)` reports `num_unindexed_rows == 0`. It can time out if writes keep adding rows faster than the index catches up. If a table has multiple FTS indexes, specify the target text column when querying instead of relying on implicit selection. ### Asynchronous API When using async connections (`connect_async`), use `create_index` with the `FTS` configuration: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import asyncio import lancedb import polars as pl from lancedb.index import FTS data = pl.DataFrame( { "id": [1, 2], "text": [ "His first language is spanish", "Her first language is english", ], } ) async def main(data: pl.DataFrame): uri = "ex_lancedb" db = await lancedb.connect_async(uri) tbl = await db.create_table("my_text", data=data, mode="overwrite") await tbl.create_index("text", config=FTS(language="English")) response = await tbl.search("spanish", query_type="fts") result = await response.limit(1).to_polars() print(result) return result if __name__ == "__main__": asyncio.run(main(data)) ``` > [!NOTE] > > The `create_fts_index` method is not available on `AsyncTable`. Use `create_index` with `FTS` config instead. The current FTS implementation is Lance-native. Legacy Tantivy-only options, including `use_tantivy`, are no longer accepted by the index creation APIs. ## Nested field paths FTS indexes can target text leaves inside struct columns by passing a dotted path (for example, `payload.text`). The same path works for [`MatchQuery`](/enterprise/v1-12-0/search/full-text-search) and [`PhraseQuery`](/enterprise/v1-12-0/search/full-text-search), and for the `columns` argument on async `nearest_to_text` queries. You can point an index at any string leaf nested in a struct, regardless of depth. The struct container itself isn't indexable: you have to name a specific text field. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MatchQuery, PhraseQuery table = db.open_table("fts-index-nested") # Index a text leaf inside a struct column using a dotted path. table.create_fts_index("payload.text", with_position=True) # The same dotted path works in MatchQuery and PhraseQuery. matches = ( table.search(MatchQuery("puppy", "payload.text")).limit(5).to_list() ) phrases = ( table.search(PhraseQuery("puppy runs", "payload.text")) .limit(5) .to_list() ) ``` LanceDB rejects paths that don't resolve to a text leaf: * A struct container (for example, `payload`): raises `ValueError: FTS index cannot be created ...`. * A non-text leaf such as an integer or float (for example, `payload.count`): raises the same error. * A path that doesn't exist in the schema (for example, `payload.missing`): raises `ValueError: Field path ... not found`. The async API accepts the same dotted paths through `create_index`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS await async_table.create_index("payload.text", config=FTS(with_position=True)) ``` ## Configuration Options ### FTS Parameters | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `with_position` | bool | `False` | Store token positions (required for phrase queries) | | `base_tokenizer` | str | `"simple"` | Text splitting method (`simple`, `whitespace`, `raw`, `ngram`, `icu`, `jieba/*`, or `lindera/*`) | | `language` | str | `"English"` | Language for stemming and stop-word filters. Choose CJK and mixed-language segmentation with `base_tokenizer`. | | `max_token_length` | int | `40` | Maximum token size; longer tokens are omitted | | `lower_case` | bool | `True` | Lowercase tokens | | `stem` | bool | `True` | Apply stemming (`running` → `run`) | | `remove_stop_words` | bool | `True` | Drop common stop words | | `ascii_folding` | bool | `True` | Normalize accented characters | | `custom_stop_words` | list\[str] | `None` | Explicit stop-word list that replaces the built-in list. Requires `remove_stop_words=True`. | | `ngram_min_length` | int | `3` | Minimum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `ngram_max_length` | int | `3` | Maximum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `prefix_only` | bool | `False` | Index only prefix n-grams rather than all substrings. Applies only when `base_tokenizer="ngram"`. | | `block_size` | int | `128` | Number of documents per compressed posting block. Supported values are `128` and `256`. Setting this to `256` opts in to the experimental FTS V3 layout. | > [!NOTE] > > * `max_token_length` can filter out base64 blobs or long URLs. > * Disabling `with_position` reduces index size but disables phrase queries. > * `ascii_folding` helps with international text (e.g., “café” → “cafe”). ### Tokenizer choices `base_tokenizer` controls segmentation before token filters run: * `simple`, `whitespace`, and `raw` cover common tokenization strategies for space-delimited text. * `ngram` indexes overlapping character spans for substring-style matching. * `icu` uses bundled ICU4X word segmentation for mixed-language text and scripts where whitespace splitting is not enough. ICU stands for [International Components for Unicode](https://icu.unicode.org/), and this tokenizer does not need external model files. * `jieba/*` is for Chinese word segmentation with Jieba. * `lindera/*` loads a compiled Lindera dictionary, such as `lindera/ipadic` for Japanese or `lindera/ko-dic` for Korean. Model-backed tokenizers such as `jieba/default`, `lindera/ipadic`, and `lindera/ko-dic` require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to another model root. For example, `jieba/default` is resolved under `<model-home>/jieba/default/...`. For a table in LanceDB Enterprise, the files must be present where the deployment builds and queries the index, so ask its administrator whether they are installed. `language` is used by token filters, not by the base tokenizer. Stemming and language-specific stop-word removal support Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. The ICU tokenizer uses a combined multilingual stop-word list. An explicit `custom_stop_words` list replaces the built-in list for either tokenizer. > [!WARNING] > > Lance `15.0.0-beta.1` revises the built-in stop-word lists, including the multilingual list used by ICU. Existing index metadata records tokenizer settings, but does not freeze these built-in lists. Rebuild affected FTS indexes with the same configuration before serving queries with the updated SDK, so stored terms and query tokens use the same lists. Indexes with stop-word removal disabled or an explicit `custom_stop_words` list are unaffected by this change. ### Posting block size `block_size` controls the number of documents packed into each compressed posting block on disk. The default of `128` matches the current FTS layout and is the right choice for most workloads. Setting it to `256` opts in to the experimental FTS V3 format, which changes how postings are encoded and may introduce breaking changes in future releases. Any other value is rejected at index creation time. You can set the option through either the synchronous or asynchronous API. In the async Python API, pass it on the `FTS` config, and in the TypeScript API use the camelCase `blockSize` field on `FtsOptions`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS await async_table.create_index("text", config=FTS(block_size=256)) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.createIndex("text", { config: lancedb.Index.fts({ blockSize: 256 }), }); ``` ### Phrase Query Configuration Enable phrase queries by setting: | Parameter | Required Value | Purpose | | :- | :- | :- | | `with_position` | `True` | Track token positions for phrase matching | | `remove_stop_words` | `False` | Preserve stop words for exact phrase matching | ## Indexing nested string fields You can build an FTS index on a string field inside a struct by passing its full dotted path, like `nested.text`. The same path is used when you query the index through `fts_columns`, and the indexed column is reported back as the full path from `list_indices()`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema: pa.struct([pa.field("text", pa.string())]) stored under the `nested` column. table.create_fts_index("nested.text") results = ( table.search("puppy", query_type="fts", fts_columns="nested.text") .limit(5) .to_list() ) ``` > [!NOTE] > > Use the canonical Lance path: dot-separate each struct field from root to leaf (for example, `metadata.author.name`). The same convention applies to scalar and vector indexes. # GPU Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/gpu-indexing Build a vector index faster with GPU acceleration, manually in LanceDB Embedded or automatically in LanceDB Enterprise. **Applies to:** Embedded ✅, Enterprise ✅ GPU acceleration can reduce the time needed to build vector indexes on large datasets. Actual build time depends on the index configuration, vector dimensions, storage throughput and available GPU resources. > [!NOTE] > > **Automatic GPU indexing** > > Automatic GPU Indexing is currently only available in [LanceDB Enterprise](/enterprise/v1-12-0/index#architecture). > Please [contact us](https://www.lancedb.com/contact) to enable this feature for your deployment. > > The vector index is created when you call `create_index`. The backend uses GPU resources > to build `IVF_PQ` indexes, with the number of GPUs set by the deployment's configuration. > > This process is also asynchronous by default, but you can use `wait_for_index` to convert it > into a synchronous process by waiting until the index is built. `wait_for_index(...)` waits for the index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. It can time out if the table is receiving continuous writes while the build is trying to catch up. GPU acceleration changes how the vector index is built, not the lifecycle after the build. In the embedded library, rows appended later still need `optimize()` before they are part of the index; a deployment adds them in the background -- see [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing). `fast_search()` only searches indexed rows. ## Manual GPU indexing in LanceDB Embedded You can use the Python SDK to manually create the `IVF_PQ` index on a GPU. You'll need [PyTorch>2.0](https://pytorch.org/). Note that GPU-based indexing is currently only supported by the synchronous SDK in LanceDB Embedded. Specify the values `cuda` or `mps` (on Apple Silicon) for the `accelerator` parameter to enable GPU training on your device. ### GPU indexing on Linux ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( num_partitions=256, num_sub_vectors=96, accelerator="cuda", ) ``` ### GPU indexing on macOS (Apple Silicon) ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( num_partitions=256, num_sub_vectors=96, accelerator="mps", ) ``` ## Performance considerations * GPU memory usage scales with `num_partitions` and vector dimensions * Size GPU memory for the training batches and index configuration * Monitor memory use while choosing training batch sizes * Measure build time and recall before changing training settings ## Troubleshooting If you encounter the error `AssertionError: Torch not compiled with CUDA enabled`, you need to [install PyTorch with CUDA support](https://pytorch.org/get-started/locally/). ## What to read next > [card] [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing) > > Keeping an index up-to-date as new data arrives. > [card] [Slurm](/enterprise/v1-12-0/deployment/slurm) > > Running these GPU workers alongside training on shared Slurm-scheduled infrastructure. # Incremental Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/incremental-indexing Keep an index up-to-date as new data arrives, without a full rebuild. **Applies to:** Embedded ✅, Enterprise ✅ As you add new data to your LanceDB tables, your indexes may become outdated. Reindexing is the process of updating the index to account for new data. This applies to either a full-text search (FTS) index or a vector index. Reindexing is an important operation to run periodically as your data grows, as it has performance implications. As data is being added and a reindex operation is running, LanceDB will combine results from the existing index with exhaustive/flat search on the new data. This is done to ensure that you're still retrieving results over all your data, but it does come at a performance cost. The more data that you add without reindexing, the impact on latency (due to exhaustive search) can be noticeable. Rather than dropping an existing index entirely and reindexing from scratch, LanceDB supports **incremental indexing**. > [!NOTE] > > **Enterprise job types:** an index build runs as `reindex_` followed by the > algorithm, such as `reindex_ivf_pq`, `reindex_btree` or `reindex_fts`, and so > does folding new rows into an existing index. A create-only build, one that must > not replace an existing index, runs as `create_` followed by the algorithm > instead; Python's `create_scalar_index` and `create_fts_index` ask for that by > default. The name says which algorithm is building, not a separate feature. ## Triggering an incremental update In the embedded library, you trigger an incremental indexing operation on updated data with the `optimize()` method on a table. A deployment does this for you and does not support `optimize()`, as described below. Table optimization performs three maintenance operations: 1. **Compaction**: merges small fragments into larger ones to improve read performance 2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/enterprise/v1-12-0/maintenance/cleanup) for how retention works 3. **Index update**: adds newly-ingested data to existing vector, scalar, and FTS indexes ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("reindexing_incremental") table.add([{"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}]) table.optimize() ``` Enterprise LanceDB Enterprise supports incremental reindexing through an automated background process. Once enough new rows have been added to a table, the system automatically adds them to its indexes. As the dataset grows, indexes are asynchronously updated in the background. * While indexes are being rebuilt, queries use brute force methods on unindexed rows, which may temporarily increase latency. If you can omit unindexed rows, set `fast_search=True` to search only indexed data. This can return incomplete results while indexing catches up. * Use `index_stats()` to view the number of unindexed rows. This will be zero when indexes are fully up-to-date. If you call `wait_for_index(...)`, it polls the same status and can time out while continuous writes keep adding unindexed rows. * Rows below the deployment's threshold stay unindexed until more arrive, so the count can stay above zero without further writes. `FM` indexes are not updated in the background. The benefit of using LanceDB Enterprise is that it automates the reindexing process and operates continuously in the background, minimizing the impact on latency under high loads. In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. Opening a table in LanceDB Embedded logs a warning at most once per table per process when any index has at least 1,000,000 unindexed rows. Set `LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default. ## Index maintenance jobs Two further Enterprise job types keep an index correct as the rows underneath it move, rather than adding new rows to it: | Job type | What it does | | - | - | | `index_remap` | Reassigns index entries after row ids shift underneath an index (the kind of remap a delta compaction can require). | | `spfresh_merge` | Merges SPFresh-managed segments for indexes that use it. | See [Advanced Conflict Resolution](/enterprise/v1-12-0/enterprise/advanced-conflict-resolution) for why `index_remap` exists as a separate, deferred job rather than happening synchronously inside every compaction. ## What to read next > [card] [Distributed Indexing](/enterprise/v1-12-0/enterprise/distributed-indexing) > > How an index build itself scales across the jobs fleet. > [card] [GPU Indexing](/enterprise/v1-12-0/indexing/gpu-indexing) > > Building a vector index faster with GPU acceleration. # Indexing Data Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/index Optimize search performance with LanceDB using vector indexes, full-text search, scalar indexes, and more. **Applies to:** Embedded ✅, Enterprise ✅ Indexes speed up searches and filters by organizing data for specific query patterns. LanceDB supports three main index families: * **Vector Index**: Efficiently searches for similar vectors across high-dimensional data (e.g. images, audio, or text embeddings) * **Full-Text Search Index**: Enables fast keyword-based searches by indexing words and phrases * **Scalar Index**: Accelerates filtering of structured numeric or categorical data ## Supported Indexes | Index | Use Case | Description | | :- | :- | :- | | `IVF` (Vector) | Large-scale vector search with configurable accuracy/speed trade-offs. | Inverted File Index: a partition-based approximate nearest neighbor algorithm that groups similar vectors into partitions for efficient search. **Quantizations**: `None/Flat` `PQ` `SQ` `RQ` | | `IVF_HNSW` (Vector) | Large-scale vector search requiring both high recall and efficient partitioning. Combines the scalability of IVF with the search quality of HNSW. | Hybrid index combining IVF partitioning with HNSW graphs in each partition. Provides improved search quality over pure IVF while maintaining scalability. **Quantizations**: `None/Flat` `SQ` `PQ` | | `FTS` (Full-text search) | String columns (e.g., title, description, content) requiring keyword-based search with BM25 ranking. | Full-text search index using BM25 ranking algorithm. Tokenizes text with configurable tokenization, stemming, stop word removal, and language-specific processing. | | `BTree` (Scalar) | Numeric, temporal, and string columns with mostly distinct values. Best for selective equality, inequality, and range predicates. | Sorted index storing sorted copies of scalar columns with block headers in a btree cache. Header entries map to blocks of rows (4096 rows per block) for efficient disk reads. | | `Bitmap` (Scalar) | Low-cardinality columns with few thousand or fewer distinct values. Accelerates equality and range filters. | Stores a bitmap for each distinct value in the column, with one bit per row indicating presence. Memory-efficient for low-cardinality data. | | `LabelList` (Scalar) | List columns (e.g., tags, categories, keywords) requiring `array_has_all` or `array_has_any` filters. | Scalar index for `List<T>` and `LargeList<T>` columns of primitive values, using an underlying bitmap index structure to enable fast array membership lookups. | | `FM` (Scalar) | String or binary columns that need raw substring search. | FM-Index over `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary` data for filters such as `contains(path, 'needle')`. Use FTS instead for tokenized word search and BM25 ranking. | | `NGram` (Scalar) | String columns that need substring search using character trigrams. | Trigram index over `Utf8` and `LargeUtf8` columns that narrows `contains(col, 'needle')` and some `LIKE` and regular expression predicates to rows sharing the query's trigrams, then rechecks the predicate. A query shorter than the trigram length cannot use it; use `FM` for arbitrary length substrings or `FTS` for tokenized word search. | The Python `NGram` configuration requires a newer client than 0.41.0; see [its SDK requirements](/enterprise/v1-12-0/indexing/scalar-index#ngram-index-for-substring-search). A deployment builds the vector indexes `IVF_FLAT`, `IVF_PQ`, `IVF_RQ` and `IVF_HNSW_SQ`. `IVF_SQ`, `IVF_HNSW_FLAT` and `IVF_HNSW_PQ` are built only by the embedded library. ## Quantization LanceDB also supports several [quantization](/enterprise/v1-12-0/indexing/vector-index) methods, used by vector indexes to compress vectors and reduce storage requirements: | Quantization | Use Case | Description | | :- | :- | :- | | `PQ` (Product Quantization) | Default choice for most vector search scenarios. Use when you need to balance index size and recall. | Divides vectors into subvectors and quantizes each subvector independently. Provides a good balance between compression ratio and search accuracy. | | `RQ` (RabitQ Quantization) | Use when you need maximum compression or have specific per-dimension requirements. | Per-dimension quantization using a RabitQ codebook. Provides fine-grained control over compression per dimension. For `IVF_RQ`, vector dimensions must be divisible by `8`. | | `SQ` (Scalar Quantization) | Use when you need faster indexing or when vector dimensions have consistent value ranges. | Quantizes each dimension independently. Simpler than PQ but typically provides less compression. | | `None/Flat` | Use for binary vectors (with `hamming` distance) or when you need maximum recall and have sufficient storage. | No quantization; stores raw vectors. Provides the highest accuracy but requires more storage and memory. | ## Performance #### Vector indexes If vector search latency climbs with table size (i.e., queries that ran in milliseconds on a small table take seconds as it grows to millions of rows), check whether the query is scanning every vector without an index. The point at which an index helps depends on vector dimensions, hardware and your latency target. Measure your workload before choosing an index. Pick the type by your data shape: | Index | When to use | | - | - | | `IVF_PQ` | General-purpose default, and what a deployment builds when it is set to index a column automatically. Higher accuracy than RQ at small dimensions (≤ 256). | | `IVF_RQ` | Maximum compression on high-dim vectors, faster builds than PQ. | | `IVF_HNSW_SQ` | Best recall/latency for unfiltered search; higher latency variance under selective filters. | | `IVF_FLAT` | Required for binary vectors with `hamming`. | The distance metric is fixed once the index is built. Pick the distance metric based on how the embedding model was trained: `cosine` (unnormalized), `dot` (already-normalized, best performance), `l2` (general-purpose, default), `hamming` (binary). If a query explicitly requests a different metric, the index cannot be used and the query falls back to a brute-force scan; a deployment can be configured to reject that scan on a large table. For parameter tuning, see [Vector Indexing](/enterprise/v1-12-0/indexing/vector-index). #### Scalar indexes Scalar indexes can reduce the rows scanned for selective filters and speed up `merge_insert` key lookups. Start with columns used frequently in those operations, then use [query plans](/enterprise/v1-12-0/basics/sql#query-plans) to check whether the index helps. Choose the index type based on the column's values: | Index | Best for | | - | - | | `BTREE` (default) | Numeric, string, temporal columns with mostly distinct values | | `BITMAP` | Boolean and low-cardinality columns (\< \~1,000 distinct values) | | `LABEL_LIST` | `List<T>` columns queried with `array_has_any` / `array_has_all` | See [Scalar Indexing](/enterprise/v1-12-0/indexing/scalar-index). #### Full-text search Token positions and retained stop words increase the information stored in a full-text index. Keep the defaults for basic keyword search; enable `with_position=True` and retain the needed stop words for phrase queries. See [FTS Indexing](/enterprise/v1-12-0/indexing/fts-index) configuration options for the full set of options. # Scalar Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/scalar-index Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization. **Applies to:** Embedded ✅, Enterprise ✅ Scalar indexes accelerate filters on values such as numbers, categories and strings. Use them for selective table queries or metadata filters combined with vector and full-text search. LanceDB supports five types of scalar indexes: * `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values. * `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags). * `LABEL_LIST`: Special index for `List<T>` and `LargeList<T>` columns of primitive values supporting `array_has_all` and `array_has_any` queries. * `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`. * `NGRAM`: Trigram index over UTF-8 string columns that accelerates substring search via `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters. > [!TIP] > > Use scalar indexes with: > > * Vector search (prefilter results using metadata) > * Full-text search (combining keyword matching with structured filters) > * SQL scans (optimizing WHERE clauses on scalar columns) > * Key-value lookups (enabling rapid primary key-based retrievals) ## Choosing the Right Index Type | Data Type | Filter | Index Type | | :- | :- | :- | | Numeric, String, Temporal | `<`, `=`, `>`, `in`, `between`, `is null` | `BTREE` | | Boolean, numbers or strings with fewer than 1,000 unique values | `<`, `=`, `>`, `in`, `between`, `is null` | `BITMAP` | | List of low cardinality of numbers or strings | `array_has_any`, `array_has_all` | `LABEL_LIST` | | String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')` | `FM` | | String (`Utf8`, `LargeUtf8`) | `contains(col, 'needle')`, `LIKE`, regex | `NGRAM` | ## Scalar Index Operations ### 1. Build the Index You can create multiple scalar indexes within a table. By default, the index will be `BTREE`, but you can always configure another type like `BITMAP` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.open_table("scalar_index_build") tbl.create_scalar_index("book_id") tbl.create_scalar_index("publisher", index_type="BITMAP") ``` > [!NOTE] > > If you are using LanceDB Enterprise, the `create_scalar_index` API returns immediately, but the building of the scalar index is asynchronous. To wait until all data is fully indexed, you can specify the `wait_timeout` parameter on `create_scalar_index()` or call `wait_for_index()` on the table. ### 2. Check Index Status ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "label_idx" table.wait_for_index([index_name]) ``` `wait_for_index(...)` waits until the named scalar indexes exist and `index_stats(...)` reports `num_unindexed_rows == 0`. If a table is receiving steady writes, that fully indexed state may not stabilize before the timeout. In LanceDB Enterprise, rows added after the index was built are indexed only once enough have accumulated, so a small remainder can also keep the wait from finishing. ### 3. Update the Index Updating the table data (adding, deleting, or modifying records) requires that you also update the scalar index. In the embedded library, call `optimize`, which will trigger an update to the existing scalar index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add([{"vector": [7, 8], "book_id": 4}]) table.optimize() ``` > [!NOTE] > > New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically. ### 4. Run Indexed Searches The following scan will be faster if the column `book_id` has a scalar index: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("books") result = table.search().where("book_id = 2").limit(10).to_pandas() ``` Scalar indexes can also speed up scans containing a vector search or full text search, and a prefilter: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("book_with_embeddings") table.search([1.2] * 2).where("book_id != 3").limit(10).to_pandas() ``` ## FM-Index for substring search The `FM` index is a scalar index built over string or binary columns that accelerates substring lookups expressed as `contains(col, 'needle')`. Unlike the tokenized [FTS index](/enterprise/v1-12-0/indexing/fts-index), which matches whole words after tokenization, the FM-Index matches arbitrary substrings of the raw bytes. It works well for URLs, file paths, identifiers, log lines, or any column where you search for a fragment rather than a word. Use the FM-Index when: * Filters use `contains(col, 'needle')` (substring), not equality or word search. * The column is `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary`. * You want substring matches without paying for tokenization, language analysis, or BM25 scoring. Pick `FTS` instead when you need word-level relevance ranking, phrase queries, or language-aware tokenization. ### Create an FM-Index Build an FM-Index with the async `create_index` API by passing the `Fm` config in Python or `Index.fm()` in TypeScript. In Rust, use `Index::Fm(FmIndexBuilder::default())`. A deployment builds FM-Indexes too, but does not add new rows to them in the background as it does for the other scalar indexes. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import Fm await tbl.create_index("text", config=Fm()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { Index } from "@lancedb/lancedb"; await tbl.createIndex("text", { config: Index.fm() }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::index::Index; use lancedb::index::scalar::FmIndexBuilder; tbl.create_index(&["text"], Index::Fm(FmIndexBuilder::default())) .execute() .await?; ``` After the index is built, substring filters use it automatically: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search().where("contains(text, 'needle')").limit(10).to_pandas() ``` `list_indices()` reports the index type as `"Fm"`. ## NGram index for substring search > [!NOTE] > > The Python `NGram` configuration is not available in Python 0.41.0. Its > example below uses the [0.42.0b8 client](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). > Use the FM index above with Python 0.41.0. Rust's 0.41.0 API already supports > `Index::NGram`; the Python binding has a separate version requirement. The `NGram` index is a scalar index over UTF-8 string columns. It tokenizes values into overlapping character n-grams (using Lance's default trigram parameters) and uses them to accelerate `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters. Unlike the `FM` index, which matches arbitrary substrings of the raw bytes, the `NGram` index is trigram based, so a query shorter than the n-gram length cannot be served by it. ### Create an NGram index Build an NGram index with the async `create_index` API by passing the `NGram` config in Python. In Rust, use `Index::NGram(NGramIndexBuilder::default())`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import NGram await tbl.create_index("text", config=NGram()) ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::index::Index; use lancedb::index::scalar::NGramIndexBuilder; tbl.create_index(&["text"], Index::NGram(NGramIndexBuilder::default())) .execute() .await?; ``` After the index is built, substring filters use it automatically: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search().where("contains(text, 'needle')").limit(10).to_pandas() ``` `list_indices()` reports the index type as `"NGram"`. ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. > [!NOTE] > > **To use `FixedSizeBinary`, ensure you have:** > > * Python SDK version `0.22.0` or later > * TypeScript SDK version `0.19.0` or later ### 1. Define UUID Type ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa ``` ### 2. Generate UUID Data ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def generate_random_names(): base_names = ["Alice", "Bob", "Carla", "David", "Eve", "Frank", "Grace"] letter = random.choice(string.ascii_uppercase) return f"{random.choice(base_names)} {letter}." def generate_uuids(num_items): return [uuid.uuid4().bytes for _ in range(num_items)] # Generate some UUIDs and random names n = 7 uuids = generate_uuids(n) names = [generate_random_names() for _ in range(n)] ``` ### 3. Create Table with UUID Column ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "index-on-uuid" uuid_array = pa.array(uuids, pa.uuid()) name_array = pa.array(names, pa.string()) schema = pa.schema( [ pa.field("id", pa.uuid()), pa.field("name", pa.string()), ] ) data_table = pa.Table.from_arrays([uuid_array, name_array], schema=schema) table = db.create_table(table_name, data=data_table, mode="overwrite") ``` ### 4. Create and Wait for the Index ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "id_idx" table.create_scalar_index("id") table.wait_for_index([index_name]) ``` ### 5. Perform Operations with the UUID Index ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} new_users = [ {"id": uuid.uuid4().bytes, "name": "Hannah D."}, {"id": uuid.uuid4().bytes, "name": "Ian B."}, ] # Insert or update using the UUID index table.merge_insert( "id" ).when_matched_update_all().when_not_matched_insert_all().execute(new_users) ``` ## Index nested fields You can build a scalar index on a field inside a struct column by passing the canonical dot-separated path to `create_index`. This is useful when filters target attributes nested under a `metadata`-style column, for example `metadata.user_id` or `metadata.event.type`. If a literal segment of the path itself contains a dot (for example a column named `user.id` nested inside `metadata`), wrap that segment in backticks so LanceDB can tell the dot apart from the path separator: `` metadata.`user.id` ``. `list_indices()` echoes the same canonical path back, so the column you pass in round-trips through index metadata regardless of nesting depth or escaping. Use the same path in filter predicates, for example `metadata.user_id = 42`. FTS and vector indexes follow the same path convention. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb.index import BTree metadata_type = pa.struct( [ pa.field("user_id", pa.int32()), pa.field("user.id", pa.int32()), ] ) data = pa.Table.from_arrays( [ pa.array([1, 2, 3], type=pa.int32()), pa.array( [ {"user_id": 10, "user.id": 100}, {"user_id": 20, "user.id": 200}, {"user_id": 30, "user.id": 300}, ], type=metadata_type, ), ], names=["user_id", "metadata"], ) table = await db.create_table("nested_scalar_index", data) # Index a nested struct field. await table.create_index( "metadata.user_id", config=BTree(), name="nested_user_id_idx" ) # Escape literal dots inside a segment with backticks. await table.create_index( "metadata.`user.id`", config=BTree(), name="escaped_user_id_idx" ) # `columns` is returned as the canonical path you passed in. for index in await table.list_indices(): print(index.name, index.columns) # nested_user_id_idx ['metadata.user_id'] # escaped_user_id_idx ['metadata.`user.id`'] ``` > [!NOTE] > > Composite indexes that cover multiple columns aren't supported yet. Each > `create_index` call must target a single (possibly nested) field path. # Vector Indexing Source: https://docs.lancedb.com/enterprise/v1-12-0/indexing/vector-index Build and manage LanceDB vector indexes. **Applies to:** Embedded ✅, Enterprise ✅ Vector indexes are robust tools in facilitating fast searches across large numeric datasets. LanceDB implements **ANN (Approximate Nearest-Neighbor)** queries with several techniques that provide benefits across a variety of use cases. ## Do you need one? Not always. LanceDB's disk-based brute-force kNN search is fast even without an index: computing 100K pairs of 1000-dimension vectors takes under 20ms in benchmarks. For datasets around 100K rows or fewer, or applications that can accept \~100ms latency, a vector index is usually unnecessary overhead. Build one once a table passes roughly a million rows, dimensionality is high, or query latency matters more than that. See [`bypass_vector_index`](#search-time-parameters) to run an exact search side-by-side and measure whether an index is worth it for your data. ## Choosing the Right Index LanceDB vector indexes are combined with several [quantization](/enterprise/v1-12-0/indexing/vector-index) techniques to admit efficient storage. The following table lists provided quantized vector indexes and their common use cases. You can specify index type manually in Lance with `index_type`. | If your priority is... | Use this index | Why | Approx. compression ratio | Python config class | | :- | :- | :- | :- | :- | | Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size with `num_bits=1` | `IvfRq` | | Higher accuracy at small dimensions (`dimension <= 256`) | `IVF_PQ` | IVF indexing with product quantization | Usually `1/64` to `1/16` of raw size (depends on `num_sub_vectors`) | `IvfPq` | | Best recall/latency trade-off | `IVF_HNSW_SQ` | IVF-HNSW indexing with scalar quantization | Typically a little larger than `1/4` of raw size | `IvfHnswSq` | | Highest recall / no quantization | `IVF_HNSW_FLAT` | IVF-HNSW indexing with no quantization; embedded library only | Around raw vector size plus HNSW graph overhead | `IvfHnswFlat` | > [!WARNING] > > If your vector search frequently includes metadata filters (`where(...)`), use `IVF_RQ` or `IVF_PQ`. In filtered workloads, HNSW-backed IVF indexes such as `IVF_HNSW_FLAT` and `IVF_HNSW_SQ` can show higher latency variance. ## Understanding Vector Indexes LanceDB offers two vector indexes, which can be created on any numeric Lance dataset: **Inverted File (IVF)** and **Hierarchical Navigable Small World (HNSW)**. ### IVF The **Inverted File Index (IVF)** accelerates ANN searches by drastically reducing the search space. The index consists of a small set of *centroids* corresponding to an approximate solution to the [$k$-means clustering](https://en.wikipedia.org/wiki/K-means_clustering) problem. Each vector remembers its nearest centroid, and each centroid remembers its associated set of vectors, called its *partition*. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/indexing/ivfpq_ivf_desc.webp?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=17979b18e9949106db93458d4e3290ef) Example partition of a geometric space, with colored marks denoting centroids. At query time, we can compare the queried vector to the smaller set of *centroids* (as opposed to the entire dataset) for a closest match, then run a brute-force comparison against its resulting partition. This technique quickly prunes a large search space, giving an approximate ANN result. However, observe that a queried vector may lie near the boundary of $2$ or more partitions; thus, the true nearest neighbors are scattered across several different partitions. To address this, LanceDB exposes the `nprobes` parameter, which specifies the number of partitions searched. A higher probe budget searches more partitions, which can improve recall at higher CPU and I/O cost. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/indexing/ivfpq_query_vector.webp?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=e99f54adc5560f6892e0ee0bac9f611c) Edge case for single-partition brute force. ### HNSW **Hierarchical Navigable Small World (HNSW)** constructs a layered graph hierarchy on the vector set, with edges representing distances. We can visualize an HNSW index as a vertical stack of graphs, with the top layer having very few edges and each other layer having a multiplicative factor more edges than the layer above it. High layers of a HNSW hierarchy represent sparse, higher-distance networks, and lower layers represent finer, lower-distance networks. To query a vector $q$, the index proceeds iteratively through layers, first finding $q$'s nearest neighbor in the graph, then proceeding recursively through the induced subhierarchy until the lowest layer is reached. ![HNSW layered graph hierarchy](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/indexing/hnsw_layered_graph.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=9ac5c3dc26cf9f341ad1fd244478677b) HNSW hierarchy: sparse network at the top layer, fine network at the bottom. To visualize this process, imagine that you must drive your car from San Francisco to a specific house in Boston. Initially, you must first drive thousands of miles on the interstate freeway I-90 E. Eventually, you merge onto the Massachusetts Turnpike, the center of the greater Boston highway system. From there, you use a series of increasingly smaller, narrower roads within the city (Charles River Bridge, St. Paul St, Thatcher St) before finally reaching the house. A key observation is that you must initially travel far distances through long-distance road networks (the interstate freeway system), before proceeding to finer and finer road networks (greater Boston highway system, central Brookline neighborhood connectors) before finally reaching your destination. This iterative series of road networks mimics the layered graph traversals performed by a HNSW query. > [!NOTE] > > **IVF + HNSW** > > In LanceDB, HNSW is not exposed as a top-level vector index. Instead, it's available as a substructure which > further indexes the selected vectors inside each IVF partition. > This combines the scalability of IVF with the high recall of HNSW. > LanceDB supports IVF-HNSW-based quantized indexes `IVF_HNSW_FLAT`, `IVF_HNSW_PQ`, and `IVF_HNSW_SQ`; a deployment builds only `IVF_HNSW_SQ`. ## Using Vector Indexes Learn how to configure, build, and search LanceDB vector indexes, including build and search time parameters, asynchronous objects, and several examples. ### Configuration #### Build-time Parameters | Parameter | Description | | :- | :- | | `distance_type` | Default is `l2`, others available are `cosine` and `dot`. | | `num_partitions` | The number of IVF partitions constructed (corresponds to the $k$ in $k$-means clustering). This takes precedence over `target_partition_size` if both are set. | | `target_partition_size` | An alternative IVF sizing knob that derives the partition count by setting the number of rows per partition. `num_partitions` takes precedence over `target_partition_size` if both are set. If neither is set the number of partitions is automatically calculated based on the number of rows and the index type. | | `num_sub_vectors` | Applies to `IVF_PQ`; defaults to `dimension // 16` (or `dimension // 8` if not a multiple of 16). Larger values produce better recall and slower search. | | `max_iterations` | Maximum number of k-means training iterations, for every IVF/HNSW index type. Default `50`. Increase for larger datasets or to improve training quality. | | `sample_rate` | Number of k-means training samples per partition, for every IVF/HNSW index type. Default `256`. Higher values increase both accuracy and training time. | #### Search-time Parameters | Parameter | Description | | :- | :- | | `limit` | Number of results to return (the `k` in `k-ANN`). | | `nprobes` | Search a fixed number of partitions per index segment. Leave unset to use Auto. | | `search_effort` | A value from `0` to `1` for tuning recall and latency. `0.5` uses Auto; higher values search more partitions. This is not a recall percentage. | | `minimum_nprobes` | Minimum number of partitions to search per segment. Auto may search more from the start. | | `maximum_nprobes` | Maximum number of partitions to search per segment. Leave unset to allow further searching when needed. A low cap can reduce recall or return fewer results than requested. | | `ef` | HNSW search-time exploration factor. Start around `1.5 * k` and increase up to `10 * k` for higher recall. | | `refine_factor` | Rerank candidates using full vectors to improve accuracy. A factor of `25` requests up to `25 * k` candidates. Higher values read more data; measure the recall gain and latency cost. | | `distance_range(lower_bound, upper_bound)` | Return only rows whose distance falls within `[lower_bound, upper_bound)`. Either bound is optional. Useful for near-duplicate detection or "close-enough" matching. | | `bypass_vector_index()` | Ignore the ANN index entirely and perform an exact (flat) scan. Can be used to measure ANN `recall@k`, or to query with a metric the index was not built for (e.g., a non-cosine query on a multivector column). | > [!NOTE] > > The `distance_type` can be specified at search time in addition to build time. If > you do this, set it to the same value used to build the vector index. If the search > metric does not match the index metric, LanceDB cannot use the index and falls > back to a costly flat search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit > can reject that search on a large table instead of executing it. An Enterprise > deployment applies the same limit only when it is configured to. > > When the search metric is omitted, current SDKs use the index metric if an index > is available. Some older SDK versions sent `l2` when it was omitted, so explicitly > set the matching metric or upgrade the SDK when querying a non-`l2` index with an > older client. **Recommended `nprobes` behavior by index type:** | Index type | Guidance | | :- | :- | | `IVF_HNSW_FLAT`, `IVF_HNSW_SQ` | Leave the probe settings unset, then tune `ef` first. Expect higher latency variance under filtered search. | | `IVF_RQ`, `IVF_PQ` | Leave the probe settings unset and configure them only when recall is insufficient. If using a selective filter you may need to increase `maximum_nprobes` if you do not receive enough results. | > [!NOTE] > > Start with Auto, then measure recall and latency before changing probe settings. > If you set both `search_effort` and `nprobes`, effort takes precedence. Explicit > min/max bounds still apply; equal bounds fix the count. See > [tuning vector search](/enterprise/v1-12-0/search/vector-search#tuning-nprobes) for examples and > guidance on choosing these controls. For a filtered search, you can let Auto choose within a range. The maximum also limits further searching if too few matches are found: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Let Auto choose between 10 and 50 partitions per segment, if available. filtered = ( table.search(query_vector) .minimum_nprobes(10) .maximum_nprobes(50) .where("id > 100") .limit(5) .to_arrow() ) ``` LanceDB also supports advanced search-time controls for thresholded retrieval, recall measurement, and working around index-level metric constraints. **Thresholding with `distance_range`:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Only return results whose distance falls within [0.0, 0.5). # Useful for near-duplicate detection or thresholded similarity search. ( table.search(np.random.random(128)) .distance_range(lower_bound=0.0, upper_bound=0.5) .limit(10) .to_pandas() ) ``` **Using `bypass_vector_index`:** Use `bypass_vector_index` to compute an exact **kNN** result. Note that exact queries may be prohibitively slow on production scales. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(128) k = 10 # Ground truth: flat (exhaustive) scan, ignoring the ANN index. truth = set(table.search(query).bypass_vector_index().limit(k).to_pandas()["id"]) # ANN results with the current nprobes setting. ann = set(table.search(query).nprobes(20).limit(k).to_pandas()["id"]) recall_at_k = len(truth & ann) / k ``` > [!NOTE] > > Multivector indexing currently requires `distance_type="cosine"`. Use `bypass_vector_index()` for non-`cosine` queries on a multivector column. See [Multivector Search](/enterprise/v1-12-0/search/vector-search) for the full rules. #### Async API and Config Objects Create vector indexes asynchronously with `await table.create_index("vector", config=...)`. The `config` object admits the same build-time parameters described above. Pass an instance of a Python config class from the table in [Choosing the Right Index](#choosing-the-right-index): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import numpy as np from lancedb.index import IvfPq async def main(): data = [ {"id": i, "vector": np.random.random(8).astype(np.float32).tolist()} for i in range(512) ] db = await lancedb.connect_async("ex_lancedb") table = await db.create_table( "vector_index_async", data=data, mode="overwrite" ) await table.create_index( "vector", config=IvfPq( distance_type="cosine", num_partitions=16, num_sub_vectors=4, ), ) return await table.list_indices() ``` ### IVF Indexes This example creates and queries an `IVF_PQ` index for a table of vectors with respect to `cosine` similarity. Specify `vector_column_name` if you have multiple vector columns or non-default names. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "vector-index-build-ivf" table = db.open_table(table_name) table.create_index( metric="cosine", vector_column_name="keywords_embeddings", ) tbl = table tbl.search(np.random.random((1536))).limit(2).nprobes(20).refine_factor( 10 ).to_pandas() ``` > [!NOTE] > > TypeScript currently doesn't support `IvfSq` (IVF with Scalar Quantization). For a vector field nested inside a struct, pass its full dotted path as `vector_column_name` (e.g. `image.embedding`). The same path is used at query time and is what `list_indices()` reports under `columns`. See [Selecting the vector column](/enterprise/v1-12-0/search/vector-search#selecting-the-vector-column) for the full path syntax. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # The vector column `embedding` is nested inside the `image` struct. # Pass its full dotted path as `vector_column_name`; the same path is used # at query time and is what `list_indices()` reports under `columns`. table.create_index( vector_column_name="image.embedding", num_partitions=1, num_sub_vectors=1, name="image_embedding_idx", ) results = ( table.search([0.0, 1.0], vector_column_name="image.embedding") .limit(1) .to_list() ) ``` ### IVF-HNSW Indexes Beyond the general build-time parameters above, two additional parameters are specific to IVF-HNSW indexes: | Parameter | Description | | :- | :- | | `m` | The number of neighbors to select for each vector in the HNSW graph. | | `ef_construction` | The number of candidates to evaluate during the construction of the HNSW graph. Start at `150`; increase for better recall, decrease for faster indexing. | Partition sizing follows the general `num_partitions`/`target_partition_size` guidance above. The snippet below builds and queries an `IVF_HNSW_SQ` index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index(index_type="IVF_HNSW_SQ") tbl = table tbl.search(np.random.random((16))).limit(2).to_pandas() ``` ### Managing Vector Indexes Enterprise-only In LanceDB Enterprise, vector indexes are managed **automatically**. The system asynchronously updates and optimizes indexes as a background process: * Automatically manages indexing parameters and storage * Can build an `IVF_PQ` index automatically on a vector column the deployment is configured to index * GPU-based `IVF_PQ` builds are available on request. [Contact support](/enterprise/v1-12-0/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. Open-Source LanceDB Embedded users can manually create vector indexes by calling `table.create_index()`. See the above sections for guidance on manually tuning index parameters as data changes. > [!NOTE] > > In LanceDB Enterprise, `create_index()` returns immediately and the vector index builds asynchronously. > To wait until all data is indexed, specify the `wait_timeout` parameter, or call `wait_for_index(...)` afterward. > It waits for the named index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. > In the embedded library the index is built before `create_index()` returns. > [!NOTE] > > Rows appended after an initial index build remain outside the index until refreshed manually (Embedded) or automatically (Enterprise). Normal > search still checks those unindexed rows with a slower fallback path; `fast_search()` skips that > fallback and searches only indexed rows. > [!NOTE] > > **Operational checks** > > In the embedded library, use `optimize()` after appends or other writes to fold new rows into existing indexes. > A deployment does this in the background, and `optimize()` is not available there. #### Check Index Status In LanceDB Enterprise, vector index creation runs in the background and may take some time to complete. While it is ongoing, you can check its status through the API or the **LanceDB Enterprise UI**. In the LanceDB Enterprise UI, navigate to your table page - the "Index" column reflects each column's index status: it is blank when no index exists, shows an "in progress" label while the index is being built, and shows the index type once the build completes. To check status programmatically, use `list_indices()` and `index_stats()`. **By default**, the index name is formed by appending `_idx` to the column name (e.g., a `keywords_embeddings` column produces `keywords_embeddings_idx`). Note that `list_indices()` only returns information after the index is fully built. Each entry returned by `list_indices()` also carries detailed per-index metadata, so you can inspect an index without a follow-up `index_stats()` call. Node.js exposes the same fields in camelCase (`num_indexed_rows` → `numIndexedRows`): | Parameter | Description | | :- | :- | | `num_indexed_rows`, `num_unindexed_rows` | Index coverage over the table | | `size_bytes` | Total size of the index files on disk | | `num_segments`, `index_version` | On-disk layout and format version | | `created_at` | Creation time (ms since the Unix epoch in Node.js) | | `index_uuid`, `type_url` | Internal identifiers for the index segment | | `index_details` | Type-specific details (e.g. IVF partition counts or quantization settings) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "keywords_embeddings_idx" table.wait_for_index([index_name]) print(table.index_stats(index_name)) ``` > [!NOTE] > > These fields are populated for LanceDB Embedded tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. #### Custom Index Names The `{column}_idx` suffix is the default naming convention. Pass `name=...` to `create_index()` to override it. Once set, the custom name will be reflected in `list_indices()`, `index_stats(name)`, and `wait_for_index([name])`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Override the default `{column}_idx` convention by passing `name=...`. table.create_index( metric="cosine", vector_column_name="keywords_embeddings", name="my_custom_index", ) table.wait_for_index(["my_custom_index"]) print(table.index_stats("my_custom_index")) ``` ## Quantization **Quantization** is used in LanceDB to efficiently compress and store vector indexes. We discuss only the quantization techniques here; discussion of LanceDB vector indexes and quantized vector indexes can be found [here](/enterprise/v1-12-0/indexing/vector-index). ### Quantization Techniques LanceDB provides $3$ distinct quantization techniques: Product Quantization (PQ), RaBitQ Quantization (RQ), and Scalar Quantization (SQ). Recall that all quantizations perform **lossy** compression, in that they irreversibly lose some degree of precision to compactly store an index. #### Product Quantization (PQ) To visualize PQ, assume a vector dataset has $d$ dimensions, with a **chunk** of a vector denoting a contiguous block of entries. Imagine that each vector has $m$ disjoint chunks of $d/m$ entries each, where the first chunk contains entries $0$ through $d/m-1$, the second contains entries $d/m$ through $2d/m-1$, and so on. Now, for each $i$, let $S_i$ represent the set containing chunk $i$ of each vector (entries $(i-1)d/m$ to $id/m-1$). For each $S_i$ independently, a small set of **centroids** is computed corresponding to an approximate solution to the $k$-means clustering problem. For each original vector in the dataset, every chunk is associated to its nearest centroid; thus, the vector itself is associated with the concatenation of $m$ centroids. We then gather all our centroids (from all chunks) into a single lookup table, and for each vector, we store the concatenation of IDs of its corresponding centroids. At query time, we need only to compare each chunk of the queried vector with our set of centroids. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/indexing/ivfpq_pq_desc.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=2910c4ddb151ef90a10cfbdf2d8508b0) In the above example, the original vector is split into chunks (subvectors), each of which is associated to a centroid. The stored quantization code for this vector is the concatenation $2 || 1 || 4 || 3$. The original vector required $128$ dimensions $\times 32$-bit floats $ =4096$ bits total, which has been compressed to $4$ chunks $\times 8$-bit integers $= 32$ bits of quantized storage. #### RaBitQ Quantization (RQ) RaBitQ is an advanced quantization technique that outperforms PQ in several ways. It needs no codebook to train, estimates distances very quickly at query-time, and can quantize each vector in (with some small overhead) as little as **one bit per dimension!** In practice, RaBitQ compresses a $1024$-dimensional `float32` vector into just a few thousand bits, while maintaining good recall. The inner workings of RaBitQ quantization are rather mathematically dense. It generates a quantization codebook by applying a uniformly random, approximately distance-preserving orthogonal transformation of the vertices of the $d$-dimensional hypercube, where $d$ is the dimensionality of the dataset. We defer the details, and an elegant theoretical error bound, to [the original paper.](https://arxiv.org/pdf/2405.12497) ##### Using RaBitQ Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, import `IvfRq` from `lancedb.index` and call `table.create_index("vector", config=IvfRq())`. Note that when using `IVF_RQ`, the dimension of the dataset must be a multiple of `8`. `num_bits` determines how many bits are used to quantize each dimension. By default, Python, Rust, and Node leave this unset and inherit Lance's default, currently `5` bits. Higher values improve recall at the cost of additional storage and query-time compute. To retain the previous one-bit default and maximum compression, explicitly set `num_bits=1` (for example, `IvfRq(num_bits=1)` in Python). Five-bit quantized vector codes use roughly five times the storage of one-bit codes; total index size also includes other overhead. > [!WARNING] > > RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout and cannot be read by some older LanceDB versions. > The new five-bit default therefore affects reader compatibility as well as index size. > Upgrade readers to versions that support multi-bit IVF_RQ before creating indexes with the default settings, or explicitly set `num_bits=1` when sharing indexes with readers that support only one-bit IVF_RQ. See this [blog post](https://lancedb.com/blog/feature-rabitq-quantization/) for further discussion and benchmarking of LanceDB's RaBitQ implementation. #### Scalar Quantization (SQ) Scalar quantization quantizes each entry of a vector independently, by simply replacing it with the closest of a pre-defined set of values. In practice, it often uses $8$ bits per dimension of a vector, and supports very fast encoding and decoding. For example, suppose we know all vector entries across our dataset lie in the range $[-128 \times 10^5, 127 \times 10^5]$. In this case, we could quantize a given value $v$ as an $8$-bit representation of the integer $j$, where $j \times 10^5$ is the closest value to $v$ among all integral multiples $\{j \times 10^5: -128 \leq j \leq 127 \}$. ### Quantization API Reference | Parameter | Description | | :- | :- | | `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (`IvfRq()` inherits Lance's default, currently `5`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | `max_iterations` and `sample_rate` also affect quantizer training, but since they apply to every IVF/HNSW index type (not just quantized ones), they're documented as general [Build-time Parameters](/enterprise/v1-12-0/indexing/vector-index#build-time-parameters) instead. All three are passed as keyword arguments to `create_index`, alongside `index_type`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( index_type="IVF_RQ", num_bits=2, max_iterations=100, sample_rate=512, ) ``` # AWS Bedrock Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/aws AWS Bedrock supports multiple base models for generating text embeddings. You need to setup the AWS credentials to use this embedding function. You can do so by using `awscli` and also add your session_token: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws configure aws configure set aws_session_token "<your_session_token>" ``` to ensure that the credentials are set up correctly, you can run the following command: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws sts get-caller-identity ``` Supported Embedding modelIDs are: * `amazon.titan-embed-text-v1` * `cohere.embed-english-v3` * `cohere.embed-multilingual-v3` Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | **name** | str | "amazon.titan-embed-text-v1" | The model ID of the bedrock model to use. Supported base models for Text Embeddings: amazon.titan-embed-text-v1, cohere.embed-english-v3, cohere.embed-multilingual-v3 | | **region** | str | "us-east-1" | Optional name of the AWS Region in which the service should be called (e.g., "us-east-1"). | | **profile_name** | str | None | Optional name of the AWS profile to use for calling the Bedrock service. If not specified, the default profile will be used. | | **assumed_role** | str | None | Optional ARN of an AWS IAM role to assume for calling the Bedrock service. If not specified, the current active credentials will be used. | | **role_session_name** | str | "lancedb-embeddings" | Optional name of the AWS IAM role session to use for calling the Bedrock service. If not specified, a "lancedb-embeddings" name will be used. | | **runtime** | bool | True | Optional choice of getting different client to perform operations with the Amazon Bedrock service. | | **max_retries** | int | 7 | Optional number of retries to perform when a request fails. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector model = get_registry().get("bedrock-text").create() class TextModel(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hello world", "goodbye world"]}) db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "bedrock-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(df) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # Cohere Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/cohere Using cohere API requires cohere package, which can be installed using `pip install cohere`. Cohere embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `COHERE_API_KEY` environment variable to use the Cohere API. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export COHERE_API_KEY="your-api-key" ``` Supported models are: * embed-english-v3.0 * embed-multilingual-v3.0 * embed-english-light-v3.0 * embed-multilingual-light-v3.0 The v2.0 models (`embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`) were retired by Cohere on April 4, 2026. Python 0.41.0 defaults to `embed-multilingual-v2.0` (768 dimensions). Python 0.42.0b8 defaults to `embed-multilingual-v3.0` (1024 dimensions). Set `name="embed-multilingual-v3.0"` explicitly, as in the example below, rather than relying on the client default. Existing tables containing vectors from a v2.0 model must be re-embedded with an active model into a table whose vector column has the matching dimension. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | v2.0 in Python 0.41.0; v3.0 in Python 0.42.0b8 | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0 | | `source_input_type` | `str` | `"search_document"` | The type of input data to be used for the source column. | | `query_input_type` | `str` | `"search_query"` | The type of input data to be used for the query. | Cohere supports following input types: | Input type | Description | | - | - | | `search_document` | Used for embeddings stored in a vector database for search use cases. | | `search_query` | Used for embeddings of search queries run against a vector database. | | `semantic_similarity` | Specifies that the text will be used for semantic textual similarity (STS). | | `classification` | Used for embeddings passed through a text classifier. | | `clustering` | Used for embeddings run through a clustering algorithm. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector cohere = ( EmbeddingFunctionRegistry.get_instance() .get("cohere") .create(name="embed-multilingual-v3.0") ) class TextModel(LanceModel): text: str = cohere.SourceField() vector: Vector(cohere.ndims()) = cohere.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cohere-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` # ColPali Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/colpali We support [ColPali](https://github.com/illuin-tech/colpali) model embeddings for multimodal multi-vector retrieval. ColPali produces multiple embedding vectors per input (multi-vector), enabling more nuanced similarity matching between text queries and image documents. Using ColPali requires the colpali-engine package, which can be installed using `pip install colpali-engine`. > [!NOTE] > > ColPali produces **multi-vector** embeddings, meaning each input generates multiple embedding vectors rather than a single vector. Use `MultiVector(func.ndims())` instead of `Vector(func.ndims())` when defining your schema. Supported models are: * Metric-AI/ColQwen2.5-3b-multilingual-v1.0 (default) * vidore/colpali-v1.3 * vidore/colqwen2-v1.0 * vidore/colSmol-256M Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `model_name` | `str` | `"Metric-AI/ColQwen2.5-3b-multilingual-v1.0"` | The name of the model to use. | | `device` | `str` | `"auto"` | The device for inference. Can be `"auto"`, `"cpu"`, `"cuda"`, or `"mps"`. | | `dtype` | `str` | `"bfloat16"` | Data type for model weights (bfloat16, float16, float32, float64). | | `pooling_strategy` | `str` | `"hierarchical"` | Token pooling strategy: `"hierarchical"`, `"lambda"`, or `None`. | | `pool_factor` | `int` | `2` | Factor to reduce sequence length when pooling is enabled. | | `batch_size` | `int` | `2` | Batch size for processing inputs. | | `quantization_config` | `Optional[BitsAndBytesConfig]` | `None` | Quantization configuration for the model (requires bitsandbytes). | This embedding function supports ingesting images as both bytes and URLs. You can query them using text. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, MultiVector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "colpali-demo")) func = get_registry().get("colpali").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: MultiVector(func.ndims()) = func.VectorField() vec_from_bytes: MultiVector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "dog", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` Now we can search using text queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} actual = ( table.search("a furry pet", vector_column_name="vector") .limit(1) .to_pydantic(Images)[0] ) print(actual.label) ``` # Gemini Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/gemini With Google's Gemini, you can represent text (words, sentences, and blocks of text) in a vectorized form, making it easier to compare and contrast embeddings. For example, two texts that share a similar subject matter or sentiment should have similar embeddings, which can be identified through mathematical comparison techniques such as cosine similarity. For more on how and why you should use embeddings, refer to the Embeddings guide. The Gemini Embedding Model API supports various task types: | Task Type | Description | | - | - | | `retrieval_query` | Specifies the given text is a query in a search/retrieval setting. | | `retrieval_document` | Specifies the given text is a document in a search/retrieval setting. Using this task type requires a title but is automatically provided by Embeddings API | | `semantic_similarity` | Specifies the given text will be used for Semantic Textual Similarity (STS). | | `classification` | Specifies that the embeddings will be used for classification. | | `clustering` | Specifies that the embeddings will be used for clustering. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector model = get_registry().get("gemini-text").create() class TextModel(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hello world", "goodbye world"]}) db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "gemini-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(df) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # HuggingFace Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/huggingface We offer support for all HuggingFace models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some HuggingFace models might require custom models defined on the HuggingFace Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Pin `revision` to a commit hash, and note that tables using such a model need it approved with `get_registry().allow_remote_code(...)` when opened in a new process. See [Trusting remote code and custom endpoints](/enterprise/v1-12-0/embedding#trusting-remote-code-and-custom-endpoints). Example usage: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "huggingface-demo")) model = get_registry().get("huggingface").create(name="facebook/bart-base") class Words(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hi hello sayonara", "goodbye world"]}) table = db.create_table("greets", schema=Words) table.add(df) query = "old greeting" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # IBM watsonx Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/ibm Generate text embeddings using IBM's watsonx.ai platform. ## Supported Models You can find a list of supported models at [IBM watsonx.ai Documentation](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx). The currently supported model names are: | Model ID | Dimensions | | - | - | | `ibm/granite-embedding-278m-multilingual` | 768 | | `ibm/slate-125m-english-rtrvr-v2` | 768 | | `ibm/slate-30m-english-rtrvr-v2` | 384 | | `intfloat/multilingual-e5-large` | 1024 | > [!NOTE] > > For new tables, pass `name="ibm/granite-embedding-278m-multilingual"`. The default `name` is still the legacy `ibm/slate-125m-english-rtrvr`, so tables created with it reload with the same model. Legacy and deprecated IDs (such as `ibm/slate-125m-english-rtrvr`, `sentence-transformers/all-minilm-l6-v2` and `sentence-transformers/all-minilm-l12-v2`) still work for tables whose stored metadata references them, but they aren't listed above for new use. ## Parameters The following parameters can be passed to the `create` method: | Parameter | Type | Default Value | Description | | - | - | - | - | | name | str | `"ibm/slate-125m-english-rtrvr"` | The model ID of the watsonx.ai model to use. Pass one of the current supported IDs above (e.g. `"ibm/granite-embedding-278m-multilingual"`) when creating new tables. | | api_key | str | None | Optional IBM Cloud API key (or set `WATSONX_API_KEY`) | | project_id | str | None | Optional watsonx project ID (or set `WATSONX_PROJECT_ID`). Mutually exclusive with `space_id`. | | space_id | str | None | Optional watsonx deployment space ID (or set `WATSONX_SPACE_ID`). Mutually exclusive with `project_id`. | | url | str | None | Optional custom URL for the watsonx.ai instance | | params | dict | None | Optional additional parameters for the embedding model (e.g. `{"truncate_input_tokens": 512}`) | > [!NOTE] > > You must supply exactly one of `project_id` or `space_id` (either as an argument or via its environment variable). Setting both, or neither, raises a `ValueError`. ## Usage Example First, the watsonx.ai library is an optional dependency, so must be installed separately: ``` pip install ibm-watsonx-ai ``` Optionally set environment variables (if not passing credentials to `create` directly): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export WATSONX_API_KEY="YOUR_WATSONX_API_KEY" # Provide exactly one of the following: export WATSONX_PROJECT_ID="YOUR_WATSONX_PROJECT_ID" # export WATSONX_SPACE_ID="YOUR_WATSONX_SPACE_ID" ``` Replace the credential placeholders with your provider credentials. The registry variable keeps the API key out of stored embedding configuration. In application code, load its value from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector registry = EmbeddingFunctionRegistry.get_instance() registry.set_var("watsonx-api-key", "your-api-key") watsonx_embed = registry.get("watsonx").create( name="ibm/slate-125m-english-rtrvr", api_key="$var:watsonx-api-key", project_id="your-project-id", ) class TextModel(LanceModel): text: str = watsonx_embed.SourceField() vector: Vector(watsonx_embed.ndims()) = watsonx_embed.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "watsonx-demo")) tbl = db.create_table("watsonx_test", schema=TextModel, mode="overwrite") tbl.add(data) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # ImageBind Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/imagebind We have support for [imagebind](https://github.com/facebookresearch/ImageBind) model embeddings. You can download our version of the packaged model via - `pip install imagebind-packaged==0.1.2`. This function is registered as `imagebind` and supports Audio, Video and Text modalities(extending to Thermal,Depth,IMU data): | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"imagebind_huge"` | Name of the model. | | `device` | `str` | `"cpu"` | The device to run the model on. Can be `"cpu"` or `"gpu"`. | | `normalize` | `bool` | `False` | set to `True` to normalize your inputs before model ingestion. | Below is an example demonstrating how the API works: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect("/tmp/imagebind-db") func = get_registry().get("imagebind").create() class ImageBindModel(LanceModel): text: str image_uri: str = func.SourceField() audio_path: str vector: Vector(func.ndims()) = func.VectorField() text_list = ["A dog.", "A car", "A bird"] image_paths = [ "./assets/dog_image.jpg", "./assets/car_image.jpg", "./assets/bird_image.jpg", ] audio_paths = [ "./assets/dog_audio.wav", "./assets/car_audio.wav", "./assets/bird_audio.wav", ] inputs = [ {"text": a, "audio_path": b, "image_uri": c} for a, b, c in zip(text_list, audio_paths, image_paths) ] table = db.create_table("img_bind", schema=ImageBindModel) table.add(inputs) ``` Now, we can search using any modality: #### image search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_image = "./assets/dog_image2.jpg" actual = table.search(query_image).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "dog") ``` #### audio search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_audio = "./assets/car_audio2.wav" actual = table.search(query_audio).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "car") ``` #### Text search You can add any input query and fetch the result as follows: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = "an animal which flies and tweets" actual = table.search(query).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "bird") ``` If you have any questions about the embeddings API, supported models, or see a relevant model missing, please raise an issue [on GitHub](https://github.com/lancedb/lancedb/issues). # Instructor Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/instructor [Instructor](https://instructor-embedding.github.io/) is an instruction-finetuned text embedding model that can generate text embeddings tailored to any task (e.g. classification, retrieval, clustering, text evaluation, etc.) and domains (e.g. science, finance, etc.) by simply providing the task instruction, without any finetuning. If you want to calculate customized embeddings for specific sentences, you can follow the unified template to write instructions. > [!NOTE] > > Represent the `domain` `text_type` for `task_objective`: > > * `domain` is optional, and it specifies the domain of the text, e.g. science, finance, medicine, etc. > * `text_type` is required, and it specifies the encoding unit, e.g. sentence, document, paragraph, etc. > * `task_objective` is optional, and it specifies the objective of embedding, e.g. retrieve a document, classify the sentence, etc. More information about the model can be found at the [source URL](https://github.com/xlang-ai/instructor-embedding). | Argument | Type | Default | Description | | - | - | - | - | | `name` | `str` | "hkunlp/instructor-base" | The name of the model to use | | `batch_size` | `int` | `32` | The batch size to use when generating embeddings | | `device` | `str` | `"cpu"` | The device to use when generating embeddings | | `show_progress_bar` | `bool` | `True` | Whether to show a progress bar when generating embeddings | | `normalize_embeddings` | `bool` | `True` | Whether to normalize the embeddings | | `quantize` | `bool` | `False` | Whether to quantize the model | | `source_instruction` | `str` | `"represent the document for retrieval"` | The instruction for the source column | | `query_instruction` | `str` | `"represent the document for retrieving the most similar documents"` | The instruction for the query | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector instructor = ( get_registry() .get("instructor") .create( source_instruction="represent the document for retrieval", query_instruction="represent the document for retrieving the most similar documents", ) ) class Schema(LanceModel): vector: Vector(instructor.ndims()) = instructor.VectorField() text: str = instructor.SourceField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "instructor-demo")) tbl = db.create_table("test", schema=Schema, mode="overwrite") texts = [ { "text": "Capitalism has been dominant in the Western world since the end of feudalism." }, { "text": "The disparate impact theory is especially controversial under the Fair Housing Act." }, { "text": "Disparate impact in United States labor law refers to practices in employment." }, ] tbl.add(texts) ``` # Jina Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/jina ## Text Embedding Models Jina embeddings are used to generate embeddings for text and image data. You also need to set the `JINA_API_KEY` environment variable to use the Jina API. You can find a list of supported models under [https://jina.ai/embeddings/](https://jina.ai/embeddings/) Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"jina-clip-v1"` | The model ID of the jina model to use | Usage Example: Replace `your-api-key` with your Jina API key. This provider reads it from `JINA_API_KEY`; the example sets it explicitly. In application code, supply it through your environment or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector os.environ["JINA_API_KEY"] = "your-api-key" jina_embed = ( EmbeddingFunctionRegistry.get_instance() .get("jina") .create(name="jina-embeddings-v2-base-en") ) class TextModel(LanceModel): text: str = jina_embed.SourceField() vector: Vector(jina_embed.ndims()) = jina_embed.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-text")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` ## Multimodal Embedding Models Jina embeddings can also be used to embed both text and image data, only some of the models support image data and you can check the list under [https://jina.ai/embeddings/](https://jina.ai/embeddings/) Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"jina-clip-v1"` | The model ID of the jina model to use | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector os.environ["JINA_API_KEY"] = "your-api-key" db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-images")) func = get_registry().get("jina").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() vec_from_bytes: Vector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "cat", "dog", "dog", "horse", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", "http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` # NVIDIA Nemotron Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/nvidia Text embeddings with Nemotron 3.5 Embed 1B and 8B in the Python SDK. > [!NOTE] > > This integration uses Python 0.42.0b8 and is not available in Python 0.41.0. > Install the [documented preview client](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions) > before following these examples, including the local Embedded example. The Python SDK registers `nvidia` for client-side text embedding with NVIDIA-hosted and self-hosted NIM endpoints. Documents use `input_type="passage"`; searches use `input_type="query"`. This provider supports text only, with floating-point output. Null and empty text values get a null vector without a request; pass `on_bad_vectors="null"` or `"drop"` to `add` to keep or skip those rows. Image and combined text/image inputs are not supported by this integration. Install the optional client and set your NVIDIA API key: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install openai export NVIDIA_API_KEY="your-api-key" ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector func = get_registry().get("nvidia").create( name="nvidia/nemotron-3.5-embed-1b", ) class Document(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() db = lancedb.connect("./nemotron-db") table = db.create_table("documents", schema=Document) table.add([{"text": "Paris is the capital of France."}]) results = table.search("What is the capital of France?").limit(3).to_list() ``` For a LanceDB Enterprise table, connect as usual, for example `lancedb.connect("db://my-database", api_key=..., region=...)`. The same schema, `add`, and `search` calls compute embeddings in the Python client. The NVIDIA key is separate from the LanceDB database key. Use a fresh table name when creating a table; reopening an existing table restores its embedding configuration. ## Models and configuration The hosted API documents these exact IDs and dimensions: | Model ID | Default dimensions | Supported `dim` | | - | -: | -: | | `nvidia/nemotron-3.5-embed-1b` | 2048 | 128–2048 | | `nvidia/nemotron-3.5-embed-8b` | 4096 | 1–4096 | | Parameter | Default | Description | | - | - | - | | `name` | `nvidia/nemotron-3.5-embed-1b` | Model ID sent to the endpoint. | | `dim` | Model default above | Output dimensions; required for other served model IDs. | | `base_url` | `https://integrate.api.nvidia.com/v1` | API base including `/v1`. | | `api_key` | `NVIDIA_API_KEY` for the hosted API | Alternatively, a registry reference such as `$var:nvidia-key`. | | `batch_size` | `32` | Maximum inputs per request. Reduce for your deployment's limits. | | `truncate` | `END` | Truncate overlong text at the end, or use `NONE` to reject it. | | `max_retries` | `7` | LanceDB's retry policy, applied to each request during automatic document/query embedding. | Requests specify `modality="text"` and `encoding_format="float"`. Returned vectors are checked for count, input indices, dimensions, and finite numeric values. The hosted input limit is 10,240 tokens per item; self-hosted limits depend on the served profile. This provider batches by item count, not token count. ## Self-hosted NIM Set `name` to the exact ID returned by your deployment's `GET /v1/models` and `dim` to an output dimension that deployment supports: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} func = get_registry().get("nvidia").create( name="nvidia/Nemotron-3.5-Embed-1B-BF16", base_url="http://localhost:8000/v1", dim=2048, ) ``` ### Authenticated endpoints Custom endpoints may run without a key. `NVIDIA_API_KEY` is only sent to the hosted API, so for authenticated endpoints use `get_registry().set_var("nvidia-key", key)` with `api_key="$var:nvidia-key"`. Registry references, rather than secret values, are stored in the schema. Restore registry variables in each process. Before using a custom endpoint restored from table metadata in a new process, call `get_registry().allow_endpoint("http://localhost:8000/v1")`. ### Output dimensions The NIM 2.4 support matrix lists `nvidia/Nemotron-3.5-Embed-8B-BF16` at 2048 dimensions, whereas the hosted 8B reference specifies 4096. For self-hosted model IDs, this provider requires an explicit `dim` and checks the response instead of assuming the hosted defaults. ## SDK support The NVIDIA provider is available in the Python SDK only. TypeScript, Rust and Java don't have an NVIDIA embedding provider. ## References NVIDIA documentation: [hosted 1B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-1b-infer), [hosted 8B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-8b-infer), [NIM request/response format](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/use-the-api-openai.html), [NIM support matrix](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/support-matrix.html). # Ollama Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/ollama Generate embeddings via the [ollama](https://github.com/ollama/ollama-python) python library. More details: * [Ollama docs on embeddings](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-embeddings) * [Ollama blog on embeddings](https://ollama.com/blog/embedding-models) For direct calls, `compute_source_embeddings` accepts a list of strings or a one-dimensional NumPy string array. Both inputs are sent to Ollama in one batch. | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `nomic-embed-text` | The name of the model. | | `host` | `str` | `http://localhost:11434` | The Ollama host to connect to. | | `options` | `ollama.Options` or `dict` | `None` | Additional model parameters listed in the documentation for the Modelfile such as `temperature`. | | `keep_alive` | `float` or `str` | `"5m"` | Controls how long the model will stay loaded into memory following the request. | | `ollama_client_kwargs` | `dict` | `{}` | kwargs that can be past to the `ollama.Client`. | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "ollama-demo")) func = get_registry().get("ollama").create(name="nomic-embed-text") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add( [ {"text": "hello world"}, {"text": "goodbye world"}, ] ) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # OpenAI Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/openai LanceDB registers the OpenAI embeddings function in the registry by default, as `openai`. Below are the parameters that you can customize when creating the instances: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"text-embedding-ada-002"` | The name of the model. | | `dim` | `int` | Model default | Requested output dimensions for models that support shortening embeddings. Required for model names other than the OpenAI ones listed by `model_names()` (for example a model served behind an OpenAI-compatible `base_url`), where it is the model's embedding dimension. Use `func.ndims()` when defining the vector field. | | `use_azure` | bool | `False` | Set true to use Azure OpenAI SDK | Python 0.41.0 accepts only the model names returned by `model_names()`; setting `dim` does not enable an arbitrary model name in that version. Custom OpenAI-compatible model names with an explicit `dim` require the [0.42.0b8 client](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). Set your OpenAI API key before running the example: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export OPENAI_API_KEY="your-api-key" ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db_path = Path(tempfile.mkdtemp()) / "openai-embeddings" db = lancedb.connect(str(db_path)) func = get_registry().get("openai").create(name="text-embedding-ada-002") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add( [ {"text": "hello world"}, {"text": "goodbye world"}, ] ) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # OpenCLIP Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/openclip We support CLIP model embeddings using the open source alternative, [open-clip](https://github.com/mlfoundations/open_clip) which supports various customizations. It is registered as `open-clip` and supports the following customizations: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"ViT-B-32"` | The name of the model. | | `pretrained` | `str` | `"laion2b_s34b_b79k"` | The name of the pretrained model to load. | | `device` | `str` | `"cpu"` | The device to run the model on. Can be `"cpu"` or `"gpu"`. | | `batch_size` | `int` | `64` | The number of images to process in a batch. | | `normalize` | `bool` | `True` | Whether to normalize the input images before feeding them to the model. | This embedding function supports ingesting images as both bytes and urls. You can query them using both text and other images. > [!NOTE] > > LanceDB supports ingesting images directly from accessible links. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "openclip-demo")) func = get_registry().get("open-clip").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() vec_from_bytes: Vector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "cat", "dog", "dog", "horse", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", "http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` Now we can search using text from both the default vector column and the custom vector column ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} actual = table.search("man's best friend").limit(1).to_pydantic(Images)[0] print(actual.label) frombytes = ( table.search("man's best friend", vector_column_name="vec_from_bytes") .limit(1) .to_pydantic(Images)[0] ) print(frombytes.label) ``` Because we're using a multimodal embedding function, we can also search using images ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from PIL import Image query_image_uri = "http://farm1.staticflickr.com/200/467715466_ed4a31801f_z.jpg" image_bytes = requests.get(query_image_uri).content query_image = Image.open(io.BytesIO(image_bytes)) actual = table.search(query_image).limit(1).to_pydantic(Images)[0] print(actual.label == "dog") other = ( table.search(query_image, vector_column_name="vec_from_bytes") .limit(1) .to_pydantic(Images)[0] ) print(other.label) ``` # Sentence Transformers Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/sentence-transformers Allows you to set parameters when registering a `sentence-transformers` object. > [!NOTE] > > Sentence transformer embeddings are normalized by default. It is recommended to use normalized embeddings for similarity search. > [!WARNING] > > Setting `trust_remote_code=True` allows the model to execute arbitrary code from its HuggingFace repository during loading. Only enable it for repositories you trust, and pin `revision` to a commit hash. When a table using such a model is opened in a new process, the model must be approved with `get_registry().allow_remote_code(...)`. See [Trusting remote code and custom endpoints](/enterprise/v1-12-0/embedding#trusting-remote-code-and-custom-endpoints). | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `all-MiniLM-L6-v2` | The name of the model | | `device` | `str` | `cpu` | The device to run the model on (can be `cpu` or `gpu`) | | `normalize` | `bool` | `True` | Whether to normalize the input text before feeding it to the model | | `trust_remote_code` | `bool` | `False` | Whether to trust and execute remote code from the model's HuggingFace repository | | `revision` | `str` | `None` | The model revision to load, such as a commit hash | **Check out available sentence-transformer models here!** ```markdown theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} - sentence-transformers/all-MiniLM-L12-v2 - sentence-transformers/paraphrase-mpnet-base-v2 - sentence-transformers/gtr-t5-base - sentence-transformers/LaBSE - sentence-transformers/all-MiniLM-L6-v2 - sentence-transformers/bert-base-nli-max-tokens - sentence-transformers/bert-base-nli-mean-tokens - sentence-transformers/bert-base-nli-stsb-mean-tokens - sentence-transformers/bert-base-wikipedia-sections-mean-tokens - sentence-transformers/bert-large-nli-cls-token - sentence-transformers/bert-large-nli-max-tokens - sentence-transformers/bert-large-nli-mean-tokens - sentence-transformers/bert-large-nli-stsb-mean-tokens - sentence-transformers/distilbert-base-nli-max-tokens - sentence-transformers/distilbert-base-nli-mean-tokens - sentence-transformers/distilbert-base-nli-stsb-mean-tokens - sentence-transformers/distilroberta-base-msmarco-v1 - sentence-transformers/distilroberta-base-msmarco-v2 - sentence-transformers/nli-bert-base-cls-pooling - sentence-transformers/nli-bert-base-max-pooling - sentence-transformers/nli-bert-base - sentence-transformers/nli-bert-large-cls-pooling - sentence-transformers/nli-bert-large-max-pooling - sentence-transformers/nli-bert-large - sentence-transformers/nli-distilbert-base-max-pooling - sentence-transformers/nli-distilbert-base - sentence-transformers/nli-roberta-base - sentence-transformers/nli-roberta-large - sentence-transformers/roberta-base-nli-mean-tokens - sentence-transformers/roberta-base-nli-stsb-mean-tokens - sentence-transformers/roberta-large-nli-mean-tokens - sentence-transformers/roberta-large-nli-stsb-mean-tokens - sentence-transformers/stsb-bert-base - sentence-transformers/stsb-bert-large - sentence-transformers/stsb-distilbert-base - sentence-transformers/stsb-roberta-base - sentence-transformers/stsb-roberta-large - sentence-transformers/xlm-r-100langs-bert-base-nli-mean-tokens - sentence-transformers/xlm-r-100langs-bert-base-nli-stsb-mean-tokens - sentence-transformers/xlm-r-base-en-ko-nli-ststb - sentence-transformers/xlm-r-bert-base-nli-mean-tokens - sentence-transformers/xlm-r-bert-base-nli-stsb-mean-tokens - sentence-transformers/xlm-r-large-en-ko-nli-ststb - sentence-transformers/bert-base-nli-cls-token - sentence-transformers/all-distilroberta-v1 - sentence-transformers/multi-qa-MiniLM-L6-dot-v1 - sentence-transformers/multi-qa-distilbert-cos-v1 - sentence-transformers/multi-qa-distilbert-dot-v1 - sentence-transformers/multi-qa-mpnet-base-cos-v1 - sentence-transformers/multi-qa-mpnet-base-dot-v1 - sentence-transformers/nli-distilroberta-base-v2 - sentence-transformers/all-MiniLM-L6-v1 - sentence-transformers/all-mpnet-base-v1 - sentence-transformers/all-mpnet-base-v2 - sentence-transformers/all-roberta-large-v1 - sentence-transformers/allenai-specter - sentence-transformers/average_word_embeddings_glove.6B.300d - sentence-transformers/average_word_embeddings_glove.840B.300d - sentence-transformers/average_word_embeddings_komninos - sentence-transformers/average_word_embeddings_levy_dependency - sentence-transformers/clip-ViT-B-32-multilingual-v1 - sentence-transformers/clip-ViT-B-32 - sentence-transformers/distilbert-base-nli-stsb-quora-ranking - sentence-transformers/distilbert-multilingual-nli-stsb-quora-ranking - sentence-transformers/distilroberta-base-paraphrase-v1 - sentence-transformers/distiluse-base-multilingual-cased-v1 - sentence-transformers/distiluse-base-multilingual-cased-v2 - sentence-transformers/distiluse-base-multilingual-cased - sentence-transformers/facebook-dpr-ctx_encoder-multiset-base - sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base - sentence-transformers/facebook-dpr-question_encoder-multiset-base - sentence-transformers/facebook-dpr-question_encoder-single-nq-base - sentence-transformers/gtr-t5-large - sentence-transformers/gtr-t5-xl - sentence-transformers/gtr-t5-xxl - sentence-transformers/msmarco-MiniLM-L-12-v3 - sentence-transformers/msmarco-MiniLM-L-6-v3 - sentence-transformers/msmarco-MiniLM-L12-cos-v5 - sentence-transformers/msmarco-MiniLM-L6-cos-v5 - sentence-transformers/msmarco-bert-base-dot-v5 - sentence-transformers/msmarco-bert-co-condensor - sentence-transformers/msmarco-distilbert-base-dot-prod-v3 - sentence-transformers/msmarco-distilbert-base-tas-b - sentence-transformers/msmarco-distilbert-base-v2 - sentence-transformers/msmarco-distilbert-base-v3 - sentence-transformers/msmarco-distilbert-base-v4 - sentence-transformers/msmarco-distilbert-cos-v5 - sentence-transformers/msmarco-distilbert-dot-v5 - sentence-transformers/msmarco-distilbert-multilingual-en-de-v2-tmp-lng-aligned - sentence-transformers/msmarco-distilbert-multilingual-en-de-v2-tmp-trained-scratch - sentence-transformers/msmarco-distilroberta-base-v2 - sentence-transformers/msmarco-roberta-base-ance-firstp - sentence-transformers/msmarco-roberta-base-v2 - sentence-transformers/msmarco-roberta-base-v3 - sentence-transformers/multi-qa-MiniLM-L6-cos-v1 - sentence-transformers/nli-mpnet-base-v2 - sentence-transformers/nli-roberta-base-v2 - sentence-transformers/nq-distilbert-base-v1 - sentence-transformers/paraphrase-MiniLM-L12-v2 - sentence-transformers/paraphrase-MiniLM-L3-v2 - sentence-transformers/paraphrase-MiniLM-L6-v2 - sentence-transformers/paraphrase-TinyBERT-L6-v2 - sentence-transformers/paraphrase-albert-base-v2 - sentence-transformers/paraphrase-albert-small-v2 - sentence-transformers/paraphrase-distilroberta-base-v1 - sentence-transformers/paraphrase-distilroberta-base-v2 - sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 - sentence-transformers/paraphrase-multilingual-mpnet-base-v2 - sentence-transformers/paraphrase-xlm-r-multilingual-v1 - sentence-transformers/quora-distilbert-base - sentence-transformers/quora-distilbert-multilingual - sentence-transformers/sentence-t5-base - sentence-transformers/sentence-t5-large - sentence-transformers/sentence-t5-xxl - sentence-transformers/sentence-t5-xl - sentence-transformers/stsb-distilroberta-base-v2 - sentence-transformers/stsb-mpnet-base-v2 - sentence-transformers/stsb-roberta-base-v2 - sentence-transformers/stsb-xlm-r-multilingual - sentence-transformers/xlm-r-distilroberta-base-paraphrase-v1 - sentence-transformers/clip-ViT-L-14 - sentence-transformers/clip-ViT-B-16 - sentence-transformers/use-cmlm-multilingual - sentence-transformers/all-MiniLM-L12-v1 ``` > [!NOTE] > > You can also load many other model architectures from the library. For example models from sources such as BAAI, Nomic, Salesforce Research, etc. See this HF hub page for all [supported models](https://huggingface.co/models?library=sentence-transformers). > [!NOTE] > > Here is an example that uses the BAAI embedding model from the HuggingFace Hub [supported models](https://huggingface.co/models?library=sentence-transformers). > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "sentence-transformers")) > model = ( > get_registry() > .get("sentence-transformers") > .create(name="BAAI/bge-small-en-v1.5", device="cpu") > ) > > class Words(LanceModel): > text: str = model.SourceField() > vector: Vector(model.ndims()) = model.VectorField() > > table = db.create_table("words", schema=Words) > table.add( > [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > ) > > query = "greetings" > actual = table.search(query).limit(1).to_pydantic(Words)[0] > print(actual.text) > ``` Visit the sentence-transformers [HuggingFace Hub](https://huggingface.co/sentence-transformers) page for more information on the available models. # Integrations Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/index Connect LanceDB with popular AI providers, frameworks, and data platforms LanceDB seamlessly plugs into the rest of your AI and data engineering stack. Use the sections below to jump straight into the guides that matter for your workflow. | Group | Description | | :- | :- | | [Embedding models](/enterprise/v1-12-0/integrations/embedding/) | Connect with popular embedding model providers including OpenAI, Cohere, HuggingFace, and more | | [Reranking models](/enterprise/v1-12-0/integrations/reranking/) | Enhance search results with advanced reranking models and techniques | | [AI platforms & frameworks](/enterprise/v1-12-0/integrations/ai/) | Integrate with LangChain, LlamaIndex, Kiln, and other AI development frameworks | | [Data platforms & frameworks](/enterprise/v1-12-0/integrations/data/) | Integrate LanceDB with popular data tools and platforms like DuckDB, Pydantic and dlt | # Garbage Collection Source: https://docs.lancedb.com/enterprise/v1-12-0/maintenance/cleanup Pruning old versions and the files only they referenced. **Applies to:** Embedded ✅, Enterprise ✅ Every write keeps the version before it, which is what makes [time travel](/enterprise/v1-12-0/management/table#versioning) possible. Cleanup is what ends that: pruning versions older than a retention window, and the files that only those versions referenced. > [!NOTE] > > **Enterprise job type:** `cleanup`. Distinct from `compact`: compaction > merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call; > Enterprise schedules them as separate jobs, and runs cleanup only when the > deployment's configuration enables it. ## Retention ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta table.optimize(cleanup_older_than=timedelta(days=30)) ``` `cleanup_older_than` defaults to **7 days**. Versions older than that are removed, along with the files only they referenced. In LanceDB Enterprise, the retention period comes from its configuration instead. The latest version is never removed, whatever you pass. `timedelta(0)` makes every older version eligible for removal, but cleanup still keeps tagged versions, as the warning below describes. > [!WARNING] > > Pruning is what makes [time travel](/enterprise/v1-12-0/management/table#versioning) finite: an > eligible version outside the retention window is gone. Cleanup keeps a version, > whatever its age, when it is: > > * the **latest** version; > * a **tagged** version. > > To keep a version recoverable, tag it, subject to the policy below, or keep > the window wide enough to cover it. > > Under the default policy, a tag can also stop cleanup. When a tagged version is > older than the window and is not the latest, cleanup refuses to run: it raises > an error naming the tag and prunes nothing. To let it proceed, move the tag to a > version inside the window, delete the tag, or widen the window. > > A tag on the latest version does not stop cleanup. But `optimize()` compacts > before it prunes, and compacting commits a new version whenever it merges > files, so a tag on what was the latest version can become an older one by the > time cleanup runs. `optimize()` then raises after compacting, and its index > update does not run. > > Enterprise background cleanup keeps tagged snapshots while pruning unrelated > expired versions. If you rely on reading untagged old versions, set the window > to cover the range you > need before running this, not after. ## Managed blob objects [Managed blobs](/enterprise/v1-12-0/management/table#managed-blobs) store out-of-line payloads under the table's `_blobs/` directory. Cleanup follows the references from retained snapshots, including protected tags, before selecting objects for deletion. Replacing a blob or deleting a row makes its old payload eligible only after no retained snapshot references it. Cleanup removes whole objects. If a packed object contains several blobs, it remains while any of them is live. Compaction preserves Managed payload objects rather than copying their bytes, so compaction alone does not reclaim the unused portion of a packed object. Use table maintenance to remove Managed objects; deleting `_blobs/` files directly can corrupt current or historical snapshots. Upgrade all clients and maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. Enterprise runs these as background jobs; Python tables connected to Enterprise do not support `optimize()`. See [Intelligent Auto-Maintenance](/enterprise/v1-12-0/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path. ## Disk usage does not drop immediately Compaction writes new, merged files before the old ones are removed, so disk usage can rise before it falls. Space is reclaimed only when cleanup prunes the versions that referenced the superseded files. If you need to reclaim space aggressively in the embedded library, shorten the retention window rather than waiting for the default: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize(cleanup_older_than=timedelta(days=1)) ``` ## Files from failed transactions A write that fails partway can leave files that look like an operation still in progress. Cleanup will not remove them until they are at least seven days old, because it cannot tell them apart from a live write. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize(delete_unverified=True) ``` This option belongs to `optimize()` in the embedded library. A deployment's cleanup jobs never set it. > [!WARNING] > > `delete_unverified=True` removes them regardless of age. Only set it when you > can guarantee **no other process is writing to the table**. Otherwise it can > delete files belonging to a write that is genuinely in progress, and corrupt > the table. ## What to read next > [card] [Compaction](/enterprise/v1-12-0/maintenance/compaction) > > Merging small files, the other half of `optimize()`. > [card] [Intelligent Auto-Maintenance](/enterprise/v1-12-0/enterprise/intelligent-auto-maintenance#cleanup) > > How Enterprise decides to run cleanup without a call from you. # Compaction and cleanup Source: https://docs.lancedb.com/enterprise/v1-12-0/maintenance/compaction Merge small files, prune old versions, and fold new rows into existing indexes. **Applies to:** Embedded ✅, Enterprise ✅ 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; a deployment handles them in the background and does not support `optimize()`. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. ## Optimize a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize() ``` Three operations, in one call: | | | | - | - | | **Compaction** | merges small files into larger ones | | **Prune** | removes versions older than the retention window (see [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup)) | | **Index** | folds newly added rows into existing indexes (see [Incremental Indexing](/enterprise/v1-12-0/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`](/enterprise/v1-12-0/maintenance/cleanup). The two are distinct jobs > even though `optimize()` bundles both in one LanceDB Embedded call. ## 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: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import IvfFlat table.create_index( "vector", config=IvfFlat(distance_type="l2", num_partitions=4), replace=True, ) ``` 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. > [!NOTE] > > Compaction rewrites files, which conflicts with a concurrent > [computed-column refresh](/enterprise/v1-12-0/feature-engineering/add-computed-column) or > [view refresh](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) planned against the > version it replaces. Sequence them rather than running both at once. See [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup) for pruning old versions, and [Incremental Indexing](/enterprise/v1-12-0/indexing/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: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta table.optimize() # 7-day default retention table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner ``` The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/enterprise/v1-12-0/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. # Catalog Source: https://docs.lancedb.com/enterprise/v1-12-0/management/catalog The unnamed root of an Enterprise deployment: initial access, the superuser bootstrap, and where privileges apply. **Applies to:** Embedded ❌, Enterprise ✅ The catalog is the unnamed root of one Enterprise deployment, identified by its endpoint rather than a name -- see [Catalog Hierarchy](/enterprise/v1-12-0/basics/catalog#hierarchy) for how it relates to the databases, namespaces and tables beneath it, and [Connecting to Catalog](/enterprise/v1-12-0/basics/catalog#connecting-to-catalog) for `connect_catalog(endpoint)` itself. This page covers what it takes to reach a brand new deployment for the first time. ## Initial access A newly deployed catalog has no databases and no grants: nobody yet holds `CREATE_DATABASE` or any other system-level privilege, so there is nothing for an ordinary principal to do with a catalog connection. Database administration starts from a **superuser**. ## Superuser A superuser is an identity your deployment operator configures outside the normal grant system, not a role anyone can be granted. It bypasses privilege checks entirely, on every object, rather than holding specific privileges -- the same way `OWNERSHIP` on an object grants full authority over that one object, a superuser has it over the whole deployment. This is what makes a brand new deployment usable. Creating a database or namespace can fall back to a system or parent-namespace privilege when the object has no owner yet -- see [Creating an object you don't own yet](/enterprise/v1-12-0/governance/privileges#creation) -- but a system-level privilege itself has no such fallback, so a superuser signs in first and grants `CREATE_DATABASE`, `OPERATE`, or other system privileges to real principals and roles. Day-to-day administration then runs through those grants, the same as any other object; reach for the superuser identity to recover access or bootstrap a new deployment, not as a standing way to work. ## Privileges The catalog connection itself is gated by privileges on the `system` object: `CREATE_DATABASE` to create one, `OPERATE` to manage jobs, caches, server configuration and role membership, and `USAGE` to list jobs and look up other identities. See [Privileges](/enterprise/v1-12-0/governance/privileges) for the full table and how a grant is addressed, and [Principals](/enterprise/v1-12-0/governance/principals) for who a grant can name. ## What to read next > [card] [Catalog Hierarchy](/enterprise/v1-12-0/basics/catalog#hierarchy) > > How the catalog relates to databases, namespaces and tables. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > Every privilege, and the grant and revoke syntax that covers each one. > [card] [Database](/enterprise/v1-12-0/management/database) > > Create and manage a database once you can reach the catalog. # Database Source: https://docs.lancedb.com/enterprise/v1-12-0/management/database Connect to LanceDB and configure storage, credentials and read consistency. **Applies to:** Embedded ✅, Enterprise ✅ A database connection provides access to tables and namespaces in a [catalog](/enterprise/v1-12-0/basics/catalog). Use it to create and open tables, list catalog objects, and configure how your application reaches the data. ## Connection URIs | URI | Offering | Where queries run | | - | - | - | | `./.lancedb` | LanceDB Embedded, with local storage | In your application | | `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | LanceDB Embedded, with object storage | In your application | | `db://my-database` | LanceDB Enterprise | On the Enterprise service | [Connect to LanceDB](/enterprise/v1-12-0/basics/catalog) has examples for each connection type. A connection to object storage still uses the embedded library: your process reads and writes the bucket directly. Enterprise runs operations remotely and manages the supporting compute and maintenance. ## Connect to Enterprise Replace the placeholders with the database URI, key, region and endpoint provided by your administrator. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` | Python option | TypeScript option | Purpose | | - | - | - | | `api_key` | `apiKey` | Authenticate the connection | | `region` | `region` | Select the database's region | | `host_override` | `hostOverride` | Set the Enterprise endpoint | | `client_config` | `clientConfig` | Configure retries, timeouts and connection pooling. A retry can [repeat an append](/enterprise/v1-12-0/ingestion/insert#performance). | Use your deployment's region rather than relying on the `us-east-1` default. For application code, load credentials from environment variables or a secrets manager. See [Authentication](/enterprise/v1-12-0/enterprise/authentication) for OAuth and [SQL](/enterprise/v1-12-0/basics/sql) for the separate SQL connection settings. ## Storage options For LanceDB Embedded tables in object storage, `storage_options` configures credentials, endpoints and options for new tables. This example enables stable row IDs for tables created through the connection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect( "s3://bucket/path", storage_options={"new_table_enable_stable_row_ids": "true"}, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("s3://bucket/path", { storageOptions: { new_table_enable_stable_row_ids: "true" }, }); ``` Set stable row IDs before creating a table that needs them, such as an ordinary materialized-view source in Python SDK 0.40.0. The option does not change tables that already exist. Enterprise storage settings are managed on the server. See [Object storage](/enterprise/v1-12-0/basics/catalog#object-storage) for provider credentials and other options. ## Read consistency For LanceDB Embedded connections, `read_consistency_interval` controls how often reads check for table versions committed by other writers. For example, check at most once every five seconds: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta db = lancedb.connect( "./.lancedb", read_consistency_interval=timedelta(seconds=5) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("./.lancedb", { readConsistencyInterval: 5 }); ``` By default, an Embedded table handle does not automatically pick up another process's writes. Reopen the table, check out its latest version, or configure a consistency interval when you need those updates. A zero interval checks on every read, with the cost of a metadata check. Enterprise manages read freshness on the server. See [Consistency](/enterprise/v1-12-0/tables/consistency) for its behavior and the distinction between seeing your own writes and seeing another client's writes. ## Database operations The connection provides methods to create, open, list and drop tables. | Operation | Python | TypeScript | | - | - | - | | Create a table | `create_table` | `createTable` | | Open a table | `open_table` | `openTable` | | List tables | `table_names`, `list_tables` | `tableNames`, `listTables` | | Drop a table | `drop_table` | `dropTable` | Use the namespace and pagination options documented in [Namespaces](/enterprise/v1-12-0/management/namespace) when working outside the root namespace or listing a large catalog. [Tables](/enterprise/v1-12-0/management/table) covers table schemas, versions and lifecycle operations. > [!WARNING] > > Dropping a table removes its history as well as its current data. You cannot > recover a dropped table through table versioning. The LanceDB Embedded `drop_database()` > and `drop_all_tables()` operations remove all tables without a confirmation prompt. ## Async connections Python's `connect_async` returns an `AsyncConnection`. Await its operations when working in an asynchronous application: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = await lancedb.connect_async("./.lancedb") table = await db.open_table("documents") ``` TypeScript's connection and table operations already return promises. An async connection and a background job serve different purposes. Async APIs let other tasks run while your application waits for an operation. A [job](/enterprise/v1-12-0/basics/jobs) represents work that can continue on the server after the submission call returns. ## Privileges A database's `OWNERSHIP`, `USAGE` and `CREATE_NAMESPACE` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers ``` See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Functions Source: https://docs.lancedb.com/enterprise/v1-12-0/management/function Register a Python function once and apply it as a column, for work SQL cannot express. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/enterprise/v1-12-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Early access Some columns cannot be written as a SQL expression: an embedding, a model call, an image decode. A function is a Python callable registered with the database, versioned, and then applied as a column. The code runs where the data is rather than pulling rows to your process. Registering and running a function needs a LanceDB Enterprise deployment with Functions enabled, which they are not by default. On a LanceDB Embedded connection `create_function` raises `NotImplementedError`. With published Embedded packages, compute derived values in your application and write them to the table. SQL computed-column declaration and refresh require an experimental source build. > [!NOTE] > > In SQL, a function is registered with [`CREATE FUNCTION`](/enterprise/v1-12-0/sql/ddl/function#create) and listed with [`SHOW FUNCTIONS`](/enterprise/v1-12-0/sql/ddl/function#show). Functions are the way to fill columns with Python in LanceDB Enterprise. If you already use [Geneva](/enterprise/v1-12-0/geneva), it remains available; see the Geneva docs for how its concepts map onto these. The steps below take a column of numbers to a filled column of their doubles. ## Define a function `@function` packages a scalar Python callable. Input and output types are inferred from annotations, so `double` takes one non-nullable `float64` parameter, `value`, and returns a non-nullable `float64`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import function @function def double(value: float) -> float: return value * 2 ``` The decorated object stays callable. Calling it runs the original function in your process, without the database, so unit tests stay ordinary tests: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(double(1.5)) # 3.0 ``` Where annotations cannot express the Arrow type precisely, pass `input_schema` and `output_schema` together: one without the other is rejected. A scalar output must be non-nullable, because a physical NULL is what marks a computed-column row as unfilled. A named-struct output may declare nullable fields: whether a row has a result at all is the struct's own validity, which Enterprise keeps in a separate internal column when it expands the result into sibling columns, so a null field is a value rather than a missing row. ## Connect and create a table The remaining steps run against your Enterprise deployment. Replace the database URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` For an ordinary stored input column, the Arrow type must match the parameter. A nullable column requires a nullable parameter, such as `Optional[float]`; a non-nullable column can bind to either. This example uses `value: float`, so the table declares `value` non-nullable. Computed-column inputs depend on the Enterprise server version. Where supported, they bind to non-nullable parameters even though the physical column is nullable: refresh skips rows whose computed input is still null. Check your deployment's support before using another computed column as an input. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema([pa.field("value", pa.float64(), nullable=False)]) table = db.create_table( "function_demo", [{"value": 1.0}, {"value": 2.0}, {"value": 3.0}], schema=schema, ) ``` ## Register it Registration returns a query-backed job; the immutable version exists once the SQL command finishes and the job succeeds. Its `job_type` is `query`, and its single `id` is the SQL query UUID. Repeated waits reuse the completed result. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.create_function_async(double) version = job.wait() ``` `create_function` is the blocking equivalent. A registered version is fetched with `db.get_function(name, version="1")`. Python 0.42.0b8 requires a string version. Enterprise 1.12.0 requires an explicit version; select one from `list_functions()` before fetching it. > [!NOTE] > > The SQL command submits an internal `create_function` image-build job and > waits for publication. The SDK returns the SQL query handle. Query handles > have no registry history and cannot be reopened with `open_job()`. ## List and describe `list_functions` pages through every published version in a namespace, ordered by name then version. Python 0.42.0b8's `get_function` takes a string version. Enterprise 1.12.0 does not resolve an omitted version. Both take `namespace_path`, defaulting to the root namespace, the same as `create_function`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for version in db.list_functions(): print(version.name, version.version, version.created_at_millis) version = db.get_function("double", version="1") ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; # async fn list_and_get(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> { let mut versions = connection.list_functions(&[], Default::default()); while let Some(version) = versions.try_next().await? { println!("{} {} {}", version.name(), version.version(), version.created_at_millis()); } let version = connection.get_function("double", "1", &[]).await?; # Ok(()) # } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW FUNCTIONS SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) DESCRIBE FUNCTION double WITH (version = '1') ``` `list_functions` returns a lazy iterator: `page_limit` bounds each request, not the total, and `page_token` resumes from a saved token. Child namespaces are not included; list each namespace separately. A version's `created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are all readable this way without applying or calling the function. ## Try it in SQL A registered function is callable in SQL by its name, the same as any other scalar function. Before applying it as a column, call it directly over the table to check the registration succeeded, without committing a schema change: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query("SELECT value, double(value) AS doubled FROM function_demo") print(reader.read_all().to_pylist()) # [{'value': 1.0, 'doubled': 2.0}, {'value': 2.0, 'doubled': 4.0}, {'value': 3.0, 'doubled': 6.0}] ``` > [!NOTE] > > Equivalent SQL: `SELECT value, double(value) AS doubled FROM function_demo`. > See [Querying with SQL](/enterprise/v1-12-0/basics/sql) for `execute_query` and other languages. ## Apply it as a column Calling the registered version binds each parameter, by name, to a column with `col(...)`. `add_columns` declares the result as a new column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col table.add_columns({"doubled": version(value=col("value"))}) ``` The column is declared empty; the function has not run yet. A mapping with one function application keeps its scalar or named-struct result in the named column. A bare named-struct application expands its result fields as one atomic binding, with aliases from `rename(columns=...)`. ### Bind more than one input, or fill more than one column Parameters bind by name, so a function that takes several arguments binds several columns in one call. `ratio` divides two existing columns, so give the table a second one first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns({"count": "value + 1"}) @function def ratio(numerator: float, denominator: float) -> float: return numerator / denominator version = db.create_function_async(ratio).wait() table.add_columns({"ratio": version(numerator=col("value"), denominator=col("count"))}) ``` A named-struct output fills more than one column from a single application. Declare the fields with `output_schema`, then alias each field to the column it fills with `rename(columns=...)` and pass the application itself, not a mapping, so both columns come from one atomic binding: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa @function( input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.schema([ pa.field("half", pa.float64(), nullable=False), pa.field("double", pa.float64(), nullable=False), ]), ) def scale(value: float): return {"half": value / 2, "double": value * 2} version = db.create_function_async(scale).wait() application = version(value=col("value")).rename( columns={"half": "value_half", "double": "value_double"} ) table.add_columns(application) ``` > [!NOTE] > > `input_schema` and `output_schema` must be given together on v0.41.0. A > version after it accepts either alone, inferring the other from the > annotations. A single refresh fills `value_half` and `value_double` together: there is no state where one is filled and the other is still empty. ## Fill the column A refresh runs the function on the cluster as a [job](/enterprise/v1-12-0/basics/jobs). `wait()` blocks until the job finishes and returns its result, including how many rows it filled: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} refresh = table.refresh_column_async("doubled") result = refresh.wait() print(result.rows_assigned) # 3 ``` The filled values are read like any other column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = table.search().select(["value", "doubled"]).to_list() print(sorted((row["value"], row["doubled"]) for row in rows)) # [(1.0, 2.0), (2.0, 4.0), (3.0, 6.0)] ``` Filling then works as it does for a SQL computed column: a later refresh fills rows added since the last one and recomputes rows whose inputs changed, and leaves filled rows with unchanged inputs alone. See [Refresh a column](/enterprise/v1-12-0/feature-engineering/refresh-column). ## Keep state in a class A function that loads a model or opens a client should not do it for every row. Decorate a class instead: its `__init__` does the expensive setup once, and `__call__` handles each row or batch. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(pip=["sentence-transformers"]) class embed: def __init__(self, model: str = "all-MiniLM-L6-v2"): # Runs on the worker, once per instance: only the worker needs the package. from sentence_transformers import SentenceTransformer self.model = SentenceTransformer(model) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() def close(self): del self.model ``` Registering the class does not construct it. `@function` reads the signature of `__init__` and packages the source, so the client never loads the model. On the cluster, each instance of the function calls `__init__` once. It then calls `__call__` for every row or batch it processes, and `close()`, if defined, once when it retires. Import heavy packages inside `__init__`, as above, so only the worker needs them installed, and declare them in `pip`. State belongs to one instance. An instance reuses it across every batch it serves, but instances do not share it, so each one holds its own copy of the model. Plan memory, or a GPU, for one copy per instance. Register it the same way as a plain function: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} embedder = db.create_function_async(embed).wait() ``` The annotated parameters of `__init__` are the function's initialization fields. Their values come from each binding rather than from the function, so one registered version can run with different settings on different columns: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col application = embedder(text=col("text"), model="all-mpnet-base-v2") ``` Pass the application to `add_columns` as [above](#apply). Initialization values are fixed for every row of a binding and take booleans, integers, floats, strings, and lists or structs of them. A parameter with a default may be omitted. Initialization values are stored with the binding, so keep credentials out of them: pass `secrets=[EnvVarSecret(...)]` to `create_function` and read the variable in `__init__`. Calling the decorated class in your own process constructs it, the same as an undecorated class, so local tests can create an instance and call it directly. ## Blob v2 columns A Function can bind a [Blob v2 column](/enterprise/v1-12-0/management/table#managed-blobs) as input and return another. In row mode, a top-level blob parameter arrives as Python `bytes`, or `None` for a nullable input, after the worker has read the payload; annotate it `BlobReader` instead for seekable, incremental reads that avoid materializing the whole payload first. Return bytes and let the destination table store the Managed payload and descriptor -- `output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather than plain Arrow `binary`; a bare annotation persists as ordinary binary instead, skipping the Managed storage path and `fetch_blobs`. See [Read and produce blobs](/enterprise/v1-12-0/curation/create-function#blobs) for a full example: extracting a frame from a stored video, chaining a second Function onto its output, persisting both as columns or a materialized view, and reading a blob input incrementally. ## Declare the environment The function runs on the Enterprise service, not in your application, so its dependencies are part of its definition: | | | | - | - | | `pip` | requirements for the function's execution environment | | `conda`, `conda_channels` | conda packages instead of pip; channels in priority order | | `env` | environment variables | | `python_version` | Python major/minor for the execution environment, defaulting to yours | | `gpu` | whether every execution requires a GPU | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(gpu=True) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # runs only on a GPU-capable worker ``` These are part of the **immutable function version**. Changing a dependency produces a new version rather than altering the one already registered, so a column filled by version 1 is unaffected by version 2. Declaring them is not optional bookkeeping. If the worker environment differs from the one the function was written against, the failures are among the hardest to diagnose in the system, because the error rarely names the cause. ### Symptoms of an environment mismatch | Symptom | Likely cause | | - | - | | `TypeError: Enum.__new__() missing 1 required positional argument` | `attrs` version mismatch | | `TypeError: Can't instantiate abstract class` | package structure differs between versions | | `ArrowInvalid: cannot cast`, or serialization errors | NumPy 1.x against 2.x | | `ModuleNotFoundError` on the worker | package installed locally but not declared | | Model loading failures | PyTorch version mismatch | | Permission denied | an API key present locally but absent from `env` | The packages worth pinning explicitly, because a mismatch in them produces the errors above rather than a clear one: **numpy, torch, pyarrow, attrs, pydantic**. > [!NOTE] > > The client version defaults `python_version`, so a function registered from a > 3.11 environment runs on 3.11 unless you say otherwise. That default is usually > right and occasionally surprising. Pin it when the function is sensitive to it. ## Remote calls and credentials A function that calls an external API needs a credential without putting it in the function's source or its `env` map in plain text. A Secret is a database-scoped named credential; `db.create_secret` stores the value once, and an `EnvVarSecret` binds it to the environment variable the function reads. Binding is a registration-time decision, passed to `create_function_async`, not to `@function`. No API returns a Secret's value, and it never appears in the function's registration: the function reads the environment variable the way it always did, and the binding is what puts a value there. A mistyped Secret name is caught at registration; a mistyped environment variable name surfaces only on the first rows, since nothing records which variables a function reads. See [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret#specify) for the full worked example. ## Failure handling By default, a Function that raises fails the refresh job. Choose how the refresh handles row errors with its error policy: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') ``` `skip` writes null outputs for failing rows and records their errors. Inspect them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still apply, and initialization or infrastructure failures can still fail the job. See the [SQL refresh options](/enterprise/v1-12-0/sql/dml/refresh-column#options). A Function that calls a transiently failing external service can handle bounded retries inside its body. Letting the job fail is the other option: fix the cause and refresh again. The next unfiltered refresh [skips rows that are filled and current](/enterprise/v1-12-0/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not count on the retry costing only the rows that did not complete. A refresh with `WHERE` recomputes every matching live row, including already-filled outputs. ## What gets packaged > [!WARNING] > > The artifact is a **snapshot**: the function source, plus exactly the > module-level names it references (modules as imports, importable classes and > functions as imports, literals inlined). > > Code that reaches the module namespace another way is rejected where it can be > seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`, > `builtins`. Closures and a non-standard `__builtins__` are rejected outright. In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. Pass `code=[module, ...]` to ship additional helper modules into the same image, for logic the function imports but that does not belong inlined into it -- a model-loading helper shared by several Functions, for example. Continuing the [`caption` Function](/enterprise/v1-12-0/curation/create-function#chain), with its model-loading code factored into a sibling module instead of inlined: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import caption_worker # a sibling module with the model-loading logic @function(gpu=True, code=[caption_worker]) def caption(jpeg: bytes) -> str: return caption_worker.run(jpeg) ``` Each module in `code` is captured and shipped the same way the function itself is: as source, snapshotted at registration. Only `.py` source files are included; package data such as JSON, YAML, prompt, or tokenizer files is not copied. `@function` warns before registration when it skips such files from a package in `code`, naming the affected paths. To use a package that includes the required resources, install it with `pip=` or `conda=` and remove that package from `code`; otherwise the Python-only copied package shadows the installed distribution. ## Drop it ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.drop_function("double", version="1") ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # async fn drop_it(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> { let dropped = connection.drop_function("double", "1", &[]).await?; # Ok(()) # } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP FUNCTION double WITH (version = '1') ``` `db.drop_function(name, version=...)` removes only that published revision from lookup and listing, preserving other revisions and their grants. It returns `False` for a repeated drop or a name that is already gone. A revision never published under an existing name is an error. The last visible revision's drop releases the name and schedules object cleanup, which can finish after the call returns as a [background job](/enterprise/v1-12-0/basics/jobs#teardown). `drop_function_async` returns `(dropped, job)`, where `job` is a query-backed handle. Waiting confirms the revision's catalog removal; physical cleanup can continue afterward. When a deployment reports dependency warnings for a boolean drop, `db.drop_function` emits each warning as a `UserWarning`. This also applies to `await db.drop_function(...)` on an async connection. The warnings are emitted after catalog removal, and standard Python warnings filters apply. If warnings are configured as errors, the call can raise after the revision has been removed; the drop is not rolled back. Servers whose DROP response omits the warning field remain silent. A deployment refuses the drop unless it also allows changes to a function's lifecycle, which is a separate setting, off by default even where Functions are enabled. ## What to read next > [card] [Create a Function](/enterprise/v1-12-0/curation/create-function) > > Scalar, batch, stateful, GPU and remote-service examples for common curation tasks. > [card] [Computed columns](/enterprise/v1-12-0/feature-engineering/refresh-column) > > Refresh semantics, and the SQL alternative. > [card] [Embedding functions](/enterprise/v1-12-0/embedding) > > Built-in embedding providers, which need no registration. # Management Source: https://docs.lancedb.com/enterprise/v1-12-0/management/index Create, list, and drop the objects in a catalog, from Python, TypeScript, or SQL. Use the SDKs or SQL to manage [catalog objects](/enterprise/v1-12-0/basics/catalog), including tables, namespaces and views. The tables below provide a quick reference to the available methods; each object's guide covers its setup and behavior. Some long-running operations also provide a submission method that returns a [job](/enterprise/v1-12-0/basics/jobs). See the operation's guide for how to track completion. ## Management APIs > [!NOTE] > > SQL is available through the Enterprise Flight SQL endpoint. > See [SQL](/enterprise/v1-12-0/basics/sql#sql-is-remote). ### Namespaces | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_namespace` | `createNamespace` | -- | | list | `list_namespaces` | `listNamespaces` | -- | | describe | `describe_namespace` | `describeNamespace` | -- | | exists | `namespace_exists` | -- | -- | | drop | `drop_namespace` | `dropNamespace` | -- | See [Namespaces](/enterprise/v1-12-0/management/namespace). ### Tables | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_table` | `createTable` | `CREATE TABLE` | | create empty | `create_table(schema=)` | `createEmptyTable` | `CREATE TABLE` | | open | `open_table` | `openTable` | -- | | list | `table_names`, `list_tables` | `tableNames`, `listTables` | -- | | exists | `table_exists` | -- | -- | | rename | `rename_table` | `renameTable` | -- | | clone | `clone_table` | `cloneTable` | -- | | drop | `drop_table`, `drop_table_async` | `dropTable`, `dropTableAsync` | `DROP TABLE` | | drop all | `drop_all_tables` | `dropAllTables` | -- | See [Tables](/enterprise/v1-12-0/management/table) for creating one and shaping its schema. ### Materialized views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_materialized_view` | `createMaterializedView` | `CREATE MATERIALIZED VIEW` | | open | `open_materialized_view` | `openMaterializedView` | -- | | list | `list_materialized_views` | `listMaterializedViews` | `SHOW MATERIALIZED VIEWS` | | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_table` | `dropTable` | `DROP TABLE` | > [!NOTE] > > Local `list_materialized_views` reads table schemas to find views. On > Enterprise, it requests the server's view listing. See [Materialized views](/enterprise/v1-12-0/management/materialized-view) for creating one, and [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) for keeping it current. ### Views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_view` | `createView` | `CREATE VIEW` | | list | `list_views` | `listViews` | -- | | drop | `drop_view`, `drop_view_async` | `dropView`, `dropViewAsync` | `DROP VIEW` | Enterprise Views exist only on an Enterprise cluster that enables them; the SDK methods send the view's SQL query to the deployment. See [Views](/enterprise/v1-12-0/management/view). ### Functions | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | | get | `get_function` | -- | `DESCRIBE FUNCTION` | | list | `list_functions` | -- | `SHOW FUNCTIONS` | | drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on a deployment that enables functions, so there is no local form. The TypeScript SDK has no function methods; use Python or SQL. See [Functions](/enterprise/v1-12-0/management/function). ### Jobs | | Python | TypeScript | SQL | | - | - | - | - | | list | `list_jobs` | `listJobs` | `SHOW JOBS` | | open | `open_job` | `openJob` | -- | | cancel | `cancel_job` | `cancelJob` | -- | | errors | `job.events` | `job.events` | `SHOW ERRORS` | See [Job Framework](/enterprise/v1-12-0/basics/jobs). ### Indexes | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_index`, `create_index_async` | `createIndex`, `createIndexAsync` | `CREATE INDEX` | | list | `list_indices` | `listIndices` | -- | | stats | `index_stats` | `indexStats` | -- | | drop | `drop_index` | `dropIndex` | `DROP INDEX` | > [!NOTE] > > SQL `CREATE INDEX` covers one column and takes no user-chosen name: the server > names it. For a multi-column or named index, use the SDK. Indexes are a performance decision rather than a structural one, so they are covered under [Maintenance](/enterprise/v1-12-0/indexing). ## Work within a namespace Most connection-level operations take a `namespace_path` (`namespacePath`) to act inside a namespace rather than at the database root: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.table_names(namespace_path=["prod", "events"]) tbl = db.open_table("clicks", namespace_path=["prod", "events"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.tableNames(["prod", "events"]); const tbl = await db.openTable("clicks", ["prod", "events"]); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM `prod$events`.clicks ``` In SQL the path is written as a `$`-joined schema instead; see [Namespace](/enterprise/v1-12-0/basics/catalog#schema) for why it isn't dotted. ## Delete catalog objects > [!WARNING] > > `drop_table` removes the table and every version of it. Table > [versioning](/enterprise/v1-12-0/management/table#versioning) does not survive the table being dropped, and > neither `drop_database` nor `drop_all_tables` asks for confirmation. Dropping a **view** removes only the saved query. Dropping a **materialized view** removes stored rows, because a materialized view is a table. # Materialized view Source: https://docs.lancedb.com/enterprise/v1-12-0/management/materialized-view Create, open, list and drop a table whose contents are defined by a query. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view is a table whose contents are defined by a query over another table. The query is recorded in the view's schema, and a refresh brings its stored rows up to date with the source. The result is an ordinary table: queryable, indexable, searchable, and present in `table_names()`. Nothing about reading it is special. This page covers creating and managing one. Keeping it current is [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view). > [!NOTE] > > In SQL, see [`REFRESH MATERIALIZED VIEW`](/enterprise/v1-12-0/sql/dml/refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/enterprise/v1-12-0/sql/ddl/materialized-view#show). ## Create a materialized view A materialized view is defined by a SQL query: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() view = db.open_materialized_view("frames_captioned") ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` See [Create a materialized view](/enterprise/v1-12-0/feature-engineering/materialized-views#create) for the full walkthrough, including joins and Functions in the query. ## Open, list and drop views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_materialized_view` | `createMaterializedView` | `CREATE MATERIALIZED VIEW` | | open | `open_materialized_view` | `openMaterializedView` | -- | | list | `list_materialized_views` | `listMaterializedViews` | `SHOW MATERIALIZED VIEWS` | | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_materialized_view` | `dropMaterializedView` | `DROP MATERIALIZED VIEW` | Enterprise Creating, refreshing and dropping a materialized view each have an async, job-returning counterpart -- `create_materialized_view_async`, `view.refresh_async()`, `drop_materialized_view_async` -- the same pattern as [`refresh_column_async`](/enterprise/v1-12-0/feature-engineering/refresh-column#async): each returns a [job](/enterprise/v1-12-0/basics/jobs) you `wait()` on instead of blocking, with the same arguments as its synchronous counterpart, including `auto_refresh_enabled` and `auto_refresh_interval_seconds`; see [Auto Refresh](/enterprise/v1-12-0/enterprise/auto-refresh). > [!NOTE] > > On a local database, `list_materialized_views` reads table schemas to find > views. On Enterprise, it asks the server for the view listing, as > `SHOW MATERIALIZED VIEWS` does. A view is dropped with `drop_materialized_view`, a dedicated operation, even though a materialized view **is** a table underneath. That also means dropping one removes stored rows, unlike dropping a [view](/enterprise/v1-12-0/management/view), which removes only a saved query. ## Read the view and its definition `view.table` is the underlying table, for querying, indexing, or search. `view.definition` has a single field, `query` -- the defining query, in the canonical spelling the server stores. Both are properties; on an async view, the definition is read with `await view.definition()`. ## Enterprise compatibility Enterprise supports creating and refreshing materialized views on remote compute. Use the SDK version supported by your deployment, or the [SQL interface](/enterprise/v1-12-0/sql/ddl/materialized-view). ## Privileges A materialized view **is** a table (see [Dropping one](/enterprise/v1-12-0/sql/ddl/materialized-view#drop)), granted through the REST ACL API or SQL `GRANT`/`REVOKE` with the same privilege names as a table, but two of them mean something different here: the server refuses a direct `INSERT`, `UPDATE` or `DELETE` on a materialized view's rows -- only a refresh writes them. `UPDATE` is instead what authorizes calling refresh, and `OWNERSHIP` is what authorizes `ALTER` (auto-refresh settings): ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts ``` That grants `analysts` read access and the ability to refresh `daily_rollup`, not row-level write access. See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax and every target it reaches. ## Related guides > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > How a refresh works, and what it writes. > [card] [Views](/enterprise/v1-12-0/management/view) > > The non-materialized counterpart, defined in SQL. # Namespaces Source: https://docs.lancedb.com/enterprise/v1-12-0/management/namespace Grouping tables into a hierarchy, and addressing them through it. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB organizes Lance tables through a catalog-level abstraction defined by the *namespace spec*. LanceDB Embedded is an embedded library for accessing those tables, and LanceDB Enterprise is a multimodal lakehouse that provides shared compute and catalog services on top of the Lance format. If you're coming from traditional databases or lakehouses, you can think of a namespace as the catalog path that says where a table name lives. Lance provides the **file** and **table** formats to store and manage your data and indexes. LanceDB operates at the catalog layer (used to organize, discover, and operate on many Lance tables) and provides a compute engine on top of the Lance format. This is why many SDK methods in LanceDB, like `create_table`, `open_table`, `drop_table`, and `rename_table`, accept namespace input. The SDK methods expose that input in the idiom of each language: Python uses `namespace_path`, Rust uses builder methods like `.namespace(...)`, and TypeScript uses `namespacePath` arguments. > [!NOTE] > > In LanceDB Enterprise SQL, a namespaced table is addressed by its > [schema](/enterprise/v1-12-0/basics/catalog#schema) -- the namespace path joined by `$`, not > by `.` -- [before the table name](/enterprise/v1-12-0/sql/dql/select#namespaces). ## Namespace hierarchy Namespaces are generalizations of catalog specs that give platform developers a clean way to present Lance tables in the structures users expect. The diagram below shows how the hierarchy can go beyond a single level. A namespace can contain a collection of tables, and it can also contain namespaces recursively. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/namespaces/lance-namespace.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=813f551c24face60f671ff635b15cd74) Before diving into examples, it helps to keep two terms in mind: the **namespace client** is the abstraction that presents a consistent namespace API, while the **namespace implementation** is the concrete backend that resolves namespaces and table locations (for example, a local directory or an external catalog). If you want to go deeper, see the Lance format [namespace documentation](https://lance.org/format/namespace/). ## Namespace paths and names A namespace path is a list of components. For example, `["prod", "search"]` means the `search` namespace inside the `prod` namespace. The empty path, `[]`, means the root namespace. Each component is a name, not a filesystem path segment, and can't be empty. Keep each one to letters, numbers, underscores, hyphens, and periods, so the same identifier is usable everywhere: a local directory namespace accepts other characters too, but other namespace implementations and deployments can refuse them. [Naming rules](/enterprise/v1-12-0/basics/naming) has the lengths and the other limits. ## Directory namespaces The simplest namespace model in LanceDB is a single root namespace, often represented by one directory. Namespaces can nest inside it, as in this hierarchy: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ./local_lancedb (root) └── prod └── search └── user (table) └── data (table) ``` The hierarchy is logical, not a tree of folders: a directory namespace records it in a `__manifest` table in the root directory, and stores each table in a directory of its own there. As a user of LanceDB Embedded, you might never notice namespaces at first, because a plain connection uses only the root namespace, which is implicit. Connecting to this namespace is as simple as connecting to the namespace root: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Connect to the directory namespace root db = lancedb.connect("./local_lancedb") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Connect to the directory namespace root const db = await lancedb.connect("./local_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; // Connect to the directory namespace root let db = connect("./local_lancedb").execute().await?; ``` A table created through this connection is stored directly under that path, as `<name>.lance`. You can also explicitly connect to a namespace using `lancedb.connect_namespace(...)` with the directory namespace implementation: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Local DirectoryNamespace root # See https://lance.org/format/namespace/dir/catalog-spec/ db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) table_name = "user" data = [{"id": 1, "vector": [0.1, 0.2], "name": "alice"}] table = db.create_table(table_name, data=data, mode="create") print(f"Created table: {table.name}") # Created table: user ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); const table = await db.createTable( "user", [{ id: 1, vector: [0.1, 0.2], name: "alice" }], { mode: "create" }, ); console.log(`Created table: ${table.name}`); // Created table: user ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; use std::sync::Arc; use arrow_schema::{DataType, Field, Schema}; // Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ let mut properties = HashMap::new(); properties.insert("root".to_string(), "./local_lancedb".to_string()); let db = lancedb::connect_namespace("dir", properties) .execute() .await?; let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), ])); let table = db .create_empty_table("user", schema) .execute() .await?; println!("Created table: {}", table.name()); // Created table: user ``` > [!NOTE] > > * For simple use cases in LanceDB Embedded, you don't need to go too deep into namespaces. > * To integrate LanceDB with external catalogs, understand how each namespace implementation resolves table names and locations in your organization's setup. ## Remote or external catalog namespaces The example above showed local directory-based namespaces. LanceDB also supports namespaces backed by remote object stores and external catalogs, via the REST namespace implementation. For remote object stores with central metadata or catalog services (either commercial or open source), use the REST namespace implementation. It is backed by REST routes (for example `POST /v1/namespace/{id}/create` and `GET /v1/namespace/{id}/list`) and server-provided table locations. For authentication, any property prefixed with `headers` is forwarded as an HTTP header (for example `headers.Authorization` becomes `Authorization`, and `headers.X-API-Key` becomes `X-API-Key`). LanceDB Enterprise REST requests use the `x-api-key` header for API-key authentication. Deployments that route multiple databases through the same endpoint can also use headers such as `x-lancedb-database` or `x-lancedb-database-prefix` for database context. Replace the catalog URL and credential placeholders below with your values. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remote RestNamespace root # See https://lance.org/format/namespace/rest/catalog-spec/ db = lancedb.connect_namespace( "rest", { "uri": "https://<your_catalog>.internal.<your_org>.com", "headers.x-api-key": "your-api-key", # or: # "headers.Authorization": "Bearer your-access-token", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ const db = await lancedb.connectNamespace("rest", { uri: "https://<your_catalog>.internal.<your_org>.com", headers: { "x-api-key": "your-api-key", // or: // Authorization: "Bearer your-access-token", }, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; // Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ let mut properties = HashMap::new(); properties.insert( "uri".to_string(), "https://<your_catalog>.internal.<your_org>.com".to_string(), ); properties.insert( "headers.x-api-key".to_string(), "your-api-key".to_string(), ); // or: // properties.insert( // "headers.Authorization".to_string(), // "Bearer your-access-token".to_string(), // ); let db = lancedb::connect_namespace("rest", properties) .execute() .await?; ``` [LanceDB Enterprise](/enterprise/v1-12-0/index#architecture) operates a REST namespace server on top of the Lance format, so any REST client that can speak the REST namespace API contract can be used to interact with it. It does not serve the contract's `exists` routes, so existence checks made through a direct REST namespace client fail against it. Python remote connections created with `lancedb.connect("db://...")` or `lancedb.connect_async("db://...")` support `namespace_exists` and `table_exists` through the existing describe routes instead with Python 0.42.0b8. In Python 0.41.0, the sync remote methods raise `NotImplementedError` and the async connection has neither helper. For authentication examples in LanceDB Enterprise, visit the [Namespaces in SDKs](#namespaces-in-lancedb-enterprise) page. ## Best practices Below, we list some best practices for working with namespaces: * For simple use cases and single, stand-alone applications, the directory-based root namespace is sufficient and requires no special configuration. * For remote storage locations, introduce explicit namespaces when multiple teams, environments, or domains share the same catalog. * Treat namespace paths as stable identifiers (for example `"prod/search"`, `"staging/recs"`). * For maintainability reasons, avoid hard-coding object-store table paths in application code. Instead, prefer catalog identifiers + namespaces. ## Table operations with namespace paths Let's imagine a scenario where your table management needs have evolved, and you now have the following multi-level structure to organize your tables outside the root namespace. ``` ./local_lancedb (root) └── prod └── search └── user (table) └── data (table) └── recommendations └── user (table) └── data (data) ``` Below, we show how you would express table operations within that namespace. Each item in the namespace list (`["prod", "search"]`) represents a level in the namespace hierarchy, and the table name is specified when you create, open, list, or drop it. The SDK methods expose the namespace path in the idiom of each language: * Python: pass `namespace_path=["prod", "search"]` to table operations. * Rust: call builder methods such as `.namespace(vec!["prod".to_string(), "search".to_string()])`. * TypeScript: pass a `namespacePath` array, for example `await db.openTable("user", ["prod", "search"])`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) # Create namespace tree: prod/search db.create_namespace(["prod"], mode="exist_ok") db.create_namespace(["prod", "search"], mode="exist_ok") db.create_namespace(["prod", "recommendations"], mode="exist_ok") db.create_table( "user", data=[{"id": 1, "vector": [0.1, 0.2], "name": "alice"}], namespace_path=["prod", "search"], mode="create", # use "overwrite" only if you want to replace existing table ) db.create_table( "user", data=[{"id": 2, "vector": [0.3, 0.4], "name": "bob"}], namespace_path=["prod", "recommendations"], mode="create", # use "overwrite" only if you want to replace existing table ) # Verify: listings return a response with the names and a page token print(db.list_namespaces().namespaces) # ['prod'] print(db.list_namespaces(namespace_path=["prod"]).namespaces) # ['recommendations', 'search'] print(db.list_tables(namespace_path=["prod", "search"]).tables) # ['user'] print(db.list_tables(namespace_path=["prod", "recommendations"]).tables) # ['user'] ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function collectNames(items: AsyncIterable<string>): Promise<string[]> { const names: string[] = []; for await (const name of items) names.push(name); return names; } const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); // Create namespace tree: prod/search and prod/recommendations await db.createNamespace(["prod"], { mode: "exist_ok" }); await db.createNamespace(["prod", "search"], { mode: "exist_ok" }); await db.createNamespace(["prod", "recommendations"], { mode: "exist_ok" }); await db.createTable( "user", [{ id: 1, vector: [0.1, 0.2], name: "alice" }], ["prod", "search"], { mode: "create" }, // use "overwrite" only if you want to replace existing table ); await db.createTable( "user", [{ id: 2, vector: [0.3, 0.4], name: "bob" }], ["prod", "recommendations"], { mode: "create" }, ); // Verify console.log(await collectNames(db.listNamespaces())); // ["prod"] console.log(await collectNames(db.listNamespaces(["prod"]))); // ["recommendations", "search"] console.log(await db.tableNames(["prod", "search"])); // ["user"] console.log(await db.tableNames(["prod", "recommendations"])); // ["user"] ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let conn = connect(uri).execute().await?; let search_namespace = vec!["prod".to_string(), "search".to_string()]; let recommendations_namespace = vec!["prod".to_string(), "recommendations".to_string()]; let schema = std::sync::Arc::new(arrow_schema::Schema::new(vec![ arrow_schema::Field::new("id", arrow_schema::DataType::Int64, false), ])); conn.create_empty_table("user", schema.clone()) .namespace(search_namespace.clone()) .execute() .await?; conn.create_empty_table("user", schema) .namespace(recommendations_namespace.clone()) .execute() .await?; let search_table_names = conn .table_names() .namespace(search_namespace) .execute() .await?; let recommendation_table_names = conn .table_names() .namespace(recommendations_namespace) .execute() .await?; println!("{search_table_names:?}"); // ["user"] println!("{recommendation_table_names:?}"); // ["user"] ``` > [!NOTE] > > Using namespaces is **optional** in LanceDB, and most basic use cases do not require to work with them. > An empty namespace (`[]`), which is the default, means the root namespace, whose tables are stored > directly under the specified root path. ## Namespace management APIs You can open/create/drop tables inside a namespace path (like `["prod", "search"]`). All three SDKs expose namespace lifecycle operations directly. In Python, use `lancedb.connect_namespace(...)` when calling namespace lifecycle methods such as `create_namespace`, `list_namespaces`, `describe_namespace`, and `drop_namespace`. In TypeScript, use `lancedb.connectNamespace(...)` and call `createNamespace`, `listNamespaces`, `describeNamespace`, and `dropNamespace` on the returned `Connection`. In Rust, use `lancedb::connect_namespace(...)` and call `create_namespace`, `list_namespaces`, and `drop_namespace`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) namespace = ["prod", "search"] db.create_namespace(["prod"]) db.create_namespace(["prod", "search"]) child_namespaces = db.list_namespaces(namespace_path=["prod"]).namespaces print(f"Child namespaces under ['prod']: {child_namespaces}") # Child namespaces under ['prod']: ['search'] metadata = db.describe_namespace(["prod", "search"]) print(f"Metadata for namespace {namespace}: {metadata}") # Metadata for namespace ['prod', 'search']: properties=None db.drop_namespace(["prod", "search"], mode="skip") db.drop_namespace(["prod"], mode="skip") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function collectNames(items: AsyncIterable<string>): Promise<string[]> { const names: string[] = []; for await (const name of items) names.push(name); return names; } const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); const namespace = ["prod", "search"]; await db.createNamespace(["prod"]); await db.createNamespace(["prod", "search"]); const childNamespaces = await collectNames(db.listNamespaces(["prod"])); console.log( `Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces, ); // Child namespaces under ["prod","search"]: [ 'search' ] const metadata = await db.describeNamespace(["prod", "search"]); console.log(`Metadata for namespace ${JSON.stringify(namespace)}:`, metadata); await db.dropNamespace(["prod", "search"], { mode: "skip" }); await db.dropNamespace(["prod"], { mode: "skip" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let mut properties = std::collections::HashMap::new(); properties.insert("root".to_string(), "./local_lancedb".to_string()); let db = lancedb::connect_namespace("dir", properties).execute().await?; let namespace = vec!["prod".to_string(), "search".to_string()]; db.create_namespace(lance_namespace::models::CreateNamespaceRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; db.create_namespace(lance_namespace::models::CreateNamespaceRequest { id: Some(namespace.clone()), ..Default::default() }) .await?; let child_namespaces = db .list_namespaces(lance_namespace::models::ListNamespacesRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; println!( "Child namespaces under {:?}: {:?}", namespace, child_namespaces ); // Child namespaces under ["prod", "search"]: ["search"] db.drop_namespace(lance_namespace::models::DropNamespaceRequest { id: Some(namespace.clone()), ..Default::default() }) .await?; db.drop_namespace(lance_namespace::models::DropNamespaceRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; ``` Namespace creation and deletion have modes that control what happens when the target already exists, doesn't exist, or contains data: * Create mode: `create` fails if the namespace already exists, `exist_ok` keeps the existing namespace, and `overwrite` replaces it. * Drop mode: `fail` reports an error when the namespace doesn't exist, and `skip` treats a missing namespace as a successful no-op. * Drop behavior: `restrict` keeps non-empty namespaces from being dropped, and `cascade` drops child namespaces and tables first. Namespace path components can't be empty, and are best kept to letters, numbers, underscores, hyphens, and periods, as [above](#namespace-paths-and-names). Listing APIs return the immediate children of the requested namespace path. Use `limit` with the returned `page_token` to page through large catalogs; pass an empty namespace path (`[]`) when you want to list from the root namespace. In Python, a listing returns a response: the names are in its `namespaces` or `tables`, and `page_token` is set when there is another page. ## Namespaces in LanceDB Enterprise In LanceDB Enterprise deployments, configure namespace-backed federated databases in a TOML file under your deployment's `config` directory. LanceDB Enterprise supports both directory-based (`ns_impl = "dir"`) and REST-based (`ns_impl = "rest"`) namespace implementations. The example below shows how to configure a directory-based namespace implementation in LanceDB Enterprise. ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Federated database configuration for DirectoryNamespace # This example uses minio storage [federated_dbs.federated_dir_test] ns_impl = "dir" root = "s3://<your-deployment>/<your-dir>" "storage.region" = "us-east-1" "storage.endpoint" = "http://localhost:9000" "storage.access_key_id" = "minioadmin" "storage.secret_access_key" = "minioadmin" "storage.allow_http" = "true" # Far future expiration (year 2100) "storage.expires_at_millis" = "4102444800000" ``` The example above uses MinIO, but the same approach applies to other cloud object storage platforms based on your deployment. For REST-based namespace servers, you can specify the namespace implementation as `"rest"` with forwarding prefixed headers for authentication and context propagation. ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [federated_dbs.federated_rest_test] ns_impl = "rest" uri = "http://<your_org>.internal.catalog.com" forward_header_prefixes = ["X-forward"] ``` With `forward_header_prefixes = ["X-forward"]`, any incoming header starting with `X-forward` is forwarded to `http://<your_org>.internal.catalog.com`. This is useful for auth propagation, for example sending `X-forward-authorization: Bearer xxxx`. For the LanceDB REST API itself, requests use `x-api-key` for API-key authentication. If your endpoint serves more than one database, LanceDB can also use headers such as `x-lancedb-database` or `x-lancedb-database-prefix` to route the request to the right database context. ## Privileges A namespace's `USAGE`, and the `CREATE_TABLE`, `CREATE_VIEW`, `CREATE_MATERIALIZED_VIEW`, `CREATE_NAMESPACE`, `CREATE_SECRET`, `CREATE_STORAGE_INTEGRATION` and `CREATE_FUNCTION` privileges for what it can hold, are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE NAMESPACE, CREATE TABLE, CREATE VIEW ON SCHEMA platform TO ROLE writers ``` See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Secret Source: https://docs.lancedb.com/enterprise/v1-12-0/management/secret Create, rotate, list, describe and drop a named credential that Functions bind by reference. **Applies to:** Embedded ❌, Enterprise ✅ Early access A **Secret** is a catalog object, like a table or a namespace: a named credential, such as a model provider's API key, stored once and addressed by name. A [Function](/enterprise/v1-12-0/curation/create-function) binds a Secret by reference when you register it, never by value; see [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret) for how that binding reaches running code. The design rule is **bind by reference, resolve late**. A Function records *which* Secret it reads, never the value, and the value is looked up each time a job starts. That is what lets a credential be rotated or revoked without touching the Functions, columns or tables that use it. ## Create and manage Every call takes an optional `namespace_path`; the default is the root namespace. ```python Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_secret("model-api-key", value, namespace_path=["platform"]) db.alter_secret("model-api-key", new_value, namespace_path=["platform"]) for name in db.list_secrets(namespace_path=["platform"]): print(name) info = db.describe_secret("model-api-key", namespace_path=["platform"]) info.created_at_millis, info.updated_at_millis db.drop_secret("model-api-key", namespace_path=["platform"]) ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '<api-key>'; ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '<api-key>'; SHOW SECRETS IN platform; DESCRIBE SECRET platform.`model-api-key`; DROP SECRET platform.`model-api-key`; ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; let namespace = vec!["platform".to_string()]; db.create_secret("model-api-key", &value, &namespace).await?; db.alter_secret("model-api-key", &new_value, &namespace).await?; let mut names = db.list_secrets(&namespace, Default::default()); while let Some(name) = names.try_next().await? { println!("{name}"); } let info = db.describe_secret("model-api-key", &namespace).await?; println!("{} {}", info.created_at_millis, info.updated_at_millis); db.drop_secret("model-api-key", &namespace).await?; ``` A Secret's value is never returned by any interface: `create` and `alter` take it as input and return nothing, and `describe` reports only metadata. Python and Rust both expose the full lifecycle shown above; TypeScript does not yet, and is tracked separately. See the [SQL reference](/enterprise/v1-12-0/sql/ddl/secret) for the same operations' SQL syntax and result rows. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function. Register Functions that > bind Secrets through the Python SDK; see > [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret). ## Properties and guarantees LanceDB guarantees that: * No API returns a Secret's value. * Values do not appear in Function source, Function versions, jobs, logs, or error messages. Errors raised by Function code are redacted, within [limits](#redaction). * A Function receives only the Secrets bound to it. * Values are always [encrypted at rest](#encryption). Redaction is a safety net, not a boundary: Function code that logs, returns or sends a credential will leak it. ### Encryption at rest Every Secret's value is encrypted directly with your deployment's key in AWS KMS, Google Cloud KMS, or Azure Key Vault -- there is no separate application data key to manage. Storage, backups and replicas hold only ciphertext. Decryption goes through your KMS, which records it in your cloud's audit log. BYOC You are responsible for the network egress policy for the jobs that run Functions. ### Redaction If a Function raises an error or skips a row with a message that contains a bound value, LanceDB replaces each exact occurrence with `[REDACTED]` before the message is recorded. Redaction matches only the exact value: a value that is base64-encoded, sliced, or otherwise transformed is not caught. Function code that prints a credential, writes it into a column, or sends it elsewhere will leak it, so review a Function bound to a Secret as code that holds that credential. ## Limits | Item | Limit | | - | - | | Secret name | 1--128 characters from `A-Z a-z 0-9 _ . -`. `$` is reserved as the namespace delimiter. | | Value | One nonempty UTF-8 string, at most 4,096 bytes. On Azure, at most 158, 286 or 414 bytes for an RSA-2048, RSA-3072 or RSA-4096 key. | | Bindings per Function | 16 | | Environment variable name | `[A-Za-z_][A-Za-z0-9_]*`, and not [reserved](#reserved) | | Variables per Function | Each bound once. Two variables may bind the same Secret. | | `describe` history | The most recent 100 alterations | ### Reserved variables A Secret cannot be bound to a variable that LanceDB sets for Functions itself. These names are reserved: * Exact names: `HOME`, `PATH`, `TEMP`, `TMP`, `TMPDIR`, `LANG`, `LC_ALL`, `LC_CTYPE`, `TZ`, `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE`, `SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, `UV_CACHE_DIR`, `UV_NATIVE_TLS`, `UV_PYTHON_INSTALL_DIR`, `RUST_BACKTRACE` * Prefixes: `DYLD_`, `LANCE_`, `LANCEDB_`, `LD_`, `PYTHON`, and a few others LanceDB reserves for its own use. `create_function` refuses a reserved name and says which one. ## Troubleshooting **`Secret 'X', bound to VAR, does not exist`** when adding a column or refreshing one: the Secret was never created in that namespace, was dropped, or its name is misspelled in the binding. Create it, or register a new Function version with the right name. **501 from a Secret API call**: Secrets aren't enabled for this deployment. Contact [LanceDB support](/enterprise/v1-12-0/deployment/support). ## Privileges A Secret is its own object in the authorization model, a namespace child like a table, so a grant names one credential rather than a whole database. See [Privileges](/enterprise/v1-12-0/governance/privileges#secret-operations) for the privilege each operation above requires, and [GRANT and REVOKE](/enterprise/v1-12-0/sql/ddl/secret#grant) for the full SQL statement syntax. ## What to read next > [card] [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret) > > Bind a Secret when you register a Function, and how rotation reaches > code that is already running. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges#sql) > > Grant and revoke privileges on a Secret. # Storage Integration Source: https://docs.lancedb.com/enterprise/v1-12-0/management/storage-integration A namespace-scoped, reusable credential for reading or importing from storage outside the deployment's own tables. **Applies to:** Embedded ❌, Enterprise ✅ A **storage integration** is a namespace-scoped catalog object, like a [Secret](/enterprise/v1-12-0/management/secret), that names a credential for reading or importing from one external storage location: an S3, GCS or Azure prefix, or a HuggingFace dataset repository. A query or import statement that reads a matching URI uses the integration automatically -- it is never named in the query itself. ## Create and manage Every provider takes a `storage_prefix` and `storage_provider`, plus provider-specific credential options. Credential options take a [Secret](/enterprise/v1-12-0/management/secret) reference, never a value directly -- either a bare name (resolved in the caller's own database, root namespace) or a `SecretReference` qualified with a database and namespace path: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token DESCRIBE STORAGE INTEGRATION hub SHOW STORAGE INTEGRATIONS DROP STORAGE INTEGRATION hub ``` See [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) for every provider's exact options, S3's two credential modes, and the full output schema -- this page covers the CRUD operations above at a glance; that one is the complete reference. | Operation | Python (not yet released) | SQL | Notes | | - | - | - | - | | Create | `create_storage_integration` | `CREATE STORAGE INTEGRATION` | Fails if the name is taken, so a create never silently replaces one. | | Describe | `describe_storage_integration` | `DESCRIBE` / `DESC` | One row: provider, prefix, credential references, and (for an AWS role integration) the generated trust policy. | | List | `list_storage_integrations` | `SHOW` / `LIST STORAGE INTEGRATIONS` | Optionally scoped to one namespace. | | Drop | `drop_storage_integration` | `DROP [IF EXISTS]` | Blocked while an attached database still depends on it. | The Python column names the methods landing in a future release (see the draft note above); use SQL today. There is no TypeScript or REST equivalent yet either. There is no `ALTER`. To rotate a credential, rotate the [Secret](/enterprise/v1-12-0/management/secret#manage) it references -- the integration's reference does not change, so nothing that reads through it needs updating. ## The S3 trust workflow An S3 integration created with `STORAGE_AWS_ROLE_ARN` (instead of a static access key pair) needs one more step outside LanceDB: `DESCRIBE` returns `trust_policy` and `permissions_policy`, the IAM policy documents your role needs, built from `aws_account_id`, `aws_iam_principal_arn` and `aws_external_id` in the same row. Attach `trust_policy` as the role's trust relationship and `permissions_policy` as its permissions, then check `access_verified` on a later `DESCRIBE` to confirm LanceDB can assume the role and read the prefix. ## Privileges A storage integration is its own object in the authorization model, a namespace child like a Secret: `CREATE_STORAGE_INTEGRATION` on the namespace to create one, `USAGE` on the integration for a query to read through it, `OWNERSHIP` for full control including dropping it. See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the privilege each operation requires and the full `GRANT`/`REVOKE` syntax. ## Troubleshooting **A query does not use the integration you expected**: integrations match by the most specific `STORAGE_PREFIX` covering the URI, not by name, and are scoped to native databases under the catalog root. Two integrations with equally specific prefixes make the query fail rather than guess; keep prefixes for the same bucket or dataset family unambiguous. **403 or access-denied reading a matching prefix**: confirm `USAGE` on the integration, and for an S3 role integration, confirm `access_verified` is `true` on `DESCRIBE` -- `false` usually means the trust policy from [above](#trust) is missing or misconfigured on the AWS side, not a LanceDB permission problem. **`DROP` refuses with a dependent database**: detach the database that still uses the integration first, then drop it. ## What to read next > [card] [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) > > The complete SQL reference: every provider's options, output columns, and GRANT syntax. > [card] [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) > > The most common use of a storage integration today: inspecting and importing HuggingFace datasets. > [card] [Secret](/enterprise/v1-12-0/management/secret) > > The credential a storage integration's `_SECRET` options reference. # Tables Source: https://docs.lancedb.com/enterprise/v1-12-0/management/table The object most operations act on: creating, opening, renaming, cloning and dropping one. **Applies to:** Embedded ✅, Enterprise ✅ A table stores data in rows and columns and keeps a history of committed versions. Queries read table data, writes update it, and indexes accelerate searches over its columns. This page covers table management, data types, schema changes and version history. For loading records, see [Ingestion](/enterprise/v1-12-0/ingestion). For changes to columns, see [Schema evolution](/enterprise/v1-12-0/management/table#schema). > [!NOTE] > > In LanceDB Enterprise, tables are also created and dropped in SQL with [`CREATE TABLE` and `DROP TABLE`](/enterprise/v1-12-0/sql/ddl/table). ## Table structure and metadata | | | | - | - | | **Columns** | including vectors, blobs, and [computed](/enterprise/v1-12-0/feature-engineering/add-computed-column) columns | | **Versions** | every write commits one, so reads can [travel back](/enterprise/v1-12-0/management/table#versioning) | | **Indexes** | vector, full-text and scalar, built over its columns | ## Create a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("documents", data) tbl = db.create_table("documents", schema=schema) # empty, typed ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.createTable("documents", data); const tbl = await db.createEmptyTable("documents", schema); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents (id BIGINT, title VARCHAR) ``` `data` can be a list of objects, an Arrow table or reader, a pandas or polars frame, or Pydantic models. [Ingesting data](/enterprise/v1-12-0/ingestion) covers each, plus `exist_ok` and `mode="overwrite"` for re-runnable scripts. > [!WARNING] > > An explicit schema is where nullability is decided. In the embedded library, > creation is also the only point at which a table can be given **stable row > ids**; in LanceDB Enterprise, whether a new table gets them is the deployment's > setting. See [Limits](/enterprise/v1-12-0/basics/limits#schema). ## Open and list tables ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.open_table("documents") db.table_names() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.openTable("documents"); await db.tableNames(); ``` Each accepts `namespace_path` to act inside a [namespace](/enterprise/v1-12-0/management/namespace) rather than at the database root. With Python 0.42.0b8, remote connections created with `lancedb.connect("db://...")` use `db.table_exists(["documents"])` to check whether a table exists. For an async remote connection, use `await db.table_exists(["documents"])`. Include namespace segments before the table name, for example `["analytics", "documents"]`. These checks return `False` when the table is missing and propagate other errors, including permission errors. In Python 0.41.0, the synchronous remote method raises `NotImplementedError` and the async connection has no `table_exists` method. Open the table and handle a missing-table error with that client. Local synchronous directory connections still raise `NotImplementedError` for `table_exists`. On a connection from `connect_namespace("dir", ...)` or `connect_namespace("rest", ...)`, it fails with an `AttributeError`. For these connections, open the table and handle the error, or look for its name in a listing. A missing table raises `ValueError` on a local directory and `lance_namespace.TableNotFoundError` on a connection from `connect_namespace`. A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. ## Rename and clone tables ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.rename_table("documents", "docs") db.clone_table( "docs_snapshot", source_uri="s3://bucket/db/documents.lance", source_version=42, # or source_tag="release-1" is_shallow=True, ) ``` Renaming is not supported on a local directory connection. In LanceDB Enterprise, whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training set to the exact version a model saw. > [!WARNING] > > A shallow clone depends on the source's files continuing to exist. If the source > is [compacted](/enterprise/v1-12-0/maintenance/compaction) past the retention window, the version > the clone points at can be pruned. LanceDB Embedded connections support shallow clones > only; `is_shallow=False` is not implemented. If the copy must outlive the > source's history, copy its data into an independent table instead. A deployment > that supports cloning also makes shallow clones only, and one whose catalog > does not support it refuses every clone. > [!NOTE] > > **Enterprise job type:** on an Enterprise cluster that drops tables in the background, > the teardown runs as a job: `drop_table`, which fences the table's directory > with a marker and deletes its content, or `drop_object`, depending on how the > deployment stores its catalog. See > [Object teardown](/enterprise/v1-12-0/basics/jobs#teardown). ## Drop a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.drop_table("documents") job = db.drop_table_async("documents") db.drop_all_tables() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.dropTable("documents"); const job = await db.dropTableAsync("documents"); await db.dropAllTables(); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP TABLE documents ``` > [!WARNING] > > Dropping removes the table and **every version of it**. > [Versioning](/enterprise/v1-12-0/management/table#versioning) does not survive a drop, and neither > `drop_all_tables` nor `drop_database` asks for confirmation. Both work only on > a local database; on an Enterprise connection the SDK raises instead. On a large table the drop can take a while, so `drop_table_async` returns a [job](/enterprise/v1-12-0/basics/jobs) rather than blocking when the deployment drops tables in the background. In the embedded library, and on an Enterprise cluster that drops inline, the returned job has already finished. ## Table management APIs | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_table` | `createTable` | `CREATE TABLE` | | create empty | `create_table(schema=)` | `createEmptyTable` | `CREATE TABLE` | | open | `open_table` | `openTable` | -- | | list | `table_names`, `list_tables` | `tableNames`, `listTables` | -- | | exists | `table_exists` | -- | -- | | rename | `rename_table` | `renameTable` | -- | | clone | `clone_table` | `cloneTable` | -- | | drop | `drop_table`, `drop_table_async` | `dropTable`, `dropTableAsync` | `DROP TABLE` | | drop all | `drop_all_tables` | `dropAllTables` | -- | ## Data types A table's schema is an **Arrow schema**: there is no separate LanceDB type system mapped onto storage, so a column is the same object to the query engine as it is to the format. | Category | Types | | - | - | | Numeric | `int8`-`int64` and unsigned, `float16`, `float32`, `float64` | | String and binary | `utf8`, `large_utf8`, `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp`, `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | | Lance extensions | vectors, [blobs](#multimodal), bfloat16 | A vector column is a `fixed_size_list<float32, dim>`, an ordinary Arrow type, which is why it is selectable and joinable but why arithmetic over it is list arithmetic rather than scalar. See [SQL data types](/enterprise/v1-12-0/sql/data-types) for the full reference, including the extension types and pseudo-columns. ## Multimodal data Store images, audio, video, and documents alongside structured columns and embeddings in the same versioned table. Use `blob` columns for these payloads. Small values stay inline in the data file, up to 64 KiB by default, and larger values are stored outside it. ### Blob columns Early access A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. SDK Arrow queries return descriptors by default, which contain metadata about the blob instead of its bytes. Enterprise SQL returns payload bytes by default; use `blob_descriptor(column)` to select metadata instead. With an SDK, you can [read the bytes in the query results](#multimodal-blob-query-results) or [fetch them by row ID](#multimodal-read-blobs). In Python, plain `to_pandas()` scans can also return `BlobFile` handles when `pylance` is installed. When you write raw bytes, Lance chooses a storage layout based on the payload size. A descriptor's `kind` tells you which one was used: | Storage mode | `kind` | Default placement | Storage behavior | | - | - | - | - | | `Inline` | `0` | Up to 64 KiB | Stored in the main data file. | | `Packed` | `1` | Above 64 KiB, up to 4 MiB | Packed with other blobs into a shared sidecar file, up to 1 GiB per file by default. | | `Dedicated` | `2` | Above 4 MiB | Stored in its own raw sidecar file. | | `Managed` | `4` or `5` | Out-of-line values when managed storage is enabled | Stored in a Lance-owned object independently of the data file. | Managed storage must be enabled separately. See [Managed blobs](#managed-blobs) for details. `kind=5` identifies a Managed object using an explicitly registered base. Lance uses the default thresholds unless you customize them. Explicitly configured thresholds are stored in the table schema and preserved on append. #### Setup Import the SDK and open a local database. The examples in this section use `db`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./blob_db") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; import { Buffer } from "node:buffer"; import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("./blob_db"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{ Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array, }; use arrow_schema::{DataType, Field, Schema}; use futures_util::TryStreamExt; use lancedb::blob::{BlobRangeRequest, blob}; use lancedb::connect; use lancedb::database::CreateTableMode; use lancedb::query::{ExecutableQuery, QueryBase}; let db = connect("./blob_db").execute().await.unwrap(); ``` #### Define a blob schema Declare a blob column with `lancedb.blob()` in Python and TypeScript, or `blob()` in Rust: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa schema = pa.schema( [ pa.field("id", pa.int64()), pa.field("label", pa.string()), lancedb.blob("image"), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const blobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field("label", new arrow.Utf8()), lancedb.blob("image"), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let blob_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("label", DataType::Utf8, true), blob("image", true), ])); ``` #### Ingest blobs Pass raw bytes for each blob value. In Python, a blob column accepts `bytes`. In TypeScript, it accepts a `Buffer`. The Python example creates two JPEGs with EXIF metadata, which we'll read using a blob handle below. For large Blob imports, [plan batches by payload size](/enterprise/v1-12-0/ingestion/insert#bulk-ingests-into-a-remote-table) and [check the write result before retrying](/enterprise/v1-12-0/ingestion/insert#performance). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from PIL import Image def jpeg_with_make(color, make): image = Image.new("RGB", (8, 8), color=color) exif = Image.Exif() exif[0x010F] = make buf = io.BytesIO() image.save(buf, format="JPEG", exif=exif) return buf.getvalue() tbl = db.create_table( "photos", data=[ {"id": 1, "label": "red", "image": jpeg_with_make("red", "TestCam")}, {"id": 2, "label": "blue", "image": jpeg_with_make("blue", "OtherCam")}, ], schema=schema, mode="overwrite", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const blobTable = await db.createEmptyTable("photos", blobSchema, { mode: "overwrite", }); await blobTable.add([ { id: 1n, label: "door", image: Buffer.from("inline_image_bytes") }, { id: 2n, label: "window", image: Buffer.from("second_image_bytes") }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let blob_table = db .create_empty_table("photos", blob_schema) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); let input_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("label", DataType::Utf8, true), Field::new("image", DataType::LargeBinary, true), ])); let input_batch = RecordBatch::try_new( input_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1_i64, 2_i64])), Arc::new(StringArray::from(vec![Some("door"), Some("window")])), Arc::new(LargeBinaryArray::from_iter_values([ b"inline_image_bytes".as_slice(), b"second_image_bytes".as_slice(), ])), ], ) .unwrap(); let input_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema), ); blob_table.add(input_reader).execute().await.unwrap(); ``` #### Read bytes in query results Python and TypeScript can return blob bytes in query results without collecting `_rowid`. Rust uses [`fetch_blobs`](#multimodal-read-blobs) with row IDs instead. ##### Python `to_list(blob_mode="bytes")` returns the `image` bytes from the `photos` table above: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") ) ``` In the Python SDK, `Table.to_pandas()`, `Table.to_arrow()`, and the query builder methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a `blob_mode` argument. Sync and async query builders support the same modes: | `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | | - | - | - | | `"lazy"` | Default. Plain scans return seekable `BlobFile` handles. Vector, full-text, hybrid, and ordered queries return descriptor dicts. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | | `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | | `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and `to_pandas(blob_mode="descriptions")` use native Arrow conversion without pylance. In Python 0.41.0 and 0.42.0b8, legacy v1 blob bytes conversion through `to_pandas(blob_mode="bytes")` still requires the `pylance` extra. Those clients reject legacy v1 blobs in native Arrow/list/batch bytes queries. Pandas conversions that need the Lance scanner, including plain-scan `"lazy"` handles and scanner-only options, also require pylance. Native Arrow/list/batch conversion and the fetch methods do not require pylance for supported local v2 blob queries. `blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise and in-memory tables raise `NotImplementedError`. On an Enterprise table, `Table.to_pandas()` and `Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in the default `"lazy"` mode because it would open `BlobFile` handles. Query with `blob_mode="descriptions"`, then read bytes with `fetch_blobs` or `fetch_blob_files`. ###### Copy a subset of blob rows SDK descriptors describe the stored payload; they are not the bytes to insert into another table. These APIs return different values: | Read path | Value | | - | - | | Enterprise SQL | Raw payload bytes by default. | | An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | | `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | | A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | To copy rows from an Enterprise table with the SDK, select the rows and fetch their bytes explicitly. The following example copies up to 100 rows from an existing `images` table with an integer `id` and a blob `image` column. Keep the source unchanged during this operation: selection and fetching are separate requests. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa source = db.open_table("images") hits = ( source.search() .where("id < 100") .select(["id"]) .with_row_id(True) .limit(100) .to_arrow() ) payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() subset = db.create_table( "image_subset", schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), ) if hits.num_rows: subset.add([ {"id": image_id, "image": payload} for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) ]) ``` Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches for larger subsets; `fetch_blobs` materializes all requested bytes in memory. For incremental decoding, use `fetch_blob_files` instead. `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs inside a list. Select those columns with `blob_mode="descriptions"`, or leave them out of the projection. Extra keyword arguments on `to_pandas()`, such as `split_blocks` and `self_destruct`, are forwarded to PyArrow. ###### Stream blob results In Python 0.41.0 and 0.42.0b8, `to_batches(blob_mode="bytes")` fetches row-addressable blob v2 payloads one batch at a time and returns them as Arrow `large_binary` values. Legacy v1 blob bytes are not supported by this native batch path in those clients. Iterate over the reader and call `batch.to_pandas()` to convert each batch to a DataFrame without collecting all payloads at once. For sync queries, call `query.to_batches(batch_size=64, blob_mode="bytes")` and iterate with `for`. For async queries, call `await query.to_batches(max_batch_length=64, blob_mode="bytes")` and iterate with `async for`. Sync full-text and hybrid queries do not support `to_batches()`. The default `"lazy"` mode returns blob v2 descriptors and keeps their automatic `_rowid` columns visible for manual fetches. `"descriptions"` returns the five-field descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; explicitly requested row IDs remain visible. Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, including no legacy blobs, blobs inside lists, Enterprise tables, namespace `QueryTable` pushdown, or query shapes that cannot preserve their row results. If concurrent writers can overwrite the table, use a separate reader checked out to a fixed version before querying. Otherwise, an overwrite can invalidate the row IDs used to fetch bytes and raise `ValueError`. ###### Optional pandas examples The lazy-handle calls below require pylance. The query example expects `tbl_async`, `query_vector`, and a `video` column, which the `photos` table does not define. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} df_lazy = tbl.to_pandas() df_bytes = tbl.to_pandas(blob_mode="bytes") df_desc = tbl.to_pandas(blob_mode="descriptions") arrow_bytes = tbl.to_arrow(blob_mode="bytes") df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) ``` Sync and async query builders accept the same `blob_mode` values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} df_lazy = ( tbl.search().where("id = 1").select(["id", "video"]).to_pandas(blob_mode="lazy") ) df_bytes = await ( tbl_async.query() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="bytes") ) df_vec = ( tbl.search(query_vector) .limit(2) .select(["id", "video"]) .to_pandas(blob_mode="bytes", split_blocks=True, self_destruct=True) ) ``` ##### TypeScript In TypeScript, `toArray()` and `toArrow()` accept a `blobMode` option: | `blobMode` | Result | | - | - | | `"descriptions"` | Default. Returns descriptors. | | `"bytes"` | Returns each top-level blob as bytes, or `null` for a null blob. Blobs nested in a struct or list keep their descriptors. | With `"bytes"`, the rows and the bytes come from the same table version. If the table changes while the query runs, the query runs again, up to three times: ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const withBytes = await blobTable .query() .select(["id", "image"]) .toArray({ blobMode: "bytes" }); const firstImage: Uint8Array | null = withBytes[0].image; ``` #### Read blobs on demand Query the rows you want and pass their `_rowid` values to a fetch method. `fetch_blob_files` opens a seekable handle and loads bytes only when you read. The Python example opens the JPEG from the ingest step and reads its EXIF Make tag with Pillow. TypeScript and Rust read the first bytes from the handle. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from PIL import ExifTags rows = tbl.search().where("id = 1").select(["label"]).with_row_id(True).to_list() with tbl.fetch_blob_files("image", [rows[0]["_rowid"]])[0] as image_file: make = Image.open(image_file).getexif().get(ExifTags.Base.Make) print(rows[0]["label"], make) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const rows = await blobTable .query() .select(["id", "label"]) .withRowId() .toArray(); const rowIds = rows.map((row) => row._rowid as bigint); const [image] = await blobTable.fetchBlobFiles("image", [rowIds[0]!]); const header = await image!.readRange(0n, 6n); await image!.close(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let batches = blob_table .query() .with_row_id() .execute() .await .unwrap() .try_collect::<Vec<_>>() .await .unwrap(); let row_ids = batches[0] .column_by_name("_rowid") .unwrap() .as_any() .downcast_ref::<UInt64Array>() .unwrap() .values() .to_vec(); let handles = blob_table .fetch_blob_files("image", &row_ids[..1]) .await .unwrap(); let header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap(); handles[0].as_ref().unwrap().close().await.unwrap(); ``` The other fetch methods load bytes directly: | Need | Python | TypeScript | Rust | | - | - | - | - | | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | | Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | * `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. * `fetch_blob_files` loads bytes when you call `read`, `read_range`, or `read_ranges`. Range reads don't move the file cursor. Null blobs produce null handles. * `fetch_blob_ranges` takes `(row_id, offset, length)` requests and returns one slice per request, in order. A request list can repeat a row to read more than one slice of that blob. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = tbl.search().select(["id"]).with_row_id(True).to_list() row_ids = [row["_rowid"] for row in rows] payloads = tbl.fetch_blobs("image", row_ids) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const payloads = await blobTable.fetchBlobs("image", rowIds); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let payloads = blob_table.fetch_blobs("image", &row_ids).await.unwrap(); ``` Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an exclusive `end`, and Rust takes `start..end` ranges: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} slices = tbl.fetch_blob_ranges("image", [(row_ids[0], 0, 2)]) with tbl.fetch_blob_files("image", [row_ids[0]])[0] as image_file: parts = image_file.read_ranges([(0, 2)]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); const parts = await secondImage!.readRanges([ { start: 0n, end: 6n }, { start: 7n, end: 12n }, ]); await secondImage!.close(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let slices = blob_table .fetch_blob_ranges( "image", [ BlobRangeRequest::new(row_ids[0], 0, 6), BlobRangeRequest::new(row_ids[1], 0, 6), BlobRangeRequest::new(row_ids[1], 7, 5), ], ) .await .unwrap(); let second_handles = blob_table .fetch_blob_files("image", &row_ids[1..2]) .await .unwrap(); let second_image = second_handles[0].as_ref().unwrap(); let parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap(); second_image.close().await.unwrap(); ``` #### Notes and limits Blob fetches fail if any requested row ID is missing or deleted. With stable row IDs enabled, IDs remain valid across compaction. A blob field can sit at the top level of the schema or inside a struct or list. Struct-nested blob columns use dotted paths such as `clip.video` in the fetch APIs. Blobs inside lists can be written and queried as descriptors. A table row ID does not address one list element, so `blob_columns()`, `fetch_blobs`, `fetch_blob_files`, and `blob_mode="bytes"` can't return those bytes. See the Lance [blob guide](https://lance.org/guide/blob/) for the storage format. ### Managed blobs (Blob v2) Set the table schema metadata `lance.blob.managed` to `true` on a table with [`lancedb.blob()`](#multimodal-blob-v2) columns to store small values inline and larger values in managed objects under the table's `_blobs/` directory. Medium values can share a packed object, and large values use a dedicated object. The table owns these objects. You do not upload them separately, keep an object catalog, or delete their files yourself. Compaction preserves each descriptor and its payload object, so merging table fragments does not rewrite the blob payloads. > [!WARNING] > > Use an SDK and Enterprise deployment that support Blob v2 Managed storage. > Upgrade every reader, writer, and maintenance worker before activating Managed > blobs on a table, and reopen existing table handles after the upgrade. Older > clients cannot safely maintain a table containing Managed blobs. #### Write and read blobs This example uses a local connection. The same schema, `add`, query, and `fetch_blobs` calls work with an Enterprise database connection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa db = lancedb.connect("./media") table = db.create_table( "images", schema=pa.schema([ pa.field("id", pa.int64(), nullable=False), lancedb.blob("image"), ], metadata={"lance.blob.managed": "true"}), ) table.add([ {"id": 1, "image": b""}, {"id": 2, "image": bytes(range(256)) * 400}, {"id": 3, "image": None}, ]) # Query descriptors first, then fetch only the selected rows' payloads. hits = ( table.search() .where("id <= 2") .select(["id", "image"]) .with_row_id(True) .to_arrow() ) images = table.fetch_blobs("image", hits).to_pylist() by_id = dict(zip(hits["id"].to_pylist(), images, strict=True)) assert by_id[1] == b"" assert len(by_id[2]) == 102400 ``` `fetch_blobs` materializes the selected payloads in memory, so fetch bounded batches when blobs are large. Row IDs belong to their table and snapshot. Keep descriptors opaque in application code, because their representation can differ between inline values and Managed objects. #### Derived blobs and maintenance Enterprise Functions can consume blob columns and return new blobs. Their output payloads are managed by the destination table. With published Embedded packages, derive blob values in your application and write them to the table. SQL computed-column declaration and refresh require an experimental source build. Deleting a row or replacing its blob does not immediately remove the old payload: retained table versions may still reference it. [Garbage Collection](/enterprise/v1-12-0/maintenance/cleanup#managed-blobs) reclaims objects after those references expire. A packed object remains while any of its contained blobs is still referenced. ### Legacy large-binary blobs Use [`lancedb.blob()`](#multimodal-blob-v2) for new tables. The sections below cover existing tables that use the V1 large-binary Blob API (`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and `DataType::LargeBinary` in Rust with `{"lance-encoding:blob": "true"}` field metadata). Changing a field's metadata alone does not migrate an existing V1 column to Blob v2. #### 1. Define a blob schema V1 blob columns use a `large_binary` field marked with `{"lance-encoding:blob": "true"}` metadata: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa # Define schema with Blob API metadata for lazy loading schema = pa.schema( [ pa.field("id", pa.int64()), pa.field( "video", pa.large_binary(), metadata={"lance-encoding:blob": "true"}, # Enable Blob API ), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const legacyBlobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "video", new arrow.LargeBinary(), true, new Map([["lance-encoding:blob", "true"]]), ), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let legacy_blob_metadata = HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]); let legacy_blob_schema = Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("video", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata), ]); ``` #### 2. Ingest large blobs Write raw bytes to a V1 blob column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./blob_db") # Create sample data data = [ {"id": 1, "video": b"fake_video_bytes_1"}, {"id": 2, "video": b"fake_video_bytes_2"}, ] # Create the table tbl = db.create_table("videos", data=data, schema=schema) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const legacyBlobData = lancedb.makeArrowTable( [ { id: 1, video: Buffer.from("fake_video_bytes_1") }, { id: 2, video: Buffer.from("fake_video_bytes_2") }, ], { schema: legacyBlobSchema }, ); const legacyBlobTable = await db.createTable( "legacy_videos", legacyBlobData, { mode: "overwrite", }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let legacy_blob_rows = vec![ (1_i64, b"fake_video_bytes_1".to_vec()), (2_i64, b"fake_video_bytes_2".to_vec()), ]; let legacy_blob_schema = Arc::new(legacy_blob_schema); let legacy_blob_batch = RecordBatch::try_new( legacy_blob_schema.clone(), vec![ Arc::new(Int64Array::from_iter_values( legacy_blob_rows.iter().map(|row| row.0), )), Arc::new(LargeBinaryArray::from_iter_values( legacy_blob_rows.iter().map(|row| row.1.as_slice()), )), ], ) .unwrap(); let legacy_blob_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema), ); let legacy_blob_table = db .create_table("legacy_videos", legacy_blob_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### 3. Convert blob tables to pandas On LanceDB Embedded tables with V1 blob columns, `to_pandas()` in Python accepts `blob_mode` (`"lazy"`, `"bytes"`, or `"descriptions"`). Enterprise tables raise `NotImplementedError`, and `"bytes"` is not supported on in-memory tables. Extra keyword arguments such as `split_blocks` or `self_destruct` are forwarded to the PyArrow / Lance pandas conversion: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Default: blob columns come back lazily df_lazy = tbl.to_pandas() # Materialize blob bytes eagerly df_bytes = tbl.to_pandas(blob_mode="bytes") # Return descriptors instead of payloads df_desc = tbl.to_pandas(blob_mode="descriptions") # Forward extra kwargs to PyArrow's to_pandas df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) ``` On query builders with V1 blob columns, plain scans support `"lazy"`, `"bytes"`, and `"descriptions"`. Vector, FTS, hybrid, and ordered queries cannot materialize V1 blob columns through `to_pandas()`, so omit those columns from the projection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Plain scan query: blob_mode is supported end to end df_lazy = ( tbl.search() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="lazy") ) # Same call shape works on async query builders df_bytes = await ( tbl_async.query() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="bytes") ) # Vector / FTS / hybrid queries can't materialize blob columns, # so omit them from the projection df_vec = ( tbl.search(query_vector) .limit(10) .select(["id", "vector"]) .to_pandas(split_blocks=True, self_destruct=True) ) ``` ### Store binary data Use a `binary` column when the query should return the raw bytes. Declare it as `pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust. #### 1. Setup and imports Import LanceDB and Arrow in your SDK. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io import lancedb import numpy as np import pyarrow as pa from PIL import Image ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; import { Buffer } from "node:buffer"; import * as lancedb from "@lancedb/lancedb"; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; use std::sync::Arc; use arrow_array::types::Float32Type; use arrow_array::{ Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, }; use arrow_schema::{DataType, Field, Schema}; use futures_util::TryStreamExt; use lancedb::connect; use lancedb::database::CreateTableMode; use lancedb::query::{ExecutableQuery, QueryBase}; ``` #### 2. Prepare data Encode each image or file into raw bytes before writing. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def create_dummy_image(color): img = Image.new("RGB", (100, 100), color=color) buf = io.BytesIO() img.save(buf, format="PNG") return buf.getvalue() data = [ { "id": 1, "filename": "red_square.png", "vector": np.random.rand(128).astype(np.float32), "image_blob": create_dummy_image("red"), "label": "red", }, { "id": 2, "filename": "blue_square.png", "vector": np.random.rand(128).astype(np.float32), "image_blob": create_dummy_image("blue"), "label": "blue", }, ] ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const createDummyImage = (color: string): Uint8Array => { const pngHeader = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]); return Buffer.concat([Buffer.from(pngHeader), Buffer.from(color, "utf8")]); }; const data = [ { id: 1, filename: "red_square.png", vector: Array.from({ length: 128 }, (_, i) => (i % 16) / 16), image_blob: createDummyImage("red"), label: "red", }, { id: 2, filename: "blue_square.png", vector: Array.from({ length: 128 }, (_, i) => ((i + 8) % 16) / 16), image_blob: createDummyImage("blue"), label: "blue", }, ]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let create_dummy_image = |color: u8| -> Vec<u8> { let mut png_like = vec![137, 80, 78, 71, 13, 10, 26, 10]; png_like.push(color); png_like }; let data = vec![ ( 1_i32, "red_square.png", vec![0.1_f32; 128], create_dummy_image(1), "red", ), ( 2_i32, "blue_square.png", vec![0.2_f32; 128], create_dummy_image(2), "blue", ), ]; ``` #### 3. Define the schema Declare the schema explicitly so Arrow and LanceDB store the field as `binary` instead of inferring a string or integer list. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} schema = pa.schema( [ pa.field("id", pa.int32()), pa.field("filename", pa.string()), pa.field("vector", pa.list_(pa.float32(), 128)), pa.field("image_blob", pa.binary()), pa.field("label", pa.string()), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schema = new arrow.Schema([ new arrow.Field("id", new arrow.Int32()), new arrow.Field("filename", new arrow.Utf8()), new arrow.Field( "vector", new arrow.FixedSizeList( 128, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("image_blob", new arrow.Binary()), new arrow.Field("label", new arrow.Utf8()), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema = Schema::new(vec![ Field::new("id", DataType::Int32, false), Field::new("filename", DataType::Utf8, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), Field::new("image_blob", DataType::Binary, false), Field::new("label", DataType::Utf8, false), ]); ``` #### 4. Ingest data Create the table from the rows and schema. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("images", data=data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const multimodalData = lancedb.makeArrowTable(data, { schema }); const tbl = await db.createTable("images", multimodalData, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema = Arc::new(schema); let image_batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))), Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( data.iter() .map(|row| Some(row.2.iter().copied().map(Some).collect::<Vec<_>>())), 128, ), ), Arc::new(BinaryArray::from_iter_values( data.iter().map(|row| row.3.as_slice()), )), Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))), ], ) .unwrap(); let image_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()), ); let table = db .create_table("images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### Retrieve binary data When you search the table, select the `binary` column alongside your metadata columns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_vector = np.random.rand(128).astype(np.float32) results = tbl.search(query_vector).limit(1).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const queryVector = Array.from({ length: 128 }, (_, i) => (i % 16) / 16); const results = await tbl.search(queryVector).limit(1).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let query_vector = vec![0.1_f32; 128]; let results = table .query() .nearest_to(query_vector) .unwrap() .limit(1) .execute() .await .unwrap() .try_collect::<Vec<_>>() .await .unwrap(); ``` #### Convert bytes back to objects Decode the returned bytes into an image or media buffer in your application. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for _, row in results.iterrows(): image_bytes = row["image_blob"] image = Image.open(io.BytesIO(image_bytes)) print(f"Retrieved image: {row['filename']}, Size: {image.size}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for (const row of results) { const imageBytes = row.image_blob as Uint8Array; console.log( `Retrieved image: ${row.filename}, Byte length: ${imageBytes.length}`, ); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for batch in &results { let filenames = batch .column_by_name("filename") .unwrap() .as_any() .downcast_ref::<StringArray>() .unwrap(); let images = batch .column_by_name("image_blob") .unwrap() .as_any() .downcast_ref::<BinaryArray>() .unwrap(); for row in 0..batch.num_rows() { let image_bytes = images.value(row); println!( "Retrieved image: {}, Byte length: {}", filenames.value(row), image_bytes.len() ); } } ``` ### Other modalities For PDFs, audio recordings, and other files, keep searchable fields in separate columns so you can filter rows before fetching blob bytes. ### bfloat16 Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. ## Schema evolution Schema evolution enables non-breaking modifications to a database table's structure (such as adding columns, altering data types, or dropping fields) to adapt to evolving data requirements without service interruptions. LanceDB supports ACID-compliant schema evolution through granular operations (add/alter/drop columns), allowing you to: * Iterate Safely: Modify schemas in production with versioned datasets and backward compatibility * Scale Seamlessly: Handle ML model iterations, regulatory changes, or feature additions * Optimize Continuously: Remove unused fields or enforce new constraints without downtime > [!NOTE] > > In SQL, schema changes are [`ALTER TABLE`](/enterprise/v1-12-0/sql/ddl/table#alter). ### Schema evolution operations LanceDB supports four primary schema evolution operations: 1. **Adding new columns**: Extend your table with additional attributes 2. **Altering existing columns**: Change column names, data types, or nullability 3. **Updating field metadata**: Attach or change per-column Arrow metadata 4. **Dropping columns**: Remove unnecessary columns from your schema > [!TIP] > > Schema evolution operations are applied immediately but do not typically require rewriting all data. However, data type changes may involve more substantial operations. Each schema evolution operation commits a new table version and returns status metadata such as the committed `version`. Run these operations from a mutable table handle; if you checked out an older version for reads, call `checkout_latest` / `checkoutLatest` before modifying the schema. ### Add new columns You can add new columns to a table with the [`add_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.add_columns) method in Python, [`addColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#addcolumns) in TypeScript/JavaScript, or `add_columns` in Rust. New columns are populated based on SQL expressions you provide. On local tables, the Python SDK also accepts precomputed values from DataFrames and Arrow readers; see [Create a computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column#computed-vs-transforms) for the supported inputs and row-order requirements. #### Set up the example table First, let's create a sample table with product data to demonstrate schema evolution: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_add_example", data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaAddData = [ { id: 1, name: "Laptop", price: 1200.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 3, name: "Headphones", price: 150.0, vector: Array.from({ length: 128 }, () => Math.random()), }, ]; const schemaAddTable = await db.createTable( "schema_evolution_add_example", schemaAddData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_add_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Float64, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_add_batch = RecordBatch::try_new( schema_add_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone", "Headphones"])), Arc::new(Float64Array::from(vec![1200.0, 800.0, 150.0])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128]), Some(vec![Some(0.3_f32); 128]), ], 128, ), ), ], ) .unwrap(); let schema_add_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_add_batch)].into_iter(), schema_add_schema.clone(), )); let schema_add_table = db .create_table("schema_evolution_add_example", schema_add_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` > [!NOTE] > > Columns derived from existing data (SQL expressions over other columns) are > covered in [Create a computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column), > because deriving values is a feature-engineering job rather than a schema one. #### Add columns with default values Add boolean columns with default values for status tracking: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a stock status column with default value table.add_columns({"in_stock": "cast(true as boolean)"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a stock status column with default value await schemaAddTable.addColumns([ { name: "in_stock", valueSql: "cast(true as boolean)", }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a stock status column with default value schema_add_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "in_stock".to_string(), "cast(true as boolean)".to_string(), )]), None, ) .await .unwrap(); ``` #### Add nullable columns Add timestamp columns that can contain NULL values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a nullable timestamp column table.add_columns({"last_ordered": "cast(NULL as timestamp)"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a nullable timestamp column await schemaAddTable.addColumns([ { name: "last_ordered", valueSql: "cast(NULL as timestamp)", }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a nullable timestamp column schema_add_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "last_ordered".to_string(), "cast(NULL as timestamp)".to_string(), )]), None, ) .await .unwrap(); ``` > [!WARNING] > > When adding columns that should contain NULL values, be sure to cast the NULL to the appropriate type, e.g., `cast(NULL as timestamp)`. ### Alter existing columns You can alter columns using the [`alter_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.alter_columns) method in Python, [`alterColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#altercolumns) in TypeScript/JavaScript, or `alter_columns` in Rust. This allows you to: * Rename a column * Change a column's data type * Modify nullability (whether a column can contain NULL values) #### Set up the example table Create a table with a custom schema to demonstrate column alterations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "schema_evolution_alter_example" if data is None: data = [ { "id": 1, "name": "Laptop", "price": 1200, "discount_price": 1080.0, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800, "discount_price": 720.0, "vector": np.random.random(128).tolist(), }, ] schema = pa.schema( { "id": pa.int64(), "name": pa.string(), "price": pa.int32(), "discount_price": pa.float64(), "vector": pa.list_(pa.float32(), 128), } ) table = db.create_table(table_name, data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaAlter = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field("name", new arrow.Utf8()), new arrow.Field("price", new arrow.Int32()), new arrow.Field("discount_price", new arrow.Float64()), new arrow.Field( "vector", new arrow.FixedSizeList( 128, new arrow.Field("item", new arrow.Float32(), true), ), ), ]); const schemaAlterData = lancedb.makeArrowTable( [ { id: 1, name: "Laptop", price: 1200, discount_price: 1080.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800, discount_price: 720.0, vector: Array.from({ length: 128 }, () => Math.random()), }, ], { schema: schemaAlter }, ); const schemaAlterTable = await db.createTable( "schema_evolution_alter_example", schemaAlterData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_alter_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Int32, false), Field::new("discount_price", DataType::Float64, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_alter_batch = RecordBatch::try_new( schema_alter_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone"])), Arc::new(Int32Array::from(vec![1200, 800])), Arc::new(Float64Array::from(vec![1080.0, 720.0])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128])], 128, ), ), ], ) .unwrap(); let schema_alter_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_alter_batch)].into_iter(), schema_alter_schema.clone(), )); let schema_alter_table = db .create_table("schema_evolution_alter_example", schema_alter_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### Rename columns Change column names to better reflect their purpose: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Rename discount_price to sale_price table.alter_columns({"path": "discount_price", "rename": "sale_price"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename discount_price to sale_price await schemaAlterTable.alterColumns([ { path: "discount_price", rename: "sale_price" }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename discount_price to sale_price schema_alter_table .alter_columns(&[ColumnAlteration::new("discount_price".to_string()) .rename("sale_price".to_string())]) .await .unwrap(); ``` #### Change data types Convert column data types for better performance or compatibility: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Change price from int32 to int64 for larger numbers table.alter_columns({"path": "price", "data_type": pa.int64()}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Change price from int32 to int64 for larger numbers await schemaAlterTable.alterColumns([ { path: "price", dataType: new arrow.Int64() }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Change price from int32 to int64 for larger numbers schema_alter_table .alter_columns(&[ColumnAlteration::new("price".to_string()).cast_to(DataType::Int64)]) .await .unwrap(); ``` #### Make columns nullable You can alter columns to contain NULL values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Make the name column nullable table.alter_columns({"path": "name", "nullable": True}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Make the name column nullable await schemaAlterTable.alterColumns([{ path: "name", nullable: true }]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Make the name column nullable schema_alter_table .alter_columns(&[ColumnAlteration::new("name".to_string()).set_nullable(true)]) .await .unwrap(); ``` Changing a column to nullable affects future writes and merges too: missing values are accepted only when the target column is nullable. #### Multiple changes at once Apply several alterations in a single operation: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Rename, change type, and make nullable in one operation table.alter_columns( { "path": "sale_price", "rename": "final_price", "data_type": pa.float64(), "nullable": True, } ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename, change type, and make nullable in one operation await schemaAlterTable.alterColumns([ { path: "sale_price", rename: "final_price", dataType: new arrow.Float64(), nullable: true, }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename, change type, and make nullable in one operation schema_alter_table .alter_columns(&[ColumnAlteration::new("sale_price".to_string()) .rename("final_price".to_string()) .cast_to(DataType::Float64) .set_nullable(true)]) .await .unwrap(); ``` #### Expression-based type changes For transformations that are not simple casts (for example, converting `"$100"` to an integer), use a SQL-expression column add, then drop and rename: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # For custom transforms, create a new column from a SQL expression. expression_table = db.create_table( "schema_evolution_expression_example", [{"id": 1, "price_text": "$100"}], mode="overwrite", ) expression_table.add_columns( {"price_numeric": "cast(replace(price_text, '$', '') as int)"} ) expression_table.drop_columns(["price_text"]) expression_table.alter_columns({"path": "price_numeric", "rename": "price"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // For custom transforms, create a new column from a SQL expression. const expressionTable = await db.createTable( "schema_evolution_expression_example", [{ id: 1, price_text: "$100" }], { mode: "overwrite" }, ); await expressionTable.addColumns([ { name: "price_numeric", valueSql: "cast(replace(price_text, '$', '') as int)", }, ]); await expressionTable.dropColumns(["price_text"]); await expressionTable.alterColumns([ { path: "price_numeric", rename: "price" }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // For custom transforms, create a new column from a SQL expression. let expression_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("price_text", DataType::Utf8, false), ])); let expression_batch = RecordBatch::try_new( expression_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1])), Arc::new(StringArray::from(vec!["$100"])), ], ) .unwrap(); let expression_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(expression_batch)].into_iter(), expression_schema.clone(), )); let expression_table = db .create_table("schema_evolution_expression_example", expression_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); expression_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "price_numeric".to_string(), "cast(replace(price_text, '$', '') as int)".to_string(), )]), None, ) .await .unwrap(); expression_table.drop_columns(&["price_text"]).await.unwrap(); expression_table .alter_columns(&[ColumnAlteration::new("price_numeric".to_string()) .rename("price".to_string())]) .await .unwrap(); ``` #### Alter embedding types and dimensions It's quite common to need to change an embedding column's schema, in case a new model becomes available with a different embedding dimension. * In Python, the example shows an in-place type update when the cast is compatible. * In TypeScript and Rust, the example shows a dimension change (`384 -> 1024`), which cannot be cast in-place. For dimension changes, use this 3-step pattern: add a new column with the target type, drop the old column, then rename the new column to the original name. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ { "id": 1, "embedding": np.random.random(vector_dim).tolist(), }, ] table = db.create_table(table_name, data, mode="overwrite") table.alter_columns( dict(path="embedding", data_type=pa.list_(pa.float32(), vector_dim)) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const oldDim = 384; const newDim = 1024; const vectorSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "embedding", new arrow.FixedSizeList( oldDim, new arrow.Field("item", new arrow.Float16(), true), ), true, ), ]); const vectorData = lancedb.makeArrowTable( [{ id: 1, embedding: Array.from({ length: oldDim }, () => Math.random()) }], { schema: vectorSchema }, ); const vectorTable = await db.createTable("vector_alter_example", vectorData, { mode: "overwrite", }); // Changing FixedSizeList dimensions (384 -> 1024) is not supported via alterColumns. // Use addColumns + dropColumns + alterColumns(rename) to replace the column. await vectorTable.addColumns([ { name: "embedding_v2", valueSql: `arrow_cast(NULL, 'FixedSizeList(${newDim}, Float16)')`, }, ]); await vectorTable.dropColumns(["embedding"]); await vectorTable.alterColumns([{ path: "embedding_v2", rename: "embedding" }]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let old_dim = 384; let new_dim = 1024; let vector_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new( "embedding", DataType::FixedSizeList( Arc::new(Field::new("item", DataType::Float32, true)), old_dim, ), true, ), ])); let vector_batch = RecordBatch::try_new( vector_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1_f32); old_dim as usize])], old_dim, ), ), ], ) .unwrap(); let vector_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(vector_batch)].into_iter(), vector_schema.clone())); let vector_table = db .create_table("vector_alter_example", vector_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); // Changing FixedSizeList dimensions (384 -> 1024) is not supported via alter_columns. // Use add_columns + drop_columns + alter_columns(rename) to replace the column. vector_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "embedding_v2".to_string(), format!("arrow_cast(NULL, 'FixedSizeList({}, Float32)')", new_dim), )]), None, ) .await .unwrap(); vector_table.drop_columns(&["embedding"]).await.unwrap(); vector_table .alter_columns(&[ColumnAlteration::new("embedding_v2".to_string()) .rename("embedding".to_string())]) .await .unwrap(); ``` > [!WARNING] > > **`FixedSizeList` Dimension Changes in TypeScript and Rust** > > `alterColumns` / `alter_columns` can cast between compatible types, but changing `FixedSizeList` dimensions (for example `384 -> 1024`) is not a compatible cast. > For such cases, use `addColumns` / `add_columns` (with `arrow_cast`), then `dropColumns` / `drop_columns`, then rename the replacement column. > [!WARNING] > > Changing data types requires rewriting the column data and may be resource-intensive for large tables. Renaming columns or changing nullability is more efficient as it only updates metadata. ### Update field metadata Each column in a LanceDB table can carry a small key/value map of Arrow field metadata, which is useful for annotating columns with units, provenance, PII flags, embedding model versions, or any other schema-level context your application needs. Use [`update_field_metadata`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.update_field_metadata) in Python, [`updateFieldMetadata`](https://lancedb.github.io/lancedb/js/classes/Table/#updatefieldmetadata) in TypeScript/JavaScript, or `update_field_metadata` in Rust to add, change, or remove these key/value pairs without rewriting the column data. Each call commits a new table version and returns the new `version`. Each update targets one field by **dot-path**: top-level columns are addressed by name (for example `"embedding"`), and nested fields by their full path (for example `"address.zip"`). By default, the keys you pass are **merged** into the field's existing metadata: keys you do not mention are preserved, and passing `None` (Python) or `null` (TypeScript) deletes a key. Set `replace: true` to swap the field's entire metadata map instead of merging. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Set two metadata keys on the `category` field. res = table.update_field_metadata( {"path": "category", "metadata": {"unit": "label", "pii": "false"}} ) print(res.version) # Merge: add a new key, delete one with None, keep the rest. table.update_field_metadata( {"path": "category", "metadata": {"source": "import", "pii": None}} ) # Arrow stores field metadata as bytes. assert table.schema.field("category").metadata == { b"unit": b"label", b"source": b"import", } ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Set two metadata keys on the `category` field. const res = await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { unit: "label", pii: "false" } }, ]); console.log(res.version); // Merge: add a new key, delete one via null, keep the rest. await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { source: "import", pii: null } }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Set two metadata keys on the `category` field. let res = field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("unit", "label") .set("pii", "false")]) .await .unwrap(); println!("version: {}", res.version); // Merge: add a new key, delete one with `.remove`, keep the rest. field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("source", "import") .remove("pii")]) .await .unwrap(); ``` To overwrite a field's metadata entirely instead of merging, set `replace` to `true`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.update_field_metadata( { "path": "category", "metadata": {"owner": "search-team"}, "replace": True, } ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { owner: "search-team" }, replace: true, }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("owner", "search-team") .replace()]) .await .unwrap(); ``` > [!TIP] > > You can pass multiple updates in a single call to change metadata on several fields at once. > Each call commits a single new table version. #### Canonical metadata keys You can use any string as a metadata key. By convention, LanceDB treats keys prefixed with `lancedb:` as canonical. LanceDB Enterprise displays these keys in the UI, and agents can rely on finding this information in a consistent place. Use them when they fit your use case: | Key | Purpose | Example | | - | - | - | | `lancedb:description` | Human-readable description of the field. | `"CLIP embedding of the product image"` | | `lancedb:tag:<name>` | User-defined key/value tag, where the suffix names the tag category. | `"lancedb:tag:model": "clip"` | | `lancedb:status` | Life cycle state of the column: `production`, `candidate`, `deprecated`, or `archived`. | `"lancedb:status": "production"` | > [!NOTE] > > These keys are conventions, not enforced constraints. LanceDB does not validate their values, > but following the conventions keeps your tables consistent with Enterprise tooling. ### Drop columns You can remove columns using the [`drop_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.drop_columns) method in Python, [`dropColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#dropcolumns) in TypeScript/JavaScript, or `drop_columns` in Rust. #### Set Up the example table Create a table with temporary columns that we'll remove: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} if data is None: data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "temp_col1": "X", "temp_col2": 100, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "temp_col1": "Y", "temp_col2": 200, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "temp_col1": "Z", "temp_col2": 300, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_drop_example", data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaDropData = [ { id: 1, name: "Laptop", price: 1200.0, temp_col1: "X", temp_col2: 100, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800.0, temp_col1: "Y", temp_col2: 200, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 3, name: "Headphones", price: 150.0, temp_col1: "Z", temp_col2: 300, vector: Array.from({ length: 128 }, () => Math.random()), }, ]; const schemaDropTable = await db.createTable( "schema_evolution_drop_example", schemaDropData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_drop_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Float64, false), Field::new("temp_col1", DataType::Utf8, false), Field::new("temp_col2", DataType::Int32, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_drop_batch = RecordBatch::try_new( schema_drop_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone", "Headphones"])), Arc::new(Float64Array::from(vec![1200.0, 800.0, 150.0])), Arc::new(StringArray::from(vec!["X", "Y", "Z"])), Arc::new(Int32Array::from(vec![100, 200, 300])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128]), Some(vec![Some(0.3_f32); 128]), ], 128, ), ), ], ) .unwrap(); let schema_drop_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_drop_batch)].into_iter(), schema_drop_schema.clone(), )); let schema_drop_table = db .create_table("schema_evolution_drop_example", schema_drop_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### Drop single columns Remove individual columns that are no longer needed: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remove the first temporary column table.drop_columns(["temp_col1"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the first temporary column await schemaDropTable.dropColumns(["temp_col1"]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the first temporary column schema_drop_table.drop_columns(&["temp_col1"]).await.unwrap(); ``` #### Drop multiple columns Remove several columns at once for efficiency: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remove the second temporary column table.drop_columns(["temp_col2"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the second temporary column await schemaDropTable.dropColumns(["temp_col2"]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the second temporary column schema_drop_table.drop_columns(&["temp_col2"]).await.unwrap(); ``` > [!WARNING] > > Dropping a column changes the latest version only. Until > [cleanup](/enterprise/v1-12-0/maintenance/cleanup) prunes the versions from before the drop, > [restoring](#versioning) one of them brings the column and its values back, > along with the rest of the table as it was then. Once those versions are > pruned, the drop cannot be undone, so check before dropping a column you may > need. ## Versioning This page shows the core table-versioning APIs used in the code snippets for Python, TypeScript, and Rust. Each operation below maps directly to methods shown in the examples. ### Basic Versioning Example Let's create a table with sample data to demonstrate LanceDB's versioning capabilities: #### Set Up the Table First, let's create a table with some sample data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "quotes_versioning_example" data = [ {"id": 1, "author": "Richard", "quote": "Wubba Lubba Dub Dub!"}, {"id": 2, "author": "Morty", "quote": "Rick, what's going on?"}, { "id": 3, "author": "Richard", "quote": "I turned myself into a pickle, Morty!", }, ] # Define schema schema = pa.schema( [ pa.field("id", pa.int64()), pa.field("author", pa.string()), pa.field("quote", pa.string()), ] ) table = db.create_table(table_name, data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tableName = "quotes_versioning_example"; const data = [ { id: 1, author: "Richard", quote: "Wubba Lubba Dub Dub!" }, { id: 2, author: "Morty", quote: "Rick, what's going on?" }, { id: 3, author: "Richard", quote: "I turned myself into a pickle, Morty!", }, ]; const table = await db.createTable(tableName, data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table_name = "quotes_versioning_example"; let data = vec![ (1, "Richard", "Wubba Lubba Dub Dub!"), (2, "Morty", "Rick, what's going on?"), (3, "Richard", "I turned myself into a pickle, Morty!"), ]; let table = db .create_table(table_name, make_quotes_reader(data)) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` **Rust helper used in this page** ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fn make_quotes_reader(rows: Vec<(i64, &str, &str)>) -> Box<dyn RecordBatchReader + Send> { let ids: Vec<i64> = rows.iter().map(|(id, _, _)| *id).collect(); let authors: Vec<&str> = rows.iter().map(|(_, author, _)| *author).collect(); let quotes: Vec<&str> = rows.iter().map(|(_, _, quote)| *quote).collect(); let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("author", DataType::Utf8, false), Field::new("quote", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from(ids)), Arc::new(StringArray::from(authors)), Arc::new(StringArray::from(quotes)), ], ) .unwrap(); let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); Box::new(reader) } ``` #### Check Initial Version After creating the table, let's check the initial version information: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() current_version = table.version print(f"Number of versions after creation: {len(versions)}") print(f"Current version: {current_version}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const versions = await table.listVersions(); const currentVersion = await table.version(); console.log(`Number of versions after creation: ${versions.length}`); console.log(`Current version: ${currentVersion}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let versions = table.list_versions().await.unwrap(); let current_version = table.version().await.unwrap(); println!("Number of versions after creation: {}", versions.len()); println!("Current version: {}", current_version); ``` ### Modify Data When you modify data through operations like update or delete, LanceDB automatically creates new versions. #### Update Existing Data Let's update some existing records to see versioning in action: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.update(where="author='Richard'", values={"author": "Richard Daniel Sanchez"}) rows_after_update = table.count_rows("author = 'Richard Daniel Sanchez'") print(f"Rows updated to Richard Daniel Sanchez: {rows_after_update}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.update({ where: "author = 'Richard'", values: { author: "Richard Daniel Sanchez" }, }); const rowsAfterUpdate = await table.countRows( "author = 'Richard Daniel Sanchez'", ); console.log(`Rows updated to Richard Daniel Sanchez: ${rowsAfterUpdate}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .update() .only_if("author = 'Richard'") .column("author", "'Richard Daniel Sanchez'") .execute() .await .unwrap(); let rows_after_update = table .count_rows(Some("author = 'Richard Daniel Sanchez'".to_string())) .await .unwrap(); println!( "Rows updated to Richard Daniel Sanchez: {}", rows_after_update ); ``` #### Add New Data Now let's add more records to the table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} more_data = [ { "id": 4, "author": "Richard Daniel Sanchez", "quote": "That's the way the news goes!", }, {"id": 5, "author": "Morty", "quote": "Aww geez, Rick!"}, ] table.add(more_data) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const moreData = [ { id: 4, author: "Richard Daniel Sanchez", quote: "That's the way the news goes!", }, { id: 5, author: "Morty", quote: "Aww geez, Rick!" }, ]; await table.add(moreData); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let more_data = vec![ (4, "Richard Daniel Sanchez", "That's the way the news goes!"), (5, "Morty", "Aww geez, Rick!"), ]; table .add(make_quotes_reader(more_data)) .execute() .await .unwrap(); ``` #### Check Version Changes Let's see how the versions have changed after our modifications: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() version_count_after_mod = len(versions) version_after_mod = table.version print(f"Number of versions after modifications: {version_count_after_mod}") print(f"Current version: {version_after_mod}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const versionsAfterMod = await table.listVersions(); const versionCountAfterMod = versionsAfterMod.length; const versionAfterMod = await table.version(); console.log( `Number of versions after modifications: ${versionCountAfterMod}`, ); console.log(`Current version: ${versionAfterMod}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let versions_after_mod = table.list_versions().await.unwrap(); let version_count_after_mod = versions_after_mod.len(); let version_after_mod = table.version().await.unwrap(); println!( "Number of versions after modifications: {}", version_count_after_mod ); println!("Current version: {}", version_after_mod); ``` ### Rollback to Previous Versions LanceDB supports fast rollbacks to any previous version without data duplication. #### View All Versions First, let's see all the versions we've created: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() for v in versions: print(f"Version {v['version']}, created at {v['timestamp']}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const allVersions = await table.listVersions(); for (const v of allVersions) { console.log(`Version ${v.version}, created at ${v.timestamp}`); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let all_versions = table.list_versions().await.unwrap(); for v in &all_versions { println!("Version {}, created at {}", v.version, v.timestamp); } ``` #### Restore a Version Snapshot Now let's restore a captured version snapshot: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.restore(version_after_mod) versions = table.list_versions() version_count_after_rollback = len(versions) print(f"Total number of versions after rollback: {version_count_after_rollback}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.checkout(versionAfterMod); await table.restore(); const versionsAfterRollback = await table.listVersions(); const versionCountAfterRollback = versionsAfterRollback.length; console.log( `Total number of versions after rollback: ${versionCountAfterRollback}`, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout(version_after_mod).await.unwrap(); table.restore().await.unwrap(); let versions_after_rollback = table.list_versions().await.unwrap(); let version_count_after_rollback = versions_after_rollback.len(); println!( "Total number of versions after rollback: {}", version_count_after_rollback ); ``` ### Tag-Based Versioning Numeric table versions like `v3` or `v17` are precise but hard to remember. Tags let you attach human-readable labels (e.g., `"prod"`, `"baseline"`, `"q3-evaluation"`) to specific versions and check those out by name. They are conceptually similar to git tags, and unlike numeric versions, **tagged versions are never pruned**. A tagged version that is older than the retention window and is not the latest stops cleanup instead (see the cleanup note at the bottom of this page). The tags API supports the standard CRUD operations (create, list, update, delete), plus checking out by tag name. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a tag pointing at a specific version table.tags.create("baseline", 1) table.tags.create("with-edits", table.version) # List all tags on this table print(table.tags.list()) # Look up the version a tag points at print(table.tags.get_version("baseline")) # Move an existing tag to a different version table.tags.update("baseline", 2) # Check out a version by tag name table.checkout("baseline") print(table.version) # Delete a tag (does not delete the underlying version) table.tags.delete("with-edits") # Return to the latest version table.checkout_latest() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tags = await tagsTable.tags(); // Create a tag pointing at a specific version await tags.create("baseline", 1); await tags.create("with-edits", await tagsTable.version()); // List all tags on this table console.log(await tags.list()); // Look up the version a tag points at console.log(await tags.getVersion("baseline")); // Move an existing tag to a different version await tags.update("baseline", 2); // Check out a version by tag name await tagsTable.checkout("baseline"); console.log(await tagsTable.version()); // Delete a tag (does not delete the underlying version) await tags.delete("with-edits"); // Return to the latest version await tagsTable.checkoutLatest(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let mut tags = tags_table.tags().await.unwrap(); // Create a tag pointing at a specific version tags.create("baseline", 1).await.unwrap(); let current_version = tags_table.version().await.unwrap(); tags.create("with-edits", current_version).await.unwrap(); // List all tags on this table let all_tags = tags.list().await.unwrap(); println!("Tags: {:?}", all_tags); // Look up the version a tag points at let baseline_version = tags.get_version("baseline").await.unwrap(); println!("baseline -> v{}", baseline_version); // Move an existing tag to a different version tags.update("baseline", 2).await.unwrap(); // Check out a version by tag name (separate method in Rust) tags_table.checkout_tag("baseline").await.unwrap(); println!("Current version: {}", tags_table.version().await.unwrap()); // Delete a tag (does not delete the underlying version) tags.delete("with-edits").await.unwrap(); // Return to the latest version tags_table.checkout_latest().await.unwrap(); ``` > [!NOTE] > > Deleting a tag only removes the label, not the version it points to. After > deletion, the underlying table version becomes eligible for cleanup again. ### Delete Data From the Table Let's demonstrate how deletions also create new versions: #### Go Back to Latest Version First, let's return to the latest version: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout_latest() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.checkoutLatest(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout_latest().await.unwrap(); ``` #### Delete Data Now let's delete some data to see how it affects versioning: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.delete("author = 'Morty'") rows_after_deletion = table.count_rows() print(f"Number of rows after deletion: {rows_after_deletion}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.delete("author = 'Morty'"); const rowsAfterDeletion = await table.countRows(); console.log(`Number of rows after deletion: ${rowsAfterDeletion}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.delete("author = 'Morty'").await.unwrap(); let rows_after_deletion = table.count_rows(None).await.unwrap(); println!("Number of rows after deletion: {}", rows_after_deletion); ``` #### Version History and Operations On a fresh table, the snippets in this guide produce this version sequence: 1. `v1`: create table (`create_table` / `createTable` / `create_table`) 2. `v2`: update rows (`update`) 3. `v3`: add rows (`add`) 4. `v4`: restore snapshot (`restore`) from `version_after_mod`/`versionAfterMod` 5. `v5`: delete rows (`delete`) Read-only and checkout operations shown here (`list_versions`/`listVersions`, `version`, `checkout`, `checkout_latest`/`checkoutLatest`) do not create new versions. The version metadata fields can differ by backend. Direct table-backed version listing exposes a timestamp, while namespace-backed listing may expose fields such as `manifest_path`, `manifest_size`, `e_tag`, and `timestamp_millis`. In deployments that use managed versioning, prefer the table version APIs exposed by LanceDB Enterprise or the namespace service instead of mixing in lower-level Lance file operations. > [!NOTE] > > **System Operations** > > System operations like `optimize()`, index updates, and table compaction also increment table version numbers. > In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), > which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background > when its configuration enables [cleanup](/enterprise/v1-12-0/maintenance/cleanup); `optimize()` is not available there. > > **Tagged versions are never pruned.** A version with a tag pointing at it is > retained regardless of age. When a tagged version is older than the retention window and > is not the latest, cleanup refuses to run instead of pruning around it: `optimize()` raises > an error naming the tag and prunes nothing. A tag on the latest version does not cause > this, but `optimize()` compacts before it prunes, and compacting commits a new version > whenever it merges files, so a tag on what was the latest version can become an older > one by the time cleanup runs; the error then comes after compacting, and the index > update does not run. To let cleanup proceed, [move the tag](#versioning-tag-based-versioning) > to a version inside the retention window, delete it, or widen the window. ## Privileges A table's `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl ``` See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Views Source: https://docs.lancedb.com/enterprise/v1-12-0/management/view A saved query, evaluated when read. **Applies to:** Embedded ❌, Enterprise ✅ A view saves a query that you can refer to by name. Reading the view executes that query against the source tables, using their read-consistency behavior. Views do not store a separate copy of the result. It is the counterpart to a [materialized view](/enterprise/v1-12-0/management/materialized-view), which stores rows and is brought up to date by a refresh. Both are [catalog objects](/enterprise/v1-12-0/basics/catalog) defined by a query; choose a materialized view when you need to store and reuse the result. | | View | Materialized view | | - | - | - | | Stores | the query | the rows | | Freshness | follows source-table reads | as of the last refresh | | Read cost | executes the saved query | queries the stored result | | Write cost | none | a refresh | Views are created in LanceDB Enterprise, either in SQL over the [Flight SQL endpoint](/enterprise/v1-12-0/sql#connecting) or with the SDKs' `create_view` / `createView`, which send the query to the deployment. Either way, the deployment must have views enabled. See [View](/enterprise/v1-12-0/sql/ddl/view) for `CREATE VIEW`, `DROP VIEW`, and listing. ## Privileges A view's `OWNERSHIP` and `SELECT` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT ON VIEW dashboard TO ROLE analysts ``` See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # SQL data types Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/data-types How Lance columns appear to SQL, including the types SQL has no name for. **Applies to:** Embedded ❌, Enterprise ✅ There is no SQL type layer over Lance storage. The table provider hands DataFusion the dataset's Arrow schema directly, so a column is the same object to the query engine as it is to the format. The consequence is that SQL type names here are **spellings of Arrow types**, not a system that maps onto them. [Data types](/enterprise/v1-12-0/sql/data-types) documents the storage side; this page covers what changes when you reach a column from SQL. ## The Arrow types a column can be | Category | Types | | - | - | | Null | `null` | | Boolean | `bool` | | Integer | `int8`, `int16`, `int32`, `int64` and their `uint` counterparts | | Floating point | `float16`, `float32`, `float64` | | String | `utf8`, `large_utf8` | | Binary | `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp` (with or without timezone), `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | | Dictionary | `dictionary(key, value)` | Two limits are worth stating because they surface as schema errors rather than as documentation: * A `map` with `keys_sorted = true` is rejected. Sorted-key maps do not survive the round trip through the Python bindings, so they are refused rather than silently unsorted. * Not every type is legal as a `fixed_size_list` child. The vector case is, which is what matters in practice. ## SQL names for Arrow types | SQL | Arrow | | - | - | | `BOOLEAN` | `Boolean` | | `TINYINT` `SMALLINT` `INT` `BIGINT` | `Int8` `Int16` `Int32` `Int64` | | `UTINYINT` … `UBIGINT` | the unsigned counterparts | | `REAL` / `FLOAT` | `Float32` | | `DOUBLE` | `Float64` | | `VARCHAR` / `TEXT` / `STRING` | `Utf8` | | `BYTEA` / `BINARY` | `Binary` | | `DATE` | `Date32` | | `TIME` | `Time64` | | `TIMESTAMP` | `Timestamp`, with or without a timezone | | `INTERVAL` | `Interval` | | `STRUCT` / `LIST` / `MAP` | the nested equivalents | DataFusion's [type reference](https://datafusion.apache.org/user-guide/sql/data_types.html) describes the full mapping. ## Types SQL has no name for Some column kinds have no SQL type name. ### Vectors A dense vector column has a fixed dimension, commonly represented as `FixedSizeList<Float32, dim>`. Other supported vector element types are possible; inspect the column with [`arrow_typeof`](/enterprise/v1-12-0/sql/dql/scalar-functions#type) rather than assuming Float32. It is selectable and testable for nullness: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents WHERE vector IS NOT NULL ``` > [!WARNING] > > A list representation does not imply that ordinary arithmetic operators > perform vector arithmetic. Use supported distance functions for similarity > calculations. SQL vector search depends on the Enterprise server version and query > plan; see [SQL](/enterprise/v1-12-0/basics/sql#no-vector-sql). ### bfloat16 Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. ## Pseudo-columns Availability depends on the SQL table provider. The ordinary table provider exposes the stored dataset schema; naming a Lance scan metadata field does not make it available as a SQL column. The `fts()` provider adds `_score` to its schema, so `_score` is included in `SELECT * FROM fts(...)`. | Column | Type | | | - | - | - | | `_rowid` | `UInt64` | Lance scan row identifier; stability requires stable row ids | | `_rowaddr` | `UInt64` | physical row address | | `_rowoffset` | `UInt64` | offset within the fragment | | `_score` | `Float32` | relevance, from [`fts()`](/enterprise/v1-12-0/sql/dql/fts) | `_rowid`, `_rowaddr`, and `_rowoffset` describe Lance scan metadata, not columns automatically registered on an ordinary SQL table. Select `_score` from an `fts()` relation explicitly when you want a projection containing it. ## Casting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT CAST(identifier AS VARCHAR) FROM documents SELECT TRY_CAST(maybe_number AS BIGINT) FROM raw ``` `TRY_CAST` yields null rather than failing the query on a value that will not convert. See [Operators](/enterprise/v1-12-0/sql/dql/operators#casting). # Database Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/database Create, describe, list, attach, and drop databases with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A database is the catalog's top-level container: it holds [namespaces](/enterprise/v1-12-0/sql/ddl/namespace), which hold tables, views and other objects. Database statements name one database, independently of the session's current database. Database creation uses the deployment's native catalog and storage settings. ## CREATE DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE DATABASE analytics CREATE DATABASE IF NOT EXISTS "team/search" ``` Creates a persistent database. Requires `CREATE DATABASE` on the system, and ownership of the database name if it already has an owner. The caller becomes the owner of a new name, following the same rules as the REST API. The result has `operation`, `name`, and `status` columns. Status is `created`, or `already_exists` with `IF NOT EXISTS`. Without that clause, an existing database is an error. Creation never overwrites an existing database. > [!NOTE] > > `WITH` options are unsupported on `CREATE DATABASE`. Use `ATTACH DATABASE` > [below](#attach) to register a database at an existing location. The > `system` database and reserved storage names cannot be created. ## DESCRIBE DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE DATABASE analytics DESC DATABASE "team/search" ``` Requires `USAGE` on the database. Returns one row with `name` and `properties`. Properties are the catalog's metadata encoded as a JSON object; a database without metadata returns `{}`, and a database mid `CASCADE` drop reports a transient property marking it as dropping. A missing database is an error. `DESCRIBE DATABASE system` returns empty properties and requires system `USAGE`. ## SHOW DATABASES ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW DATABASES ``` Returns a sorted `name` column containing the databases the caller has `USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters are unsupported. ## ATTACH DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH DATABASE analytics WITH (location = 'analytics') ATTACH DATABASE IF NOT EXISTS analytics WITH (location = 'analytics') ATTACH DATABASE analytics WITH (location = 's3://customer-bucket/raw/analytics/') ATTACH DATABASE analytics WITH (location = 'az://customer-data@customeraccount.blob.core.windows.net/raw/analytics') ``` Registers an existing database at a path relative to the catalog's storage root, or at an external S3, GCS or Azure location, instead of creating a new one. `location` is the only supported option -- naming a storage integration explicitly is refused. For an external location, the deployment automatically binds the most specific [storage integration](/enterprise/v1-12-0/sql/ddl/storage-integration) whose prefix covers it; one must already exist. An Azure location must be account-qualified (`az://container@account.blob.core.windows.net/path`); a bare `az://container/path` is refused. `ATTACH DATABASE` requires the same creation privileges as `CREATE DATABASE`. For an external location, it also requires `USAGE` on the storage integration that binds it, and on that integration's own database and namespace; the integration itself must live in a native, root-backed database under the catalog root. Attaching writes Enterprise's own tracking metadata into the location to bring it under management -- it does not rewrite, move, or re-encode any existing table's data. > [!WARNING] > > A relative-path location never accepts an absolute path (`/tmp/db`), a > `file://` URI, a Windows path (`C:/db`), a `..` segment, an empty string, > or a doubled slash (`sub//db`). An S3 or GCS location must be a concrete > prefix, not a bare scheme (`s3://`) on its own. `IF NOT EXISTS` makes the statement a no-op rather than an error when the database is already attached. > [!NOTE] > > A quoted name reaches characters a bare identifier cannot, such as > `ATTACH DATABASE "team/search" WITH (location = 'team-search')`. > Removing an externally attached database with `DROP DATABASE` unregisters > the attachment and releases its storage-integration reference, without > deleting the underlying data. ## DROP DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP DATABASE analytics DROP DATABASE IF EXISTS analytics RESTRICT DROP DATABASE analytics CASCADE ``` Requires `USAGE` and `OWNERSHIP` on the database. The default, `RESTRICT`, refuses a database that still contains objects. `CASCADE` refuses new objects in the database, revokes every grant in it, and starts a job that drops its contents; deployments without cascade support reject it. An externally attached database cannot be dropped with `CASCADE`. `RESTRICT` returns `operation`, `name`, and `status` columns: `dropped`, or `not_found` with `IF EXISTS` for a missing database. `CASCADE` returns `operation`, `job_id`, and `status` columns: the job's id with `dropping`, or an empty `job_id` with `not_found`. The name stays taken until the job finishes and the dropped storage is cleaned up. The `system` database and federated databases cannot be dropped. > [!NOTE] > > `ALTER DATABASE` is unsupported. ## What to read next > [card] [Namespace](/enterprise/v1-12-0/sql/ddl/namespace) > > CREATE SCHEMA inside an attached database. > [card] [Table](/enterprise/v1-12-0/sql/ddl/table) > > Creating tables once a database and namespace exist. > [card] [Database](/enterprise/v1-12-0/management/database) > > The SDK equivalent, and connection settings. # Function Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/function Create, describe, alter, list, and drop registered functions with SQL. **Applies to:** Embedded ❌, Enterprise ✅ Early access [SQL runs in LanceDB Enterprise.](/enterprise/v1-12-0/sql) ## CREATE FUNCTION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION f(x int64) RETURNS int64 LANGUAGE python AS 'def f(x): return x * 2' WITH (pip = 'numpy==1.26.4', python_version = '3.11') ``` A function takes more than one parameter; each one binds a separate column or literal where the function is called: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION ratio(numerator float64, denominator float64) RETURNS float64 LANGUAGE python AS 'def ratio(numerator, denominator): return numerator / denominator' ``` Parameter and result types are Arrow type names, not SQL ones: `int64`, `float64`, `utf8`, `bool`, `date32`, and lists such as `list<float32>` or `fixed_size_list<float32, 768>`. `BIGINT` is refused. A parameter accepts nulls unless it is declared `NOT NULL`. The body is Python source. Its dependencies are declared with it and are part of the **immutable function version**. Changing one produces a new version rather than altering the registered one, so a column filled by an earlier version is unaffected. | Option | | | - | - | | `pip` | pip requirements for the worker environment | | `conda` | conda packages instead of pip | | `conda_channels` | channels in priority order; requires `conda` | | `apt` | OS packages to install in the worker environment | | `image` | a specific container image to run the worker in, such as `'host/repo@sha256:...'` | | `python_version` | worker Python version; `3.12` when omitted, whatever Python you send the statement from | | `gpu` | `'true'` when every execution needs a GPU | | `gpu_class` | which configured GPU class to run on, when `gpu = 'true'` | | `result_stability` | `'input_and_context'` or `'per_call'` | | `batch_size` | maximum rows per Function call | | `row_timeout_seconds` | per-row (or per-batch, for a vectorized Function) execution timeout | **Errors and limits** | | | | - | - | | `LANGUAGE` other than `python` | refused | | `pip` and `conda` together | refused (pick one) | | `conda_channels` without `conda` | refused | | `gpu` set to anything but `'true'` | refused | | An empty body | refused | | Any other option | refused, and the message lists what is supported | > [!NOTE] > > **Enterprise job type:** `create_function`. Registration returns a job because > the function is baked into an image before the version becomes usable. ## Artifact registration `CREATE FUNCTION name FROM '<registration JSON>'` accepts the artifact, signature, runtime, optional secret bindings, and result stability produced by the SDK's registration request. Omit its `name` property because the SQL identifier supplies it. Escape apostrophes in the JSON as doubled apostrophes. By default, the command waits for its internal image-build job to publish the version, then returns one UTF-8 `definition` column containing FunctionVersion JSON. `WITH (wait = false)` instead returns the existing image-build registry job ID in `job_id`, with `operation` and `status` columns. The SDK's ordinary registration handle has type `query` and uses the SQL query UUID as its single `id`; the internal image-build job has type `create_function`. ## DESCRIBE and ALTER FUNCTION ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE FUNCTION embed WITH (version = '1', include_source = true) ``` DESCRIBE returns one `definition` JSON column for the exact version. Enterprise 1.12.0 requires `version`; omitting it is an error. `include_source` defaults to false; source-inclusive reads report an omission when the stored artifact exceeds the inline source limit. `ALTER FUNCTION name FROM '<pinned update JSON>'` accepts a `reference` with name, namespace, object ID, location, version, and manifest digest, plus optional `metadata` and `disabled` updates. The command checks that reference before appending a revision and returns the resulting `definition` JSON. ## Call it Once registered, a function is callable by name in any query, the same as a built-in scalar function: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, f(x) AS doubled FROM my_table ``` This is also the fastest way to check a new registration before binding it to a column: call it over a few rows, or over literal arguments, before committing to [a computed column](/enterprise/v1-12-0/sql/ddl/table#computed-column) that fills from it. ## SHOW FUNCTIONS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW FUNCTIONS SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) ``` `SHOW FUNCTIONS` returns the highest published numeric revision for each name. Add `HISTORY` to list every published revision, as Python's `list_functions()` does. Rows are ordered by name and numeric revision, so `2` comes before `10`. `after_name` and `after_version` must be supplied together for keyset pagination. `limit` bounds the response; `include_definition = false` omits the optional definition JSON. ## DROP FUNCTION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP FUNCTION embed WITH (version = '1') DROP FUNCTION IF EXISTS embed WITH (version = '1') ``` DROP removes only the requested revision from lookup and listing. Other published revisions and their grants remain available. Dropping the last visible revision releases the name and object binding; physical cleanup continues separately. The result reports `dropped` or `not_found`. `IF EXISTS` allows a missing name or a repeated drop of a previously published revision. A revision that was never published under an existing name is an error. All function object commands retain shared results even when general query-result copying is disabled, so asynchronous polling can resume on another query node. ## What to read next > [card] [Function](/enterprise/v1-12-0/management/function) > > Registering one from the SDK, and diagnosing environment mismatches. > [card] [Computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) > > Filling a column with a function instead of an expression. # Grant Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/grant GRANT and REVOKE: privileges on every catalog object, from a database down to a Function. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT <privilege>[, <privilege>...] ON <target> TO <grantee>[, <grantee>...] REVOKE <privilege>[, <privilege>...] ON <target> FROM <grantee>[, <grantee>...] <target> ::= SYSTEM | DATABASE <name> | SCHEMA <namespace> | NAMESPACE <name> [IN <schema>] | TABLE <name> | VIEW <name> | MATERIALIZED VIEW <name> | SECRET <name> | STORAGE INTEGRATION <name> | FUNCTION <name> <grantee> ::= [ROLE] <role> | [USER] { <name> | ID '<id>' } | [GROUP] { <name> | ID '<id>' } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice, GROUP ID 'g1' GRANT USAGE ON FUNCTION platform.embed TO ROLE research GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins REVOKE USAGE ON FUNCTION platform.embed FROM ROLE research ``` ## Privileges | Target | Privileges it accepts | | - | - | | `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | | `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | | `SCHEMA` (a namespace) | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | | `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | | `VIEW` | `OWNERSHIP`, `SELECT` | | `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | | `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | | `FUNCTION` | `OWNERSHIP`, `USAGE` (call it in a query, bind it to a column, or refresh a column it computes) | > [!WARNING] > > `OWNERSHIP` cannot be revoked, only granted to someone else, which transfers > it: an object always has exactly one owner. `GRANT OWNERSHIP` is refused with > more than one grantee for the same reason. See [Privileges](/enterprise/v1-12-0/governance/privileges) for what each privilege allows in full, and how a creation privilege resolves against an object's parent when the object doesn't exist yet. ## Grantees A grantee is a role, or a user or group named by its identity-directory name or its directory ID. A grantee with no leading `ROLE`/`USER`/`GROUP` keyword takes the kind of the one before it, so `TO ROLE a, b` names two roles -- but the first grantee in the list always needs its keyword. An unquoted name is folded to lowercase before it is looked up; quote one that has capitals, such as `TO ROLE "DataEng"`. ## Naming the target A `SECRET` or `FUNCTION` target can be qualified with its namespace and database, the same as anywhere else: `SECRET analytics.api_key`, `SECRET db1.analytics.api_key`. `SCHEMA` and `NAMESPACE` both target a namespace but aren't interchangeable: `SCHEMA <namespace>` takes the namespace's complete path, while `NAMESPACE <name> [IN <schema>]` takes one unqualified component, resolved under an explicit parent schema or the session's current namespace when `IN` is omitted -- `NAMESPACE a.b` (a qualified name with no `IN`) is refused. A `MATERIALIZED VIEW` is a table for authorization purposes: the same privileges apply, and granting one does not reach the non-materialized `VIEW` beside it. ## How a statement is applied * A statement applies all of its changes or none of them. * The caller must already hold `OWNERSHIP` on the object to change any grant on it. * Granting a privilege a grantee already holds, or revoking one it does not hold, is a no-op. * `GRANT` requires the object to exist; `REVOKE` does not, so an entry left on a dropped object can still be removed. A role need not exist beforehand, but a `USER` or `GROUP` name must resolve to exactly one identity in your identity provider -- checked only after the caller's `OWNERSHIP` -- or the statement fails. The `ID '<id>'` form is not looked up. * `GRANT ... ON ... FROM ...` and `REVOKE ... ON ... TO ...` are both refused; `GRANT` always takes `TO`, `REVOKE` always takes `FROM`. * Returns one row per privilege and grantee, with status `granted`, `already_granted`, `revoked` or `not_granted`. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function; that's a > registration-time argument to `create_function` in the Python SDK. See > [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret). ## SHOW GRANTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GRANTS [ON <target>] [TO <grantee>[, <grantee>...]] [LIMIT n] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GRANTS SHOW GRANTS ON TABLE events TO ROLE readers LIMIT 2 SHOW GRANTS ON NAMESPACE features IN analytics.team SHOW GRANTS TO USER ID 'p1' ``` Lists grants as rows of `subject_id`, `subject_name`, `object` and `privilege`. `ON` filters to one target's own grants; `TO` filters to one or more grantees; combine both, or omit both for every grant the caller can see. `ON <target>` requires `USAGE` on that target; a target-less call requires system `USAGE` instead, since it can surface grants across the whole catalog. `SHOW ROLE BINDINGS` is the counterpart for role membership rather than object privileges -- see [Role membership in SQL](/enterprise/v1-12-0/governance/principals#membership). ## What to read next > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > The full privilege model, and how creation privileges resolve upward. > [card] [Namespace](/enterprise/v1-12-0/sql/ddl/namespace) > > Creating the schemas these privileges apply to. # Index Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/index CREATE INDEX and DROP INDEX: one column, with the algorithm chosen by USING. **Applies to:** Embedded ❌, Enterprise ✅ ## CREATE INDEX ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE INDEX ON documents USING btree (title) CREATE INDEX text_search ON documents USING fts (text) ``` `USING` is required: it names the algorithm. The scalar algorithms are `btree`, `bitmap` and `label_list`; `fts` builds a full-text index; and the vector algorithms are `ivf_pq`, `ivf_rq`, `ivf_flat`, `ivf_hnsw_sq` and `ivf_hnsw_pq`, where the deployment supports them. Index options go in a `WITH (...)` clause. > [!NOTE] > > In LanceDB Enterprise, SQL `CREATE INDEX` covers **one column**. A name between > `INDEX` and `ON` names the index, where the deployment's configuration allows > it; without one, the server names it after the column, as in `title_idx`. For a > multi-column index, use the SDK's [`create_index`](/enterprise/v1-12-0/indexing). > [!NOTE] > > **Enterprise job type:** `reindex_` followed by the algorithm, such as > `reindex_btree` or `reindex_ivf_pq`; the name says which algorithm is building, > not a different feature. An SDK build that must not replace an existing index > runs as `create_` followed by the algorithm instead. See > [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing). ## DROP INDEX ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP INDEX documents.title_idx ``` Takes the qualified `table.index` name. Find it with the SDK's [`list_indices`](/enterprise/v1-12-0/indexing) if you created the index without naming it yourself. A deployment builds the index in the background after `CREATE INDEX` returns; until that build finishes, the index is not listed and `DROP INDEX` reports it as not found. ## What to read next > [card] [Indexing](/enterprise/v1-12-0/indexing) > > Choosing an index type from the SDK. > [card] [Incremental Indexing](/enterprise/v1-12-0/indexing/incremental-indexing) > > Keeping an index current as data arrives. # Job Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/job SHOW JOBS, SHOW JOB EVENTS, DESCRIBE JOB, SHOW ERRORS, and controlling a running job with PAUSE, RESUME and CANCEL. **Applies to:** Embedded ❌, Enterprise ✅ A [job](/enterprise/v1-12-0/basics/jobs) is not a catalog object (it has no schema and is not namespaced), but it has its own SQL statements, grouped here the same way the catalog objects are. ## SHOW JOBS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOBS SHOW JOBS FOR TABLE documents SHOW JOBS FOR JOB '<parent_job_id>' [LIMIT n] ``` The unfiltered command lists jobs in the connected database, newest first: id, type, state, creation time -- the SQL counterpart of `list_jobs`. `FOR TABLE` filters that listing by the current namespace's table name. `FOR JOB` lists the parent's direct child jobs using the REST API's child model. Child rows expose their ID, kind, phase, row progress and attempt; unknown values remain NULL. Children are read-only diagnostic identities. `FOR JOB` defaults to 1,000 children and accepts `LIMIT` from 1 to 10,000, following backend continuation pages up to that limit. Child history can be `available`, `not_yet_recorded`, or `unavailable` after archival. > [!NOTE] > > A job you completed weeks ago eventually stops appearing here -- it was > archived, not deleted. Two deployment-scheduled jobs sweep the registry on a > per-database schedule: `job_registry_archive` moves terminal jobs out of the > active registry into archival storage, and `job_events_export` separately > copies terminal jobs' event histories into a curated system table for > metering, where the deployment enables it. A job's events can survive in > that exported table after the job itself is archived. ## SHOW JOB EVENTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOB EVENTS '<parent_or_child_job_id>' [LIMIT n] ``` Events are returned newest first. Parent history does not include child history. The default limit is 1,000; valid limits range from 1 to 10,000. The result includes event sequence, state, timestamps, origin, claim and resource/work fields. Child `kind` and `details` expose the REST API's allowlisted diagnostics; raw parent payloads are excluded. ## DESCRIBE JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE JOB '<job_id>' [FORMAT TEXT | TABLE | JSON] DESC JOB '<job_id>' [FORMAT TEXT | TABLE | JSON] ``` Both spellings show a finished root job's timing profile. `TEXT` is the default; `TABLE` returns typed phase/step rows and `JSON` returns the profile as one document. A running job has no profile rows. ## SHOW ERRORS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW ERRORS ON <table> [FOR JOB '<job-id>'] [LIMIT <n>] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW ERRORS ON documents SHOW ERRORS ON documents FOR JOB 'job-abc' LIMIT 100 ``` Why rows failed. Reach for this when a [refresh](/enterprise/v1-12-0/sql/dml/refresh-column) reports fewer filled rows than you expected. ### Errors and limits | | | | - | - | | `LIMIT` | defaults to 10,000; must be between 1 and 100,000 | | Failed jobs scanned without `FOR JOB` | 32 most recent | | Tables the server does not open directly | not supported | Without `FOR JOB` this surveys recent failures and stops at 32 jobs. When the listing stops at your `LIMIT`, the message says so. Narrow with `FOR JOB` rather than raising the limit blindly. > [!NOTE] > > `SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB` and `SHOW ERRORS` require > system `USAGE`, as do the equivalent REST diagnostics. Explicit table > listings additionally use the table-list authorization policy. ## PAUSE JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} PAUSE JOB 'j-ci-abc-def' ``` ## RESUME JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} RESUME JOB 'j-ci-abc-def' ``` ## CANCEL JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CANCEL JOB 'j-ci-abc-def' ``` The job id is always a quoted string literal. All three take exactly one and nothing after it: a second token on the line is a syntax error rather than being ignored. Pause requires the deployment's pause-write opt-in and a resumable job type; it may return `pausing` while workers drain, and resume may return `still_pausing` until drain finishes. > [!NOTE] > > `PAUSE JOB`, `RESUME JOB` and `CANCEL JOB` require system `OPERATE` -- a > broader privilege than the `USAGE` that reading job state needs, since > these change what a running job does. > [!NOTE] > > Cancellation is a request, matching the SDK's > [`cancel()`](/enterprise/v1-12-0/basics/jobs#managing): it does not guarantee the job stops before > doing more work, and asking twice or cancelling a finished job does nothing. > `CANCEL JOB` itself can be unavailable on an Enterprise cluster with no job registry > configured, which is a deployment condition rather than something you can work > around from SQL. ## Compatibility `SHOW JOBS FOR <table>` (without the `TABLE` keyword), `SHOW JOB SUMMARY`, and `SHOW JOB SPLITS` retain their existing behavior as compatibility forms. Prefer `SHOW JOBS FOR TABLE`/`FOR JOB` and `DESCRIBE JOB` going forward. See [`SHOW JOBS FOR JOB`](#show) for the per-split diagnostics form -- each split is a child job, listed with its own phase and progress. See [Watching a refresh](/enterprise/v1-12-0/sql/dml/refresh#watching) for `SHOW JOB SPLITS`'s full column reference and a `DESCRIBE JOB` example. ## What to read next > [card] [Query and job](/enterprise/v1-12-0/basics/jobs) > > The handle these statements are the SQL view of. > [card] [Intelligent Auto-Maintenance](/enterprise/v1-12-0/enterprise/intelligent-auto-maintenance#cleanup) > > A job type the deployment schedules on its own, without a call. # Materialized View Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/materialized-view CREATE MATERIALIZED VIEW and SHOW MATERIALIZED VIEWS; refreshing is a REFRESH statement. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view stores a query's result as rows, kept current by a refresh. It is the counterpart to a [view](/enterprise/v1-12-0/sql/ddl/view), which stores only the query. > [!NOTE] > > Materialized views are off by default in LanceDB Enterprise and have to be enabled > there. Which statements and query shapes a deployment accepts, whether it needs > the source table to have stable row ids, and how it refreshes a view depend on > its LanceDB Enterprise version and configuration. ## CREATE MATERIALIZED VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW <name> AS SELECT ... ``` Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/enterprise/v1-12-0/management/materialized-view#create). ## SHOW MATERIALIZED VIEWS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW MATERIALIZED VIEWS ``` > [!NOTE] > > This asks the server for its views, as the SDK's `list_materialized_views` does > on a `db://` connection. ## Refreshing one ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks ``` See [REFRESH MATERIALIZED VIEW](/enterprise/v1-12-0/sql/dml/refresh-materialized-view) for the full syntax, and compatibility notes for older server versions. ## Dropping one ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP MATERIALIZED VIEW <name> ``` A dedicated statement; the SDKs emit it rather than [`DROP TABLE`](/enterprise/v1-12-0/sql/ddl/table#drop), even though a materialized view **is** a table underneath. For the same reason, dropping one removes stored rows, unlike dropping a [view](/enterprise/v1-12-0/sql/ddl/view#drop). > [!NOTE] > > **Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the > same underlying job as dropping any table, `drop_table` or `drop_object`. ## What to read next > [card] [Materialized View](/enterprise/v1-12-0/management/materialized-view) > > Creating one from the SDK. > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > How a refresh works, in LanceDB Enterprise. # Namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/namespace Create, alter, describe, list, and drop namespace paths with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A [namespace](/enterprise/v1-12-0/management/namespace) is addressed in SQL as a `SCHEMA`, the standard's name for the same concept. A **schema** is a complete namespace path, optionally qualified by a database; a nested path occupies one backtick-quoted identifier with `$` between components, such as `` analytics.`team$features` ``. A **namespace**, as a separate keyword, names one path component, relative to an explicit parent schema or the session's current schema -- it cannot contain `$` or be qualified with a database. `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete schema identifier. Names are lowercased unless quoted. ## CREATE SCHEMA and CREATE NAMESPACE Create a namespace using its complete schema path: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SCHEMA analytics CREATE SCHEMA db1.`ns1$ns2` CREATE SCHEMA IF NOT EXISTS `ns1$ns2` ``` Alternatively, create the same namespace by naming its component and parent: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE NAMESPACE features IN team ``` To supply creation metadata and tolerate an existing namespace: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE NAMESPACE IF NOT EXISTS features IN analytics.team WITH (owner = 'search-team', purpose = 'retrieval') ``` A nested namespace is one backtick-quoted name with `$` between its components: `` db1.`ns1$ns2` `` creates `ns2` inside `ns1` in database `db1`. Both forms create namespaces in the same catalog, and missing ancestors are created automatically -- the part before the first dot is always the database. `public` is the database's root namespace, which is never created or dropped. `IF NOT EXISTS` makes the statement a no-op rather than an error when the namespace is already there, though it does not replace an existing namespace's properties. Without it, an existing target is an error. Properties are string values stored on the target only; implicitly created ancestors receive no properties, and duplicate property keys are errors. The result has `operation`, `name`, and `status` columns. The operation is `CREATE SCHEMA` for either spelling; the name is the resolved path and the status is `created`. > [!NOTE] > > Creation requires `CREATE NAMESPACE` on the database and the parent > namespace -- the same privileges the > [namespace REST API](/enterprise/v1-12-0/management/namespace) checks. The caller becomes the > owner of each newly created namespace, including implicitly created > ancestors. See [Grant](/enterprise/v1-12-0/sql/ddl/grant#privileges) for the full privilege > list a namespace accepts. ## ALTER SCHEMA and ALTER NAMESPACE | Operation | SCHEMA syntax | NAMESPACE syntax | | - | - | - | | Set metadata | ``ALTER SCHEMA `team$features` SET (purpose = 'retrieval')`` | `ALTER NAMESPACE features IN team SET (purpose = 'retrieval')` | | Remove metadata | ``ALTER SCHEMA `team$features` UNSET (purpose)`` | `ALTER NAMESPACE features IN team UNSET (purpose)` | `SET` adds or replaces the listed string properties, preserving other keys. `UNSET` removes the listed keys; a missing key is ignored. Lists must be nonempty, and duplicate keys are errors. Quote a key containing punctuation, for example `SET ("owner.team" = 'search')`. Each statement updates metadata atomically and preserves unrelated concurrent changes. Metadata changes do not change ownership or grants. Use `DESCRIBE` to read the updated properties. A missing namespace is an error. > [!NOTE] > > Requires `USAGE` on the database and the namespace, and `OWNERSHIP` on the > namespace itself. > [!NOTE] > > `ALTER` metadata is supported by native manifest-backed databases. Legacy > directory and external catalogs report an unsupported-operation error. The > implicit `public` root and the read-only `system` database cannot be > altered. The result has `operation`, `name`, and `status` columns, with operation `ALTER SCHEMA` for either spelling and status `altered`. ## DESCRIBE SCHEMA and DESCRIBE NAMESPACE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE SCHEMA analytics.`team$features` DESCRIBE NAMESPACE features IN analytics.team DESC NAMESPACE features IN team ``` Returns one row with `name` (the complete `$`-joined schema path) and `properties` (a JSON object). An unannotated namespace returns `{}`. A missing namespace is an error. `DESC` is an alias for `DESCRIBE`. > [!NOTE] > > Requires `USAGE` on the database and the namespace. ## SHOW SCHEMAS and SHOW NAMESPACES ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW SCHEMAS SHOW NAMESPACES SHOW NAMESPACES IN analytics.team ``` `SHOW SCHEMAS` returns complete paths in the current database, recursively, including `public` when the caller can use it. It does not accept `IN`. `SHOW NAMESPACES` lists only immediate child names under the session's current schema. `IN` selects a different parent schema, optionally in another database -- use `IN public` for the current database's root, or `IN analytics.public` for another database's root. A missing parent is an error. Both forms return a sorted `name` column and omit namespaces the caller cannot use. Large listings that exceed 10,000 namespaces, or recursive listings deeper than 32 levels, return an error suggesting a narrower listing. ## DROP SCHEMA and DROP NAMESPACE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP SCHEMA analytics.`team$features` DROP NAMESPACE IF EXISTS features IN analytics.team RESTRICT DROP NAMESPACE team CASCADE ``` The default, `RESTRICT`, refuses a namespace with children or objects -- tables, views and other objects inside must be dropped explicitly first. In native manifest-backed databases, `CASCADE` instead removes the namespace and all descendant bindings atomically in one catalog commit, then submits a background job that cleans up their storage; deployments without cascade support reject it. A storage integration used by an attached database blocks the drop of its namespace. > [!NOTE] > > Requires `USAGE` and `OWNERSHIP` on the namespace. A dropped Secret is > eligible for immediate deletion even when jobs still reference it: a > process that already holds the value keeps it for the rest of its run, but > a later launch that needs the Secret can fail once it's gone. `RESTRICT` returns `operation`, `name`, and `status`, with status `dropped` or `not_found`. `CASCADE` returns `operation`, `job_id`, and `status`, with status `dropping`, or an empty job ID and `not_found` for a missing target with `IF EXISTS`. Inspect a cascade drop's child jobs with [`SHOW JOBS FOR JOB`](/enterprise/v1-12-0/sql/ddl/job#show). Both spellings report operation `DROP SCHEMA`. ## Correcting invalid syntax | Invalid form | Use instead | | - | - | | `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | | `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | | `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | | `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next > [card] [Database](/enterprise/v1-12-0/sql/ddl/database) > > Attaching the database a namespace lives in. > [card] [Namespace](/enterprise/v1-12-0/management/namespace) > > The SDK equivalent, and how a namespace fits the catalog hierarchy. > [card] [Table](/enterprise/v1-12-0/sql/ddl/table) > > Creating tables inside a namespace. # Secret Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/secret CREATE, ALTER, DROP, SHOW and DESCRIBE SECRET, and granting privileges on Secrets. Early access Enterprise [SQL runs in LanceDB Enterprise.](/enterprise/v1-12-0/sql) A [Secret](/enterprise/v1-12-0/management/secret) is a named credential that Functions bind by reference. These statements store, rotate, list, describe and drop Secrets. A Secret is addressed like a table: `[db.][namespace.]name`. An unqualified name uses the session's database and namespace. A nested namespace is one backtick-quoted name with `$` between its components, and `public` is the database's root namespace. A Secret name may contain letters, digits, `_`, `.` and `-`, so quote one that contains `.` or `-`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} api_key platform.`model-api-key` analytics.`ml$vision`.`model-api-key` ``` `CREATE`, `ALTER` and `DROP` return one row of `operation`, `name` and `status`. Without `IF [NOT] EXISTS`, a taken name (for `CREATE`) or a missing Secret (for `ALTER` and `DROP`) is an error rather than a status. ## CREATE SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '<api-key>' CREATE SECRET IF NOT EXISTS api_key TYPE = GENERIC_STRING SECRET_STRING = $$<api-key>$$ ``` Stores a new Secret. `TYPE = GENERIC_STRING` is required; it is currently the only supported type. The value may be single-quoted or dollar-quoted, or a bound `$1` parameter -- the same choice `ALTER SECRET` offers below -- so the value never has to appear in the SQL text itself: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query( "CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = $1", parameters=["<api-key>"], ) ``` Requires `CREATE SECRET` on the namespace; the caller becomes the Secret's owner. The status is `created`, or `already_exists` with `IF NOT EXISTS`. It never overwrites an existing Secret; use `ALTER SECRET`. ## ALTER SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '<api-key>' ALTER SECRET IF EXISTS api_key SET SECRET_STRING = $$<api-key>$$ ``` Replaces the Secret's value -- `SECRET_STRING` takes the same single-quoted, dollar-quoted, or bound `$1` parameter forms `CREATE SECRET` does. Every Function bound to it gets the latest value the next time a job starts -- a job already running, and its retries, keep the value they captured at their own start -- without a new Function version. Requires `UPDATE` on the Secret. The status is `altered`, or `not_found` with `IF EXISTS`. ## DROP SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP SECRET platform.`model-api-key` DROP SECRET IF EXISTS api_key ``` Deletes the Secret and every grant on it. Functions bound to it fail at their next job, naming the Secret. Requires `OWNERSHIP` on the Secret. The status is `dropped`, or `not_found` with `IF EXISTS`. > [!WARNING] > > `DROP SECRET` cannot be undone. A new Secret created under the same name is > picked up by every Function still bound to that name. ## SHOW SECRETS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW SECRETS SHOW SECRETS IN platform SHOW SECRETS IN analytics.`ml$vision` SHOW SECRETS IN public SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 ``` Lists the Secret names in one namespace as a sorted `name` column. Without `IN`, it lists the session's namespace; `IN public` lists the root. `WHERE name > '<cursor>'` pages past the last name already seen, and `LIMIT` bounds the page size; `WHERE` must compare `name` with `>`. Requires `USAGE` on the database and the namespace. ## DESCRIBE SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE SECRET platform.`model-api-key` DESC SECRET api_key ``` Returns one row: | Column | Type | Meaning | | - | - | - | | `name` | string | The Secret's name | | `created_at_millis` | int64 | When it was created, in milliseconds since the Unix epoch | | `updated_at_millis` | int64 | When its value was last set. Watch this change to confirm a rotation landed. | | `history` | list of struct `{generation: uint64, at_millis: int64}` | Creation and each rotation since, oldest first, up to the most recent 100 | A missing Secret is an error. Requires `USAGE` on the Secret. ## GRANT and REVOKE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE SECRET ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` `CREATE SECRET` on the containing `SCHEMA` creates one; `OWNERSHIP`, `USAGE` (bind it to a Function) and `UPDATE` (rotate it) apply to the Secret itself. See [GRANT and REVOKE](/enterprise/v1-12-0/sql/ddl/grant) for the full statement grammar, every target type, and the shared mechanics -- grantee forms, no-op rules, and the status a statement returns -- which apply the same way to a Secret as to any other object. ## The value stays out of output A Secret's value never appears in a statement's result, an error message, `EXPLAIN` output, or the query log. The query log masks everything after the name in `CREATE SECRET`, and everything after `SET` in `ALTER SECRET`. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function. Register Functions that > bind Secrets through the Python SDK; see > [Vend a Secret to a Function](/enterprise/v1-12-0/curation/vend-secret). ## What to read next > [card] [Secret](/enterprise/v1-12-0/management/secret) > > Create, rotate, list and drop the credential from the Python SDK and SQL. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges#sql) > > Every object's privileges, and how grants resolve. # Storage Integration Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/storage-integration CREATE, DESCRIBE, SHOW and DROP STORAGE INTEGRATION: a namespace-scoped, reusable credential for reading or importing from external storage. **Applies to:** Embedded ❌, Enterprise ✅ A storage integration is a namespace-scoped catalog object that lets a query read from, or import from, a storage location outside the deployment's own tables -- an S3, GCS or Azure prefix, or a HuggingFace dataset repository -- without embedding a credential in the query itself. It is addressed and scoped the same way a [Secret](/enterprise/v1-12-0/sql/ddl/secret) is: a 1-3 part identifier, `name`, `namespace.name` or `database.namespace.name`, with a nested namespace path `$`-joined into that middle part. ## CREATE STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION <name> STORAGE_PROVIDER = 'S3' | 'AZURE' | 'GCP' | 'HUGGINGFACE' STORAGE_PREFIX = '<uri-prefix>' [ <provider option> = <value> [...] ] ``` `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. Options ending in `_SECRET` take a [Secret](/enterprise/v1-12-0/sql/ddl/secret) identifier, not a quoted string: `name`, `namespace.name` or `database.namespace.name`, with a nested namespace path `$`-joined in the middle part (``db.`team$prod`.key``). Omitted parts default to the session's current database and namespace. Creating the integration requires `USAGE` on each referenced Secret and on its database and namespace. Passing an option a provider does not accept, such as an Azure option on an `S3` integration, is refused. ### S3 ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ACCESS_KEY_ID_SECRET = bootstrap.credentials.aws_key_id STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = bootstrap.credentials.aws_key_secret ``` | Option | Type | Meaning | | - | - | - | | `STORAGE_AWS_ROLE_ARN` | string | an IAM role to assume, by cross-account trust (see [below](#trust)) | | `STORAGE_AWS_ACCESS_KEY_ID_SECRET` | Secret ref | a static access key ID, paired with the secret key below | | `STORAGE_AWS_SECRET_ACCESS_KEY_SECRET` | Secret ref | the matching static secret access key | | `STORAGE_AWS_REGION` | string, optional | the bucket's region | | `STORAGE_AWS_ENDPOINT` | string, optional | an S3-compatible endpoint URL (MinIO, Tigris, ...) instead of AWS itself | Give either `STORAGE_AWS_ROLE_ARN` alone, or both key-pair options together \-- mixing the two, or supplying only one half of the key pair, is refused. ### Azure ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION blobs STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = 'az://customer-data/raw/' STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' STORAGE_AZURE_TENANT_ID_SECRET = bootstrap.credentials.tenant STORAGE_AZURE_CLIENT_ID_SECRET = bootstrap.credentials.client STORAGE_AZURE_CLIENT_SECRET_SECRET = bootstrap.credentials.credential ``` | Option | Type | Meaning | | - | - | - | | `STORAGE_AZURE_STORAGE_ACCOUNT` | string | the storage account name | | `STORAGE_AZURE_TENANT_ID_SECRET` | Secret ref | Entra ID tenant | | `STORAGE_AZURE_CLIENT_ID_SECRET` | Secret ref | service principal client ID | | `STORAGE_AZURE_CLIENT_SECRET_SECRET` | Secret ref | service principal client secret | All four are required together; there is no role-based alternative for Azure. ### GCP ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION gcs STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = 'gs://customer-data/raw/' GCP_CREDENTIALS_JSON_SECRET = bootstrap.credentials.gcp ``` `GCP_CREDENTIALS_JSON_SECRET` -- note the option name has no `STORAGE_` prefix, unlike every other provider's options -- names a Secret holding the full service-account JSON key. It is required; GCP has no role-based alternative here. ### HuggingFace ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token ``` `HUGGINGFACE_TOKEN_SECRET` is the only HuggingFace option, and it is required: creating an integration without it is refused. For anonymous access, at HuggingFace's default anonymous rate limits, register no integration for that prefix at all. See [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) for the full read and import workflow this integration unlocks. ### The S3 trust policy Creating an `STORAGE_AWS_ROLE_ARN` integration does not finish the AWS side of the setup. The result row's `trust_policy`, `permissions_policy` and `configuration_instructions` columns -- also visible from [`DESCRIBE`](#describe) -- are the IAM policy documents your role needs: attach `trust_policy` as the role's trust relationship, scoped to `aws_account_id`, `aws_iam_principal_arn` and `aws_external_id` from the same row, and attach `permissions_policy` to grant that role read access to the bucket. `access_verified` reports whether the deployment already confirmed it can assume the role and read the prefix; `false` typically means the trust policy has not been attached yet. ## Reading and importing through the integration A query or `CREATE TABLE ... AS SELECT` can reference a matching URI directly, once an integration covers it -- the integration is never named in the statement. What the URI reads depends on the provider: * **HuggingFace** (`hf://datasets/...`) reads Parquet files from a dataset repository. See [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) for the full workflow, including how a CTAS import distributes across plan executors. * **S3, GCS and Azure** (`s3://`, `gs://`, `az://`) read an existing Lance dataset at that prefix, the same way as a managed table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM 's3://customer-data/raw/events.lance' LIMIT 10 CREATE TABLE events_copy AS SELECT * FROM 's3://customer-data/raw/events.lance' ``` A CTAS import distributes the same way regardless of provider: disjoint file and row-group ranges go to plan-executor workers, each writes uncommitted Lance files, and a coordinator commits the table once every worker finishes. See [`CREATE TABLE`](/enterprise/v1-12-0/sql/ddl/table#create) for `CREATE TABLE AS SELECT` syntax in general. ## DESCRIBE STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE STORAGE INTEGRATION raw DESC STORAGE INTEGRATION platform.hub ``` Returns one row with every column `CREATE` returns: the provider, prefix, the Secret references and plain-string options that apply to its provider (the rest are null), `created_at_millis`, `access_verified`, and \-- for an `STORAGE_AWS_ROLE_ARN` integration -- the generated AWS policy documents from [above](#trust). No call ever returns a Secret's value, only the reference naming it. ## SHOW STORAGE INTEGRATIONS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW STORAGE INTEGRATIONS SHOW STORAGE INTEGRATIONS IN platform LIST STORAGE INTEGRATIONS ``` `LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` narrows the listing to one namespace. ## DROP STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP STORAGE INTEGRATION raw DROP STORAGE INTEGRATION IF EXISTS raw ``` Returns `dropped`, `true` or `false`. There is no `ALTER STORAGE INTEGRATION`: to rotate a credential, rotate the Secret it references (see [Secret](/enterprise/v1-12-0/sql/ddl/secret)) rather than dropping and recreating the integration. A storage integration an attached database still depends on blocks the drop; detach the database first. ## GRANT and REVOKE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE STORAGE INTEGRATION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research GRANT OWNERSHIP ON STORAGE INTEGRATION platform.hub TO ROLE platform_admins REVOKE USAGE ON STORAGE INTEGRATION platform.hub FROM ROLE research ``` `CREATE_STORAGE_INTEGRATION` on the namespace creates one; `USAGE` on the integration itself lets a query match and read through it; `OWNERSHIP` grants full control, including dropping it. See [Privileges](/enterprise/v1-12-0/governance/privileges#sql) for the full statement syntax, every grantee form, and how a query picks a matching integration without naming one. ## What to read next > [card] [Inspect Datasets](/enterprise/v1-12-0/curation/inspect-datasets) > > Query and import HuggingFace or object-storage datasets, the most common use of a storage integration today. > [card] [Secret](/enterprise/v1-12-0/sql/ddl/secret) > > The credential storage integration options reference. > [card] [Privileges](/enterprise/v1-12-0/governance/privileges) > > Every privilege, and the grant and revoke syntax that covers each one. # Table Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/table CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE. **Applies to:** Embedded ❌, Enterprise ✅ ## CREATE TABLE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents (id BIGINT, title VARCHAR, created_at TIMESTAMP) CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ``` Column types are Arrow types under SQL names. See [Data types](/enterprise/v1-12-0/sql/data-types). A table inside a [namespace](/enterprise/v1-12-0/sql/ddl/namespace) is written with its [schema](/enterprise/v1-12-0/basics/catalog#schema) before the name: `` `prod$events`.clicks ``. ## DESCRIBE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE documents ``` The table's columns and types, without a plan. The SQL counterpart of `table.schema`. ## ALTER TABLE What `ALTER TABLE ... ADD COLUMN` does depends on what follows the column name. ### A plain column SQL `ADD COLUMN` requires an `AS` binding, so a plain column such as `ALTER TABLE t ADD COLUMN c INT` is rejected. Add an empty, nullable column with the SDK instead. See [Add nullable columns](/enterprise/v1-12-0/management/table#schema-add-nullable-columns). ### A computed column ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN doubled AS value * 2 ``` `AS <expression>` declares a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column). The column is committed empty and the expression is stored, not evaluated: declaring one on a billion-row table costs what declaring one on an empty table costs. [`REFRESH COLUMN`](/enterprise/v1-12-0/sql/dml/refresh-column) fills it. ### A function column ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN embedded AS embed(name) WITH (version = 'fv_1') ``` When the expression calls a [registered function](/enterprise/v1-12-0/sql/ddl/function), the column is filled by running that function on workers. `version` pins which immutable function version fills it, so a later registration does not silently change what the column means. Several modifiers narrow what gets computed: | | | | - | - | | `FILTER (WHERE pred)` | only rows matching `pred` are computed | | `IGNORE NULLS` | rows with null inputs are skipped | | `OVER (PARTITION BY col)` | the function sees rows grouped by `col` | A function returning several values fills several columns at once: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN (label, score) AS classify(text) WITH (version = 'fv_1') ``` ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN c AS f(x) FILTER (WHERE keep) WITH (version = 'fv_1') REFRESH COLUMN c ON t WITH (num_workers = 2) ``` > [!NOTE] > > Declaration `WITH` accepts `auto_refresh_enabled` and > `auto_refresh_interval_seconds`. Function bindings also accept `version` and > `branch`. Worker resource options such as `num_workers` belong on > `REFRESH COLUMN ... WITH (...)`. ### Table properties ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t SET UNENFORCED PRIMARY KEY (id) ``` Records which column identifies a row. **Unenforced** is not a hedge in the naming: uniqueness is not checked on write, and declaring it does not make duplicates impossible. It tells the planner what to assume. The column must be declared `NOT NULL`. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t SET RTE ALTER TABLE t SET RTE WITH (sharding = 'bucket', column = 'id', buckets = 4) ALTER TABLE t SET RTE WITH (maintained_indexes = '') ALTER TABLE t UNSET RTE ``` The [real time engine](/enterprise/v1-12-0/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be the table's unenforced primary key, and inserts into the table then need a scalar index on that key. `maintained_indexes` chooses which indexes are kept current against WAL rows; omitted, every supported index is kept current, including ones created later. A table with a computed column cannot take a write-ahead log. See [RTE Compaction](/enterprise/v1-12-0/enterprise/realtime-engine-compaction) for how the log gets folded back into the table. > [!WARNING] > > [`TABLESAMPLE`](/enterprise/v1-12-0/sql/dql/sampling) is refused on a WAL-backed table, because > rows a sample would draw from are not all in the fragments yet. ### Errors and limits | | | | - | - | | `ALTER TABLE ... DROP COLUMN` | not supported | Dropping, renaming, or retyping a column is an SDK operation ([`drop_columns`](/enterprise/v1-12-0/management/table#schema) and [`alter_columns`](/enterprise/v1-12-0/management/table#schema)), not a SQL statement. ## CLONE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE docs_snapshot CLONE documents CREATE TABLE docs_at_v42 CLONE documents AT 42 CREATE TABLE docs_at_release CLONE documents AT TAG 'release-1' CREATE TABLE docs_yesterday CLONE documents AT TIMESTAMP '2026-09-01T00:00:00Z' ``` A **shallow clone**: the new table shares the source's data files rather than copying them, so it costs one metadata commit regardless of the source's size. `AT` pins the point in the source's history to clone. A bare integer is a version and a bare quoted string is a timestamp; `VERSION`, `TAG` and `TIMESTAMP` say so explicitly, and a tag always needs its keyword: a bare quoted string cannot be both a tag name and a timestamp. > [!WARNING] > > The clone depends on the source's files continuing to exist. If the source is > [compacted](/enterprise/v1-12-0/maintenance/cleanup) past the retention window, the version the > clone points at can be pruned. The SDK's > [`clone_table`](/enterprise/v1-12-0/management/table#rename-clone) also offers a deep clone for > when the copy has to outlive the source's history. ## DROP TABLE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP TABLE documents ``` > [!WARNING] > > Removes the table and every version of it. There is no undrop. > [!NOTE] > > **Enterprise job type:** `drop_table` or `drop_object`, depending on how the > deployment stores its catalog. See > [Object teardown](/enterprise/v1-12-0/basics/jobs#teardown). ## What to read next > [card] [Table](/enterprise/v1-12-0/management/table) > > The SDK equivalent, and what a table carries. > [card] [Schema evolution](/enterprise/v1-12-0/management/table#schema) > > Renaming, retyping and dropping columns from the SDK. # View Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/ddl/view Create, describe, list, and drop saved queries with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A view stores a **query**, not rows. Reading it runs the query against current data, so a view is never stale, and never faster than the query it wraps. It is the counterpart to a [materialized view](/enterprise/v1-12-0/sql/ddl/materialized-view), which stores rows and is brought up to date by a refresh; both are [catalog objects](/enterprise/v1-12-0/basics/catalog) defined by a query, differing only in when that query runs. The SDK methods `create_view`, `describe_view`, `list_views`, and `drop_view` submit SQL through the connection's Flight endpoint. `drop_view_async` returns a job of type `query` whose single `id` is the SQL query UUID. Waiting confirms catalog removal; physical cleanup can continue afterward. ## CREATE VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE VIEW "recent_matches" AS SELECT t1.floats FROM "documents" AS t1 INNER JOIN "categories" AS t2 ON t1.ints = t2.ints ``` The statement returns one row with UTF-8 `name`, `query`, and `schema` columns. `query` contains the stored query, including any declared column aliases, and `schema` contains its Arrow schema as JSON. The schema metadata keys `lancedb::view::default_db` and `lancedb::view::default_namespace` identify the defining database and namespace. The root namespace is `public`; nested namespace components are separated by `$`. `DESCRIBE VIEW "recent_matches"` returns the same metadata shape. Anything the [dialect](/enterprise/v1-12-0/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions. ## Reading one A view is queried like a table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM "recent_matches" WHERE floats > 0.5 ``` Predicates applied to the view compose with the query inside it rather than filtering its output afterwards, so a selective filter does not pay for rows the view would have produced and then discarded. ## DROP VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP VIEW "recent_matches" ``` Removes the saved query. Unlike dropping a table, no data is removed: there was none to begin with. ## Listing ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW VIEWS SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 ``` `SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to the selected namespace. Object commands retain their small results in shared storage even when general query-result copying is disabled, so asynchronous polling can use any query node. Views and tables share a namespace, and both are things you can query. The catalog distinguishes them: | | | | - | - | | view names | the views in the database | | table names | the tables | | relation names | everything queryable (both) | Use the relation listing when the question is "what can I select from," and the separate listings when the distinction matters: before dropping, for instance, since dropping a view removes only the saved query while dropping a table removes data. ## Choosing between a view and a materialized view | | View | Materialized view | | - | - | - | | Stores | the query | the rows | | Freshness | always current | as of the last refresh | | Read cost | the full query, every read | a table scan | | Write cost | none | a refresh | Reach for a **view** when the query is cheap, or when reading stale rows would be wrong. Reach for a **materialized view** when the query is expensive and the data changes less often than it is read. The privileges are separate too: `CREATE_VIEW` and `CREATE_MATERIALIZED_VIEW` are distinct grants on a namespace, so the ability to create one does not imply the other. See [Authorization](/enterprise/v1-12-0/governance/authorization). ## What to read next > [card] [Materialized View](/enterprise/v1-12-0/sql/ddl/materialized-view) > > The stored-rows counterpart. > [card] [Management](/enterprise/v1-12-0/management) > > Where views fit among the other catalog objects. # Copy Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/copy COPY ... TO: writing a query result to object storage as files. > [!WARNING] > > Recent deployment versions refuse `COPY` over the SQL endpoint with "COPY is not > supported". On those, export a result by reading it through a Flight SQL client > or an SDK and writing the files from your application. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} COPY (SELECT id, title FROM documents) TO 's3://bucket/export/' STORED AS PARQUET ``` Writes a query result to object storage. This is the export path when the consumer is another engine rather than an application: results land as files rather than streaming to a client. ## What to read next > [card] [Insert](/enterprise/v1-12-0/sql/dml/insert) > > Bringing rows in, rather than exporting them. # Delete Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/delete DELETE FROM ... WHERE: rows are marked, not erased. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DELETE FROM documents WHERE created_at < TIMESTAMP '2025-01-01 00:00:00' ``` Compare a timestamp column with a typed literal, as above, or with `CAST('2025-01-01' AS TIMESTAMP)`. A bare string such as `'2025-01-01'` is rejected in a `DELETE` predicate, even though a `SELECT` accepts it. Deletion marks rows rather than erasing them, so the data remains recoverable for as long as the version holding it survives [retention](/enterprise/v1-12-0/maintenance/cleanup). Commits a new table version, so [versioning](/enterprise/v1-12-0/management/table#versioning) and the [write guarantees](/enterprise/v1-12-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Delete](/enterprise/v1-12-0/ingestion/delete) > > The SDK equivalent. # Insert Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/insert INSERT INTO, including INSERT ... SELECT to move rows server-side. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSERT INTO documents (id, title) VALUES (1, 'Merlin'), (2, 'Arthur') INSERT INTO archive SELECT * FROM documents WHERE created_at < '2026-01-01' ``` `INSERT ... SELECT` is the form worth knowing: it moves rows between tables server-side, without a round trip through your process. Commits a new table version, so [versioning](/enterprise/v1-12-0/management/table#versioning) and the [write guarantees](/enterprise/v1-12-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Insert](/enterprise/v1-12-0/ingestion/insert) > > The SDK equivalent. > [card] [Merge Insert](/enterprise/v1-12-0/ingestion/merge-insert) > > Upsert (matching incoming rows against existing keys) has no SQL form. # REFRESH Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/refresh Filling computed columns and bringing materialized views up to date. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB extensions with no DataFusion equivalent. They are what makes [feature engineering](/enterprise/v1-12-0/feature-engineering) reachable from SQL: a column declared by [DDL](/enterprise/v1-12-0/sql/ddl/table#computed-column) starts empty, and a refresh fills it. ## REFRESH COLUMN ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN <column> ON [TABLE] <table> [WHERE <predicate>] [WITH (<option> = <value> [, ...])] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` Without `WHERE`, a refresh fills unassigned rows and recomputes values whose inputs changed, leaving other current values alone. A retry after a failure can still repeat work that was not committed. With `WHERE`, a refresh **recomputes every matching live row**, including rows that already have current values. Repeating the same predicate can repeat the Function calls and their cost. To fill only null outputs within a slice, add the output column to the predicate: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even if their inputs changed. It also selects outputs that were successfully computed as `NULL`; a null value does not necessarily mean the row has never been computed. Use an unfiltered refresh to let LanceDB track which outputs need updating. An initialized Function instance and its mutable state may survive across refresh jobs. Do not assume a new refresh resets instance state or calls `__init__` again. Instances are not shared across workers. Refresh computed columns in dependency order. A refresh fails before writing if the rows it would compute read another computed or Function column that has not been refreshed for its current inputs. Refresh that input first. A computed input that is current but evaluates to `NULL` is a valid value, not an unfilled placeholder. `WHERE` scopes the refresh, which is how you fill a slice and check it before committing to the whole table. It does not narrow the per-fragment input readiness checks: if a selected fragment contains unfilled computed input rows anywhere, refresh that input first and then rerun the filtered child. ### Previewing a refresh ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` `EXPLAIN` and `EXPLAIN VERBOSE` take the same options and validation as `REFRESH COLUMN` and return DataFusion's `plan_type`, `plan` rows: * `logical_plan`: the `RefreshColumn` statement. * `physical_plan`: a `RefreshJobExec` root carrying what the job runs with (the snapshot, worker count or Function resource budget, error policy, batch size, row timeout, how many fragments have work, which fragment is shown) over the plan each worker executes for one fragment: a `RefreshStageExec` stages the replacement file from the stored values and the rows `StaleRowsExec` selects, computed by a `ProjectionExec` for an expression column or a `PythonUdfExec` for a Function column. Nothing runs: the plan is built against a snapshot without submitting a job, starting a Function executor or taking a table lock. A refresh started later pins its own source version. Job metadata and the final result retain the original Job `source_version`. If a concurrent `UPDATE` or compaction invalidates staged fragments, a Function declaring `result_stability=input_and_context` and `side_effects=none` can re-plan the affected connected fragments for at most three job-wide rounds. Each successor request explicitly pins the newer snapshot it plans, executes, and finalizes against. These request-local snapshots do not replace the Job's original source pin. Unaffected staged results commit without rerunning, while effectful or per-call Functions fail with the named concurrent-write error. `EXPLAIN [VERBOSE] JOB '<job_id>'` renders the same tree for a submitted job, with the registry's view on the root: state, progress and the job's options. The tree is rebuilt from the job's spec against the table's current version on its branch (the root's `source=`), not the snapshot the job pinned when it started, so a representative fragment can differ from what a worker ran. A job whose work is not a plan, such as an index build or a compaction, renders its root alone. The predicate also accepts `_rowaddr` and `_rowid`. To retry specific rows reported by `table.function_errors()`, use each record's `row_id` with `_rowid` when it is present. This stable ID continues to identify the same logical row after compaction or another rewrite: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE _rowid IN (506, 507) ``` For records without `row_id`, combine `fragment_id` and `row_offset` as `(fragment_id << 32) | row_offset` and select those physical addresses before compaction or another rewrite moves the rows: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE _rowaddr IN (0, 4294967297) ``` Only matching live rows are recomputed. A successful Function refresh removes their earlier row errors from `function_errors()` and `SHOW ERRORS` when their physical locations have not changed; rows that fail again remain listed. After compaction or another rewrite moves a row, `_rowid` still selects it, but its earlier error may remain listed even when the retry succeeds. Error clearing currently matches physical locations, not stable row IDs. Older error records and tables without stable row IDs may omit `row_id`. Errors without an individual row location, including those whose per-row detail was capped, cannot all be selected individually. ### Options | Option | Meaning | | - | - | | `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | | `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | | `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | | `gpu_class` | operator-defined GPU pool, such as `'a10g'` or `'h100'` | | `gpu_count` | aggregate GPU ceiling across the refresh's Function workers | | `max_executor_processes_per_worker` | cap on executor processes per worker | | `batch_size` | hard maximum rows passed to one Function call; LanceDB normally chooses a smaller adaptive size | | `error_policy` | Function columns only: `'fail'` (default) stops after configured retries; `'skip'` writes null outputs and records row errors, subject to failure limits | | `retry_policy` | JSON policy for bounded retries of failed user-code calls; overrides the Function default | | `max_failed_fraction` | with `'skip'`, fail after more than this fraction of evaluated rows fail; between `0` and `1` | | `max_failed_rows` | with `'skip'`, fail after more than this many evaluated rows fail | | `row_timeout_seconds` | maximum time per Function call in seconds; overrides the Function's declared deadline and informs adaptive call sizing for this refresh | | `init_timeout_seconds` | maximum time for a Function `__init__` handshake in seconds; default `900`, separate from row execution and task preparation timeouts | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` `num_workers` sets a fixed worker count for expression-backed refreshes. Registered Function columns reject `num_workers`, even without a resource budget. Their worker count adapts within the aggregate resource ceiling. The example above allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the Function workers together. It does not reserve those resources for each worker or guarantee that all of them will be used. `gpu_count` may be set alone to use the deployment's default CPU and memory. When setting either `cpu_millis` or `memory_bytes`, provide all three budget fields. For a CPU-only Function, use `gpu_count = 0` in the complete budget: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN caption_length ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 0) ``` LanceDB adjusts the amount of work sent to each worker from observed execution time. `batch_size` limits rows in one Function call; it does not set the worker count or the size of a checkpoint. Small initial batches are expected while the refresh learns how long rows take. GPU class names are lowercase names of at most 63 letters, digits, or hyphens. The REST `backfill_column` body accepts `gpu_class`, `gpu_count`, and `init_timeout_seconds` as top-level options with the same validation and budget semantics as SQL. ### Retrying temporary Function errors Set `retry_policy` on a source Function at registration, or override it for one refresh. The same JSON object is accepted by `CREATE FUNCTION ... WITH (retry_policy = '...')` and by the registration and refresh REST APIs. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN caption ON videos WITH ( retry_policy = '{"max_attempts":3,"transient":true,"initial_backoff_seconds":0.2,"max_backoff_seconds":30}', error_policy = 'skip' ) ``` `max_attempts` includes the first call and accepts 1–100. An explicit `{"max_attempts":1}` disables user-code retries, including the built-in transient retry. Omitting the option preserves the Function default and existing behavior. Choose one or more matchers; matching any one allows retry: | Field | Matches | | - | - | | `exception_types` | Exception class names, preferably qualified, such as `["builtins.ConnectionError"]`; subclasses also match | | `message_pattern` | A regular expression in the rendered exception class and message | | `error_codes` | Structured provider codes or HTTP status codes, such as `["SlowDown", "503"]` | | `transient` | Built-in `ConnectionError`/`TimeoutError`, the Botocore transport exceptions listed below, HTTP 429/503, and provider codes `SlowDown`/`ServiceUnavailable` | The Botocore transport exceptions are `ReadTimeoutError`, `ConnectTimeoutError`, and `EndpointConnectionError` from `botocore.exceptions`. Requests and HTTPX transport exceptions require explicit `exception_types`, such as `["requests.exceptions.ConnectionError", "httpx.TransportError"]`. The runtime also checks wrapped causes. It does not infer a transient error from digits such as `429` appearing in an arbitrary message. An adapter may signal throttling with `status_code` or `code`, and `retry_after_seconds`. Message patterns must compile under both Rust's regex validator and the Function environment's Python `re` module. Retries use exponential backoff with full jitter. `initial_backoff_seconds` defaults to 0.2 and `max_backoff_seconds` to 30; both must be finite, between 0 and 3600, with the initial value no larger than the maximum. `honor_retry_after` defaults to `true` and honors HTTP `Retry-After` or the adapter's `retry_after_seconds`. A requested delay above the configured maximum ends retry instead of calling the provider early. Cancellation interrupts backoff. The retry unit is one row for a row Function and one whole call for a batch Function. Completed calls are not repeated. With an explicit policy, a failed batch is not bisected after retries: `skip` nulls every row in that failed call and records its error and `attempts`. Use a row Function when failures must be isolated to individual rows. Output conversion and partially consumed generator results are not retried. Invalid values in a returned batch are isolated from that existing result, without calling the Function again. Only opt in when repeating a partially failed call is safe. The runtime cannot undo effects a call performed before raising. Functions declaring external side effects are refused. User-code retries do not consume the worker's infrastructure attempt budget; initialization, worker loss and OOM recovery keep their own policy. After exhaustion, `fail` fails the job and `skip` records the last error and count in `SHOW ERRORS` and the table errors API, subject to the normal failure limits. A Function image created before retry support must be registered as a new version before a refresh can override its policy. ### Hugging Face model snapshots A Function can declare immutable Hugging Face repositories and revisions during registration. The worker prepares each declared snapshot before it creates the user Function instance: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import HuggingFaceModel, udf MODEL = HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", ) @udf( name="embed_text", pip=["sentence-transformers==3.3.1"], models=[MODEL], ) class EmbedText: def __init__(self): from sentence_transformers import SentenceTransformer self.model = SentenceTransformer( "sentence-transformers/all-MiniLM-L6-v2", ) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() ``` Each repository may be declared once, and its revision must be the full 40-character commit hash. A completed snapshot stores that revision in `refs/main`, so the original no-revision `SentenceTransformer(repo)` call resolves without contacting the Hub. Model-declaring Functions run with a private `HF_HOME`, `HF_HUB_OFFLINE=1`, and `TRANSFORMERS_OFFLINE=1`; those environment variables cannot be overridden through the Function `env`. Before SQL execution or refresh worker admission, a shared preparation job imports the snapshot into database object storage. Concurrent consumers with the same database storage, pinned Secret scope, repository and revision reuse that attempt and its immutable snapshot. A code-only Function version can reuse the snapshot when these inputs are unchanged. Preparation failures are retained: waiting consumers do not automatically retry Hugging Face. An operator with System `Operate` privilege can retry the observed preparation job through `POST /v1/jobs/retry_model_preparation`, with `{"job_id":"<observed preparation attempt>"}`. After preparation succeeds, resubmit failed queries or refreshes; retrying the import does not restart them. Workers read prepared snapshots from database storage into a local model cache. With `computedRefresh.execution.imageCache.hostPath`, workers on one node share those local bytes. Without it, local materialization is private to the worker, while the shared snapshot still avoids repeated origin downloads. `computedRefresh.execution.modelCache.maxBytes` bounds local model bytes independently of the image cache, with a default of 32 GiB. A snapshot that does not fit is rejected before user code starts. For refreshes, `computedRefresh.execution.modelCache.preparationConcurrency` limits concurrent worker preparation requests to 16 by default. A request releases its slot when the snapshot is ready, without waiting for Python initialization. This per-refresh window does not impose a cluster-wide bandwidth quota. Without `models`, the existing behavior is unchanged: the Hub client may still request metadata or missing files, so a cached model and pinned revision alone do not guarantee offline execution. ### Discovering GPU classes ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GPU CLASSES; ``` The result lists the legacy `default` class first, followed by named classes. Columns are `name`, `resource_name`, `gpu_model`, `gpu_memory_bytes`, `max_gpu_count_per_worker`, `cpu_millis`, `memory_bytes`, and `ephemeral_storage_bytes`. Optional values are `NULL` when the operator did not configure them. A non-NULL `max_gpu_count_per_worker` bounds adaptive growth for one worker; NULL leaves the refresh's aggregate GPU budget as the ceiling. The authenticated REST endpoint `GET /v1/gpu/classes` returns the same catalog as `gpu_classes`. It reports configured hardware, not current free capacity. ### Row errors Set `error_policy` on the refresh, not on the Function definition. With `skip`, inspect the recorded failures with `SHOW ERRORS` or `table.function_errors()` and retry the affected rows after fixing the cause. Skipping row errors does not suppress initialization, infrastructure, or publication failures. Under `error_policy = 'skip'`, a refresh defaults to failing when more than 50% of the first 1,000 evaluated rows in a fragment part fail. It also fails if the first 100 evaluated rows fail before any successful row. `max_failed_fraction` or `max_failed_rows` replaces that default fraction; when both are present, either limit can fail the Job. The counters are evaluated rows, not Function calls. Checks continue cumulatively after the 1,000-row sample and also run when a smaller part finishes. `batch_size` defines call boundaries: the worker checks the shared counts after every inner Function call, so a row-capped batch cannot continue past the ceiling. The part that crosses a limit is not published; fragments committed before it remain visible. LanceDB normally sizes calls from observed row latency and targets at most 25% of the row deadline. `batch_size` remains a hard upper bound, not a tuning requirement. For a Function whose image declares `result_stability=input_and_context` and `side_effects=none`, a timeout or resource failure can enter range recovery, which retries smaller physical-row ranges with a fresh executor. Under `error_policy = 'skip'`, a row timeout can enter range recovery when the Function declares `side_effects=none`, including when its result stability is undeclared or `per_call`. Ordinary vectorized batch exceptions already use the same best-effort bisection under skip. Because a failed batch has no row results to salvage, healthy calls in that batch run again and a per-call Function may return different values. A single row that still times out is written as null and recorded as one `RowTimeoutError`. Functions with declared effects are not replayed automatically. A quarantined terminal row is an exception to the per-part failure limits. Under `skip`, this applies to an OOM-poison row in a replay-safe Function, a typed `OversizedRows` failure for exactly one physical row after range recovery has reduced the unfinished work to that same row, and a non-interruptible row timeout in a `side_effects=none` Function. Oversized-row quarantine requires the executor evidence to name one physical row that matches the only unfinished row in the recovery range; multi-row or mismatched evidence does not become a skipped row. OOM and oversized-row quarantine require `result_stability=input_and_context` and `side_effects=none`; declared effects disable automatic replay. Under the default `fail`, a terminal oversized row fails the refresh without a skipped-row record. Quarantine writes one null row as a synthetic part, so applying the per-part fraction or initial-100-row guard there would reject every quarantine. Before bisecting, the supervisor retries the OOM-killed claim once by itself with one executor process on the largest eligible worker class; a row timeout reaches quarantine only after its execution range has been reduced to one row. The skipped row still counts toward the cumulative job-level failure limits, and the job fails if the quarantined rows cross either limit. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip', max_failed_fraction = 0.05) ``` Per-row Function failures can include a Python traceback, bounded to a UTF-8 prefix or omitted when the reported errors exceed the byte limit. The compact error message and skipped-row count remain complete. The persisted error file can retain a prefix of records in row order while `rows_skipped` covers the full count. If the compact skipped-row reports alone exceed the event limit, the refresh fails before publication. Skipped-row tracebacks require a newly baked source image. ### Long-running Functions Source Functions default to a 300-second deadline per row. Set `row_timeout_seconds` high enough for the longest row, for example: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN analysis ON videos WITH (row_timeout_seconds = 3600) ``` The batch watchdog accommodates the row deadline and the number of input rows, so a row allowed an hour can run past 15 minutes. In vectorized mode, the row deadline applies to each vectorized call. Automatic sizing starts with a small probe and adjusts later calls; an explicit `batch_size` only lowers the ceiling. A source Function can call `heartbeat()` from the runtime-provided `lance_progress` module inside `__call__` to report liveness. Heartbeats do not extend the row deadline. `init_timeout_seconds` bounds only the interval from `Initialize` until the worker receives `Initialized`; image preparation, Secret resolution, and cleanup have their own bounded task handling. While a worker is waiting for `Initialized`, `SHOW JOBS` progress reports the `initializing` phase and initialized worker counts. It does not count endpoint readiness as initialization completion. If the budget expires, the refresh fails with an initialization-stage error and the bounded child stderr, even when `error_policy = 'skip'`. The row deadline does not extend the job's execution limit. On AWS deployments that vend temporary storage credentials, a Function refresh attempt is capped at **11 hours 40 minutes (42,000 seconds)**. A shorter deployment or job limit still applies; increasing the deployment timeout cannot lift this credential limit. Split longer work into disjoint filtered refreshes, keeping in mind that each predicate recomputes all matching rows. Other deployments use their configured job limit. Automatic column refreshes also have a 24-hour execution limit; an explicit refresh is still subject to the deployment and credential limits. > [!NOTE] > > `num_workers` is refused for a column filled by a registered > [function](/enterprise/v1-12-0/management/function); a Function refresh's worker count follows > its own resource budget instead. `error_policy` (and the other Function-only > options in the table above) is the reverse: it's refused for a plain > SQL-expression column, which has no per-row failures to skip, and accepted > only for a Function column. ### Automatic refresh timing Automatic column refresh requires a supporting server release and an enabled deployment. A column's `auto_refresh_interval_seconds` sets a minimum delay after its last successful refresh, not a completion deadline. The scheduler also waits for its computed inputs, available workers, and other refreshes. The deployment default allows one column refresh in flight per table. Failed automatic Function refreshes start with a 15-minute retry delay by default, then double it for consecutive failures: 15, 30, 60, 120 minutes, and so on. This is failure backoff, not a fixed refresh cadence. A manual refresh can run during that wait. Cancelling a Function refresh blocks automatic refresh for that binding on the same branch until a later explicit refresh completes or the binding is replaced. Check job history when automatic results stop appearing. ## REFRESH MATERIALIZED VIEW The syntax and options below apply to Enterprise deployments that support explicit `full = false` in SQL. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW <name> [WITH (full = <boolean>)] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks REFRESH MATERIALIZED VIEW chunks WITH (full = false) REFRESH MATERIALIZED VIEW chunks WITH (full = true) ``` A refresh updates the view's stored result. Refresh views in dependency order, starting with their source views. `CASCADE` is not supported. | Option | Meaning | | - | - | | `full = false` (default) | Refresh incrementally when supported, or rebuild when incremental refresh is unavailable. An eligible view whose sources are unchanged completes without rewriting data. | | `full = true` | Rebuild the complete stored result, even when the sources are unchanged. | > [!NOTE] > > Servers without SQL refresh option support require the basic statement without > `WITH`. Older servers may accept only `full = true`; some also accept `CASCADE`. > A local SDK's `refresh()` options do not determine which SQL options a server > accepts. ### Function row errors in materialized views Choose the policy when creating the view: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW captions WITH (error_policy = 'skip') AS SELECT id, caption(video) AS text FROM videos; ``` `error_policy = 'fail'` is the default, including for views created without this option. A Function failure aborts the refresh and preserves the previously published result. With `skip`, a failing scalar Function input produces NULL; a failing table Function input produces no output rows. Planning, storage, worker, and commit failures propagate to normal job failure and recovery handling; they are not converted into skipped inputs. Custom Function images must report a failure as attributable to the input before it can be skipped. Errors from older images that do not distinguish callable failures from worker failures stop the refresh. Use `SHOW ERRORS ON captions` or the SDK's `table.function_errors()` to inspect the diagnostics. `SHOW ERRORS` adds an `input` column containing JSON identifying the Function invocation and input offset. When a failed input can be traced to stored source rows, it also includes the source table, pinned version, and row address or stable row ID. Inputs computed by expressions or aggregations may have no single source row. Input offsets are not physical row offsets in the view. SDK error messages also include the source locator; use it instead of the view fragment fields for MV errors. Error records describe attempts and remain available after a later successful refresh. An incremental refresh over appended source rows leaves previously skipped inputs alone. When a change to existing source rows recomputes a block of the view, every input in that block runs again, skipped ones included. To retry them all, run: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW captions WITH (full = true); ``` A full refresh recomputes all inputs, including previously successful ones. The policy is fixed at creation; refresh does not accept a policy override. ### Interrupted materialized-view jobs LanceDB can replay `CREATE MATERIALIZED VIEW` and supported `REFRESH MATERIALIZED VIEW` operations, including `full = true`, after an infrastructure interruption. Other SQL statements remain non-replayable. A replacement worker keeps the same Job, job handle, and original deadline. A counted infrastructure disruption can use one replacement worker. User cancellation and permanent SQL or Function errors terminate the Job, and a terminal Job is not restarted. Recovery can run Function code again when the data commit has not completed, so external side effects from that attempt can repeat. After the data commit, receipt recovery finishes state and catalog publication without computing the committed rows again, and it does not need to plan the original source or Function. Cancellation does not guarantee that an in-flight storage write stops; a data or catalog request that was already issued or sent may still complete. Recovery therefore does not guarantee exactly-once execution of external side effects. ## Watching a refresh When a client requests an early job handle and the server can make the job registry available to it, the refresh returns a `job_id` with status `submitted`. The work then outlives the request. Track it with [`SHOW JOBS`](/enterprise/v1-12-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/enterprise/v1-12-0/sql/ddl/job#errors). The registry APIs require both `System Usage` and `System Operate`; refresh access scoped to a database or table is not enough. Submitting a Function refresh creates work; it does not reserve Function worker capacity or guarantee that a warm worker is available. A queued job reports a current admission observation when the dispatcher has one, but submission has no global queue position or start-time estimate. `CREATE MATERIALIZED VIEW` returns `(operation, name, status, job_id)`. The original three columns keep their positions; `job_id` is appended and is empty when the statement ran natively without a registry job. When the caller lacks both system privileges above, the server omits the early job-handle acknowledgement and the query continues through ordinary adaptive polling. Continue polling the returned descriptor until it completes, then read the result; the final refresh success or error is delivered through that path. When the bounded retained-run store is full, the server runs the refresh synchronously and reports its actual outcome without announcing a change of mode. A client must use the early acknowledgement and status `submitted`, rather than the presence of `job_id` alone, to decide that it received an early registry handle. Published view results remain visible whether the refresh was polled or run through the synchronous capacity fallback. Use `SHOW JOBS FOR JOB '<job_id>'` to discover a refresh's child jobs and inspect their phase, row progress, and attempt information. Pass a returned child ID to the same event command used for the parent: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOBS FOR TABLE frames; SHOW JOBS FOR JOB '<parent_job_id>'; SHOW JOB EVENTS '<child_job_id>' LIMIT 100; ``` Parent events do not include child events. Child diagnostics can expire at archival; the CLI reports unavailable history even when no rows remain. While a supervised refresh runs, `SHOW JOBS` includes a `progress` column containing a JSON sample: rows planned, computed, skipped and remaining, published and retained, failed rows, fragments planned and completed, active workers and active fragments, and the last row-progress timestamp when available. The same `progress` object is returned by `POST /v1/jobs/describe` and `POST /v1/jobs/list`. Samples update approximately every 30 seconds and after tracked progress changes. While at least one worker endpoint is ready and the latest sampled worker phase is `preparing`, `initializing`, or `initialized`, startup samples are published approximately every second so short initialization transitions are more likely to be observed. They are absent before the first sample and while the job is paused. Succeeded, failed, timed out, and canceled jobs retain the latest row progress and timing from the execution that ended, when a sample was recorded. Terminal jobs zero live worker, GPU, and active fragment counts and clear `resource_classes`, `warm_reused`, and wait reasons. `sample_at_millis` and `execution_epoch` identify that sample. A client may estimate remaining time from two observations only when the epoch and planned work are unchanged and accounted work advances; an estimate is unknown at startup, after a pause or epoch change, and when either sample is missing or stale. The Python SDK exposes a defensible estimate as `estimated_remaining_time_millis` and omits the field when the evidence is insufficient; the server does not persist or return a historical sampler. The optional `worker_fleet` object reports the Function-role worker cohorts from the supervisor's latest completed status observation. `desired` is the policy target for Function workers and can exceed the cohorts that have been created. `launched` counts surviving workers whose cohort launch was confirmed, `pending_workers` counts observed active workers not yet ready to accept dispatch, including workers still initializing. `ready` counts distinct endpoints in that launched set that can accept dispatch after status and worker announcements are merged. When an observation does not provide a usable pending count, readers may derive it from `active - ready`; this fallback only describes currently visible endpoint evidence and is not a guarantee about workers that have not yet become visible. `resource_classes` lists the observed class names. Draining, reaping, and dead workers are excluded consistently. `requested_gpus` totals the GPU devices requested by the observed Function cohorts; `ready_gpus` totals devices on dispatchable endpoints. Neither number is free cluster capacity or a queue position. `warm_reused` is `true` when at least one observed cohort was proven to come from a reusable pool. It is `false` only when every observed cohort was proven cold, and absent when no cohort was observed or the observations are incomplete. A `true` value does not guarantee that every worker in the fleet avoided a cold start. `worker_fleet` is absent until a coherent Function-worker observation exists. `first_launched_at_millis`, `first_ready_at_millis`, and `last_ready_at_millis` record milestones for the current supervisor run. Readiness means a dispatchable endpoint, not that Python initialization or the first function call has completed. When no dispatchable endpoint exists, `worker_fleet.wait_reason` may carry a fixed substrate-derived wait reason; it is cleared once an endpoint is ready or the job reaches a terminal state. The top-level `SHOW JOBS.phase` reports `queued`, `paused`, `starting`, `waiting_for_workers` (no Function workers have launched), and `starting_workers` (workers have launched but no endpoint is ready). Once an endpoint is ready, it mirrors the nested `progress.phase`, falling back to `running` until the first worker sample. The nested phase reports the observed worker phase: `preparing` before the initialization handshake, `initializing` while the worker is inside the `Initialize` handshake, `initialized` after a successful `Initialized` response, `running` while processing rows, `finalizing` while publishing, and `staged` after local output is staged. The top-level phase becomes `committing` once all planned rows are accounted for. Terminal jobs report `finished`, `failed`, or `cancelled` when the outcome is known. `workers_initializing` and `workers_initialized` count distinct live workers at those handshake boundaries; endpoint readiness alone does not increment either counter. These are sampled observations, so a short phase may be missed, and neither phase claims that every worker is in the same state. `queue_reason` is populated only from a current substrate observation; in particular, before a Function supervisor starts, the dispatcher may report that the job is waiting for executor capacity and include the worker slots requested and currently available. Those values are a point-in-time admission observation. A GPU-capacity reason requires PodScheduled=False evidence naming the requested GPU resource. CPU pressure, taints, and image-pull failures are not relabeled as GPU capacity waits. The object does not report global queue position or an ETA. `rows_computed` counts evaluated rows, including work later recomputed. `rows_published` counts evaluated rows backed by accepted publication receipts at the sample. `rows_retained` counts completed staged output that no accepted receipt has published yet; it is a sampled lower bound, not an exact final cancellation count. `rows_failed` is present only when a successful terminal result carries a typed failed-row count; it is not inferred from in-flight or non-successful job state. `active_workers` counts owners of execute claims, including workers that have not reported their first batch yet; it is separate from `worker_fleet.ready`. Job listings return the most recently created jobs first across tables. `SHOW JOB SPLITS '<job_id>'` returns completed splits and, while the refresh runs, the latest task for each split that has not completed. `state` preserves the worker's serialized phase, including phases introduced by a newer server; `queued`, `assigned`, `initializing`, `running`, `failed`, and `completed` do not share a closed mapping in older clients. Measurements that live evidence has not established are `NULL`, never a fabricated zero. `error_count` counts explicit failed execute completions for the current task identity in the current execution epoch, including failures that happened before a later retry or success. Expired leases are shown as `queued`; retries, expiry, success, replaced tasks, skipped rows, and row-level errors do not increment `error_count`, and they do not erase failures already recorded. Canceling a refresh leaves already published results visible. A later refresh of the same definition may reuse completed staged parts while its inputs and source provenance still match; parts affected by newer inputs or writes are recomputed or rejected under the concurrency rules above. Dropping a Function output column retires its binding and automatically cancels running and queued refreshes for that binding on the same table generation and branch. Failed drops and `IF EXISTS` drops that remove nothing leave refreshes running. Refreshes for other bindings are unaffected. `SHOW JOB SPLITS '<job_id>'` reports, per split: task, split and fragment identifiers, the worker that ran it, its row range, rows skipped, bytes read and staged, part and attempt counts, batch count, start and finish times, `state`, `error_count`, and the executor batch latency as p50/p95/p99/max in milliseconds. A split the supervisor recovered from a checkpoint rather than a worker report carries `recovered = true`. `POST /v1/jobs/query_splits` reports completed split records only -- not the live, not-yet-completed rows the SQL form returns while the refresh is still running -- and its records carry a different shape: no `state` or `error_count`, and a raw latency histogram in place of the SQL form's precomputed quantiles. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOB SPLITS 'j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames'; ``` `DESCRIBE JOB '<job_id>'` -- also spelled `SHOW JOB SUMMARY '<job_id>'`, or abbreviated `DESC JOB` -- shows where a finished job spent its time, one line per row as `EXPLAIN` shows a plan: its totals, a timeline of its phases, and for a phase that runs on many workers at once, what their time went to. It works for any job; for a Function refresh the phases are queued, planning, starting workers, running splits and committing. A job still running returns no rows. `FORMAT TABLE` returns the same profile as typed rows, with `unit` saying whether `millis` is wall time or worker time, and `FORMAT JSON` as one JSON document. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE JOB 'j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames'; ``` ``` j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames 18.7 s · 6 fragments · 300,000 rows · 102 splits · 6 workers Timeline at took queued +0.00 s 0.18 s planning +0.18 s 0.13 s starting workers +0.31 s 0.36 s launch 0.12 s, ready 0.01 s, dispatch 0.23 s running splits +0.67 s 16.45 s 88% committing +17.12 s 1.47 s publishing 1.40 s, final claim 0.06 s finishing +18.59 s 0.11 s Worker time, running splits (109 s) supervisor handoff 36% 39.6 s instance start 30% 33.0 s finalizing fragments 13% 14.6 s in the Function 10% 10.8 s idle 7% 7.5 s reading and writing 1% 1.6 s other 1% 1.5 s reporting, slot waits, uploads ``` Across refreshes, the `system.public.function_refresh_metering` view holds one row per succeeded refresh with the same summary, once the job events export has run. It needs system Usage and Select on the view. This grants access to refresh metering across all databases in the cluster; the connection's database does not filter the view. Only grant this access to users who may read cluster-wide usage. `SHOW JOBS` instead lists jobs in the connected database. Choosing a database in the SDK does not narrow an API key's permissions. For a database-specific report, filter `database_name` explicitly, as below. This query filter is not an access control boundary. Compare a Function's versions, or follow one over time: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT function_version, count(*) AS refreshes, avg(slot_occupancy) AS mean_occupancy, max(batch_latency_p95_millis) AS worst_p95_millis FROM system.public.function_refresh_metering WHERE database_name = 'my_database' AND function_id = 'embed' GROUP BY function_version; SELECT job_id, rows_assigned, splits, finished_at_millis - supervisor_started_at_millis AS millis FROM system.public.function_refresh_metering WHERE database_name = 'my_database' AND function_id = 'embed' AND ended_at_millis > 1793000000000 ORDER BY ended_at_millis DESC; ``` ## See also > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > The same operation from the SDKs, and what a refresh guarantees. > [card] [Table](/enterprise/v1-12-0/sql/ddl/table#alter) > > Declaring the columns this fills. # REFRESH COLUMN Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/refresh-column Fill computed outputs and select rows to recompute. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB extension with no DataFusion equivalent. It is what makes [feature engineering](/enterprise/v1-12-0/feature-engineering) reachable from SQL: a column declared by [DDL](/enterprise/v1-12-0/sql/ddl/table#computed-column) starts empty, and a refresh fills it. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN <column> ON [TABLE] <table> [WHERE <predicate>] [WITH (<option> = <value> [, ...])] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` Without `WHERE`, a refresh fills unassigned rows and recomputes values whose inputs changed, leaving other current values alone. A retry after a failure can still repeat work that was not committed. With `WHERE`, a refresh **recomputes every matching live row**, including rows that already have current values. Repeating a predicate can repeat the Function calls and their cost. To select only null outputs within a slice: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even if their inputs changed. It also selects outputs that were successfully computed as `NULL`. Use an unfiltered refresh to let LanceDB track which outputs need updating. ## Options | Option | Meaning | | - | - | | `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | | `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | | `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | | `gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | | `gpu_class` | GPU class name for the refresh's workers. Function columns only | | `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | | `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` The example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the Function workers together. It does not reserve those resources per worker or guarantee a worker count. When setting CPU or memory, provide all three budget fields. A complete CPU-only budget uses `gpu_count = 0`. Set `error_policy` on the refresh, not on the Function definition. With `skip`, inspect failures with `SHOW ERRORS` or `table.function_errors()` and retry the affected rows after fixing the cause. Initialization, infrastructure, and publication failures can still fail the job. > [!NOTE] > > `num_workers` is refused for a column filled by a registered > [function](/enterprise/v1-12-0/management/function), which sizes its own workers from the CPU, > memory and GPU options instead. `error_policy` (and the Function-only options > above it in the table) is the reverse: it's refused for a plain SQL-expression > column, which has no per-row failures to skip -- it's accepted only for a > Function column. ## Watching a refresh A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/enterprise/v1-12-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/enterprise/v1-12-0/sql/ddl/job#errors). For per-split progress, worker fleet detail, and a `DESCRIBE JOB` example, see [Watching a refresh](/enterprise/v1-12-0/sql/dml/refresh#watching). ## See also > [card] [Refresh a computed column](/enterprise/v1-12-0/feature-engineering/refresh-column) > > The same operation from the SDKs, and what a refresh guarantees. > [card] [Table](/enterprise/v1-12-0/sql/ddl/table#alter) > > Declaring the columns this fills. > [card] [REFRESH MATERIALIZED VIEW](/enterprise/v1-12-0/sql/dml/refresh-materialized-view) > > Bringing a view's stored result up to date, instead of a column. # REFRESH MATERIALIZED VIEW Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/refresh-materialized-view Bringing a materialized view's stored result up to date. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB extension with no DataFusion equivalent. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW <name> [WITH (full = <boolean>)] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks REFRESH MATERIALIZED VIEW chunks WITH (full = true) ``` A refresh updates the view's stored result. Refresh views in dependency order, starting with their source views. `full = true` forces a complete rebuild even when the sources are unchanged; the default, `false`, refreshes incrementally when supported and rebuilds otherwise. > [!NOTE] > > `CASCADE` is not accepted by the SQL implementation described here, > regardless of what a local SDK's `refresh()` method accepts -- do not > assume the two option sets match. ## Resource budgets Enterprise 1.12.0 supports only the `full` refresh option. It rejects CPU, memory and GPU budget options for materialized-view refreshes. ## Watching a refresh A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/enterprise/v1-12-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/enterprise/v1-12-0/sql/ddl/job#errors). For per-split progress, worker fleet detail, and a `DESCRIBE JOB` example, see [Watching a refresh](/enterprise/v1-12-0/sql/dml/refresh#watching). ## See also > [card] [Materialized View](/enterprise/v1-12-0/sql/ddl/materialized-view) > > Creating the view this refreshes. > [card] [Refresh a materialized view](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view) > > The same operation from the SDKs, and automatic refresh. > [card] [REFRESH COLUMN](/enterprise/v1-12-0/sql/dml/refresh-column) > > Filling a computed column, instead of a view. # Update Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dml/update UPDATE ... SET ... WHERE, and why it does not recompute derived columns. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} UPDATE documents SET title = upper(title) WHERE category = 'film' ``` Assignments take any expression the [dialect](/enterprise/v1-12-0/sql/dql/functions) supports, including references to other columns of the same row. Without a `WHERE` clause every row is updated. > [!WARNING] > > An update does not recompute [computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column) > that derive from the column you changed. Those rows keep the value computed from > the old input until the next refresh recomputes them. See > [Guarantees](/enterprise/v1-12-0/basics/guarantees#jobs). Commits a new table version, so [versioning](/enterprise/v1-12-0/management/table#versioning) and the [write guarantees](/enterprise/v1-12-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Update](/enterprise/v1-12-0/ingestion/update) > > The SDK equivalent. # Aggregation Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/aggregation GROUP BY, HAVING, and the aggregate function set. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL aggregates to summarize records, either across a whole table or within groups. Common examples include counts by category, totals and averages. ## Grouping ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, count(*) AS n, avg(score) AS mean_score FROM documents GROUP BY category HAVING count(*) > 10 ORDER BY n DESC ``` `WHERE` filters rows before grouping; `HAVING` filters groups after. Use `WHERE` for row-level conditions and `HAVING` for conditions on aggregate results. The planner may push eligible predicates earlier in the query. Grouping by several expressions produces one row per distinct combination: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, source, count(*) FROM documents GROUP BY category, source ``` ## Aggregate without grouping Omitting `GROUP BY` aggregates the whole table into one row, which is the usual way to ask how big something is: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*), min(created_at), max(created_at) FROM documents ``` `count(*)` counts rows; `count(col)` counts non-null values, which is how you measure how populated a [computed column](/enterprise/v1-12-0/feature-engineering/add-computed-column) is before deciding to refresh it again. ## The function set Registered in DataFusion 54. Names below are what is actually available. **General** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} count sum min max avg median bit_and bit_or bit_xor bool_and bool_or first_value last_value nth_value grouping ``` **Statistical** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} stddev stddev_pop stddev_samp var var_pop var_samp corr covar_pop covar_samp regr_slope regr_intercept regr_count regr_r2 regr_avgx regr_avgy regr_sxx regr_syy regr_sxy ``` **Approximate** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} approx_distinct approx_median approx_percentile_cont approx_percentile_cont_with_weight percentile_cont ``` **Collecting** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} array_agg string_agg ``` The approximate functions are the ones worth reaching for on a large table. `approx_distinct` answers "roughly how many distinct values" for a fraction of what `count(DISTINCT ...)` costs, which can help with high-cardinality columns. Measure the accuracy and runtime for your workload. `DISTINCT` works inside an aggregate: `count(DISTINCT category)`. `FILTER` narrows one aggregate without narrowing the others: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*) AS total, count(*) FILTER (WHERE score > 0.9) AS confident FROM documents ``` ## Aggregating a sample For an estimate over a very large table, aggregate a [sample](/enterprise/v1-12-0/sql/dql/sampling) rather than the whole thing: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, count(*) * 100 AS estimated FROM documents TABLESAMPLE (1) GROUP BY category ``` For a uniform percentage sample, counts and sums can be scaled by the inverse of the sample fraction to estimate whole-table values. Do not apply that scaling to averages, minima or maxima. Small samples can miss rare categories; consider the sampling method and uncertainty when interpreting the result. ## What aggregation does not do Aggregates run over rows the query already produced. Whether a statement can include [vector search](/enterprise/v1-12-0/search/vector-search) is described under [SQL vector search](/enterprise/v1-12-0/basics/sql#no-vector-sql). If your server does not support that query form, run the search in an SDK and aggregate its result, or materialize the search output first. # BLOB_DESCRIPTOR Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/blob-descriptor The blob_descriptor() scalar function: a BlobV2 column's payload location, without reading it. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, blob_descriptor(video) AS descriptor FROM videos ``` A plain `SELECT` of a [BlobV2](/enterprise/v1-12-0/management/table#managed-blobs) column returns its payload as `large_binary`. `blob_descriptor` instead returns a small struct describing where the payload lives, without reading the payload. Pass one row's descriptor to the SDK's blob file reader to open that payload directly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM videos").read_all().to_pylist() with table.open_blob_file(rows[0]["descriptor"]) as reader: payload = reader.read() ``` A descriptor is pinned to the table version it was read at: it keeps resolving correctly even after the table is appended to and checked out to a newer version. ## What to read next > [card] [Managed blobs](/enterprise/v1-12-0/management/table#managed-blobs) > > The BlobV2 column type this function describes. # Changes since a version Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/changes CHANGES: read the rows appended to a table since an earlier version. **Applies to:** Embedded ❌, Enterprise ✅ `CHANGES` reads the rows appended to a table since an earlier [version](/enterprise/v1-12-0/management/table#versioning), without rescanning rows that were already there: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) ``` This returns the rows appended after version 42, up to the table's current version at the time the query runs. ## Strictly append-only The clause is named for what it requires, not just what it does: every change to the table between the starting version and the current one must be an append. If any of them inserted with changes other than a pure append \-- an update, a delete, a merge -- the query is refused rather than silently returning an incomplete or wrong result. Re-run it with a later starting version that is itself after the non-append write, or read the table in full instead of incrementally. `INFORMATION => APPEND_ONLY` is the only supported value: it names what kind of history the clause is willing to read, not a choice among several. `AT (VERSION => ...)` takes a positive integer; there is no `AT (TIMESTAMP => ...)` form for this clause, unlike other version qualifiers. ## Where the clause can go It attaches to a table in `FROM`, including inside a subquery, a CTE, a join, a set operation, or `EXPLAIN`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH recent AS ( SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) ) SELECT count(*) FROM recent SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 10) a JOIN events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 20) b ON a.id = b.id ``` Each occurrence of a table keeps its own starting version, even when the same table is referenced more than once in one statement. ## Unsupported forms | | | | - | - | | `CHANGES (INFORMATION => DEFAULT)` | only `APPEND_ONLY` is supported | | `AT (TIMESTAMP => ...)` | only `AT (VERSION => ...)` is supported | | `AT (VERSION => 0)` | the starting version must be positive | | `... END (VERSION => ...)` | not supported; the current version is always the end | | `CHANGES ... TABLESAMPLE (...)` | cannot be combined on the same table reference | ## What to read next > [card] [Table](/enterprise/v1-12-0/sql/ddl/table) > > CREATE, ALTER, CLONE and versioning basics. > [card] [Select](/enterprise/v1-12-0/sql/dql/select) > > The rest of the query grammar this clause attaches to. # CONTAINS_TOKENS Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/contains-tokens The contains_tokens() scalar function: an index-accelerated keyword predicate usable directly in WHERE. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM my_docs WHERE contains_tokens(text, 'fox jumps dog') ``` `contains_tokens(column, tokens)` is true when `column` contains **all** the tokens in `tokens`, split on whitespace and punctuation. It is equivalent to an [`fts()`](/enterprise/v1-12-0/sql/dql/fts) match query with fuzziness off, `AND` semantics and the simple tokenizer -- reach for it when you need a keyword test in a `WHERE` clause and have no use for a relevance score. **Index-accelerated.** When the column has a full-text index that suits the query, the planner uses it instead of scanning, which is the reason to prefer it over `LIKE` or `contains` for keyword tests. See [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain) to confirm the plan uses the index. ## What to read next > [card] [Full-Text Search](/enterprise/v1-12-0/sql/dql/fts) > > The `fts()` table function, for relevance-ranked results and fuzzy, > phrase, boolean, boost and multi-match queries. > [card] [FTS Index](/enterprise/v1-12-0/indexing/fts-index) > > Build the full-text index this predicate accelerates against. # DEDUPE Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/dedupe The dedupe() table function: one representative row per near-duplicate group, scanned over the index. **Applies to:** Embedded ❌, Enterprise ✅ `dedupe` scans a vector column's [index](/enterprise/v1-12-0/indexing/vector-index) partitions for rows closer than a distance threshold, resolves the overlapping pairs it finds into duplicate groups, and returns one representative row per group -- without a full pairwise scan or a shuffle. See [`duplicate_pairs`](/enterprise/v1-12-0/sql/dql/duplicate-pairs) to inspect the pairs themselves before committing to this resolution. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe( <table>, <vector_column>, distance_threshold => <float> [, resolution => 'connected_components' | 'direct_representative'] ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe( 'frames', 'vec', distance_threshold => 0.02 ) ``` > [!NOTE] > > Earlier releases spelled this `vector_dedup`; that name is rejected on > current deployments. ## Input | Argument | Type | Required | Meaning | | - | - | - | - | | table name | string literal | yes | the table to scan | | vector column | string literal | yes | the indexed vector column to compare | | `distance_threshold` | float | yes | maximum distance for a pair to count as close | | `resolution` | `'connected_components'` (default) \| `'direct_representative'` | no | how overlapping pairs group together -- see [Resolution](#resolution) | `dedupe` always scans every partition and returns original rows -- sampling a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/enterprise/v1-12-0/sql/dql/duplicate-pairs#input) but refused here. ## Output One row per duplicate group, **in the table's own schema** -- every column of `<table>`, including a BlobV2 column, comes through unchanged on the representative row Lance selected for that group. Unlike [`duplicate_pairs`](/enterprise/v1-12-0/sql/dql/duplicate-pairs#output), there is no fixed `dedupe`-specific schema to document: the output schema is the source table's schema. Because the result is already shaped like the table, it composes directly into a new table or a materialized view: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'vec', distance_threshold => 0.02 ) ``` ## Resolution `resolution` chooses how overlapping pairs group together: | `resolution` value | How pairs group | | - | - | | `connected_components` (default) | groups transitively: if a~~b and b~~c are both close, all three resolve together | | `direct_representative` | only pairs within the threshold of each other resolve together | ## Estimating on a sample first `dedupe` itself always scans every partition. To estimate a duplicate rate on a large table before committing to a full scan, sample partitions with [`duplicate_pairs`](/enterprise/v1-12-0/sql/dql/duplicate-pairs#sampling) instead, which accepts `selection`, `count` and `seed` for exactly this. ## What to read next > [card] [DUPLICATE_PAIRS](/enterprise/v1-12-0/sql/dql/duplicate-pairs) > > Inspect the close pairs themselves instead of the resolved groups. > [card] [Deduplicate near-duplicates](/enterprise/v1-12-0/curation/dedupe) > > When to reach for this instead of exact-key deduplication. # DUPLICATE_PAIRS Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/duplicate-pairs The duplicate_pairs() table function: every close pair in a vector column, scanned over the index. **Applies to:** Embedded ❌, Enterprise ✅ `duplicate_pairs` scans a vector column's [index](/enterprise/v1-12-0/indexing/vector-index) partitions for every pair of rows closer than a distance threshold, without a full pairwise scan or a shuffle. It returns one row per close pair, not one row per source row -- use it to inspect what would be collapsed before committing to [`dedupe`](/enterprise/v1-12-0/sql/dql/dedupe), which resolves these same pairs into groups. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( <table>, <vector_column>, distance_threshold => <float> [, id_column => <column>] [, selection => 'all' | 'first' | 'random', count => <int>, seed => <int>] ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02 ) ``` > [!NOTE] > > Earlier releases spelled this `vector_duplicate_pairs`; that name is rejected > on current deployments. ## Input | Argument | Type | Required | Meaning | | - | - | - | - | | table name | string literal | yes | the table to scan | | vector column | string literal | yes | the indexed vector column to compare | | `distance_threshold` | float | yes | maximum distance for a pair to count as close | | `id_column` | column name | no | project this column's value instead of the internal row ID -- see [Application-level identifiers](#id-column) | | `selection` | `'all'` (default) \| `'first'` \| `'random'` | no | which index partitions to scan | | `count` | int | no | number of partitions to sample when `selection => 'random'` | | `seed` | int | no | random seed when `selection => 'random'` | `resolution` is refused on `duplicate_pairs`: a pair has no notion of a group, only [`dedupe`](/enterprise/v1-12-0/sql/dql/dedupe#input) accepts it. ## Output One row per close pair found, in a fixed schema independent of the source table: | Column | Type | Meaning | | - | - | - | | `row_id_a` | uint64 | internal row ID of the first row in the pair, the same identifier as the [`_rowid`](/enterprise/v1-12-0/sql/data-types#pseudo-columns) pseudo-column | | `row_id_b` | uint64 | internal row ID of the second row in the pair | | `distance` | float32 | distance between the pair's vectors, at or below `distance_threshold`. For `l2`, this is the squared distance, not its square root | | `segment_id` | Utf8 | which index segment the pair was found in, a UUID | | `partition_id` | uint64 | which index partition the pair was found in | | `dataset_version` | uint64 | the dataset version the scan ran against | ### Application-level identifiers A row ID is internal and not stable across compaction. Pass `id_column`, a top-level scalar column such as a primary key, to also project its value: `id_a`/`id_b`, typed like `id_column`, are appended alongside `row_id_a`/`row_id_b`, which remain in the output. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02, id_column => 'frame_id' ) ``` ## Sampling partitions `selection` scopes the scan to a sample of partitions instead of all of them, the same `all` (default) / `first` / `random` choice as [`ivf_partition`](/enterprise/v1-12-0/sql/dql/ivf-partition). Use it to estimate a distance threshold or duplicate rate on a large table before scanning it in full: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02, selection => 'random', count => 100, seed => 42 ) ``` ## What to read next > [card] [DEDUPE](/enterprise/v1-12-0/sql/dql/dedupe) > > Resolve these same pairs into one representative row per group. > [card] [Deduplicate near-duplicates](/enterprise/v1-12-0/curation/dedupe) > > When to reach for this instead of exact-key deduplication. # Explain Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/explain EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE: reading and measuring a plan from SQL. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN SELECT * FROM documents WHERE identifier < 1000 EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` | Statement | What it returns | | - | - | | `EXPLAIN <query>` | Logical and physical plan, without executing the query. | | `EXPLAIN ANALYZE <query>` | Executes the query and annotates each operator with runtime metrics (rows, timing). | | `EXPLAIN VERBOSE <query>` | Adds intermediate optimizer plans on top of `EXPLAIN`. | The result is a small relation with `plan_type` and `plan` columns, read through the same client you use for regular queries. See [Connecting](/enterprise/v1-12-0/sql#connecting). SQL plans and the SDK's [`explain_plan` and `analyze_plan`](/enterprise/v1-12-0/basics/sql#query-plans) output share scan and index operators. Use the same approach to inspect index coverage and filter pushdown; SQL can also add joins, aggregates and other operators: > [card] [What it shows](/enterprise/v1-12-0/basics/sql#inspect-a-query-plan) > > Reading a plan: operators, pushdown, index usage. > [card] [What it measures](/enterprise/v1-12-0/basics/sql#analyze-a-query-plan) > > Reading the metrics, and a worked before/after. ## What to look for | Sign | Means | | - | - | | `ScalarIndexQuery` | the predicate used a scalar index | | `LanceScan` with high `bytes_read` | inspect the selected columns, filter pushdown and index use | | `FilterExec` above a search | the filter ran after search rather than pushing into it | | `ANNSubIndex` / `ANNIvfPartition` | the vector index was used | A `LanceScan` feeding a join is the common one worth acting on. See [Joins](/enterprise/v1-12-0/sql/dql/join#performance). For a table's columns and types without a plan, see [`DESCRIBE`](/enterprise/v1-12-0/sql/ddl/table#describe). # Full-Text Search Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/fts The fts() table function: match, fuzzy, phrase, boolean, boost and multi-match queries from SQL. **Applies to:** Embedded ❌, Enterprise ✅ Full-text search is a **table function**, `fts(table, query)`, rather than a predicate: it produces a relevance score alongside the matching rows, and a `WHERE` clause has nowhere to put one. The two string-literal arguments are the table name and a JSON-encoded query, built with the same query-builder classes used from the SDK and serialized with `.to_json()`. ## Setup Run these statements in order, sending one statement per SQL request. Semicolons separate the statements for clients that execute a script. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE my_docs (id INT, text STRING, category STRING, author STRING); INSERT INTO my_docs VALUES (1, 'The happy puppy runs merrily in the park', 'animals', 'Alice'), (2, 'A curious kitten jumps quickly over the fence', 'animals', 'Bob'), (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); CREATE INDEX ON my_docs USING fts (text); ``` > [!WARNING] > > Phrase queries need position information, which costs extra index size. > Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, > [phrase queries](#phrase) find nothing. See > [FTS parameters](/enterprise/v1-12-0/indexing/fts-index#fts-parameters). ## Basic search The query builder produces the JSON string used as the second SQL argument. The SQL examples below spell out the equivalent match object so they can be run directly after the setup above. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MatchQuery query = MatchQuery("puppy", "text") json_query = query.to_json() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, category FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) LIMIT 5 ``` By default the top 5 matches come back in **arbitrary order**. Select `_score` and order by it for relevance ranking: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, _score FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) ORDER BY _score DESC LIMIT 5 ``` `_score` is a pseudo-column carrying the query's BM25 relevance for the row; it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/enterprise/v1-12-0/sql/data-types#pseudo-columns). ## Fuzzy Tolerates typos, up to a character-edit budget: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} MatchQuery("pupy", "text", fuzziness=2) ``` ## Phrase Exact phrase, or with `slop` to allow words between terms: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import PhraseQuery PhraseQuery("happy puppy", "text") PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` ## Boolean Combine queries with `&` (AND) or `|` (OR): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} MatchQuery("puppy", "text") & MatchQuery("happy", "text") MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` ## Boost Weight a query up or down relative to another: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import BoostQuery BoostQuery( positive=MatchQuery("puppy", "text"), negative=MatchQuery("kitten", "text"), negative_boost=0.2, ) ``` ## Multi-match Search several columns at once, optionally weighting them differently: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MultiMatchQuery MultiMatchQuery("puppy", ["text", "category"]) MultiMatchQuery("puppy", ["text", "category"], boosts=[2.0, 1.0]) # text weighted 2x ``` ## Combining with SQL `fts()` is a relation, so it composes with the rest of the SQL surface. Filter, join, or aggregate over it same as any table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, category FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) WHERE category = 'animals' LIMIT 5 ``` ## What to read next > [card] [Full-Text Search](/enterprise/v1-12-0/search/full-text-search) > > The query-builder equivalent, and every query form in full. > [card] [FTS Index](/enterprise/v1-12-0/indexing/fts-index) > > Tokenizers, and the position information phrase queries need. # Functions Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/functions Where to find each kind of function, and the dialect version they come from. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB executes SQL with [Apache DataFusion](https://datafusion.apache.org), currently **version 54**. The function set is DataFusion's default registration plus what Lance adds. | | | | - | - | | [Scalar functions](/enterprise/v1-12-0/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct | | [Aggregate functions](/enterprise/v1-12-0/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | | [Window functions](/enterprise/v1-12-0/sql/dql/window#functions) | per window: ranking, offset, running aggregates | | [Table functions](#table-functions) | produce a relation rather than a value | > [!NOTE] > > Function availability is version-specific. DataFusion adds functions in most > releases, so one documented on `main` may not exist in 54. When a name is not > recognised, check it against the reference for that version before assuming a > bug. ## Table functions A table function appears in `FROM` and produces a relation, which is what lets it return columns a scalar function has nowhere to put. Each has its own reference page: | | | | - | - | | [`fts(table, query)`](/enterprise/v1-12-0/sql/dql/fts) | full-text search, with a relevance score alongside the matching rows | | [`dedupe(table, column, ...)`](/enterprise/v1-12-0/sql/dql/dedupe) | one representative row per near-duplicate group | | [`duplicate_pairs(table, column, ...)`](/enterprise/v1-12-0/sql/dql/duplicate-pairs) | every close pair, before resolving into groups | | [`generate_series(start, stop)`](/enterprise/v1-12-0/sql/dql/generate-series) | rows from a range | `_score`, the relevance pseudo-column `fts()` produces, is not a function; see [Data types](/enterprise/v1-12-0/sql/data-types#pseudo-columns). ## What Lance accelerates `contains_tokens` uses an index rather than scanning, which is the difference between a fast predicate and a slow one: | | Index used | | - | - | | [`contains_tokens`](/enterprise/v1-12-0/sql/dql/contains-tokens) | full-text index | Confirm with [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain): an accelerated predicate shows an index node rather than a `LanceScan` followed by a filter. # GENERATE_SERIES Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/generate-series The generate_series() table function: rows from a range. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM generate_series( 1, 10 ) ``` Rows from a range, useful for building a dense axis to left-join sparse data onto. ## What to read next > [card] [Functions](/enterprise/v1-12-0/sql/dql/functions#table-functions) > > The other table functions: `fts`, `dedupe`, and `duplicate_pairs`. # IVF_PARTITION Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/ivf-partition The ivf_partition() scalar function: assign each row to its trained IVF index partition. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT ivf_partition(embedding, selection => 'random', count => 100, seed => 42) AS partition, array_agg(id) AS ids FROM documents GROUP BY partition ``` `ivf_partition` reads an existing IVF-family vector index's trained partitions and assigns each row to the one its vector falls into. The column needs an up-to-date, single-segment index before the function runs -- the same requirement [`dedupe`](/enterprise/v1-12-0/curation/dedupe#example-data) has. Grouping by its result buckets rows by vector proximity without a full pairwise scan -- useful for blocking a large table into comparable chunks, such as before a pairwise similarity pass. ## Input `ivf_partition` takes exactly 1, 3, or 4 arguments -- the vector column alone (scans every partition), or the vector column plus `selection` and `count`, plus `seed` only when `selection` is `'random'`: | Argument | Type | Required | Meaning | | - | - | - | - | | vector column | column reference | yes | the indexed vector column to assign | | `selection` | `'first'` \| `'random'` | required with `count` | which partitions to sample -- there is no explicit `'all'`; omit `selection` and `count` entirely to scan every partition | | `count` | int, > 0 | required with `selection` | number of partitions to sample | | `seed` | int, >= 0 | required for `'random'`, refused for `'first'` | random seed | Arguments can be passed positionally, `ivf_partition(embedding, 'random', 100, 42)`, or named as shown above. `count` and `seed` are the same scan-scoping arguments [`duplicate_pairs`](/enterprise/v1-12-0/sql/dql/duplicate-pairs#sampling) accepts, so a sampled partition estimate carries over -- but not `dedupe`, which always scans every partition and refuses sampling arguments entirely. ## What to read next > [card] [Cluster records by index partition](/enterprise/v1-12-0/curation/clustering) > > Use this function to group and sample records by an existing index's partitions. > [card] [DEDUPE](/enterprise/v1-12-0/sql/dql/dedupe) > > The packaged table function for the deduplication use case, over the same index. # Joins Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/join Combining rows from more than one table, including across namespaces. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL joins to combine rows from two or more tables. ## The join types ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.title, c.name FROM documents AS d JOIN categories AS c ON c.id = d.category_id ``` | | What it keeps | | - | - | | `[INNER] JOIN` | rows matching on both sides | | `LEFT [OUTER] JOIN` | every left row, nulls where the right has no match | | `RIGHT [OUTER] JOIN` | every right row | | `FULL [OUTER] JOIN` | every row from both | | `CROSS JOIN` | every combination (the product of the two) | `USING (col)` is shorthand for an equality join on a shared column name, and avoids repeating it in the select list. ## Across namespaces Tables in different [namespaces](/enterprise/v1-12-0/management/namespace) join like any other table, each addressed by its full `database.schema.table` identifier. The catalog is one catalog, so there is nothing to federate: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT c.id, u.email FROM prod.events.clicks AS c JOIN prod.reference.users AS u ON u.id = c.user_id ``` ## Joining a search result [`fts()`](/enterprise/v1-12-0/sql/dql/fts) is a table function, so its result is a relation and joins like any other. This example assumes `my_docs` has `text` and `category_id` columns, a full-text index on `text`, and a `categories` table with `id` and `name` columns: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT c.name, count(*) AS hits FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) AS m JOIN categories AS c ON c.id = m.category_id GROUP BY c.name ORDER BY hits DESC ``` That composition is the reason full-text search is a relation rather than a predicate: a `WHERE` clause has nowhere to put the relevance score. ## Performance A [scalar index](/enterprise/v1-12-0/indexing/scalar-index) can accelerate supported filters on the input tables. An index on a join key does not by itself guarantee an index lookup join. Use SQL [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain) to inspect the scans, filters, and join chosen for the complete statement. > [!WARNING] > > Avoid selecting blob or vector columns you do not need on either side of a join. > The join multiplies rows before projection is applied in some plans, so a wide > column can be materialized many more times than the result has rows. ## Late materialization for wide columns The planner can avoid the multiplication above: when a join narrows down to a key column before a wide one is needed, it can defer reading a BlobV2 or vector column until after the join has already settled which rows survive. See [Blob Late Materialization](/enterprise/v1-12-0/curation/blob-late-materialization) for the eligibility conditions, the `RemoteTake` operator, and how to confirm a specific query got the deferred read with [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain). # Operators and literals Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/operators Comparison, logical and arithmetic operators, literals, and precedence. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB uses DataFusion's SQL operators. This page describes comparison, logical and arithmetic operators, literal values, type conversions and operator precedence. ## Comparison | | | | - | - | | `=` `!=` `<>` `<` `<=` `>` `>=` | ordinary comparison | | `IS NULL` / `IS NOT NULL` | null test (`= NULL` is never true) | | `IS DISTINCT FROM` | comparison that treats null as a value | | `BETWEEN a AND b` | inclusive range | | `IN (...)` | set membership | | `LIKE` / `ILIKE` | pattern match, `%` and `_` | | `~` `~*` `!~` | regular expression match | > [!NOTE] > > For keyword matching on a text column, [`contains_tokens`](/enterprise/v1-12-0/sql/dql/contains-tokens) > is index-accelerated where `LIKE` is not. Reach for `LIKE` only when you need > its wildcard semantics. ## Logical `AND`, `OR`, `NOT`. Three-valued: a comparison against null is **unknown**, and `NOT unknown` is still unknown. A `WHERE` clause keeps only rows where the predicate is true, so unknown behaves like false there, but not inside `NOT IN`, which is the usual place this bites. See [Subqueries](/enterprise/v1-12-0/sql/dql/subqueries#in-exists). ## Arithmetic `+` `-` `*` `/` `%`, with the usual precedence. String concatenation is `||`. > [!WARNING] > > Arithmetic over a vector column is **list** arithmetic, not scalar arithmetic: > a vector is a `FixedSizeList<Float32>`. When the operation you want is a > similarity comparison, use [vector search](/enterprise/v1-12-0/search/vector-search); whether SQL > can express it [depends on the Enterprise server version](/enterprise/v1-12-0/basics/sql#no-vector-sql). ## Literals | | | | - | - | | String | `'text'`, with a doubled quote to escape: `'it''s'` | | Number | `42`, `3.14` | | Boolean | `TRUE`, `FALSE` | | Null | `NULL` | | Date / timestamp | `DATE '2026-01-01'`, `TIMESTAMP '2026-01-01 12:00:00'` | | Interval | `INTERVAL '7 days'` | | Array | `[1, 2, 3]` | Identifiers are quoted with double quotes when they need to be (a reserved word or a name with mixed case): `SELECT "order" FROM "MyTable"`. ## Casting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT CAST(identifier AS VARCHAR) AS with_cast, identifier::VARCHAR AS with_colons FROM documents ``` Both forms work. Give each its own alias when one projection uses both: they produce the same expression name, and a projection refuses two columns with one name. `TRY_CAST` returns null instead of erroring on a value that will not convert, which is the one to use over a column you do not control. ## Precedence Highest to lowest: `::` → unary `-` → `* / %` → `+ -` → `||` → comparison → `IS` → `NOT` → `AND` → `OR`. Parenthesize anything mixing `AND` and `OR`. `a OR b AND c` is `a OR (b AND c)`, which is rarely what was meant. # Random sampling Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/sampling TABLESAMPLE: draw a random subset of a table, by rows or by fragments. **Applies to:** Embedded ❌, Enterprise ✅ Use `TABLESAMPLE` to explore a subset of a table or estimate aggregate statistics. The sampling method determines how much data is read and whether the table's physical layout influences the sample. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE (10) -- 10 percent SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows ``` A bare number is a **percentage**. Add `ROWS` for a count instead. ## Rows or fragments The standard calls these two methods of one clause. They are different operations, and the difference matters on Lance: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE BERNOULLI (10) SELECT * FROM documents TABLESAMPLE SYSTEM (10) ``` | Method | Aliases | What it picks | | - | - | - | | `BERNOULLI` | `ROW` | rows, each considered independently | | `SYSTEM` | `BLOCK` | **Lance fragments**, and takes whatever rows they hold | `BERNOULLI` gives a genuinely uniform sample and reads across the whole table to get it. `SYSTEM` reads far less (it skips entire fragments), but the sample is only as uniform as the data's layout. If rows were written in an order that correlates with what you are measuring, a fragment sample inherits that correlation. Use `SYSTEM` for a quick look at the data and `BERNOULLI` when you need independent row sampling. Omitting the method gives `BERNOULLI`. ## Repeatability Without a seed, every execution resamples: running the same query twice gives different rows. `REPEATABLE` fixes the draw: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE (10) REPEATABLE (42) ``` Use the same seed and table snapshot to reproduce a sampling run. For a fixed evaluation set, save the selected row IDs or materialize the sample and retain its version. A seed alone does not preserve membership after source changes or changes to the physical layout. ## Where the clause can go It attaches to a table in `FROM`, including inside a subquery, a CTE, or either side of a join: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d SELECT * FROM a TABLESAMPLE (5 ROWS) JOIN b ON a.id = b.id SELECT * FROM t a TABLESAMPLE (10) JOIN t b TABLESAMPLE (10) ON a.id = b.id ``` Each side of a join samples independently. Sampling both sides of a join shrinks the *result* far more than either fraction suggests, because a row only survives if both its sides were drawn. ## Unsupported sampling forms Sampling is semantics, not a hint. A clause that were read and then not applied would be a wrong answer rather than a missing feature, so anything that cannot be honoured exactly is an error: | | | | - | - | | `TABLESAMPLE (101)` | a percentage outside `0..=100` is refused, not clamped | | `TABLESAMPLE (1.5 ROWS)` | a row count must be whole | | `TABLESAMPLE (BUCKET 1 OUT OF 4)` | bucket sampling is not supported | | `(SELECT ...) d TABLESAMPLE (10)` | a subquery's result cannot be sampled; sample the table inside it | | the `SAMPLE` spelling | use `TABLESAMPLE` | | the `OFFSET` modifier | not supported | > [!NOTE] > > `TABLESAMPLE` is also refused on a WAL-backed table, where the rows a sample > would draw from are not all in the fragments yet. ## Sampling outside SQL For a training loop rather than a query, the SDKs read a table in a shuffled order without going through SQL at all. See [Training](/enterprise/v1-12-0/training/data-loading), where a permutation drives the data loader. # Scalar functions Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/scalar-functions The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds. **Applies to:** Embedded ❌, Enterprise ✅ Functions that take a value and return a value, one row at a time. The set is based on DataFusion's registration plus Lance and deployment-specific functions. The names below are selected examples, not an exhaustive catalog for every deployment. Availability depends on the deployed version and build. For per-group functions see [Aggregation](/enterprise/v1-12-0/sql/dql/aggregation); for per-window, [Window functions](/enterprise/v1-12-0/sql/dql/window). ## Math ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} abs ceil floor round trunc signum power sqrt cbrt exp ln log log2 log10 factorial gcd lcm pi random nanvl isnan iszero cot degrees radians to_degrees to_radians sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh ``` ## String ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ascii bit_length btrim chr concat concat_ws contains ends_with starts_with levenshtein lower upper ltrim rtrim octet_length repeat replace split_part to_hex uuid ``` Unicode-aware variants: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} character_length find_in_set initcap left right lpad rpad reverse strpos substr substr_index substring translate ``` > [!NOTE] > > For keyword matching on a text column, [`contains_tokens`](/enterprise/v1-12-0/sql/dql/contains-tokens) > is index-accelerated where `contains` and `LIKE` are not. ## Regular expressions ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} regexp_count regexp_instr regexp_like regexp_match regexp_replace ``` ## Date and time ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} current_date current_time date_bin date_part date_trunc from_unixtime to_unixtime make_date make_time to_char to_date to_time to_local_time ``` `date_bin` is the one worth knowing for analytics: it buckets timestamps into fixed-width intervals, which is how you build a time series without a self-join. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT date_bin(INTERVAL '1 hour', created_at) AS hour, count(*) FROM events GROUP BY hour ORDER BY hour ``` ## Arrays and maps ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} make_array array_has array_filter array_transform array_any_match array_compact array_normalize array_slice arrays_zip cardinality flatten range generate_series ``` ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} map map_keys map_values map_entries map_extract ``` Distance functions over arrays: `cosine_distance`, `distance`, `exact_distance`, `inner_product`. Only `distance` and `exact_distance` take an options string, and only `distance` can plan as vector search; see [Vector distance functions](/enterprise/v1-12-0/sql/dql/vector-distance). ## Structs and fields ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} named_struct get_field coalesce nullif nvl nvl2 greatest least union_extract union_tag ``` ## Crypto and encoding ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} digest md5 sha224 sha256 sha384 sha512 encode decode ``` ## Type functions ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} arrow_cast arrow_try_cast arrow_typeof arrow_field arrow_metadata with_metadata version ``` Use `arrow_typeof` to inspect the Arrow data type of a column or expression: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT arrow_typeof(vector) FROM documents LIMIT 1 -- FixedSizeList(Field { name: "item", data_type: Float32, .. }, 1536) ``` `arrow_cast` casts to an Arrow type by name, reaching types SQL has no spelling for. See [Data types](/enterprise/v1-12-0/sql/data-types). ## What Lance adds These are registered by Lance on top of DataFusion's set, each with its own reference page: | | | | - | - | | [`contains_tokens`](/enterprise/v1-12-0/sql/dql/contains-tokens) | index-accelerated keyword predicate, usable in `WHERE` | | [`ivf_partition`](/enterprise/v1-12-0/sql/dql/ivf-partition) | assign each row to its trained IVF index partition | | [`blob_descriptor`](/enterprise/v1-12-0/sql/dql/blob-descriptor) | a BlobV2 column's payload location, without reading it | ## Additional scalar functions SQL queries can call functions registered with the server, including functions not listed on this page. Consult [DataFusion's scalar function reference](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) for version 54. Functions documented for a newer DataFusion release may not be available in your LanceDB Enterprise version. # SELECT Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/select Projection, filtering, ordering, and composing queries out of other queries. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [WITH cte AS (...)] SELECT [ALL | DISTINCT] select_expr [, ...] FROM from_item [[JOIN ...] ON ...] [WHERE predicate] [GROUP BY expr [, ...]] [HAVING predicate] [WINDOW name AS (...)] [ORDER BY expr [ASC | DESC] [NULLS FIRST | LAST] [, ...]] [LIMIT n] [OFFSET n] ``` ## Projection ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, title, identifier FROM documents ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search().select(["id", "title", "identifier"]).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.query().select(["id", "title", "identifier"]).toArrow(); ``` Name the columns you need instead of using `SELECT *`, particularly for tables containing images, video or large vectors. Projection lets the engine avoid loading unnecessary columns, although columns used by filters, joins or other expressions may still need to be read. Row metadata is available as [pseudo-columns](/enterprise/v1-12-0/sql/data-types#pseudo-columns) (`_rowid`, `_rowaddr`, `_rowoffset`) but only when named, so they stay out of `SELECT *`. `DISTINCT` deduplicates the projected rows. ## Filtering ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents WHERE identifier > 0 AND identifier < 1000000 ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search().where("identifier > 0 AND identifier < 1000000").to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.query().where("identifier > 0 AND identifier < 1000000").toArrow(); ``` The SDK `where` takes the same expression language, so a predicate moves between them unchanged. A supported predicate can use a scalar index; confirm the chosen plan with [`explain_plan`](/enterprise/v1-12-0/basics/sql#query-plans). See [Filtering](/enterprise/v1-12-0/search/filtering) for the operators and their pushdown behaviour. ## Ordering and limiting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, title FROM documents ORDER BY created_at DESC NULLS LAST LIMIT 100 OFFSET 200 ``` `ORDER BY` on a large table is a sort over the whole result, so pair it with a `LIMIT` unless you genuinely need every row ordered. ## Set operations `UNION`, `UNION ALL`, `INTERSECT` and `EXCEPT` combine whole queries: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents WHERE category = 'film' UNION ALL SELECT id FROM archived_documents WHERE category = 'film' ``` `UNION` deduplicates and `UNION ALL` does not, which makes `UNION ALL` the cheaper one when you already know the inputs are disjoint. ## Common table expressions ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH recent AS ( SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ) SELECT category, count(*) FROM recent GROUP BY category ``` A CTE is scoped to the statement. One you want to keep is a [view](/enterprise/v1-12-0/management/view); one whose rows you want stored is a [materialized view](/enterprise/v1-12-0/management/materialized-view). ## Subqueries Subqueries are allowed anywhere an expression or a relation is (in `FROM`, in `WHERE` with `IN` or `EXISTS`, and as a scalar in the select list): ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) ``` ## Namespaced tables A table inside a [namespace](/enterprise/v1-12-0/management/namespace) is written with its schema -- the `$`-joined namespace path, not a dotted one -- before the table name; see [Schema](/enterprise/v1-12-0/basics/catalog#schema) for why: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM `prod$events`.clicks ``` ## Reading the plan `EXPLAIN` and `EXPLAIN ANALYZE` work as DataFusion defines them, and produce the same operators the SDK methods do: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` See [Explain](/enterprise/v1-12-0/basics/sql#inspect-a-query-plan) and [Explain Analyze](/enterprise/v1-12-0/basics/sql#analyze-a-query-plan). # Subqueries Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/subqueries Queries inside queries: scalar, IN, EXISTS, correlated, and derived tables. **Applies to:** Embedded ❌, Enterprise ✅ A subquery is allowed anywhere an expression or a relation is. ## As a relation ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM ( SELECT category, count(*) AS n FROM documents GROUP BY category ) AS counts WHERE n > 100 ``` A derived table needs an alias. Its result cannot be [sampled](/enterprise/v1-12-0/sql/dql/sampling); sample the table inside it instead: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d ``` ## As a scalar ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title, (SELECT count(*) FROM revisions r WHERE r.doc_id = d.id) AS revisions FROM documents AS d ``` A scalar subquery returns one column and at most one row. No rows produces `NULL`; more than one row is an error. ## IN and EXISTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) SELECT title FROM documents AS d WHERE EXISTS (SELECT 1 FROM revisions r WHERE r.doc_id = d.id) ``` Use `EXISTS` to test whether a matching row exists and `IN` to test membership in a set of values. The optimizer may rewrite either into a join; inspect `EXPLAIN` before choosing one for performance reasons. `NOT IN` and `NOT EXISTS` differ on nulls: `NOT IN` against a set containing a null yields no rows, because the comparison is unknown rather than false. Prefer `NOT EXISTS` unless you have ruled nulls out. ## Correlated subqueries A subquery referencing a column from the enclosing query, such as `d.id` above, is correlated, and is conceptually evaluated per outer row. The planner usually rewrites it into a join. > [!NOTE] > > Check with [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain) when a correlated subquery is slow. A plan > showing a join has been optimized; one showing a repeated scan has not, and > rewriting it as an explicit [join](/enterprise/v1-12-0/sql/dql/join) is the fix. ## CTEs as an alternative A [CTE](/enterprise/v1-12-0/sql/dql/select#ctes) is a named subquery, and is usually more readable when the same subquery appears twice or when nesting gets deep. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH active AS (SELECT id FROM categories WHERE active) SELECT title FROM documents WHERE category_id IN (SELECT id FROM active) ``` # Vector distance functions Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/vector-distance cosine_distance, distance, exact_distance and inner_product: per-row vector distance, and the ORDER BY rewrite into vector search. **Applies to:** Embedded ❌, Enterprise ✅ ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cosine_distance distance exact_distance inner_product ``` > [!WARNING] > > Distance functions can evaluate arrays per row. Some deployment versions also > recognize `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan > and plan it as vector search, with indexed or flat search as appropriate. > Where available, `exact_distance` evaluates distance without that rewrite. > Confirm the functions supported by your deployment and inspect SQL > [`EXPLAIN`](/enterprise/v1-12-0/sql/dql/explain); the function name alone does not guarantee an > index-backed plan. See [SQL vector search](/enterprise/v1-12-0/basics/sql#no-vector-sql). A third, optional argument is a comma-separated options string, and only `distance` and `exact_distance` accept one; `cosine_distance` and `inner_product` are plain two-argument functions. `metric` selects `l2` (default, alias `euclidean`), `cosine`, or `dot`. `nprobes` and `use_index` only affect `distance`, since it's the only one of the two that the index-search rewrite applies to in the first place -- `exact_distance` is never rewritten into an index search, so passing it `use_index`/`nprobes` does nothing; use a plain `distance` call with `use_index=false` to force a flat scan instead: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'metric=cosine,nprobes=20') LIMIT 10 -- Force a flat scan, bypassing the index: SELECT id FROM documents ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'use_index=false') LIMIT 10 ``` ## What to read next > [card] [SQL vector search](/enterprise/v1-12-0/basics/sql#no-vector-sql) > > Server-version requirements and the supported `ORDER BY` query forms. > [card] [EXPLAIN](/enterprise/v1-12-0/sql/dql/explain) > > Confirm whether a query planned as an index-backed vector search. # Window functions Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/dql/window Compute over a set of rows related to the current one, without collapsing them. **Applies to:** Embedded ❌, Enterprise ✅ A window function computes across a set of rows related to the current one and returns a value **per row**. That is the difference from [aggregation](/enterprise/v1-12-0/sql/dql/aggregation), which collapses the rows it covers. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title, score, row_number() OVER (PARTITION BY category ORDER BY score DESC) AS rank FROM documents ``` Every row survives; each one gains its rank within its category. ## The window ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} OVER ( [PARTITION BY expr [, ...]] [ORDER BY expr [, ...]] [ROWS | RANGE BETWEEN frame_start AND frame_end] ) ``` `PARTITION BY` splits the rows into independent groups. `ORDER BY` orders them inside each partition. Supply an ordering for useful ranks, and a stable tie-breaker when selecting one row from several equal values. The frame clause narrows the window further, which is how running totals and moving averages are expressed: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT created_at, sum(amount) OVER (ORDER BY created_at ROWS UNBOUNDED PRECEDING) AS running_total, avg(amount) OVER (ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS trailing_7 FROM transactions ``` A `WINDOW` clause names a definition when several functions share one: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_number() OVER w, lag(score) OVER w FROM documents WINDOW w AS (PARTITION BY category ORDER BY score DESC) ``` ## The functions Registered in DataFusion 54. **Ranking** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} row_number rank dense_rank percent_rank cume_dist ntile ``` **Offset and positional** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lag lead first_value last_value nth_value ``` **Aggregates** Any [aggregate function](/enterprise/v1-12-0/sql/dql/aggregation#functions) used with `OVER` becomes a window function. This is how running totals and moving averages are written. ## Deduplicating with a window The common practical use: keep one row per key, chosen by some ordering. A window ranks, and an outer query filters: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER (PARTITION BY doc_id ORDER BY version DESC) AS rn FROM revisions ) SELECT * FROM ranked WHERE rn = 1 ``` The outer query is needed because a window function cannot appear in `WHERE`: windows are computed after filtering, so the predicate would have nothing to read. > [!NOTE] > > Window functions sort within each partition, so on a large table they are among > the more expensive things you can ask for. Filter first, and check the cost with > [Explain Analyze](/enterprise/v1-12-0/basics/sql#analyze-a-query-plan). # SQL reference Source: https://docs.lancedb.com/enterprise/v1-12-0/sql/index SQL statements, expressions and data types supported by LanceDB Enterprise. LanceDB Enterprise supports SQL through an Arrow Flight SQL endpoint. This reference covers statement syntax, data types and expressions. To set up a client and run your first query, see [SQL](/enterprise/v1-12-0/basics/sql). ## The dialect LanceDB uses [Apache DataFusion](https://datafusion.apache.org) for SQL planning and execution. These pages describe LanceDB's supported statements and extensions. DataFusion's reference is useful for expression syntax, but does not establish that every DataFusion statement or feature is exposed by LanceDB. ## Connecting Use Python's `execute_query` or a Flight SQL client after configuring the [Enterprise connection](/enterprise/v1-12-0/basics/sql#sql-is-remote). TypeScript applications use a Flight SQL client for SQL queries. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query("SELECT id, text FROM my_docs LIMIT 10") for batch in reader: print(batch) ``` SQL results arrive as Arrow record batches. Iterating over the reader avoids collecting the entire result in application memory. See [Read and manage results](/enterprise/v1-12-0/basics/sql#results) for more. ## Usage The endpoint executes one statement per request and is meant for the queries and DDL/DML pages below. Reach for the SDKs instead for table-management operations that have no SQL form, such as a merge insert. See [What SQL cannot do](#cannot). ## Reference ### DDL, by object | | | | - | - | | [Database](/enterprise/v1-12-0/sql/ddl/database) | `CREATE`, `DESCRIBE`, `SHOW`, `ATTACH`, `DROP DATABASE` | | [Namespace](/enterprise/v1-12-0/sql/ddl/namespace) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SCHEMA`/`NAMESPACE` | | [Table](/enterprise/v1-12-0/sql/ddl/table) | `CREATE`, `DESCRIBE`, `ALTER`, `CLONE`, `DROP TABLE` | | [View](/enterprise/v1-12-0/sql/ddl/view) | `CREATE VIEW`, `DROP VIEW` | | [Materialized view](/enterprise/v1-12-0/sql/ddl/materialized-view) | `CREATE MATERIALIZED VIEW`, `SHOW MATERIALIZED VIEWS` | | [Secret](/enterprise/v1-12-0/sql/ddl/secret) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SECRET` | | [Storage Integration](/enterprise/v1-12-0/sql/ddl/storage-integration) | `CREATE`, `DESCRIBE`, `SHOW`, `DROP STORAGE INTEGRATION` | | [Index](/enterprise/v1-12-0/sql/ddl/index) | `CREATE INDEX`, `DROP INDEX` | | [Function](/enterprise/v1-12-0/sql/ddl/function) | `CREATE FUNCTION`, `SHOW FUNCTIONS`, `DROP FUNCTION` | | [Job](/enterprise/v1-12-0/sql/ddl/job) | `SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB`, `SHOW ERRORS`, `PAUSE`/`RESUME`/`CANCEL JOB` | ### DML | | | | - | - | | [Insert](/enterprise/v1-12-0/sql/dml/insert) | `INSERT INTO`, including `INSERT ... SELECT` | | [Update](/enterprise/v1-12-0/sql/dml/update) | `UPDATE ... SET` | | [Delete](/enterprise/v1-12-0/sql/dml/delete) | `DELETE FROM` | | [Copy](/enterprise/v1-12-0/sql/dml/copy) | `COPY` (refused by recent deployment versions) | | [Refresh column](/enterprise/v1-12-0/sql/dml/refresh-column) | filling a computed column | | [Refresh materialized view](/enterprise/v1-12-0/sql/dml/refresh-materialized-view) | bringing a view's stored result up to date | ### DQL | | | | - | - | | [Data types](/enterprise/v1-12-0/sql/data-types) | how Lance columns appear to SQL, and pseudo-columns | | [Select](/enterprise/v1-12-0/sql/dql/select) | projection, filtering, ordering, set operations, CTEs | | [Subqueries](/enterprise/v1-12-0/sql/dql/subqueries) | scalar, `IN`, `EXISTS`, correlated, derived tables | | [Joins](/enterprise/v1-12-0/sql/dql/join) | inner, outer, cross, and namespace-qualified paths | | [Aggregation](/enterprise/v1-12-0/sql/dql/aggregation) | `GROUP BY`, `HAVING`, the aggregate set | | [Window functions](/enterprise/v1-12-0/sql/dql/window) | `OVER`, framing, ranking and offset functions | | [Sampling](/enterprise/v1-12-0/sql/dql/sampling) | `TABLESAMPLE`, by rows or by fragments | | [Changes](/enterprise/v1-12-0/sql/dql/changes) | `CHANGES`: rows appended since an earlier version | | [Full-Text Search](/enterprise/v1-12-0/sql/dql/fts) | the `fts()` table function, and its query forms | | [Operators](/enterprise/v1-12-0/sql/dql/operators) | comparison, logical, arithmetic, literals, precedence | | [Functions](/enterprise/v1-12-0/sql/dql/functions) | where to find each kind, and table functions | | [Scalar functions](/enterprise/v1-12-0/sql/dql/scalar-functions) | the per-row catalogue, and what Lance accelerates | | [Explain](/enterprise/v1-12-0/sql/dql/explain) | `EXPLAIN`, `EXPLAIN ANALYZE`, `EXPLAIN VERBOSE` | ## SQL limitations and alternatives | | | | - | - | | Vector search | See [SQL vector search](/enterprise/v1-12-0/basics/sql#no-vector-sql) for supported query forms and server-version requirements. The [SDK query builder](/enterprise/v1-12-0/search/vector-search) also supports vector search. | | Merge insert | no SQL form: it needs a source relation and a per-match policy | | `information_schema` | not enabled, so `SHOW TABLES` and `SHOW COLUMNS` fail | | `COPY` | refused by recent deployment versions (see [Copy](/enterprise/v1-12-0/sql/dml/copy)) | | `PREPARE` / `EXECUTE` | preparation is a [protocol feature](/enterprise/v1-12-0/basics/sql#prepared-statements), not a statement | | Run on a local database | no engine to plan the statement | See [Limits](/enterprise/v1-12-0/basics/limits#sql) for the bounds these pages enforce. # Checkpointing Source: https://docs.lancedb.com/enterprise/v1-12-0/training/checkpointing Save StreamingDataset's read position alongside your model, so a failed run can pick back up. **Applies to:** Embedded ✅, Enterprise ✅ [`StreamingDataset`](/enterprise/v1-12-0/training/data-loading) provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, save it alongside your model weights, and `load_state_dict()` to restore the last saved position -- see [Resuming](/enterprise/v1-12-0/training/resuming) for the load side. This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` terminology from [Distributed Training](/enterprise/v1-12-0/training/distributed-training#parallelism-and-elasticity). A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset global_batch_size = 48 # one sample per split in each global step batch_size = global_batch_size // world_size dataset = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, num_workers=0, ) for step, batch in enumerate(dataloader): train_step(batch) if (step + 1) % checkpoint_interval == 0: torch.save( {"model": model.state_dict(), "dataset": dataset.state_dict()}, f"checkpoint_{step + 1}.pt", ) ``` ## Checkpointing with Multiple DataLoader Workers Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.streaming import StreamingDataset, StreamingDataLoader dataset = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) dataloader = StreamingDataLoader( dataset, batch_size=batch_size, num_workers=4, ) for step, batch in enumerate(dataloader): train_step(batch) if (step + 1) % checkpoint_interval == 0: torch.save( {"model": model.state_dict(), "dataset": dataset.state_dict()}, f"checkpoint_{step + 1}.pt", ) ``` `StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: * `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). * `in_order = True` is required so that consumer-committed checkpoints stay deterministic. * `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. * `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches first. ## Next steps > [card] [Resuming](/enterprise/v1-12-0/training/resuming) > > Load a saved checkpoint back, on the same or a different topology. > [card] [Distributed Training](/enterprise/v1-12-0/training/distributed-training) > > The rank, world size and split terminology checkpointing builds on. # PyTorch Data Loader Source: https://docs.lancedb.com/enterprise/v1-12-0/training/data-loading Stream, shuffle, transform, and resume model training data with StreamingDataset. **Applies to:** Embedded ✅, Enterprise ✅ Advanced data loading scenarios can be handled by the `StreamingDataset`. This object allows you to apply preprocessing before training, pipelined reads, and more. Use this when the training data does not fit in memory, or when you need deterministic global batches across cluster sizes. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset db = lancedb.connect("file://some/db/path") table = db.open_table("some_table") dataset = StreamingDataset(table, shuffle_seed=42) dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, num_workers=0, ) for batch in dataloader: train_step(batch) ``` The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. > [!NOTE] > > `StreamingDataset` is built on the [`Permutation`](/enterprise/v1-12-0/training/permutation) API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage. ## Filtering The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. You can also use the `columns` parameter to load only a subset of columns. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ds = StreamingDataset( table, shuffle_seed=42, columns=["image", "label"], # skip all other columns filter="category = 'train'", # only training rows ) ``` ## Shuffling Rows In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. > [!NOTE] > > `StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs > with the same inputs remain reproducible. Set `shuffle_seed = None` to generate a random seed upon pipeline initialization. ### Row-Level Shuffle By default, `shuffle_clump_size` is `None` and rows are shuffled individually: the rows of the source dataset are shuffled according to a pseudorandom permutation, then fed in batches to the accelerator. This gives the best possible randomness, but can exhibit low throughput. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1-phase shuffled read: rows shuffled individually. for epoch in range(num_epochs): ds = StreamingDataset( table, shuffle_seed=42, epoch=epoch, # changes the permutation each epoch ) for sample in ds: train_step(sample) #Evaluation: deterministic sequential order, no shuffle. eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` ### Clumped Shuffle Setting `shuffle_clump_size` to an integer shuffles contiguous groups ("clumps") of that many rows instead of single rows. Each clump keeps its rows in storage order and moves as a unit, so storage I/O consists mostly of contiguous reads rather than single-row fetches. Larger clumps improve I/O locality, which matters most on object storage, at the cost of randomness. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Clumped shuffled read: rows are shuffled in groups of contiguous rows # instead of individually, trading a bit of randomness for much cheaper I/O. for epoch in range(num_epochs): ds = StreamingDataset( table, shuffle_seed=42, epoch=epoch, shuffle_clump_size=1024, # contiguous rows that move together ) for sample in ds: train_step(sample) # Evaluation: deterministic sequential order, no shuffle. eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` ## Fetching Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). In addition to batching requests, the prefetching mechanism reads ahead in the background. While one batch is being processed, `StreamingDataset` reads several subsequent batches. The `io_queue_depth` parameter specifies the number of batches simultaneously kept in flight per split (default = `4`); it replaces `prefetch_batches`, which still works but is deprecated. A larger value provides more buffering against jittery workloads, but also increases memory use and I/O concurrency. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ds = StreamingDataset( table, shuffle_seed=42, read_batch_size=256, # rows fetched per LanceDB call per split io_queue_depth=8, # batches to keep in flight per split ) ``` ## Transforming Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. A transformation function must receive a PyArrow `RecordBatch` and return an iterable. For example, the default transform function returns a list of Python dictionaries. Furthermore, the input expected by PyTorch must match the collation function used in the PyTorch data loader. PyTorch's default collation function accepts a Python dictionary and several other types, and is thus compatible with the default `StreamingDataset` transform function. If your custom transform function returns something different (for example, Arrow record batches), you may need to provide a compatible PyTorch collation function. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa def normalize(batch: pa.RecordBatch) -> list[dict]: # This pure-Python loop holds the GIL and is shown for illustration only. # In practice, prefer a library like torchvision or numpy that releases the # GIL so the ThreadPoolExecutor can run transforms in parallel. rows = batch.to_pylist() for row in rows: row["image"] = [v / 255.0 for v in row["image"]] return rows ds = StreamingDataset(table, shuffle_seed=42, transform=normalize) ``` `StreamingDataset` manages expensive transforms through a `ThreadPoolExecutor` whose worker count equals the number of available CPUs (`transform_parallelism`). Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. Heavier per-sample work belongs in the same function, such as decoding video. Store each clip in a Blob v2 column (`lancedb.blob("video")`). A scan returns small descriptors instead of the video bytes, so reading other columns never pulls video in. `fetch_blob_files` opens the clips for a batch of rows as file handles, and `torchcodec`'s `VideoDecoder` decodes just the frames you ask for. `ExtractFrames` samples 8 evenly spaced frames from each clip: ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import functools from torchcodec.decoders import VideoDecoder class ExtractFrames: def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: self.uri, self.name, self.num_frames = uri, name, num_frames @functools.cached_property def table(self) -> lancedb.table.Table: return lancedb.connect(self.uri).open_table(self.name) def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: samples = [] for blob in self.table.fetch_blob_files("video", rb["_rowid"]): decoder = VideoDecoder(blob) idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) return samples # `clips` is the table "clips" in the database at `uri`, with a Blob v2 column "video" train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) ``` Real data has bad rows, such as a truncated frame. Raise inside the transform and set `on_transform_error="skip"` (or `"warn"` to log each failure). `StreamingDataset` re-runs the failing batch one row at a time, drops only the rows that raise, and counts them in `dataset.rows_skipped`. When the bad rows match a SQL predicate, prefer `filter=` instead: it runs before the splits are built, so every split keeps the same length. ### DataLoader Workers The thread-based transformation model that `StreamingDataset` uses by default is only effective when the transform function releases the GIL. This is true for many Python scientific libraries, including NumPy, PyArrow, and TorchVision, but not for pure-Python transforms. PyTorch can launch multiple DataLoader worker processes per rank, and `StreamingDataset` uses `get_worker_info()` to give each worker a non-overlapping group of splits. Multiprocessing adds pickling and transfer overhead and increases memory use. Start with `num_workers=0`, which keeps loading in the rank's main process, and add workers only after confirming an unavoidable GIL bottleneck. If you use workers, `num_splits` must be divisible by `world_size * num_workers`. Use the `forkserver` or `spawn` multiprocessing context because LanceDB uses internal threads. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, num_workers=2, multiprocessing_context="forkserver", persistent_workers=True, ) ``` By default, `StreamingDataset` serializes enough table state to reopen the table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the same way: workers reopen the table from the pickled connection state. Replace the URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager: ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.util import tbl_to_tensor db = lancedb.connect( "db://my-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", ) table = db.open_table("my_table") dataloader = torch.utils.data.DataLoader( table, batch_size=512, num_workers=4, multiprocessing_context="forkserver", collate_fn=tbl_to_tensor, ) ``` > [!NOTE] > > This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. #### Providing a custom connection factory For custom connection setup, pass a picklable `connection_factory` callable that accepts a table name and returns an open table. This avoids serializing connection credentials into worker state: it loads the API key inside each worker instead. Set it in the shell before starting the Python program, then replace the database URI, region and endpoint in the factory with your deployment details: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_API_KEY="your-api-key" ``` ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import torch from lancedb.permutation import Permutation def open_table(name: str): db = lancedb.connect( "db://my-database", api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-endpoint", ) return db.open_table(name) table = open_table("my_table") permutation = ( Permutation.identity(table) .with_connection_factory(open_table) ) dataloader = torch.utils.data.DataLoader( permutation, batch_size=512, num_workers=4, multiprocessing_context="forkserver", ) ``` ## Next steps > [card] [Permutation](/enterprise/v1-12-0/training/permutation) > > The lower-level row ordering StreamingDataset is built on. > [card] [Observability](/enterprise/v1-12-0/training/observability) > > Pipeline counters for diagnosing loader bottlenecks. > [card] [Distributed Training](/enterprise/v1-12-0/training/distributed-training) > > Multi-GPU sharding and elastic determinism. > [card] [Checkpointing](/enterprise/v1-12-0/training/checkpointing) > > Save progress so a failed run can pick back up. > [card] [Training Cache](/enterprise/v1-12-0/training/training-cache) > > How an Enterprise connection speeds up repeated epochs. # Distributed Training Source: https://docs.lancedb.com/enterprise/v1-12-0/training/distributed-training Shard StreamingDataset across ranks and workers, with elastic determinism across topologies. **Applies to:** Embedded ✅, Enterprise ✅ To understand the wide range of scenarios handled by [`StreamingDataset`](/enterprise/v1-12-0/training/data-loading) across a distributed job, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism (DDP). In this example, we need to load batches onto multiple GPUs across multiple servers. After each batch is processed, the GPUs exchange weights and the next batch is loaded. We fix the following terminology: * **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ GPUs each, the world size is $8$. * **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. Each rank is allocated a disjoint portion of the source data. * **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. * **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. Other concepts, such as read batch size and `num_workers`, are introduced in [PyTorch Data Loader](/enterprise/v1-12-0/training/data-loading). ## Parallelism & Elasticity When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` (the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, and `epoch`. The following constraints apply: * `num_splits` must be divisible by `world_size`. * With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. * For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of `num_splits`. * The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to `num_splits - 1` surplus rows are dropped so that every split has the same length. For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch.distributed as dist from lancedb.streaming import StreamingDataset dist.init_process_group("nccl") rank = dist.get_rank() world_size = dist.get_world_size() # num_splits=48 is divisible by many integers, # so this dataset works unchanged as you add or remove GPUs. ds = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) for sample in ds: train_step(sample) ``` ## Next steps > [card] [Checkpointing](/enterprise/v1-12-0/training/checkpointing) > > Save progress so a failed run can pick back up. > [card] [Resuming](/enterprise/v1-12-0/training/resuming) > > Load a saved checkpoint back, on the same or a different topology. # Observability Source: https://docs.lancedb.com/enterprise/v1-12-0/training/observability Pipeline counters for diagnosing StreamingDataset bottlenecks. **Applies to:** Embedded ✅, Enterprise ✅ Optimizing data loader performance can be tricky, as runtime bottlenecks are often difficult to locate across various stages of the I/O and CPU pipelines. To help distinguish bottlenecks, [`StreamingDataset`](/enterprise/v1-12-0/training/data-loading) exposes several pipeline counters: `raw_queue_depth` shows the number of loaded rows waiting to be transformed, and `prefetch_queue_depth` is the number of transformed rows ready to be consumed. `unscanned_rows` and `consumed_rows` show how far the current iterator has progressed. If the `prefetch_queue_depth` is consistently zero but the `raw_queue_depth` is not, then you likely have a CPU transformation bottleneck. You should investigate GIL bottlenecks or look for ways to optimize your transformation. This can often be done by batching the compute work. If both `prefetch_queue_depth` and `raw_queue_depth` are consistently zero while the consumer is waiting, I/O is the likely bottleneck. A larger read batch size or clumped shuffling could help. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import threading, time from lancedb.streaming import StreamingDataset ds = StreamingDataset(table, shuffle_seed=42) def log_pipeline_health(): while True: print( f"unscanned={ds.unscanned_rows} " f"raw={ds.raw_queue_depth} " f"cooked={ds.prefetch_queue_depth} " f"consumed={ds.consumed_rows}" ) time.sleep(1.0) monitor = threading.Thread(target=log_pipeline_health, daemon=True) monitor.start() for sample in ds: train_step(sample) print( f"bytes loaded: {ds.bytes_loaded} " f"fetch time: {ds.fetch_time:.2f}s " f"transform time: {ds.transform_time:.2f}s" ) ``` `bytes_loaded` measures raw Arrow buffer bytes before transformation. `bytes_loaded`, `fetch_time`, and `transform_time` are cumulative across iterations of the same dataset instance; because work runs concurrently, the summed stage times can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters reflect the latest iterator snapshot. ## Next steps > [card] [PyTorch Data Loader](/enterprise/v1-12-0/training/data-loading) > > Stream, shuffle and transform training data with StreamingDataset. > [card] [Checkpointing](/enterprise/v1-12-0/training/checkpointing) > > Save progress so a failed run can pick back up. # Permutation Source: https://docs.lancedb.com/enterprise/v1-12-0/training/permutation The low-level, customizable row ordering that StreamingDataset is built on. **Applies to:** Embedded ✅, Enterprise ✅ Most model training frameworks feed data into a model by sequencing through successive batches, a process often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation db = lancedb.connect("file://some/db/path") table = db.open_table("some_table") for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): print(batch.to_pydict()) ``` In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full [`StreamingDataset`](/enterprise/v1-12-0/training/data-loading) object. In these cases, use `Permutation`, the lower-level functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` and batched access through `__getitems__()`. ## Version Pinning A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows that existed when it was built, and rows appended to the base table afterwards are not visible through the existing permutation. To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) against the updated table. Permutations written before this behavior shipped continue to read as they did before. ## Output formats By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a column-major `torch.Tensor` with shape `(columns, rows)`. `Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` with one of the transform formats described below. To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, `pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and `torch` formats will all require at least one full copy of the data and are the slowest options. ### Using the torch column format with a torch data loader The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the entire Arrow batch to a *column-major* `torch.Tensor`. In other words, given C columns and R rows, the resulting Tensor will have shape `(C, R)`. However, this format generates an error if you are using a `torch.utils.data.DataLoader` with the default collation function: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor ``` This error occurs because the default collation function does not currently expect a single two-dimensional tensor. It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function in addition to specifying the `torch_col` format. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation permutation = Permutation.identity(table).with_format("torch_col") dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` This will now output a single two-dimensional tensor for each batch. ## Selecting columns By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need a subset of columns, you can significantly reduce your I/O requirements by selecting only the columns you need. The `Permutation` class provides a `select_columns` method that provides this functionality. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import torch from lancedb.permutation import Permutation db = lancedb.connect("memory://") prompts = db.create_table( "prompts", pa.table( { "id": range(4), "prompt": ["north", "south", "east", "west"], "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], } ), ) permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) dataloader = torch.utils.data.DataLoader( permutation, batch_size=1024, shuffle=True ) for batch in dataloader: print(sorted(batch)) # ['id', 'prompt']: the embedding is never read ``` Each batch is a dict of the selected columns, the default `Permutation` format described above. # Resuming Source: https://docs.lancedb.com/enterprise/v1-12-0/training/resuming Load a saved StreamingDataset checkpoint back, on the same topology or a different one. **Applies to:** Embedded ✅, Enterprise ✅ Resuming loads a `StreamingDataset` checkpoint saved by [Checkpointing](/enterprise/v1-12-0/training/checkpointing) back into a fresh dataset and `DataLoader`, so a failed or restarted run picks up where it left off rather than rereading from the start. This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` terminology from [Distributed Training](/enterprise/v1-12-0/training/distributed-training#parallelism-and-elasticity). ## Resuming on the same topology ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset checkpoint = torch.load("checkpoint_100.pt") model.load_state_dict(checkpoint["model"]) dataset_state = checkpoint["dataset"] dataset = StreamingDataset( table, num_splits=dataset_state["num_splits"], shuffle_seed=dataset_state["shuffle_seed"], epoch=dataset_state["epoch"], rank=rank, world_size=world_size, # same as the run that saved the checkpoint ) dataset.load_state_dict(dataset_state) # The combined batch size across every rank, the same value used when the # checkpoint was saved; each rank's DataLoader gets its world_size share of it. global_batch_size = 48 dataloader = torch.utils.data.DataLoader( dataset, batch_size=global_batch_size // world_size, num_workers=0, ) for batch in dataloader: train_step(batch) ``` `load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings, and keep `world_size` the same -- changing it is a topology change, covered next. The number of DataLoader workers may still change as long as the batch-size divisibility constraints from [Distributed Training](/enterprise/v1-12-0/training/distributed-training#parallelism-and-elasticity) hold. ## Resuming Across Different Topologies When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with `StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, regardless of whether the topology grew, shrank, or stayed the same. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # On each rank of the previous run: state = dataset.state_dict() # ...gather `state` from every rank into a single list `states` (for example # via torch.distributed all-gather or by saving one file per rank). merged = StreamingDataset.merge_state_dicts(states) # On each rank of the resumed run (world_size may differ): dataset = StreamingDataset( table, num_splits=merged["num_splits"], shuffle_seed=merged["shuffle_seed"], epoch=merged["epoch"], rank=rank, world_size=new_world_size, ) dataset.load_state_dict(merged) ``` ## Next steps > [card] [Checkpointing](/enterprise/v1-12-0/training/checkpointing) > > Save progress, including with multiple DataLoader workers. > [card] [Distributed Training](/enterprise/v1-12-0/training/distributed-training) > > The rank, world size and split terminology resuming builds on. # Training Cache Source: https://docs.lancedb.com/enterprise/v1-12-0/training/training-cache Connect the PyTorch data loader to LanceDB Enterprise and training reads automatically benefit from the plan executor's data page cache. **Applies to:** Embedded ❌, Enterprise ✅ The [PyTorch data loader](/enterprise/v1-12-0/training/data-loading) reads training data the same way any other query does -- there is no training-specific read path. Point `StreamingDataset` or a `DataLoader` at a table opened through an Enterprise connection instead of a local one, and every read it makes flows through the same [plan executors](/enterprise/v1-12-0/enterprise/data-page-cache) that serve every other query, with the same data page cache in front of object storage. No training-specific configuration turns this on; it's a consequence of connecting to Enterprise at all. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader<br/>/ StreamingDataset"] --> T["Enterprise-connected table"] T --> PE["Plan executor"] PE --> C{"In data page cache?"} C -->|hit| Fast["Served from memory<br/>or local disk"] C -->|miss| O[("Object storage")] O --> Fill["Fills the cache,<br/>served"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Fast accent ``` This covers the ordinary tabular columns a query reads -- the data page cache's unit is a fixed-size page of table data. A [Blob v2](/enterprise/v1-12-0/management/table#managed-blobs) column's payload is fetched through a separate range-request path keyed to its own descriptor, not through this cache, so a training table mixing plain feature columns with Blob v2 images or video gets this benefit only for the former. A custom collate function or transform that does its own file or network I/O -- decoding an image, say -- is also outside this cache; only reads that go through the table query path benefit. ## Why this matters for training specifically Training reads the same rows repeatedly: once per epoch, often for many epochs. The first epoch's reads behave like any cold cache -- a miss per page, each one filling the cache on the way. Every epoch after that reads the same pages again, so a dataset that fits the cache's budget serves almost entirely from memory or local disk after the first pass, instead of re-reading object storage every epoch. A local-file or Embedded connection has no equivalent remote cache to warm this way -- its locality comes from whatever the local filesystem or OS page cache already does. [Cache Prewarm](/enterprise/v1-12-0/enterprise/cache-prewarm) extends this further: a plan executor can warm its cache at startup, before training even begins, instead of paying the first-epoch cold-cache cost during the run itself. ## What to read next > [card] [PyTorch Data Loader](/enterprise/v1-12-0/training/data-loading) > > Connecting a DataLoader to an Enterprise table. > [card] [Data Page Cache](/enterprise/v1-12-0/enterprise/data-page-cache) > > How the cache a training read benefits from actually works. > [card] [Cache Prewarm](/enterprise/v1-12-0/enterprise/cache-prewarm) > > Warming the cache before the first epoch instead of during it. # REST API Reference Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/index API reference for LanceDB [Lance REST Namespace](https://lance.org/format/namespace/) spec is an OpenAPI protocol that enables reading, writing and managing Lance tables by connecting those metadata services or building a custom metadata server in a standardized way. LanceDB Embedded allows you to interface with Lance tables via the REST Namespace. LanceDB Enterprise provides an extended REST API with additional endpoints for managing tables and data. If you have specific needs or questions about the Enterprise REST API Namespace, please [contact us](mailto:support@lancedb.com). ## Authentication Enterprise All HTTP requests to LanceDB APIs must contain an x-api-key header that specifies a valid API key and must be encoded as JSON or Arrow RPC. To authenticate to the Enterprise REST API, you need the endpoint for your deployment and a valid API key for that deployment. ### Get your Enterprise credentials 1. Obtain the following values from your LanceDB administrator or the LanceDB team that provisioned your Enterprise deployment: * an API key * your Enterprise REST endpoint * your database name, if your deployment uses a private endpoint or `host_override` 2. Export those values in your terminal: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_API_KEY="<your-api-key>" export LANCEDB_HOST_OVERRIDE="https://your-enterprise-endpoint.com" export LANCEDB_DATABASE="your-database-name" ``` `LANCEDB_HOST_OVERRIDE` is the endpoint the SDKs take as `host_override`; the database name is the part of its `db://` URI after `db://`. 3. If your Enterprise deployment is private, connect through the private network endpoint provided for your deployment. For example, Azure Private Link deployments commonly use a private IP or an internal DNS name as the endpoint. ### Verify authentication 4. Check that you can reach the deployment and list tables: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X GET "$LANCEDB_HOST_OVERRIDE/v1/table/" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" ``` The response lists one page of table names, with a token for the next page when there are more. If your deployment endpoint already includes the database host name, you can omit the `x-lancedb-database` header. 5. Create a table to confirm write access. Let's call it `words`. A table is created from an Arrow IPC stream, which this writes with PyArrow: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -c "import pyarrow as pa, sys; t = pa.table({'word': ['hello', 'world']}); w = pa.ipc.new_stream(sys.stdout.buffer, t.schema); w.write_table(t); w.close()" > words.arrow curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \ -H "Content-Type: application/vnd.apache.arrow.stream" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ --data-binary @words.arrow ``` 6. Check that the table has been created: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/describe" \ -H "Content-Type: application/json" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ -d '{}' ``` That's it. You're connected! Now, you can start adding data and querying it. You can visit the tutorial section to build your own applications with LanceDB. > [card] [Tutorials](/enterprise/v1-12-0/tutorials/) > > Check out our tutorials on building various applications with LanceDB. # Check if a namespace exists Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/check-if-a-namespace-exists /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/exists Check if namespace `id` exists. This operation must behave exactly like the DescribeNamespace API, except it does not contain a response body. REST NAMESPACE ONLY REST namespace conveys the result through the HTTP status code with no response body. The REST response maps to the `NamespaceExistsResponse` model as follows: - a `200` response means the namespace exists; a `404` response means it does not - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Create a new namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/create-a-new-namespace /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/create Create new namespace `id`. During the creation process, the implementation may modify user-provided `properties`, such as adding additional properties like `created_at` to user-provided properties, omitting any specific property, or performing actions based on any property value. # Describe a namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/describe-a-namespace /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/describe Describe the detailed information for namespace `id`. # Drop a namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/drop-a-namespace /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/drop Drop namespace `id` from its parent namespace. # List namespaces Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/list-namespaces /enterprise/v1-12-0/api-reference/rest/openapi.yaml get /v1/namespace/{id}/list List all child namespace names of the parent namespace `id`. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListNamespacesRequest` information in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List tables in a namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/namespace/list-tables-in-a-namespace /enterprise/v1-12-0/api-reference/rest/openapi.yaml get /v1/namespace/{id}/table/list List all child table names of the parent namespace `id`. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListTablesRequest` information in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `include_declared`: pass through query parameter of the same name # Check if a table exists Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/check-if-a-table-exists /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/exists Check if table `id` exists. This operation should behave exactly like DescribeTable, except it does not contain a response body. REST NAMESPACE ONLY REST namespace conveys the result through the HTTP status code with no response body. The REST response maps to the `TableExistsResponse` model as follows: - a `200` response means the table exists; a `404` response means it does not - response headers map to `context` via the `header.` prefix (see the `Context` schema) For DirectoryNamespace implementation, a table exists if either: - The table has Lance data versions (regular table created with CreateTable) - A `.lance-reserved` file exists in the table directory (declared table created with DeclareTable) # Deregister a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/deregister-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/deregister Deregister table `id` from its namespace. # Describe information of a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/describe-information-of-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/describe Describe the detailed information for table `id`. REST NAMESPACE ONLY REST namespace passes `with_table_uri`, `load_detailed_metadata`, and `check_declared` as query parameters instead of in the request body. # Drop a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/drop-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/drop Drop table `id` and delete its data. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `DropTableRequest` information is passed in the following way: - `id`: pass through path parameter of the same name # List all tables Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/list-all-tables /enterprise/v1-12-0/api-reference/rest/openapi.yaml get /v1/table List all tables across all namespaces. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListAllTablesRequest` information in the following way: - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `delimiter`: pass through query parameter of the same name - `include_declared`: pass through query parameter of the same name # Register a table to a namespace Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/register-a-table-to-a-namespace /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/register Register an existing table at a given storage location as `id`. # Rename a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/rename-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/rename Rename table `id` to a new name. # Restore table to a specific version Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/restore-table-to-a-specific-version /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/restore Restore table `id` to a specific version. # ADE20K Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/ade20k A Lance-formatted version of the full ADE20K scene parsing benchmark, sourced from 1aurent/ADE20K. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/ade20k-lance) > > Source dataset card and downloadable files for `lance-format/ade20k-lance`. Each row is one scene image with its inline JPEG bytes, a per-pixel semantic segmentation map encoded as PNG bytes, an optional instance map, scene class labels, the full per-polygon object-name list, an OpenCLIP image embedding, and pre-built indices — all available directly from the Hub at `hf://datasets/lance-format/ade20k-lance/data`. ## Key features * **Inline image and segmentation bytes** — both the JPEG image and the RGB-encoded PNG segmentation map ride on the same row, so an annotated example is a single row read with no sidecar files. * **Per-polygon object metadata** — `object_names` keeps the full list (one entry per annotated polygon), `objects_present` is the deduped set used for class-presence filters, and `num_objects` is precomputed. * **CLIP image embeddings** (`image_emb`, OpenCLIP ViT-B/32, 512-d, cosine-normalized) for visual retrieval over scenes. * **Indices shipped on disk** — `IVF_PQ` on `image_emb`, `BTREE` on `num_objects`, and `LABEL_LIST` on `objects_present` for fast `array_has_any` / `array_has_all` predicates. ## Splits | Split | Rows | | - | - | | `train.lance` | 25,574 | | `validation.lance` | 2,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `segmentation` | `large_binary` | Inline PNG bytes — semantic segmentation map (RGB encoding per ADE20K spec) | | `instance` | `large_binary?` | Inline PNG bytes — instance map; null if not provided | | `filename` | `string` | ADE20K relative filename | | `scene` | `list<string>` | Scene class labels (e.g. `["bathroom"]`) | | `object_names` | `list<string>` | Per-polygon object names (one entry per polygon, not deduped) | | `objects_present` | `list<string>` | Deduped object names — feeds the `LABEL_LIST` index | | `num_objects` | `int32` | Number of annotated objects | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP ViT-B/32 image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `num_objects` — fast range filters on scene complexity * `LABEL_LIST` on `objects_present` — supports `array_has_any` / `array_has_all` for class-presence filtering ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/ade20k-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["filename"], row["scene"], row["num_objects"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and any mutation are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/ade20k-lance --repo-type dataset --local-dir ./ade20k-lance > ``` > > Then point LanceDB at `./ade20k-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor scene retrieval a single call. In production you would encode a query image through the same OpenCLIP ViT-B/32 model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored on row 42 as a runnable stand-in, so the snippet works without loading any model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "filename", "scene"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["filename", "scene", "objects_present"]) .limit(10) .to_list() ) print("query scene:", seed["scene"]) for r in hits: print(f" {r['filename']} scene={r['scene']} objs={r['objects_present'][:5]}") ``` Because the embeddings are cosine-normalized, the first hit will typically be the source image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate Curation for a semantic-segmentation workflow usually means picking scenes that contain specific classes, possibly bounded by complexity. The `LABEL_LIST` index on `objects_present` makes class-presence predicates trivial, and Lance evaluates them inside the same scan as a structural filter on `num_objects`. The bounded `.limit(500)` keeps the result small and inspectable, and the `segmentation` blob is left out of the projection so the candidate scan is dominated by metadata, not PNG bytes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "array_has_all(objects_present, ['bed', 'window']) AND num_objects >= 8", prefilter=True, ) .select(["id", "filename", "scene", "objects_present", "num_objects"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first scene: {candidates[0]['scene']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. Swapping `array_has_all` for `array_has_any` widens the recall; replacing the structural predicate with `num_objects BETWEEN 3 AND 6` selects simpler scenes for an ablation slice. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `has_person` flag and a `scene_label` string pulled out of the `scene` list, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./ade20k-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "has_person": "array_has_any(objects_present, ['person'])", "scene_label": "element_at(scene, 1)", "complexity_bucket": "CASE WHEN num_objects < 5 THEN 'sparse' " "WHEN num_objects < 15 THEN 'medium' ELSE 'dense' END", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline panoptic ids, predictions from a baseline segmenter, a second-pass embedding), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "baseline_miou": pa.array([0.41, 0.55, 0.62]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., re-running a segmentation model over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a semantic-segmentation run, project the JPEG bytes and the segmentation PNG bytes; both are decoded inside the training step. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "segmentation"]) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) for batch in loader: # batch carries only the JPEG and PNG byte columns; decode both, # remap the ADE20K RGB-encoded mask to class ids, forward, loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "objects_present"]` to `select_columns(...)` on the next run skips JPEG and PNG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight scene classifier or a class-presence probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./ade20k-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("segmenter-baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="segmenter-baseline-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A serving pipeline locked to `segmenter-baseline-v1` keeps reading the exact same segmentation maps and class lists while the dataset evolves in parallel; newly merged predictions or evolved columns do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, so changes in mIoU reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(objects_present, ['bed', 'sofa', 'chair']) AND num_objects >= 5") .select(["id", "image", "segmentation", "filename", "scene", "objects_present", "num_objects", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./ade20k-indoor-subset") local_db.create_table("train", batches) ``` The resulting `./ade20k-indoor-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/ade20k-lance/data` for `./ade20k-indoor-subset`. ## Source & license Converted from [`1aurent/ADE20K`](https://huggingface.co/datasets/1aurent/ADE20K). Review the MIT CSAIL [ADE20K Terms of Use](https://ade20k.csail.mit.edu/terms/): images are available for non-commercial research and educational use, while the software and annotations are covered by the BSD 3-Clause license. ## Citation ``` @inproceedings{zhou2017scene, title={Scene Parsing through ADE20K Dataset}, author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio}, booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2017} } ``` # ChartQA Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/chartqa A Lance-formatted version of ChartQA, a benchmark for question answering over scientific and business charts that demands a mix of logical and visual reasoning, redistributed via lmms-lab/ChartQA. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/chartqa-lance) > > Source dataset card and downloadable files for `lance-format/chartqa-lance`. Each row carries the chart image as inline JPEG bytes, the natural-language question and reference answer(s), a question-type tag (`human` vs `augmented`), and paired CLIP embeddings for the image and the question — all available directly from the Hub at `hf://datasets/lance-format/chartqa-lance/data`. ## Key features * **Inline chart image bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (ViT-B/32, 512-dim, cosine-normalized) — so visual and textual retrieval are one indexed lookup. * **All reference answers preserved in `answers`** alongside a canonical `answer` string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the question and answer strings, and the `type` tag. ## Splits | Split | Rows | Notes | | - | - | - | | `test.lance` | 2,500 | Public test slice from `lmms-lab/ChartQA` | > The `lmms-lab/ChartQA` redistribution exposes the test split only. Train and validation live in the original ChartQA release; extend `chartqa/dataprep.py` with additional sources to add them. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string?` | Source does not assign explicit ids — null | | `question_id` | `string?` | Source does not assign explicit ids — null | | `question` | `string` | Natural-language question | | `answers` | `list<string>` | Reference answer(s), typically a single string | | `answer` | `string` | First reference answer — canonical, used for FTS | | `type` | `string?` | Question type (`human` vs `augmented`) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BITMAP` on `type` — fast filtering by question type ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/chartqa-lance", split="test", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/chartqa-lance --repo-type dataset --local-dir ./chartqa-lance > ``` > > Then point LanceDB at `./chartqa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes question-to-question retrieval a single call: encode a query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question", "answer", "type"]) .limit(10) .to_list() ) print("query:", seed["question"]) for r in hits: print(f" [{r['type']}] {r['question'][:70]} -> {r['answer']}") ``` Swap `vector_column_name="question_emb"` for `image_emb` to do question-to-chart retrieval against the visual embedding instead — useful for finding charts whose layout is similar to a given prompt encoding. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "percentage" or "highest bar" must literally appear in the question but you still want CLIP to do the heavy lifting on semantic similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="question_emb") .vector(seed["question_emb"]) .text("percentage") .select(["question", "answer", "type"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" [{r['type']}] {r['question'][:70]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass combines a content predicate on the question text with a structural predicate on the question-type tag. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. The example below collects human-authored questions that mention a percentage, which is a common slice for evaluating numeric-reasoning behaviour. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") candidates = ( tbl.search("percentage OR percent") .where("type = 'human'", prefilter=True) .select(["id", "question", "answer", "type"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question and answer text rather than chart JPEGs. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `answer_length`, an `is_yes_no` flag, and an `is_numeric` flag, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./chartqa-lance/data") # local copy required for writes tbl = db.open_table("test") tbl.add_columns({ "answer_length": "length(answer)", "is_yes_no": "lower(answer) IN ('yes', 'no')", "is_numeric": "regexp_match(answer, '^-?[0-9]+(\\.[0-9]+)?%?$') IS NOT NULL", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (model predictions on the test set, reasoning-chain annotations, a difficulty score), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2]), "pred_answer": pa.array(["12%", "Yes", "34"]), "is_correct": pa.array([True, True, False]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a chart-OCR model over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For fine-tuning a VLM on chart QA, project the chart bytes plus the question and answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question/answer pair, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight answer-classifier or a linear probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./chartqa-lance/data") local_tbl = local_db.open_table("test") local_tbl.tags.create("eval-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("test", version="eval-v1") tbl_v5 = db.open_table("test", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `eval-v1` keeps producing comparable scores while the dataset evolves in parallel — newly added prediction columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same charts and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") remote_tbl = remote_db.open_table("test") batches = ( remote_tbl.search("percentage OR percent") .where("type = 'human'") .select(["id", "image", "question", "answer", "type", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./chartqa-human-subset") local_db.create_table("test", batches) ``` The resulting `./chartqa-human-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/chartqa-lance/data` for `./chartqa-human-subset`. ## Source & license Converted from [`lmms-lab/ChartQA`](https://huggingface.co/datasets/lmms-lab/ChartQA). The original ChartQA dataset is released under the GNU GPL-3.0 license by Masry et al. ## Citation ``` @inproceedings{masry2022chartqa, title={ChartQA: A Benchmark for Question Answering about Charts with Visual and Logical Reasoning}, author={Masry, Ahmed and Long, Do Xuan and Tan, Jia Qing and Joty, Shafiq and Hoque, Enamul}, booktitle={Findings of the Association for Computational Linguistics: ACL 2022}, year={2022} } ``` # CIFAR-10 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/cifar10 A Lance-formatted version of CIFAR-10 covering 60,000 32×32 RGB images across ten balanced object classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/cifar10-lance) > > Source dataset card and downloadable files for `lance-format/cifar10-lance`. Each row carries inline PNG bytes, the integer label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/cifar10-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so class filters and class-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 50,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (32×32 RGB) | | `label` | `int32` | Class id (0–9) | | `label_name` | `string` | One of `airplane`, `automobile`, `bird`, `cat`, `deer`, `dog`, `frog`, `horse`, `ship`, `truck` | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the class id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/cifar10-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/cifar10-lance --repo-type dataset --local-dir ./cifar10-lance > ``` > > Then point LanceDB at `./cifar10-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query image (or, for cross-modal text→image lookup, a tokenized prompt) through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query class:", seed["label_name"]) for r in hits: print(f" id={r['id']:>5} {r['label_name']}") ``` Because CIFAR-10 has only ten classes and the embeddings are cosine-normalized, near-neighbors of a seed image cluster tightly inside the seed's own class. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for a classification workflow narrows the table to a single class (or a small set of confusable classes) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label_name IN ('cat', 'dog')", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} cat/dog candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_animal` flag and an `is_target_class` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./cifar10-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_animal": "label_name IN ('bird', 'cat', 'deer', 'dog', 'frog', 'horse')", "is_target_class": "label = 3", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([3, 8, 0], type=pa.int32()), "pred_conf": pa.array([0.91, 0.74, 0.99]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, apply augmentations, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./cifar10-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('cat', 'dog')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./cifar10-cats-dogs") local_db.create_table("train", batches) ``` The resulting `./cifar10-cats-dogs` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/cifar10-lance/data` for `./cifar10-cats-dogs`. ## Source & license Converted from [`uoft-cs/cifar10`](https://huggingface.co/datasets/uoft-cs/cifar10). CIFAR-10 was collected by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton at the University of Toronto. ## Citation ``` @techreport{krizhevsky2009cifar10, title={Learning multiple layers of features from tiny images}, author={Krizhevsky, Alex and Hinton, Geoffrey}, year={2009}, institution={University of Toronto} } ``` # COCO Captions 2017 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/coco-captions-2017 A Lance-formatted version of the COCO Captions 2017 corpus, redistributed via lmms-lab/COCO-Caption2017. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/coco-captions-2017-lance) > > Source dataset card and downloadable files for `lance-format/coco-captions-2017-lance`. Each row is one image with **5–7 human-written captions**, a cosine-normalized CLIP image embedding, and a cosine-normalized CLIP text embedding of the canonical caption — all stored inline and available directly from the Hub at `hf://datasets/lance-format/coco-captions-2017-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `text_emb` (ViT-B/32, 512-dim, cosine-normalized) — so cross-modal retrieval is one indexed lookup. * **All 5–7 raw captions kept in `captions`** alongside a `caption` canonical string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the canonical caption, and `image_id`. ## Splits | Split | Rows | Notes | | - | - | - | | `val.lance` | 5,000 | Canonical COCO 2017 val set | | `test.lance` | 40,700 | Public test slice from `lmms-lab/COCO-Caption2017` | > The 2017 train split (118 k images, \~18 GB of source JPEGs) is intentionally not bundled here because the `lmms-lab/COCO-Caption2017` redistribution does not include it. To extend with train, run `coco_captions_2017/dataprep.py` against your local COCO 2017 train mirror. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string` | COCO image id | | `filename` | `string` | Original filename (e.g. `000000179765.jpg`) | | `captions` | `list<string>` | All 5–7 captions for the image | | `caption` | `string` | First caption — canonical text used for FTS | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `text_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `caption` — keyword and hybrid search * `BTREE` on `image_id` — fast lookup by COCO image id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/coco-captions-2017-lance", split="val", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/coco-captions-2017-lance --repo-type dataset --local-dir ./coco-captions-2017-lance > ``` > > Then point LanceDB at `./coco-captions-2017-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a text query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `text_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a caption", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") seed = ( tbl.search() .select(["text_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "caption"]) .limit(10) .to_list() ) print("query caption:", seed["caption"]) for r in hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Because OpenAI-style CLIP embeddings are normalized, cosine is the right metric and the first hit will typically be the source image itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `text_emb` to do text→text retrieval against the canonical captions instead. Because the dataset also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "yellow taxi" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["text_emb"]) .text("a man riding a surfboard") .select(["image_id", "caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a captioning or contrastive-training workflow combines a content filter on the captions with a structural filter on the image. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") candidates = ( tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) >= 5", prefilter=True) .select(["image_id", "caption", "captions"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first caption: {candidates[0]['caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by caption text rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `num_captions` and a `long_caption` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./coco-captions-2017-lance/data") # local copy required for writes tbl = db.open_table("val") tbl.add_columns({ "num_captions": "array_length(captions)", "long_caption": "length(caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, a second-pass caption from a different model), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "image_id": pa.array(["179765", "000139"]), "scene_label": pa.array(["beach", "kitchen"]), }) tbl.add_columns([f for f in labels.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second CLIP variant over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a CLIP-style contrastive run, project the JPEG bytes and a sampled caption; for a reranker or probe on top of frozen features, project the precomputed embeddings instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the captions, encode, contrastive loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "text_emb"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./coco-captions-2017-lance/data") local_tbl = local_db.open_table("val") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("val", version="clip-vitb32-v1") tbl_v5 = db.open_table("val", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and captions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") remote_tbl = remote_db.open_table("test") batches = ( remote_tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) >= 5") .select(["image_id", "image", "caption", "captions", "image_emb", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./coco-surf-subset") local_db.create_table("train", batches) ``` The resulting `./coco-surf-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/coco-captions-2017-lance/data` for `./coco-surf-subset`. ## Source & license Converted from [`lmms-lab/COCO-Caption2017`](https://huggingface.co/datasets/lmms-lab/COCO-Caption2017). Original COCO 2017 annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the underlying images are subject to Flickr terms of service. Please review the [COCO Terms of Use](https://cocodataset.org/#termsofuse) before redistribution. ## Citation ``` @inproceedings{lin2014microsoft, title={Microsoft COCO: Common objects in context}, author={Lin, Tsung-Yi and Maire, Michael and Belongie, Serge and Hays, James and Perona, Pietro and Ramanan, Deva and Doll{\'a}r, Piotr and Zitnick, C Lawrence}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # COCO 2017 Detection Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/coco-detection-2017 A Lance-formatted version of the COCO 2017 object detection benchmark, sourced from detection-datasets/coco. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/coco-detection-2017-lance) > > Source dataset card and downloadable files for `lance-format/coco-detection-2017-lance`. Each row is one image with its inline JPEG bytes, the full per-image list of bounding boxes, COCO 80-class category ids and names, per-object areas, an OpenCLIP image embedding, and pre-built indices — all available directly from the Hub at `hf://datasets/lance-format/coco-detection-2017-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Per-object annotations as parallel list columns** — `bboxes`, `categories`, `category_names`, and `areas` are aligned position-for-position, so iterating boxes alongside their labels is a single row read. * **Pre-aggregated annotation summaries** — `num_objects` (int) and `categories_present` (deduped string list) precompute the predicates curation queries hit most. * **CLIP image embeddings** (`image_emb`, OpenCLIP ViT-B/32, 512-d, cosine-normalized) with a bundled `IVF_PQ` index for visual retrieval. ## Splits | Split | Rows | | - | - | | `train.lance` | 117,000+ | | `val.lance` | 4,950+ | Total annotated boxes: \~860k train / \~37k val. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `int64` | COCO image id (natural join key) | | `width`, `height` | `int32` | Image dimensions in pixels | | `bboxes` | `list<list<float32, 4>>` | Each box is `[x_min, y_min, x_max, y_max]` in absolute pixel coordinates | | `categories` | `list<int32>` | COCO 80-class id (0–79), aligned with `bboxes` | | `category_names` | `list<string>` | Human-readable class name per object (e.g. `person`, `dog`) | | `areas` | `list<float32>` | Bounding-box area in pixels², aligned with `bboxes` | | `num_objects` | `int32` | Number of annotated objects in the image | | `categories_present` | `list<string>` | Deduped class names — feeds the `LABEL_LIST` index | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP ViT-B/32 image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `image_id` — fast lookup by COCO image id * `BTREE` on `num_objects` — range filters on image complexity * `LABEL_LIST` on `categories_present` — supports `array_has_any` / `array_has_all` for class-presence filtering ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/coco-detection-2017-lance", split="val", streaming=True) for row in hf_ds.take(3): print(row["image_id"], row["num_objects"], row["categories_present"][:5]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and any mutation are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/coco-detection-2017-lance --repo-type dataset --local-dir ./coco-detection-2017-lance > ``` > > Then point LanceDB at `./coco-detection-2017-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor visual retrieval a single call. In production you would encode a query image through the same OpenCLIP ViT-B/32 model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored on row 42 as a runnable stand-in, so the snippet works without loading any model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") seed = ( tbl.search() .select(["image_emb", "image_id", "categories_present"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["image_id", "categories_present", "num_objects"]) .limit(10) .to_list() ) print("query categories:", seed["categories_present"]) for r in hits: print(f" image_id={r['image_id']:>10} n={r['num_objects']:>3} cats={r['categories_present'][:5]}") ``` Because the embeddings are cosine-normalized, the first hit will typically be the source image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate Curation for a detection workflow usually means picking images that contain a specific class combination, possibly bounded by scene complexity. The `LABEL_LIST` index on `categories_present` makes class-presence predicates trivial, and Lance evaluates them inside the same scan as range filters on `num_objects` or `width`/`height`. The bounded `.limit(500)` keeps the result small and inspectable, and the `image` column is left out of the projection so the candidate scan is dominated by annotation metadata, not JPEG bytes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") candidates = ( tbl.search() .where( "array_has_all(categories_present, ['person', 'frisbee']) " "AND num_objects BETWEEN 3 AND 12", prefilter=True, ) .select(["image_id", "categories_present", "num_objects", "width", "height"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first image_id: {candidates[0]['image_id']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. Swapping `array_has_all` for `array_has_any` widens recall to images containing any of the listed classes; replacing the structural predicate with `num_objects >= 10` selects busy scenes for crowd-detection ablations. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `has_person` flag, an `aspect_ratio`, and a `max_box_area` that surfaces the largest annotated object area per image — all of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./coco-detection-2017-lance/data") # local copy required for writes tbl = db.open_table("val") tbl.add_columns({ "has_person": "array_has_any(categories_present, ['person'])", "aspect_ratio": "CAST(width AS DOUBLE) / CAST(height AS DOUBLE)", "max_box_area": "array_max(areas)", "crowded": "num_objects >= 10", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline predictions from a baseline detector, per-image difficulty scores, or a second-pass embedding), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "image_id": pa.array([397133, 37777, 252219], type=pa.int64()), "baseline_map": pa.array([0.31, 0.48, 0.22]), }) tbl.add_columns([f for f in predictions.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second detector over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a detector training run, project the JPEG bytes alongside the parallel annotation columns the loss consumes — boxes, category ids, and (optionally) areas. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["image", "bboxes", "categories", "areas"] ) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4, collate_fn=lambda b: b) # detection targets are ragged for batch in loader: # batch is a list of dicts: decode each JPEG, stack the bboxes / categories # into the target dictionary your detector expects, forward, loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "categories_present"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight multi-label classifier or a class-presence probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./coco-detection-2017-lance/data") local_tbl = local_db.open_table("val") local_tbl.tags.create("detector-baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("val", version="detector-baseline-v1") tbl_v5 = db.open_table("val", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `detector-baseline-v1` keeps scoring against the exact same boxes and category ids while the dataset evolves in parallel; newly merged predictions or evolved columns do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and annotations, so changes in mAP reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(categories_present, ['dog', 'cat']) AND num_objects >= 2") .select(["image_id", "image", "bboxes", "categories", "category_names", "areas", "num_objects", "categories_present", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./coco-pets-subset") local_db.create_table("train", batches) ``` The resulting `./coco-pets-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/coco-detection-2017-lance/data` for `./coco-pets-subset`. ## Source & license Converted from [`detection-datasets/coco`](https://huggingface.co/datasets/detection-datasets/coco). COCO annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the underlying images are subject to Flickr terms of service. See the [COCO Terms of Use](https://cocodataset.org/#termsofuse) before redistribution. ## Citation ``` @inproceedings{lin2014microsoft, title={Microsoft COCO: Common objects in context}, author={Lin, Tsung-Yi and Maire, Michael and Belongie, Serge and Hays, James and Perona, Pietro and Ramanan, Deva and Doll{\'a}r, Piotr and Zitnick, C Lawrence}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # DocVQA Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/docvqa A Lance-formatted version of DocVQA, a benchmark for visual question answering over document images such as industry and government scans, multi-page reports, forms, and receipts, redistributed via lmms-lab/DocVQA (DocVQA config). > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/docvqa-lance) > > Source dataset card and downloadable files for `lance-format/docvqa-lance`. Each row carries the page image as inline JPEG bytes, the question and reference answer span(s), the original DocVQA question-type tags, UCSF Industry Documents Library provenance, and paired CLIP embeddings for the image and the question — all available directly from the Hub at `hf://datasets/lance-format/docvqa-lance/data`. ## Key features * **Inline page image bytes** in the `image` column — no sidecar files, no document folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (ViT-B/32, 512-dim, cosine-normalized) — so visual and textual retrieval are one indexed lookup. * **All reference answer spans preserved in `answers`** alongside a canonical `answer` string used for full-text search. * **Pre-built ANN, FTS, scalar, and label-list indices** covering both embedding columns, the question and answer text, the document ids, and the `question_types` tag list. ## Splits | Split | Rows | Notes | | - | - | - | | `validation.lance` | 5,349 | Canonical DocVQA validation set | | `test.lance` | 5,188 | Public test slice from `lmms-lab/DocVQA` | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes (page image) | | `image_id` | `string?` | DocVQA `docId` (alias of `doc_id`) | | `question_id` | `string?` | DocVQA `questionId` | | `question` | `string` | Natural-language question | | `answers` | `list<string>` | Reference answer span(s) | | `answer` | `string` | First reference answer — canonical, used for FTS | | `doc_id` | `string?` | DocVQA document id | | `ucsf_document_id` | `string?` | UCSF Industry Documents Library id | | `ucsf_document_page_no` | `string?` | Page number within the source document | | `data_split` | `string?` | Original split label from the source | | `question_types` | `list<string>` | DocVQA question-type tags (`form`, `figure`, `table`, …) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BTREE` on `image_id`, `question_id`, `doc_id` — fast lookup by document or question id * `LABEL_LIST` on `question_types` — set-membership filtering over question-type tags ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/docvqa-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/docvqa-lance --repo-type dataset --local-dir ./docvqa-lance > ``` > > Then point LanceDB at `./docvqa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes question-to-question retrieval a single call: encode a query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question_id", "question", "answer", "question_types"]) .limit(10) .to_list() ) print("query:", seed["question"]) for r in hits: print(f" {r['question_id']:>8} {r['question'][:60]} -> {r['answer']}") ``` Swap `vector_column_name="question_emb"` for `image_emb` to retrieve pages whose visual layout is similar to a given embedding — useful when you want to find other forms or invoices that look like a seed page. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "invoice total" or "date of birth" must literally appear in the question but you still want CLIP to do the heavy lifting on semantic similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="question_emb") .vector(seed["question_emb"]) .text("invoice total") .select(["question_id", "question", "answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['question_id']:>8} {r['question'][:60]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a document-VQA workflow combines a content filter on the question with a structural filter on the question-type tags. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. The example below collects form-style questions that mention a date, which is a common slice for evaluating form-understanding behaviour. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search("date") .where("array_has_any(question_types, ['form'])", prefilter=True) .select(["question_id", "doc_id", "question", "answer", "question_types"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question and answer text rather than page JPEGs. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `answer_length`, an `is_form_question` flag, and a `has_table` flag, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./docvqa-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "answer_length": "length(answer)", "is_form_question": "array_has_any(question_types, ['form'])", "has_table": "array_has_any(question_types, ['table/list'])", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (OCR-extracted page text, model predictions, layout-detector outputs), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["49153", "49154", "49155"]), "pred_answer": pa.array(["$1,234.56", "John Doe", "2018-04-12"]), "is_correct": pa.array([True, True, False]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running OCR or a layout model over the page bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For fine-tuning a document-VLM, project the page bytes plus the question and answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question/answer pair, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight answer-classifier or a linear probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./docvqa-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("eval-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="eval-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `eval-v1` keeps producing comparable scores while the dataset evolves in parallel — newly added prediction columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same pages and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search("date") .where("array_has_any(question_types, ['form'])") .select(["id", "image", "question_id", "doc_id", "question", "answer", "question_types", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./docvqa-forms-subset") local_db.create_table("validation", batches) ``` The resulting `./docvqa-forms-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/docvqa-lance/data` for `./docvqa-forms-subset`. ## Source & license Converted from [`lmms-lab/DocVQA`](https://huggingface.co/datasets/lmms-lab/DocVQA). DocVQA is released under the MIT license; the underlying documents come from the [UCSF Industry Documents Library](https://www.industrydocuments.ucsf.edu/) — review their access conditions before redistribution. ## Citation ``` @inproceedings{mathew2021docvqa, title={DocVQA: A Dataset for VQA on Document Images}, author={Mathew, Minesh and Karatzas, Dimosthenis and Jawahar, CV}, booktitle={Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV)}, year={2021} } ``` # EuroSAT Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/eurosat A Lance-formatted version of EuroSAT, the canonical Sentinel-2 RGB land-cover benchmark, sourced from blanchon/EuroSAT_RGB. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/eurosat-lance) > > Source dataset card and downloadable files for `lance-format/eurosat-lance`. Each row is a single 64×64 RGB tile with its integer class id, the human-readable class name, and a cosine-normalized OpenCLIP image embedding — all stored inline and available directly from the Hub at `hf://datasets/lance-format/eurosat-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar TIF folders, no per-class subdirectories. * **Pre-computed OpenCLIP image embeddings** (`image_emb`, ViT-B/32, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both label representations** — integer `label` (0-9) and string `label_name` — with scalar indices on both for fast class filters. * **One columnar dataset** — scan labels and embeddings cheaply, fetch tile bytes only for the rows you actually need. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 16,200 | Training split | | `validation.lance` | 5,400 | Validation split | | `test.lance` | 5,400 | Held-out test split | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes (64×64 RGB Sentinel-2 tile) | | `label` | `int32` | Class id (0-9) | | `label_name` | `string` | One of `Annual_Crop`, `Forest`, `Herbaceous_Vegetation`, `Highway`, `Industrial_Buildings`, `Pasture`, `Permanent_Crop`, `Residential_Buildings`, `River`, `SeaLake` | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality / range filters by class id * `BITMAP` on `label_name` — fast set-membership filters by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/eurosat-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/eurosat-lance --repo-type dataset --local-dir ./eurosat-lance > ``` > > Then point LanceDB at `./eurosat-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visually-similar-tile retrieval a single call. In production you would encode a query tile through the same OpenCLIP `ViT-B-32` model used at ingest (cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print(f"reference tile class: {seed['label_name']}") for r in hits: print(f" id={r['id']:>6} {r['label_name']}") ``` Because the embeddings are cosine-normalized at ingest, `metric="cosine")` is the right choice and the first hit will typically be the seed tile itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a land-cover classification or retrieval study narrows the dataset to a single class and then retrieves the visually closest tiles to a seed. Lance evaluates the vector search and the metadata filter inside a single query, so the candidate set comes back already filtered. The example below pulls the 500 forest tiles most similar to a chosen seed; the bounded `.limit(500)` keeps the output small enough to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(0) .to_list()[0] ) candidates = ( tbl.search(seed["image_emb"]) .where("label_name = 'Forest'", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} Forest candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by the small metadata payload rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse `is_urban` flag that captures whether a tile belongs to one of the built-environment classes, useful as a direct predicate in later `where` clauses without re-evaluating the class set on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./eurosat-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_urban": "label_name IN ('Highway', 'Industrial_Buildings', 'Residential_Buildings')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a coarse climate label per class, an external aesthetic score, model predictions from a separate eval), add the new fields and update matching rows by `label_name`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa climate = pa.table({ "label_name": pa.array(["Forest", "Pasture", "SeaLake", "River"]), "climate_zone": pa.array(["temperate", "temperate", "marine", "freshwater"]), }) tbl.add_columns([f for f in climate.schema if f.name != "label_name"]) tbl.merge_insert("label_name").when_matched_update_all().execute(climate) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative remote-sensing model over the tile bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward through a CNN or ViT, cross-entropy loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight classifier head on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./eurosat-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same tiles, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('Forest', 'River', 'SeaLake')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./eurosat-natural-subset") local_db.create_table("train", batches) ``` The resulting `./eurosat-natural-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/eurosat-lance/data` for `./eurosat-natural-subset`. ## Source & license Converted from [`blanchon/EuroSAT_RGB`](https://huggingface.co/datasets/blanchon/EuroSAT_RGB). EuroSAT is released under the MIT license by Helber et al. The underlying Sentinel-2 imagery is © European Space Agency, made available under the [Copernicus open data policy](https://www.copernicus.eu/en/access-data/copyright-and-licences). ## Citation ``` @inproceedings{helber2019eurosat, title={EuroSAT: A novel dataset and deep learning benchmark for land use and land cover classification}, author={Helber, Patrick and Bischke, Benjamin and Dengel, Andreas and Borth, Damian}, journal={IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing}, year={2019} } ``` # Fashion-MNIST Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/fashion-mnist A Lance-formatted version of Fashion-MNIST covering 70,000 28×28 grayscale clothing images across ten balanced apparel classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/fashion-mnist-lance) > > Source dataset card and downloadable files for `lance-format/fashion-mnist-lance`. Each row carries inline PNG bytes, the integer label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/fashion-mnist-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so apparel-class filters and class-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 60,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) | | `label` | `int32` | Class id (0–9) | | `label_name` | `string` | One of `T-shirt_top`, `Trouser`, `Pullover`, `Dress`, `Coat`, `Sandal`, `Shirt`, `Sneaker`, `Bag`, `Ankle_boot` | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | > The original Fashion-MNIST class strings `T-shirt/top` and `Ankle boot` are sanitized to `T-shirt_top` and `Ankle_boot` for use as filename-safe identifiers, so SQL filters on `label_name` should reference the underscored form. ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the class id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/fashion-mnist-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/fashion-mnist-lance --repo-type dataset --local-dir ./fashion-mnist-lance > ``` > > Then point LanceDB at `./fashion-mnist-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query image (or, for cross-modal text→image lookup, a tokenized prompt like "a black ankle boot") through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query class:", seed["label_name"]) for r in hits: print(f" id={r['id']:>5} {r['label_name']}") ``` Because the embeddings are cosine-normalized and CLIP separates apparel categories cleanly, near-neighbors of a seed image are typically dominated by the seed's own class, with the most confusable garments (Shirt vs T-shirt_top, Sneaker vs Sandal) showing up next. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for an apparel-classification workflow narrows the table to a confusable subset of classes (for example, the three upper-body garments that share silhouettes) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label_name IN ('Shirt', 'T-shirt_top', 'Pullover')", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} upper-body-garment candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_footwear` flag that groups the three shoe-like classes and an `is_target_class` flag for one-vs-rest experiments, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fashion-mnist-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_footwear": "label_name IN ('Sandal', 'Sneaker', 'Ankle_boot')", "is_target_class": "label = 6", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([9, 0, 3], type=pa.int32()), "pred_conf": pa.array([0.94, 0.81, 0.77]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, normalize to [0, 1], forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./fashion-mnist-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('Shirt', 'T-shirt_top', 'Pullover')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./fashion-mnist-upper-body") local_db.create_table("train", batches) ``` The resulting `./fashion-mnist-upper-body` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/fashion-mnist-lance/data` for `./fashion-mnist-upper-body`. ## Source & license Converted from [`zalando-datasets/fashion_mnist`](https://huggingface.co/datasets/zalando-datasets/fashion_mnist). Released under the MIT license. ## Citation ``` @online{xiao2017fashionmnist, title={Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms}, author={Xiao, Han and Rasul, Kashif and Vollgraf, Roland}, year={2017}, eprint={1708.07747}, archivePrefix={arXiv}, primaryClass={cs.LG} } ``` # FineWeb-Edu Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/fineweb-edu A Lance-formatted version of FineWeb-Edu — over 1.5 billion educational web passages with cleaned text, source metadata, language detection signals, and 384-dim text embeddings — available directly from the Hub at hf://datasets/lance-format/fineweb-edu/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/fineweb-edu) > > Source dataset card and downloadable files for `lance-format/fineweb-edu`. ## Key features * **Cleaned passage text** in the `text` column with the source `url` and `title` carried alongside. * **Language detection signals** (`language`, `language_probability`) for filtered subsets. * **Pre-computed 384-dim text embeddings** in `text_embedding`, ready for ANN search once an index is built locally. * **One columnar dataset** — scan metadata cheaply, project just the columns each query needs, defer the heavy `text` and `text_embedding` reads to the rows that matter. > **No pre-built indices on the Hub copy yet.** At 1.5 B+ rows the on-disk indices are too large to ship comfortably alongside the data on the Hub. The Search, Curate, Evolve, and Train sections below describe the same APIs you'd use against a fully indexed dataset, but vector and full-text examples assume a local copy with `IVF_PQ` and `INVERTED` indices built once after download. See the Materialize-a-subset section at the end for a focused-subset workflow that makes indexing tractable. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `text` | `string` | Cleaned passage body | | `title` | `string` | Page or article title when available | | `url` | `string` | Canonical source URL | | `language` | `string` | Detected language code (e.g., `en`) | | `language_probability` | `float32` | Confidence of the language detector | | `text_embedding` | `fixed_size_list<float32, 384>` | Passage embedding for retrieval | | *FineWeb-Edu quality metadata* | — | Heuristic scores and length statistics carried over from the upstream corpus | ## Pre-built indices None bundled at present. Build the recommended indices on a local copy: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") tbl = db.open_table("train") tbl.create_index( metric="cosine", vector_column_name="text_embedding", index_type="IVF_PQ", num_partitions=2048, num_sub_vectors=96, ) tbl.create_fts_index("text", replace=True) ``` Both indices live next to the data, so subsequent queries against the same local path pick them up automatically. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/fineweb-edu", split="train", streaming=True) for row in hf_ds.take(3): print(row["title"] or row["url"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but at 1.5 B+ rows random access and any kind of search are dramatically faster against a local copy, and ANN / FTS require local indices anyway: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/fineweb-edu --repo-type dataset --local-dir ./fineweb-edu > ``` > > Then point LanceDB at `./fineweb-edu/data`. For most workflows, the Materialize-a-subset section is a better starting point than downloading the full 1.5 B-row corpus. ## Search Once an `IVF_PQ` index exists on `text_embedding`, dense retrieval is a single call. In production you would encode a query string through the same 384-dim text encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") # local copy with the indices from the section above tbl = db.open_table("train") seed = ( tbl.search() .select(["text_embedding", "url"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_embedding"]) .metric("cosine") .where("language = 'en' AND language_probability > 0.9", prefilter=True) .select(["title", "url", "text"]) .limit(10) .to_list() ) for r in hits: print(f"{r['url']}\n {(r['title'] or '')[:80]}") ``` The result set carries only the projected columns. The `text_embedding` vector is never read on the result side, and the `text` body is fetched only for the ten passages that actually came back, keeping the working set small even though the corpus is enormous. Because the recommended setup also builds an `INVERTED` index on `text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase must literally appear in the passage but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["text_embedding"]) .text("quantum computing") .where("language = 'en'", prefilter=True) .select(["title", "url", "text"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['url']}\n {(r['title'] or '')[:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass over a web corpus starts with a metadata filter — pick high-confidence English, drop short or low-quality fragments, restrict to a domain — before any text gets read. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "language = 'en' " "AND language_probability > 0.95 " "AND length(text) >= 1000", prefilter=True, ) .select(["url", "title", "language_probability"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first url: {candidates[0]['url']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of URLs, or hand to the Materialize-a-subset section below for export to a writable local copy. Neither the `text` body nor the `text_embedding` vector is read by this scan, so a 1000-row curation pass against the Hub moves only kilobytes of metadata even though the underlying table is in the billions. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `text_length` and a `long_passage` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull a larger slice first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "text_length": "length(text)", "long_passage": "length(text) >= 1000", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, topic classifications, alternate embeddings from a stronger model), add the new fields and update matching rows by `url`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "url": pa.array(["https://example.com/a", "https://example.com/b"]), "topic": pa.array(["math", "history"]), }) tbl.add_columns([f for f in labels.schema if f.name != "url"]) tbl.merge_insert("url").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For language-model pretraining the natural projection is just the `text` column; for a retrieval probe or a reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./fineweb-edu/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["text"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=8) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["text_embedding"]` to `select_columns(...)` on the next run reads only the 384-d vectors and skips the text body entirely, which is the right shape for training a lightweight retrieval head on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./fineweb-edu/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("english-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="english-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `english-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same passages, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset At 1.5 B+ rows, very few workflows want the full corpus on local disk. The practical entry point is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. The result is a writable LanceDB database scoped to the rows that actually matter for the downstream task, sized to index and iterate cheaply. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "language = 'en' " "AND language_probability > 0.95 " "AND length(text) >= 1000" ) .select(["url", "title", "text", "language", "language_probability", "text_embedding"]) .to_batches() ) local_db = lancedb.connect("./fineweb-edu-en") local_db.create_table("train", batches) ``` The resulting `./fineweb-edu-en` is a first-class LanceDB database. Build the recommended indices on it once (the same `create_index` / `create_fts_index` calls shown in the Pre-built indices section, pointed at the local path), and every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/fineweb-edu/data` for `./fineweb-edu-en`. ## Source & license Converted from [`HuggingFaceFW/fineweb-edu`](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu). FineWeb-Edu is distributed under [ODC-BY 1.0](https://opendatacommons.org/licenses/by/1-0/); individual document content remains subject to the rights of the original publishers. Review the [upstream dataset card](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) before downstream use. ## Citation ``` @misc{lozhkov2024finewebedu, title = {FineWeb-Edu: the Finest Collection of Educational Content the Web Has to Offer}, author = {Lozhkov, Anton and Ben Allal, Loubna and von Werra, Leandro and Wolf, Thomas}, year = {2024}, url = {https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu} } ``` # Flickr30k Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/flickr30k A Lance-formatted version of Flickr30k, redistributed via lmms-lab/flickr30k. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/flickr30k-lance) > > Source dataset card and downloadable files for `lance-format/flickr30k-lance`. Each row is one image with **5 human-written captions**, a cosine-normalized CLIP image embedding, and a cosine-normalized CLIP text embedding of the canonical caption — all stored inline and available directly from the Hub at `hf://datasets/lance-format/flickr30k-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `text_emb` (ViT-B/32, 512-dim, cosine-normalized) — so cross-modal retrieval is one indexed lookup. * **All 5 raw captions kept in `captions`** alongside a `caption` canonical string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the canonical caption, and `image_id`. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 31,783 | All Flickr30k images; the `lmms-lab/flickr30k` redistribution merges the original train/val/test labels into a single split | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string` | Original Flickr image id | | `filename` | `string?` | Original filename (e.g. `1000092795.jpg`) | | `captions` | `list<string>` | All 5 captions for the image | | `caption` | `string` | First caption — canonical text used for FTS | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `text_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `caption` — keyword and hybrid search * `BTREE` on `image_id` — fast lookup by Flickr image id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/flickr30k-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/flickr30k-lance --repo-type dataset --local-dir ./flickr30k-lance > ``` > > Then point LanceDB at `./flickr30k-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a text query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `text_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a caption", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["text_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "caption"]) .limit(10) .to_list() ) print("query caption:", seed["caption"]) for r in hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Because OpenAI-style CLIP embeddings are normalized, cosine is the right metric and the first hit will typically be the source image itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `text_emb` to do text→text retrieval against the canonical captions instead. Because the dataset also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "dog playing in the snow" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["text_emb"]) .text("dog playing in the snow") .select(["image_id", "caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a captioning or contrastive-training workflow combines a content filter on the captions with a structural filter on the row. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") candidates = ( tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) = 5", prefilter=True) .select(["image_id", "caption", "captions"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first caption: {candidates[0]['caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by caption text rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `num_captions` and a `long_caption` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./flickr30k-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "num_captions": "array_length(captions)", "long_caption": "length(caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, an aesthetic or NSFW score, a second-pass caption from a different model), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "image_id": pa.array(["1000092795", "10002456"]), "scene_label": pa.array(["outdoor", "indoor"]), }) tbl.add_columns([f for f in labels.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second CLIP variant over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a CLIP-style contrastive run, project the JPEG bytes and a sampled caption; for a reranker or probe on top of frozen features, project the precomputed embeddings instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the captions, encode, contrastive loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "text_emb"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./flickr30k-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and captions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) = 5") .select(["image_id", "image", "caption", "captions", "image_emb", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./flickr30k-surf-subset") local_db.create_table("train", batches) ``` The resulting `./flickr30k-surf-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/flickr30k-lance/data` for `./flickr30k-surf-subset`. ## Source & license Converted from [`lmms-lab/flickr30k`](https://huggingface.co/datasets/lmms-lab/flickr30k), which is itself a parquet redistribution of the [original Flickr30k corpus](https://shannon.cs.illinois.edu/DenotationGraph/). Original images come from Flickr; review the Flickr30k licensing terms before redistribution. ## Citation ``` @article{young2014image, title={From image descriptions to visual denotations: New similarity metrics for semantic inference over event descriptions}, author={Young, Peter and Lai, Alice and Hodosh, Micah and Hockenmaier, Julia}, journal={Transactions of the Association for Computational Linguistics}, volume={2}, pages={67--78}, year={2014} } ``` # Food-101 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/food101 A Lance-formatted version of Food-101, the fine-grained dish-classification benchmark of 101,000 photos spread evenly across 101 dish classes, sourced from ethz/food101. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/food101-lance) > > Source dataset card and downloadable files for `lance-format/food101-lance`. Each row carries the inline JPEG bytes, the integer `label`, the human-readable `label_name`, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/food101-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both numeric and string labels** (`label`, `label_name`) so filters can target either the class id or the dish name without an external mapping table. * **Scalar indices on both label columns** so class-based curation is a quick predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 75,750 | Canonical Food-101 train split (750 images per class) | | `validation.lance` | 25,250 | Canonical Food-101 test split (250 images per class) | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (256x256, quality 92) | | `label` | `int32` | Class id (0–100) | | `label_name` | `string` | One of 101 dish names, underscore-spaced (`apple_pie`, `baby_back_ribs`, …) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast lookup by class id * `BITMAP` on `label_name` — fast lookup by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/food101-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/food101-lance --repo-type dataset --local-dir ./food101-lance > ``` > > Then point LanceDB at `./food101-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without a model loaded; the first hit is expected to be the seed image itself, which is a useful sanity check on the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print("seed dish:", seed["label_name"]) for r in hits: print(f" {r['id']:>6} {r['label_name']}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a fine-grained classifier combines a class-based filter with the bundled vector search to assemble a small, focused candidate set. The `BITMAP` index on `label_name` makes the predicate effectively free, and the bounded `.limit(200)` keeps the result small enough to inspect or hand off to a training run. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where("label_name IN ('sushi', 'sashimi', 'ramen')") .select(["id", "label", "label_name"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidate Japanese-cuisine rows; first: {candidates[0]['label_name']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read by this query, so the network traffic is dominated by the small label fields rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse cuisine bucket and an `is_target_dish` flag for a focused training run, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./food101-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_target_dish": "label_name IN ('sushi', 'ramen', 'pho')", "is_dessert": "label_name IN ('apple_pie', 'cheesecake', 'tiramisu', 'ice_cream', 'donuts')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, a second classifier's predictions, human-verified taste tags), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2]), "model_v2_pred": pa.array(["sushi", "sashimi", "sushi"]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second embedding model over the JPEG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch image classifier, project the JPEG bytes and the integer label; for a linear probe or reranker on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward, cross-entropy against `label`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./food101-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="clip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('sushi', 'sashimi', 'ramen', 'pho', 'dumplings')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./food101-asian-subset") local_db.create_table("train", batches) ``` The resulting `./food101-asian-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/food101-lance/data` for `./food101-asian-subset`. ## Source & license Converted from [`ethz/food101`](https://huggingface.co/datasets/ethz/food101). The Food-101 dataset is by Bossard et al. (ETH Zurich) — see the [original dataset page](https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/) for licensing details. ## Citation ``` @inproceedings{bossard2014food, title={Food-101 -- Mining Discriminative Components with Random Forests}, author={Bossard, Lukas and Guillaumin, Matthieu and Van Gool, Luc}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # GQA testdev-balanced Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/gqa-testdev-balanced A Lance-formatted version of the canonical GQA testdev_balanced slice — 12,578 compositional VQA questions joined against the matching 398 images — sourced from lmms-lab/GQA. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/gqa-testdev-balanced-lance) > > Source dataset card and downloadable files for `lance-format/gqa-testdev-balanced-lance`. The original redistribution ships instructions and images as separate parquet configs; here they are pre-joined on `image_id`, so each row carries the question text, the short answer, the GQA reasoning-program tags, paired CLIP image and question embeddings, and the inline JPEG bytes — all available directly from the Hub at `hf://datasets/lance-format/gqa-testdev-balanced-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column, duplicated across rows that share an `image_id` so each Q/A row is self-contained. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (512-dim, cosine-normalized) — for cross-modal retrieval as one indexed lookup. * **Compositional reasoning metadata** — `structural`, `semantic`, and `detailed` question-type tags plus the `semantic_str` reasoning program. * **Pre-built ANN, FTS, scalar, and bitmap indices** covering both embeddings, the question and short answer, the reasoning-type tags, and the image/question ids. ## Splits | Split | Rows | Distinct images | | - | - | - | | `testdev.lance` | 12,578 | 398 | The train_balanced (\~943 k Q's × 72 k images) and val_balanced splits are not bundled by default; pass `--instr-config` / `--images-config` to `gqa/dataprep.py` to extend. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes (duplicated across rows that share an `image_id`) | | `image_id` | `string` | GQA scene-graph image id | | `question_id` | `string` | GQA question id | | `question` | `string` | Compositional natural-language question | | `answers` | `list<string>` | One-element list (the GQA short answer) | | `answer` | `string` | Canonical short answer (used for FTS) | | `full_answer` | `string?` | Full-sentence answer | | `structural` | `string?` | One of `verify`, `query`, `compare`, `choose`, `logical` | | `semantic` | `string?` | One of `attr`, `cat`, `global`, `obj`, `rel` | | `detailed` | `string?` | Fine-grained type (e.g. `weatherVerifyC`) | | `is_balanced` | `bool` | GQA balanced subset flag | | `group_global`, `group_local` | `string?` | GQA reasoning-group ids | | `semantic_str` | `string?` | Compact description of the reasoning program | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BITMAP` on `structural`, `semantic`, `detailed` — fast categorical filters on the reasoning program * `BTREE` on `image_id`, `question_id` — fast lookup by GQA id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/gqa-testdev-balanced-lance", split="testdev", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/gqa-testdev-balanced-lance --repo-type dataset --local-dir ./gqa-testdev-balanced-lance > ``` > > Then point LanceDB at `./gqa-testdev-balanced-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") seed = ( tbl.search() .select(["question_emb", "question", "answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "answer", "structural"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["answer"]) for r in hits: print(f" {r['image_id']:>12} [{r['structural']}] {r['question'][:70]}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased or topically related questions instead. The dataset also ships an `INVERTED` index on `question` and `answer`, so the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is useful when a noun like "umbrella" must appear in the question text but you still want CLIP to handle visual similarity over the candidate set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("umbrella") .select(["image_id", "question", "answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['question'][:70]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a compositional-reasoning study combines a predicate on the question text (or the GQA short answer) with a structural filter on the reasoning program, so the candidate set is both topically and structurally consistent. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") candidates = ( tbl.search() .where( "structural = 'verify' AND answer IN ('yes', 'no') AND question LIKE 'Is %'", prefilter=True, ) .select(["question_id", "image_id", "question", "answer", "semantic"]) .limit(500) .to_list() ) print(f"{len(candidates)} verify-style yes/no candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by the question and answer strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_binary_answer` flag and a `question_length` integer, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./gqa-testdev-balanced-lance/data") # local copy required for writes tbl = db.open_table("testdev") tbl.add_columns({ "is_binary_answer": "answer IN ('yes', 'no')", "question_length": "length(question)", "answer_length": "length(answer)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, scene-graph features, or per-question predictions from an external model), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["20240268", "20240269"]), "model_answer": pa.array(["yes", "left"]), "model_confidence": pa.array([0.91, 0.62]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation, Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a VQA fine-tune, project the JPEG bytes, the question, and the short answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question, forward through the VLM, compute the loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for a lightweight reasoning probe over frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./gqa-testdev-balanced-lance/data") local_tbl = local_db.open_table("testdev") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("testdev", version="clip-vitb32-v1") tbl_v5 = db.open_table("testdev", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added model predictions or reasoning annotations do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") remote_tbl = remote_db.open_table("testdev") batches = ( remote_tbl.search() .where("structural = 'verify' AND answer IN ('yes', 'no')") .select(["question_id", "image_id", "image", "question", "answer", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./gqa-yesno-subset") local_db.create_table("testdev", batches) ``` The resulting `./gqa-yesno-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/gqa-testdev-balanced-lance/data` for `./gqa-yesno-subset`. ## Source & license Converted from [`lmms-lab/GQA`](https://huggingface.co/datasets/lmms-lab/GQA). GQA is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) by Hudson and Manning (Stanford NLP). ## Citation ``` @inproceedings{hudson2019gqa, title={GQA: A New Dataset for Real-World Visual Reasoning and Compositional Question Answering}, author={Hudson, Drew A. and Manning, Christopher D.}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2019} } ``` # Handwriting OCR Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/handwriting-ocr This Lance-formatted version of the Doctor's Handwritten Prescription BD dataset contains 4,680 cropped PNG images of handwritten medicine names from Bangladesh. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/handwriting-ocr) > > Source dataset card and downloadable files for `lance-format/handwriting-ocr`. Each row keeps the original image bytes with the medicine and generic-name labels, plus deterministic search metadata derived from those labels. The dataset contains three source-preserved splits: train, validation, and test. > [!NOTE] > > **Training note:** The same samples appear repeatedly because a model (during training) should learn from multiple *different handwritten crops* of the same medicine, because they capture different writers, pen strokes, sizes, and image quality. The dataset would need to be shuffled and sampled appropriately before running downstream training tasks ## Key features * **Original inline PNG bytes** in `image`, with no image folders or sidecar files required. * **Three preserved splits**: 3,120 training, 780 validation, and 780 test examples. * **Medicine annotations**: 78 medicine names mapped to 15 generic names. * **Built-in text retrieval** over `searchable_summary`, with scalar indices matching the companion OCR retrieval project. ## Splits | Split | Rows | Source directory | | - | -: | - | | `train` | 3,120 | `Training` | | `validation` | 780 | `Validation` | | `test` | 780 | `Testing` | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | Stable split-qualified row identifier | | `image` | `large_binary` | Original inline PNG bytes | | `medicine_name` | `string` | Source medicine-name label | | `generic_name` | `string` | Source generic-name label | | `normalized_text` | `string` | Deterministic normalization of `medicine_name` | | `category` | `string` | `medication` for every source row | | `is_medical` | `bool` | `true` for every source row | | `needs_human_review` | `bool` | `false`; this conversion does not run OCR confidence assessment | | `searchable_summary` | `string` | Label-derived text: `Medication mention: <medicine> (<generic>)` | | `source_dataset` | `string` | Upstream Kaggle dataset identifier | | `split` | `string` | Original source split name: `Training`, `Validation`, or `Testing` | | `image_filename` | `string` | Original PNG filename within the source split | `normalized_text`, `category`, `is_medical`, `needs_human_review`, and `searchable_summary` are deterministic conversion metadata. They are not OCR or clinical-model predictions. ## Pre-built indices * `INVERTED` (FTS) on `searchable_summary` * `BTREE` on `id` * `BITMAP` on `category` * `BITMAP` on `needs_human_review` ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets through the standard Hugging Face `datasets` interface when you want a streaming sample or your pipeline already uses `Dataset` / `IterableDataset`. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset( "lance-format/handwriting-ocr", split="train", streaming=True, ) for row in hf_ds.take(3): print(row["medicine_name"], row["generic_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the downloaded dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, and Versioning examples below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip - for production use, download locally first.** Streaming from the Hub works for exploration, but repeated random access and training are faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/handwriting-ocr --repo-type dataset --local-dir ./handwriting-ocr > ``` > > Then run the examples below from `./handwriting-ocr`, where `./data` contains the downloaded Lance splits. ## Search The bundled full-text index makes medicine and generic-name lookups efficient without an embedding model. `searchable_summary` combines the two labels, so a text query can return the matching word image and its annotations in one bounded result set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") hits = ( tbl.search("Paracetamol") .select(["id", "medicine_name", "generic_name", "searchable_summary"]) .limit(10) .to_list() ) for row in hits: print(row["medicine_name"], "-", row["generic_name"]) ``` The FTS index operates on label-derived text, not a transcription produced from the image. It is useful for inspecting the handwritten examples associated with known medicine or generic names. ## Curate Filters produce small, explicit candidate sets for experiments. The example selects a bounded set of Paracetamol examples while avoiding image bytes until a later step needs them. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") candidates = ( tbl.search() .where("generic_name = 'Paracetamol'") .select(["id", "image_filename", "medicine_name", "generic_name"]) .limit(100) .to_list() ) ``` This list can be reviewed directly, saved as an experiment manifest, or used as the input to an annotation or training workflow. ## Evolve Lance can append new columns without rewriting the original images or annotations. For example, a local copy can add a flag for a specific generic name using a SQL expression, then merge independently produced labels by `id`. > **Note**: Mutations require a local copy. The examples in this card assume the dataset was downloaded into the current directory, as shown above. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa db = lancedb.connect("./data") tbl = db.open_table("train") # SQL-derived columns append a column file without rewriting existing columns or indices tbl.add_columns({"is_paracetamol": "generic_name = 'Paracetamol'"}) review_labels = pa.table({ "id": ["train_00000"], "review_status": ["reviewed"], }) tbl.add_columns([pa.field("review_status", pa.string())]) tbl.merge_insert("id").when_matched_update_all().execute(review_labels) ``` Matched rows receive the new labels while unmatched rows stay `null`, and each mutation becomes visible to queries as soon as its new table version commits. ## Train Projection lets a training loop read only the columns it needs. The image bytes and medicine label below are projected through a standard PyTorch `DataLoader`; fields added later do not add read cost unless selected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "medicine_name"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # Decode PNG bytes and train an OCR or classification model. ... ``` This keeps the original image representation available for training while avoiding unrelated columns on each epoch. ## Versioning Every Lance mutation creates a version, so the table history can identify the exact split and annotation state used by a retrieval service or experiment. The downloaded dataset can list its history and create tags for reproducible local workflows. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) tbl.tags.create("labels-v1", tbl.version) ``` A pinned version or tag keeps retrieval and training tied to a known dataset state even as review labels or derived columns are added later. ## Materialize a subset Use a filtered query to materialize a compact local LanceDB table for writes or intensive training. The query streams matching rows and projected columns without materializing the full result set in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb source_db = lancedb.connect("./data") source_tbl = source_db.open_table("train") batches = ( source_tbl.search() .where("generic_name = 'Paracetamol'") .select(["id", "image", "medicine_name", "generic_name", "searchable_summary"]) .to_batches() ) local_db = lancedb.connect("./paracetamol-subset") local_db.create_table("train", batches) ``` The resulting local table can replace `./data` in the Evolve, Train, and Versioning examples when a compact writable subset is sufficient. ## Citation Please cite both the upstream dataset and the associated research paper: ```bibtex theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @inproceedings{mia2024deep, title={A Deep Neural Network Approach with Pioneering Local Dataset to Recognize Doctor's Handwritten Prescription in Bangladesh}, author={Mia, Abdur Rahim and Chowdhury, Mohammad Abdullah-Al-Sajid and Mamun, Abdullah Al and Ruddra, Aurunave Mollik and Tanny, Nawshin Tabassum}, booktitle={2024 International Conference on Advances in Computing, Communication, Electrical, and Smart Systems}, pages={1--6}, year={2024}, publisher={IEEE}, doi={10.1109/iCACCESS61735.2024.10499631} } ``` Source dataset: [Mamun1113, Doctor's Handwritten Prescription BD dataset](https://www.kaggle.com/datasets/mamun1113/doctors-handwritten-prescription-bd-dataset). Associated paper: [IEEE Xplore](https://ieeexplore.ieee.org/document/10499631). ## License The upstream Kaggle metadata identifies the database license as [Open Database License (ODbL) v1.0](https://opendatacommons.org/licenses/odbl/1.0/) and states that the contents are copyright the original authors. The upstream page also describes the dataset as free for educational and research use. Downstream users should review the upstream dataset page and publication, satisfy the ODbL obligations, and obtain any additional permissions needed for their intended use. # HotpotQA distractor Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/hotpotqa-distractor A Lance-formatted version of HotpotQA using the distractor config — multi-hop reading-comprehension questions where each answer requires combining facts from two Wikipedia paragraphs, with 10 candidate paragraphs per question (gold + 8 distractors). > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/hotpotqa-distractor-lance) > > Source dataset card and downloadable files for `lance-format/hotpotqa-distractor-lance`. The dataset ships with MiniLM question embeddings, flattened context text for full-text search, and pre-built ANN/FTS indices, available directly from the Hub at `hf://datasets/lance-format/hotpotqa-distractor-lance/data`. ## Key features * **Multi-hop questions with gold supporting facts** — each row carries the question, the canonical short answer, and the `(title, sent_id)` pointers into the paragraphs that justify it. * **Ten candidate paragraphs per question** in the parallel `context_titles` / `context_sentences` columns, plus a flattened `context_text` field that feeds the FTS index. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question lookup. * **One columnar dataset** — scan metadata cheaply, then read the heavy context text only for the rows you actually want. ## Splits | Split | Rows | | - | - | | `train.lance` | 90,447 | | `validation.lance` | 7,405 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | HotpotQA question id | | `question` | `string` | The question | | `answer` | `string` | Reference short answer (`yes` / `no` / span) | | `type` | `string?` | `bridge` or `comparison` | | `level` | `string?` | `easy` / `medium` / `hard` | | `supporting_titles` | `list<string>` | Wikipedia titles that contain the gold facts | | `supporting_sent_ids` | `list<int32>` | Sentence indices into those titles | | `context_titles` | `list<string>` | All 10 paragraph titles (gold + distractors) | | `context_sentences` | `list<list<string>>` | Sentences per paragraph | | `context_text` | `string` | Flattened paragraphs — feeds the FTS index | | `num_supporting_facts` | `int32` | Number of gold supporting facts | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM question embedding | ## Pre-built indices * `IVF_PQ` on `question_emb` — semantic question lookup (cosine) * `INVERTED` (FTS) on `question` and `context_text` — keyword and hybrid search * `BTREE` on `id`, `answer` — stable lookup by identifier * `BITMAP` on `type`, `level` — cheap predicate evaluation for question class ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/hotpotqa-distractor-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`train`, `validation`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/hotpotqa-distractor-lance --repo-type dataset --local-dir ./hotpotqa-distractor-lance > ``` > > Then point LanceDB at `./hotpotqa-distractor-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes nearest-neighbour question lookup a single call. In production you would encode an incoming user question through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("level = 'hard'", prefilter=True) .select(["question", "answer", "supporting_titles", "type"]) .limit(10) .to_list() ) for r in hits: print(f"[{r['type']}] {r['question']} -> {r['answer']}") ``` The result set carries only the projected columns; the 384-d `question_emb` is never read on the result side, and the long `context_text` body is left untouched, keeping the working set small even when the underlying scan touches every row of the train split. Because the dataset also ships an `INVERTED` index on both `question` and `context_text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the full paragraph text. LanceDB merges the two result lists and reranks them in a single call, which is useful when a named entity must literally appear in one of the supporting paragraphs but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("inception dunkirk") .select(["question", "answer", "supporting_titles"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["question"], "->", r["answer"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate Building a focused evaluation slice usually means stacking predicates over the question metadata before any context text gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(2000)` keeps the output small enough to inspect. The example below assembles a set of hard, multi-hop comparison questions for which the gold answer is a real span rather than `yes`/`no`. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "type = 'comparison' " "AND level = 'hard' " "AND num_supporting_facts >= 2 " "AND answer NOT IN ('yes', 'no') " "AND length(question) >= 40", prefilter=True, ) .select(["id", "question", "answer", "supporting_titles"]) .limit(2000) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Evolve and Train sections below. Neither `context_text` nor `context_sentences` is read by this scan, so a 2000-row curation pass against the Hub moves only kilobytes of metadata. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length` column and a `is_multi_hop` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./hotpotqa-distractor-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "is_multi_hop": "num_supporting_facts >= 2", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline retriever scores, reranker logits, alternate embeddings from a stronger model), add the new fields and update matching rows by question `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa retriever_scores = pa.table({ "id": pa.array(["5a8b57f25542995d1e6f1371", "5a8c7595554299585d9e36b6"]), "bm25_top1_score": pa.array([12.7, 9.4]), }) tbl.add_columns([f for f in retriever_scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(retriever_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different encoder over the question text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a multi-hop QA model the natural projection is the question plus the flattened context and the gold answer; for a question-encoder retraining loop the precomputed embedding is enough on its own. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["question", "context_text", "answer"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "answer"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the short answer string, which is the right shape for fine-tuning a retrieval head on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./hotpotqa-distractor-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("hard-multihop-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="hard-multihop-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A QA system locked to `hard-multihop-v1` keeps returning stable supporting facts while the dataset evolves in parallel — newly added retriever scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and contexts, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "type = 'comparison' " "AND level = 'hard' " "AND num_supporting_facts >= 2" ) .select(["id", "question", "answer", "supporting_titles", "context_text", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./hotpotqa-hard-comparison") local_db.create_table("train", batches) ``` The resulting `./hotpotqa-hard-comparison` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/hotpotqa-distractor-lance/data` for `./hotpotqa-hard-comparison`. ## Source & license Converted from [`hotpot_qa`](https://huggingface.co/datasets/hotpot_qa) (`distractor` config). HotpotQA is released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @inproceedings{yang2018hotpotqa, title={HotpotQA: A Dataset for Diverse, Explainable Multi-hop Question Answering}, author={Yang, Zhilin and Qi, Peng and Zhang, Saizheng and Bengio, Yoshua and Cohen, William W. and Salakhutdinov, Ruslan and Manning, Christopher D.}, booktitle={Empirical Methods in Natural Language Processing (EMNLP)}, year={2018} } ``` # ImageNet-1k Validation Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/imagenet-1k-val A Lance-formatted version of the canonical 50,000-image ImageNet-1k (ILSVRC2012) validation split, sourced from benjamin-paine/imagenet-1k. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/imagenet-1k-val-lance) > > Source dataset card and downloadable files for `lance-format/imagenet-1k-val-lance`. Each row is one image with its integer class id, a string class name, and a cosine-normalized OpenCLIP image embedding — all stored inline and available directly from the Hub at `hf://datasets/lance-format/imagenet-1k-val-lance/data`. The 1.28 M ImageNet-1k train split (\~155 GB) is intentionally out of scope for this redistribution; the val split is the canonical evaluation slice for classification benchmarks and is small enough (\~7 GB Lance) to ride entirely in inline storage alongside its embeddings. ## Key features * **Inline JPEG bytes** in the `image` column — no per-class folders, no sidecar files. * **Pre-computed OpenCLIP image embeddings** (`image_emb`, ViT-B/32 trained on `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both label representations** — integer `label` (0-999) and string `label_name` (first synonym of the WordNet synset, e.g. `golden_retriever`) — with scalar indices on both for fast class filters. * **One columnar dataset** — scan labels and embeddings cheaply, fetch image bytes only for the rows you actually need. ## Splits A single split, shipped as `validation.lance` (50,000 rows). ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split, 0-49,999 (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `label` | `int32` | Class id (0-999) | | `label_name` | `string` | First synonym of the synset, underscore-spaced (e.g. `golden_retriever`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k` image embedding (cosine-normalized) | The full comma-separated WordNet synset descriptions for each class are stored in the dataset metadata under `lance:class_names`. ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine, `num_partitions=64`) * `BTREE` on `label` — fast equality / range filters by class id * `BITMAP` on `label_name` — fast set-membership filters by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/imagenet-1k-val-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/imagenet-1k-val-lance --repo-type dataset --local-dir ./imagenet-1k-val-lance > ``` > > Then point LanceDB at `./imagenet-1k-val-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes nearest-neighbor retrieval over the validation set a single call. In production you would encode a query image through the same OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k` model used at ingest (cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print(f"reference class: {seed['label_name']}") for r in hits: print(f" id={r['id']:>6} {r['label_name']}") ``` Because the embeddings are cosine-normalized at ingest, `metric="cosine"` is the right choice and the first hit will typically be the seed image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for an ImageNet-style classification or robustness study narrows the validation set to a single class (or a synset prefix) and then materializes a small candidate set for inspection. Stacking the filter and the projection inside a single scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where("label_name = 'golden_retriever'") .select(["id", "label", "label_name"]) .limit(200) .to_list() ) print(f"{len(candidates)} golden_retriever validation rows") ``` The `BITMAP` index on `label_name` resolves the predicate without scanning, and the `image` column is never read, so the network traffic for the candidate scan is dominated by the small metadata payload rather than JPEG bytes. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. To grab a family of related classes, replace the equality with a `LIKE` predicate such as `label_name LIKE 'tabby%'` or an `IN` set over a curated synset list. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse `is_dog` flag over a curated set of canine synsets, which can then be used directly in later `where` clauses without re-listing the class set on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./imagenet-1k-val-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_dog": "label_name IN ('golden_retriever', 'Labrador_retriever', 'beagle', 'pug', 'poodle')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table — per-class hypernyms from WordNet, ImageNet-A / ImageNet-R membership flags, model-prediction logs from an external eval run — add the new fields and update matching rows by `label_name`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa hypernyms = pa.table({ "label_name": pa.array(["golden_retriever", "tabby", "espresso"]), "hypernym": pa.array(["dog", "cat", "beverage"]), }) tbl.add_columns([f for f in hypernyms.schema if f.name != "label_name"]) tbl.merge_insert("label_name").when_matched_update_all().execute(hypernyms) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative vision backbone over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop — or, more commonly for this split, an evaluation loop — read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") eval_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(eval_ds, batch_size=128, shuffle=False, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward through your classifier, accumulate top-1 / top-5... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight classifier head on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./imagenet-1k-val-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("clip-vitb32-laion2b-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="clip-vitb32-laion2b-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `clip-vitb32-laion2b-v1` keeps reporting numbers against a fixed snapshot of labels and embeddings even as the dataset evolves in parallel; newly added columns or relabelings do not change what the tag resolves to. A research experiment pinned to the same tag can be rerun later against the exact same images, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training or evaluation loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where("label_name IN ('golden_retriever', 'Labrador_retriever', 'beagle', 'pug', 'poodle')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./imagenet-dogs-subset") local_db.create_table("validation", batches) ``` The resulting `./imagenet-dogs-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/imagenet-1k-val-lance/data` for `./imagenet-dogs-subset`. ## Source & license Converted from [`benjamin-paine/imagenet-1k`](https://huggingface.co/datasets/benjamin-paine/imagenet-1k), itself a redistribution of the [ILSVRC2012 ImageNet-1k validation split](https://image-net.org/challenges/LSVRC/2012/). All use is subject to the [ImageNet terms of access](https://image-net.org/download.php) — **for research use only**. ## Citation ``` @inproceedings{deng2009imagenet, title={ImageNet: A Large-Scale Hierarchical Image Database}, author={Deng, Jia and Dong, Wei and Socher, Richard and Li, Li-Jia and Li, Kai and Fei-Fei, Li}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2009} } ``` # Datasets Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/index Browse Lance-format datasets ready to query directly from the Hugging Face Hub. The [`lance-format`](https://huggingface.co/lance-format) organization on Hugging Face publishes a growing catalog of multimodal datasets in Lance format. Each one bundles the raw data (images, audio, video, or text), pre-computed embeddings, and on-disk vector / full-text indices as first-class columns in the same dataset — so vector search, full-text search, and filtered scans work directly via `hf://` URIs without downloading. This is powered under the hood by the [Lance format's native Hugging Face integration](https://lance.org/integrations/huggingface/). LanceDB sits on top of Lance and gives you a convenient table-style interface to query these datasets straight from the Hub: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/<dataset-name>/data") tbl = db.open_table("train") # Vector search, full-text search, or filtered scans — directly on the Hub results = tbl.search(query).limit(10).to_list() ``` Click any card below for usage examples, schema, and pre-built indices. For a complete walkthrough of the integration itself, see the [Hugging Face Hub integration page](/enterprise/v1-12-0/integrations/ai/huggingface). ## Image Classification > [card] [MNIST](/enterprise/v1-12-0/datasets/mnist) > > `lance-format/mnist-lance` — A Lance-formatted version of the classic MNIST handwritten-digit dataset covering 70,000 28×28 grayscale digits across ten balanced classes. > [card] [CIFAR-10](/enterprise/v1-12-0/datasets/cifar10) > > `lance-format/cifar10-lance` — A Lance-formatted version of CIFAR-10 covering 60,000 32×32 RGB images across ten balanced object classes. > [card] [Fashion-MNIST](/enterprise/v1-12-0/datasets/fashion-mnist) > > `lance-format/fashion-mnist-lance` — A Lance-formatted version of Fashion-MNIST covering 70,000 28×28 grayscale clothing images across ten balanced apparel classes. > [card] [Food-101](/enterprise/v1-12-0/datasets/food101) > > `lance-format/food101-lance` — A Lance-formatted version of Food-101, the fine-grained dish-classification benchmark of 101,000 photos spread evenly across 101 dish classes, sourced from ethz/food101. > [card] [Oxford-IIIT Pet](/enterprise/v1-12-0/datasets/oxford-pets) > > `lance-format/oxford-pets-lance` — A Lance-formatted version of the Oxford-IIIT Pet dataset — 7,390 cat and dog photos across 37 breeds — sourced from pcuenq/oxford-pets. > [card] [Stanford Cars](/enterprise/v1-12-0/datasets/stanford-cars) > > `lance-format/stanford-cars-lance` — A Lance-formatted version of the Stanford Cars fine-grained benchmark — 8,144 photographs across 196 make/model/year classes — sourced from Multimodal-Fatima/StanfordCars_train. > [card] [ImageNet-1k Validation](/enterprise/v1-12-0/datasets/imagenet-1k-val) > > `lance-format/imagenet-1k-val-lance` — A Lance-formatted version of the canonical 50,000-image ImageNet-1k (ILSVRC2012) validation split, sourced from benjamin-paine/imagenet-1k. > [card] [EuroSAT](/enterprise/v1-12-0/datasets/eurosat) > > `lance-format/eurosat-lance` — A Lance-formatted version of EuroSAT, the canonical Sentinel-2 RGB land-cover benchmark, sourced from blanchon/EuroSAT_RGB. ## OCR & Handwriting > [card] [Handwriting OCR](/enterprise/v1-12-0/datasets/handwriting-ocr) > > `lance-format/handwriting-ocr` — This Lance-formatted version of the Doctor's Handwritten Prescription BD dataset contains 4,680 cropped PNG images of handwritten medicine names from Bangladesh. ## Object Detection & Segmentation > [card] [COCO 2017 Detection](/enterprise/v1-12-0/datasets/coco-detection-2017) > > `lance-format/coco-detection-2017-lance` — A Lance-formatted version of the COCO 2017 object detection benchmark, sourced from detection-datasets/coco. > [card] [Pascal VOC 2012 Segmentation](/enterprise/v1-12-0/datasets/pascal-voc-2012-segmentation) > > `lance-format/pascal-voc-2012-segmentation-lance` — A Lance-formatted version of the Pascal VOC 2012 semantic segmentation split, sourced from nateraw/pascal-voc-2012. > [card] [ADE20K](/enterprise/v1-12-0/datasets/ade20k) > > `lance-format/ade20k-lance` — A Lance-formatted version of the full ADE20K scene parsing benchmark, sourced from 1aurent/ADE20K. > [card] [KITTI 2D Detection](/enterprise/v1-12-0/datasets/kitti-2d-detection) > > `lance-format/kitti-2d-detection-lance` — A Lance-formatted version of the KITTI 2D Object Detection benchmark, sourced from nateraw/kitti so no manual signup or download from cvlibs.net is required. ## Image Retrieval > [card] [COCO Captions 2017](/enterprise/v1-12-0/datasets/coco-captions-2017) > > `lance-format/coco-captions-2017-lance` — A Lance-formatted version of the COCO Captions 2017 corpus, redistributed via lmms-lab/COCO-Caption2017. > [card] [Flickr30k](/enterprise/v1-12-0/datasets/flickr30k) > > `lance-format/flickr30k-lance` — A Lance-formatted version of Flickr30k, redistributed via lmms-lab/flickr30k. > [card] [LAION-1M](/enterprise/v1-12-0/datasets/laion-1m) > > `lance-format/laion-1m` — A Lance-formatted slice of the LAION image-text corpus (\~1M rows) with inline JPEG bytes, CLIP image embeddings (img_emb), full metadata, and a pre-built ANN index — all available directly from the Hub at hf://datasets/lance-format/laion-1m/data/train.lance. ## Visual Question Answering > [card] [ChartQA](/enterprise/v1-12-0/datasets/chartqa) > > `lance-format/chartqa-lance` — A Lance-formatted version of ChartQA, a benchmark for question answering over scientific and business charts that demands a mix of logical and visual reasoning, redistributed via lmms-lab/ChartQA. > [card] [DocVQA](/enterprise/v1-12-0/datasets/docvqa) > > `lance-format/docvqa-lance` — A Lance-formatted version of DocVQA, a benchmark for visual question answering over document images such as industry and government scans, multi-page reports, forms, and receipts, redistributed via lmms-lab/DocVQA (DocVQA config). > [card] [TextVQA](/enterprise/v1-12-0/datasets/textvqa) > > `lance-format/textvqa-lance` — A Lance-formatted version of TextVQA — visual question answering where the question requires reading text in the image (street signs, product labels, screen captures) — sourced from lmms-lab/textvqa. > [card] [VQAv2](/enterprise/v1-12-0/datasets/vqav2) > > `lance-format/vqav2-lance` — A Lance-formatted version of VQAv2 — open-ended visual question answering on COCO images — sourced from lmms-lab/VQAv2. > [card] [GQA testdev-balanced](/enterprise/v1-12-0/datasets/gqa-testdev-balanced) > > `lance-format/gqa-testdev-balanced-lance` — A Lance-formatted version of the canonical GQA testdev_balanced slice — 12,578 compositional VQA questions joined against the matching 398 images — sourced from lmms-lab/GQA. ## Text QA > [card] [SQuAD v2](/enterprise/v1-12-0/datasets/squad-v2) > > `lance-format/squad-v2-lance` — A Lance-formatted version of SQuAD v2 — the Stanford Question Answering Dataset with both answerable and deliberately unanswerable questions over Wikipedia passages — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/squad-v2-lance/data. > [card] [TriviaQA](/enterprise/v1-12-0/datasets/trivia-qa) > > `lance-format/trivia-qa-lance` — A Lance-formatted version of TriviaQA (rc.nocontext config) — a large reading-comprehension dataset of trivia questions paired with a canonical answer, accepted aliases, and entity-type metadata — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/trivia-qa-lance/data. > [card] [HotpotQA distractor](/enterprise/v1-12-0/datasets/hotpotqa-distractor) > > `lance-format/hotpotqa-distractor-lance` — A Lance-formatted version of HotpotQA using the distractor config — multi-hop reading-comprehension questions where each answer requires combining facts from two Wikipedia paragraphs, with 10 candidate paragraphs per question (gold + 8 distractors). > [card] [Natural Questions Validation](/enterprise/v1-12-0/datasets/natural-questions-val) > > `lance-format/natural-questions-val-lance` — A Lance-formatted version of the Natural Questions validation split — 7,830 real Google search queries paired with the full Wikipedia article a human used to answer them, plus 1–5 annotator labels per question. > [card] [MS MARCO v2.1](/enterprise/v1-12-0/datasets/ms-marco-v2) > > `lance-format/ms-marco-v2.1-lance` — A Lance-formatted version of MS MARCO v2.1 — Microsoft's machine-reading-comprehension benchmark built from anonymized Bing query logs. ## Text Corpora > [card] [FineWeb-Edu](/enterprise/v1-12-0/datasets/fineweb-edu) > > `lance-format/fineweb-edu` — A Lance-formatted version of FineWeb-Edu — over 1.5 billion educational web passages with cleaned text, source metadata, language detection signals, and 384-dim text embeddings — available directly from the Hub at hf://datasets/lance-format/fineweb-edu/data/train.lance. ## Speech > [card] [LibriSpeech clean](/enterprise/v1-12-0/datasets/librispeech-clean) > > `lance-format/librispeech-clean-lance` — A Lance-formatted version of the LibriSpeech ASR clean configuration, sourced from openslr/librispeech_asr. ## Video > [card] [OpenVid-1M](/enterprise/v1-12-0/datasets/openvid) > > `lance-format/openvid-lance` — A Lance-formatted version of the OpenVid-1M corpus — 937,957 high-quality clips with inline MP4 bytes, 1024-dim video embeddings, captions, and rich per-clip quality signals — available directly from the Hub at hf://datasets/lance-format/openvid-lance/data/train.lance. ## Robotics > [card] [LeRobot PushT](/enterprise/v1-12-0/datasets/lerobot-pusht) > > `lance-format/lerobot-pusht-lance` — A Lance-formatted version of lerobot/pusht — the canonical PushT benchmark from the Diffusion Policy paper — packaged using the same three-table layout as lance-format/lerobot-xvla-soft-fold so consumers can flip between datasets without changing code. > [card] [LeRobot X-VLA Soft-Fold](/enterprise/v1-12-0/datasets/lerobot-xvla-soft-fold) > > `lance-format/lerobot-xvla-soft-fold` — A Lance-formatted version of lerobot/xvla-soft-fold — a multi-camera robotics dataset from the X-VLA project — packaged as three Lance tables for efficient frame-level training, episode-level trajectory loading, and direct access to the original encoded videos. ## Share your own dataset Got a multimodal dataset you want to publish? Convert it to Lance and push it to the Hub! Anyone who opens it gets vector search, full-text search, and filtered scans on the data out of the box, without recreating the embeddings or indexes on their end. > [card] [Upload Lance datasets to the Hugging Face Hub](https://www.lancedb.com/blog/upload-lance-datasets-to-hf-hub) > > A step-by-step walkthrough on the LanceDB blog covering CLI setup, packaging your dataset, pushing to your namespace, and writing a dataset card. Or browse the [latest trending Lance datasets](https://huggingface.co/datasets?format=format:lance\&sort=trending) on Hugging Face. # KITTI 2D Detection Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/kitti-2d-detection A Lance-formatted version of the KITTI 2D Object Detection benchmark, sourced from nateraw/kitti so no manual signup or download from cvlibs.net is required. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/kitti-2d-detection-lance) > > Source dataset card and downloadable files for `lance-format/kitti-2d-detection-lance`. Each row is a single driving frame with inline JPEG bytes, the full set of 2D and 3D object annotations stored as parallel per-object lists, plus a cosine-normalized OpenCLIP `ViT-B-32` image embedding — all available directly from the Hub at `hf://datasets/lance-format/kitti-2d-detection-lance/data`. KITTI is the canonical autonomous-driving detection benchmark with 8 object classes drawn from real street scenes around Karlsruhe. It is widely used for AV perception research and serves as a small-scale companion to nuScenes and Waymo. ## Key features * **Inline JPEG bytes** in the `image` column — no parallel `image_2/` and `label_2/` folders to keep in sync. * **Per-object 2D and 3D annotations on the same row** — bounding boxes, observation angles, 3D dimensions, locations, yaw, occlusion and truncation flags travel as parallel list columns of equal length. * **Pre-computed CLIP image embeddings** (`image_emb`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for visual similarity over driving scenes. * **Scalar and label-list indices** on `num_objects` and `types_present` make per-class and crowdedness filters cheap on the Hub copy and locally. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 7,481 | Official KITTI training set with labels | The KITTI `test` split has no public labels and is intentionally not bundled. Add it via `--splits train test` in `kitti/dataprep.py` if you want the unlabeled images for inference. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (re-encoded from the source PNG) | | `bboxes` | `list<list<float32, 4>>` | 2D box per object — `[left, top, right, bottom]` in pixel coords | | `alphas` | `list<float32>` | Observation angle per object (radians, KITTI convention) | | `dimensions` | `list<list<float32, 3>>` | 3D box `(h, w, l)` per object, in metres | | `locations` | `list<list<float32, 3>>` | 3D centre `(x, y, z)` per object in camera coords, in metres | | `rotation_y` | `list<float32>` | Yaw per object in camera coords (radians) | | `occluded` | `list<int8>` | KITTI occlusion flag (0=visible, 1=partly, 2=largely, 3=unknown) | | `truncated` | `list<float32>` | Truncation fraction per object (0.0-1.0) | | `types` | `list<string>` | Class name per object (`Car`, `Van`, `Truck`, `Pedestrian`, `Person_sitting`, `Cyclist`, `Tram`, `Misc`, `DontCare`) | | `num_objects` | `int32` | Number of annotated objects in the frame | | `types_present` | `list<string>` | Deduped class names — feeds the LABEL_LIST index | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | All `list<...>` annotation columns on the same row are aligned — index `i` across `bboxes`, `alphas`, `dimensions`, `locations`, `rotation_y`, `occluded`, `truncated`, and `types` describes the same physical object. ## Pre-built indices * `IVF_PQ` on `image_emb` — `metric=cosine` * `BTREE` on `num_objects` * `LABEL_LIST` on `types_present` ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/kitti-2d-detection-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["id"], row["num_objects"], row["types_present"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/kitti-2d-detection-lance --repo-type dataset --local-dir ./kitti-2d-detection-lance > ``` > > Then point LanceDB at `./kitti-2d-detection-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visual nearest-neighbour search over driving scenes a single call. In production you would encode a query frame (or a scene prototype) through OpenCLIP `ViT-B-32` at runtime and pass the resulting 512-d cosine-normalized vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "types_present"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "num_objects", "types_present"]) .limit(10) .to_list() ) print("query scene types:", seed["types_present"]) for r in hits: print(f" id={r['id']:>5} n={r['num_objects']:>2} {r['types_present']}") ``` Because the embeddings are cosine-normalized, `metric="cosine"` is the natural choice and the first hit is typically the seed row itself. Visual neighbours tend to share scene-level structure (highway vs. urban intersection vs. parked-cars row) before they share class composition, which is what makes the cross between `image_emb` and the `types_present` / `num_objects` indices useful for the curation patterns below. ## Curate KITTI's parallel per-object list columns make composition-based filters natural: pick scenes by which classes are present, by how many objects are in them, or by the occlusion profile of those objects. Lance evaluates these predicates inside a single filtered scan, and the bounded `.limit(...)` keeps the candidate set small and explicit. The first snippet below finds crowded scenes that contain at least one cyclist and one pedestrian — a useful slice for vulnerable-road-user studies. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") vru = ( tbl.search() .where( "array_has_all(types_present, ['Cyclist', 'Pedestrian']) AND num_objects >= 8", prefilter=True, ) .select(["id", "num_objects", "types_present"]) .limit(200) .to_list() ) print(f"{len(vru)} VRU-rich frames") ``` A second pass can combine a structural filter with visual similarity: take a crowded urban seed frame and look for visually similar frames whose object lists also contain cars. This is a one-shot retrieval against the `IVF_PQ` index, joined with the `LABEL_LIST` index on `types_present` inside a single query. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} seed = ( tbl.search() .where("num_objects >= 10 AND array_contains(types_present, 'Car')", prefilter=True) .select(["image_emb"]) .limit(1) .to_list()[0] ) similar_crowded = ( tbl.search(seed["image_emb"]) .metric("cosine") .where("array_contains(types_present, 'Car')", prefilter=True) .select(["id", "num_objects", "types_present"]) .limit(50) .to_list() ) ``` The results are plain lists of dictionaries, ready to inspect, persist as manifests of `id`s, or feed into the Evolve and Train workflows below. The annotation list columns and `image_emb` are read; the JPEG bytes are not touched until you ask for them. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds per-frame counts for the two most safety-relevant classes plus a `has_vru` flag, all of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./kitti-2d-detection-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "num_cars": "array_length(array_filter(types, x -> x = 'Car'))", "num_pedestrians": "array_length(array_filter(types, x -> x = 'Pedestrian'))", "has_vru": "array_has_any(types_present, ['Pedestrian', 'Cyclist'])", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table — detector predictions on the same frames, LIDAR-derived per-frame features, or human re-annotation — add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_num_cars": pa.array([3, 5, 0], type=pa.int32()), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (running a fresh detector over the JPEG bytes, deriving alternative embeddings), Lance also provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a 2D detector, project the JPEG bytes together with the per-object `bboxes` and `types` lists; everything else (3D annotations, CLIP embeddings) stays on disk until you opt in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") train_ds = ( Permutation.identity(tbl) .select_columns(["image", "bboxes", "types"]) ) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; 3D fields and image_emb stay on disk. # decode the JPEGs, drop DontCare boxes, build target tensors, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "types_present"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight scene classifier or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./kitti-2d-detection-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("kitti-clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="kitti-clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A perception service locked to `kitti-clip-vitb32-v1` keeps returning stable retrieval results while the dataset evolves in parallel — newly added detector predictions or alternative embeddings do not change what the tag resolves to. A detection-training experiment pinned to the same tag can be rerun later against the exact same frames and annotations, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. The filter below carves out a vulnerable-road-user training set — frames that contain at least one pedestrian or cyclist — and writes them to a local LanceDB database. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(types_present, ['Pedestrian', 'Cyclist'])") .select(["id", "image", "bboxes", "types", "num_objects", "types_present", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./kitti-vru-subset") local_db.create_table("train", batches) ``` The resulting `./kitti-vru-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/kitti-2d-detection-lance/data` for `./kitti-vru-subset`. ## Source & license Converted from [`nateraw/kitti`](https://huggingface.co/datasets/nateraw/kitti). KITTI is released under the [CC BY-NC-SA 3.0 license](https://creativecommons.org/licenses/by-nc-sa/3.0/) by Karlsruhe Institute of Technology and Toyota Technological Institute at Chicago — **non-commercial research use only**. See the [KITTI license page](https://www.cvlibs.net/datasets/kitti/) for details. ## Citation ``` @inproceedings{geiger2012are, title={Are we ready for autonomous driving? The KITTI vision benchmark suite}, author={Geiger, Andreas and Lenz, Philip and Urtasun, Raquel}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2012} } ``` # LAION-1M Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/laion-1m A Lance-formatted slice of the LAION image-text corpus (~1M rows) with inline JPEG bytes, CLIP image embeddings (img_emb), full metadata, and a pre-built ANN index — all available directly from the Hub at hf://datasets/lance-format/laion-1m/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/laion-1m) > > Source dataset card and downloadable files for `lance-format/laion-1m`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`img_emb`, 768-dim) with a bundled `IVF_PQ` index for similarity search. * **Full LAION metadata** — captions, URLs, NSFW flags, EXIF, dimensions, similarity scores. * **One columnar dataset** — scan metadata cheaply, then fetch image bytes only for the rows you want. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `key` | `int64` | Row key (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes | | `image_path` | `string` | Original filename | | `caption` | `string` | Image caption | | `url` | `string` | Source URL | | `NSFW` | `int64` | 0 = safe, 1 = NSFW | | `LICENSE` | `string` | Per-row license tag | | `similarity` | `float64` | CLIP image–text cosine similarity | | `width`, `height` | `int64` | Image dimensions | | `original_width`, `original_height` | `int64` | Original dimensions before resize | | `exif`, `md5`, `status`, `error_message` | `string` | Provenance / metadata | | `img_emb` | `fixed_size_list<float32, 768>` | CLIP image embedding | ## Pre-built indices * `IVF_PQ` on `img_emb` — vector similarity search (L2) ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/laion-1m", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, and Versioning examples below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/laion-1m --repo-type dataset --local-dir ./laion-1m > ``` > > Then point LanceDB at `./laion-1m/data`. ## Search The bundled `IVF_PQ` index on `img_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a user prompt or query image through CLIP at runtime and pass the resulting 768-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") query = ( tbl.search() .select(["img_emb"]) .limit(1) .offset(42) .to_list()[0]["img_emb"] ) hits = ( tbl.search(query) .metric("L2") .select(["caption", "url", "similarity"]) .limit(10) .to_list() ) for r in hits: print(f"{r['similarity']:.3f} | {r['caption'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate Building a focused subset usually means combining similarity with metadata filters. Lance evaluates both inside a single query, so the candidate set comes back already filtered. The example below finds images visually similar to a seed row and restricts the result to safe-rated, high-resolution rows in one call. The bounded `.limit(500)` keeps the output small enough to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["img_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) candidates = ( tbl.search(seed["img_emb"]) .where('"NSFW" = 0 AND similarity > 0.3 AND width >= 512', prefilter=True) .select(["key", "url", "caption", "similarity"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates around: {seed['caption'][:60]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row keys, or feed into the Evolve and Train workflows below. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a precomputed `aspect_ratio` and an `is_high_res` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note**: Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./laion-1m/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "aspect_ratio": "CAST(width AS DOUBLE) / CAST(height AS DOUBLE)", "is_high_res": "width >= 512 AND height >= 512", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, aesthetic scores), add the new fields and update matching rows by `key`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "key": pa.array([0, 1, 2]), "aesthetic_score": pa.array([7.1, 6.4, 8.9]), }) tbl.add_columns([f for f in labels.schema if f.name != "key"]) tbl.merge_insert("key").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an embedding model over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; img_emb / img_emb_dinov3 stay on disk. # decode the JPEG bytes, tokenize the captions, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["img_emb_dinov3", "caption"]` to `select_columns(...)` on the next run reads only those columns, with no data movement or shard reorganization. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./laion-1m/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("aesthetic-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="aesthetic-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `aesthetic-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same data, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where('"NSFW" = 0 AND similarity > 0.35 AND width >= 512') .select(["key", "image", "caption", "url", "img_emb"]) .to_batches() ) local_db = lancedb.connect("./laion-subset") local_db.create_table("train", batches) ``` The resulting `./laion-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/laion-1m/data` for `./laion-subset`. ## Citation ``` @article{schuhmann2022laion5b, title={LAION-5B: An open large-scale dataset for training next generation image-text models}, author={Schuhmann, Christoph and others}, journal={NeurIPS Datasets and Benchmarks Track}, year={2022} } ``` ## License Content inherits LAION's original licensing and safety guidelines. Review [LAION policy](https://laion.ai/blog/laion-5b/) before downstream use. # LeRobot PushT Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/lerobot-pusht A Lance-formatted version of lerobot/pusht — the canonical PushT benchmark from the Diffusion Policy paper — packaged using the same three-table layout as lance-format/lerobot-xvla-soft-fold so consumers can flip between datasets without changing code. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/lerobot-pusht-lance) > > Source dataset card and downloadable files for `lance-format/lerobot-pusht-lance`. Available directly from the Hub at `hf://datasets/lance-format/lerobot-pusht-lance/data`. ## Key features * **Three-table layout** — `frames`, `episodes`, `videos` — so frame-level training, episode-level trajectory work, and raw video access live side-by-side without scattered parquet shards or sidecar MP4 directories. * **Inline MP4 segments** in `episodes.lance` (one blob per camera, with `from_timestamp` / `to_timestamp` bounds) and full source MP4s in `videos.lance`, all surfaced as lazy `BlobFile` handles via `fetch_blob_files` so metadata scans never read the bytes. * **Frame-level observations and actions** in `frames.lance` with stable `episode_index`, `frame_index`, and `index` columns for joining or temporal iteration. * **Schema-evolution friendly** — add alternate camera streams, language annotations, or model predictions later without rewriting the data. ## Tables | Table | Rows \~ | Purpose | | - | - | - | | `frames.lance` | one row per frame | Per-frame observations, actions, episode/task indices | | `episodes.lance` | one row per episode | Full per-episode trajectories plus per-camera MP4 segment blobs and timestamp bounds | | `videos.lance` | one row per source MP4 | Raw source video blobs and file-level provenance (path, size, sha256) | Use `frames.lance` for low-level training (loss-per-timestep, state-conditioned policies). Use `episodes.lance` when you need the full trajectory and the matching video segments together. Use `videos.lance` when you want direct access to the original encoded video files. ## Schemas ### `frames.lance` | Column | Type | Notes | | - | - | - | | `observation_state` | `list<float32>` | Robot state vector for that frame | | `action` | `list<float32>` | Action vector for that frame | | `timestamp` | `float` | Canonical frame timestamp (seconds) | | `frame_index` | `int64` | Frame index within episode | | `episode_index` | `int64` | Parent episode id | | `index` | `int64` | Global frame index | | `task_index` | `int64` | Task id | ### `episodes.lance` | Column | Type | Notes | | - | - | - | | `episode_index` | `int64` | Episode id | | `task_index` | `int64` | Task id | | `fps` | `int32` | Frame rate of the episode video segments | | `timestamps` | `list<float32>` | Per-frame timestamps | | `actions` | `list<list<float32>>` | Per-frame action vectors | | `observation_state` | `list<list<float32>>` | Per-frame robot state vectors | | `<camera>_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for each camera, read lazily via `fetch_blob_files` | | `<camera>_from_timestamp` | `float64` | Segment start time | | `<camera>_to_timestamp` | `float64` | Segment end time | ### `videos.lance` | Column | Type | Notes | | - | - | - | | `camera_angle` | `string` | Camera key | | `chunk_index`, `file_index` | `int32` | IDs parsed from the source path | | `relative_path`, `filename` | `string` | Provenance | | `file_size_bytes` | `int64` | Source MP4 size | | `sha256` | `string` | SHA256 of the MP4 bytes | | `video_blob` | `large_binary` (blob-encoded) | Raw source MP4 bytes | ## Pre-built indices None bundled. Build indices on a local copy if a workload calls for them — e.g., a `BTREE` on `frames.episode_index` for fast episode lookup, or a vector index after attaching observation embeddings via Evolve. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. Each Lance table is a separate `datasets` config. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/lerobot-pusht-lance", split="frames", streaming=True) for row in hf_ds.take(3): print(row["episode_index"], row["frame_index"], row["action"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name. The same handles are used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") episodes = db.open_table("episodes") videos = db.open_table("videos") print(len(frames), len(episodes), len(videos)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access to video segments and any kind of indexed search are dramatically faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/lerobot-pusht-lance --repo-type dataset --local-dir ./lerobot-pusht > ``` > > Then point LanceDB at `./lerobot-pusht/data`. ## Search PushT does not ship a vector index out of the box — observation states are low-dimensional and most robotics workflows look up by index rather than by similarity. The bundled identifier columns (`episode_index`, `task_index`, `frame_index`) make exact lookups a single filtered scan. The example below pulls the first few frames of episode 0 from the frames table. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") slice_ = ( frames.search() .where("episode_index = 0 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(10) .to_list() ) for r in slice_: print(r["frame_index"], r["timestamp"], r["action"]) ``` For similarity-style search across states or actions, attach an embedding column via Evolve and build an `IVF_PQ` index on it (see Evolve below). For visual similarity over rendered frames, the pre-extracted-frames pattern in Train below produces a table that can carry a learned image embedding alongside the pixels. ## Curate A typical curation pass for a robotics workflow starts with an episode-level filter — pick episodes with a particular task, length, or initial condition — and then drops down to the frames within those episodes. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(...)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") episodes = db.open_table("episodes") frames = db.open_table("frames") # Pick a handful of episodes for the default task. ep_rows = ( episodes.search() .where("task_index = 0", prefilter=True) .select(["episode_index", "fps", "observation_images_image_from_timestamp", "observation_images_image_to_timestamp"]) .limit(10) .with_row_id(True) .to_list() ) ep_ids = [r["episode_index"] for r in ep_rows] # Pull the frames belonging to those episodes for the next stage. frame_rows = ( frames.search() .where(f"episode_index IN ({', '.join(map(str, ep_ids))})", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(2000) .to_list() ) print(f"{len(ep_rows)} episodes, {len(frame_rows)} frames selected") ``` Neither scan reads any video bytes. The MP4 segments live in the blob-encoded `_video_blob` columns and stay on disk until something explicitly asks for them. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `action_magnitude` and a `large_action` flag to the frames table, either of which can then be used directly in `where` clauses. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./lerobot-pusht/data") # local copy required for writes frames = db.open_table("frames") frames.add_columns({ "action_magnitude": "SQRT(action[1] * action[1] + action[2] * action[2])", "large_action": "SQRT(action[1] * action[1] + action[2] * action[2]) > 5.0", }) ``` The original columns and the inline video blobs are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reward labels, classifier predictions, learned observation embeddings), add the new fields and update matching rows by the appropriate key — `index` for frames or `episode_index` for episodes: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa rewards = pa.table({ "index": pa.array([0, 1, 2]), "reward_to_go": pa.array([1.4, 1.3, 1.2]), }) frames.add_columns([f for f in rewards.schema if f.name != "index"]) frames.merge_insert("index").when_matched_update_all().execute(rewards) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a visual encoder over the decoded video frames), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for vision-conditioned policy training is to pre-extract decoded frame pixels once into a derived LanceDB table — one row per frame, with the per-frame `action` and `observation_state` already joined in — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each episode's MP4 segment is randomly addressable in `episodes.lance` (the `from_timestamp` / `to_timestamp` columns give the segment bounds), so the pass can subset bytes on demand and write decoded frames into a fresh table without an external file store. Other workflows project the `_video_blob` columns from `episodes.lance` directly and decode at the batch boundary, or skip pixels entirely and train a state-only policy on `frames.lance` — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. For a state-only policy, the frames table is already in the right shape — no pre-extraction needed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") train_ds = Permutation.identity(frames).select_columns(["observation_state", "action"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) ``` For a vision-conditioned policy, train against a pre-extracted frames-with-pixels table that joins each frame's decoded image to its `action` and `observation_state`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./lerobot-pusht-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "observation_state", "action"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) ``` The inline `_video_blob` storage and `fetch_blob_files` still earn their place outside of the training loop — visualizing an episode in a notebook, sampling for human review, one-off evaluation against a held-out task, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance table, whether it adds a column, merges labels, or builds an index, commits a new version. Each of `frames`, `episodes`, and `videos` is versioned independently, so a column added to `frames` does not bump the version of `episodes`. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") print("frames version:", frames.version) print("history:", frames.list_versions()) print("tags:", frames.tags.list()) ``` Once you have a local copy, tag the table for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./lerobot-pusht/data") local_frames = local_db.open_table("frames") local_frames.tags.create("pusht-v1", local_frames.version) ``` Reopen by tag or by version number against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames_v1 = db.open_table("frames", version="pusht-v1") frames_v5 = db.open_table("frames", version=5) ``` Pinning supports two workflows. A policy locked to `pusht-v1` keeps reproducing the same behavior while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same frames, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation, index builds) need a writable backing store, and a training pipeline benefits from a local copy with fast random access into the video blobs. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") remote_frames = remote_db.open_table("frames") batches = ( remote_frames.search() .where("task_index = 0 AND episode_index < 50") .select(["episode_index", "frame_index", "index", "timestamp", "action", "observation_state"]) .to_batches() ) local_db = lancedb.connect("./pusht-task0-subset") local_db.create_table("frames", batches) ``` The resulting `./pusht-task0-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/lerobot-pusht-lance/data` for `./pusht-task0-subset`. The same pattern applies to `episodes` and `videos` — narrow each table to the rows your workload needs, and the resulting database stays small enough to index and iterate cheaply. ## Source & license Converted from [`lerobot/pusht`](https://huggingface.co/datasets/lerobot/pusht) (LeRobot v3.0 dataset format). PushT is released under the Apache 2.0 license by the LeRobot project and the Diffusion Policy authors. ## Citation ``` @misc{cadene2024lerobot, title={LeRobot: State-of-the-art Machine Learning for Real-World Robotics in PyTorch}, author={R{\'e}mi Cadene and Simon Alibert and Alexander Soare and Quentin Gallou{\'e}dec and Adil Zouitine and Steven Palma and Pepijn Kooijmans and Michel Aractingi and Mustafa Shukor and Martino Russi and Francesco Capuano and Caroline Pascal and Jade Choghari and Jess Moss and Thomas Wolf}, year={2024}, url={https://github.com/huggingface/lerobot} } @inproceedings{chi2023diffusion, title={Diffusion Policy: Visuomotor Policy Learning via Action Diffusion}, author={Chi, Cheng and Feng, Siyuan and Du, Yilun and Xu, Zhenjia and Cousineau, Eric and Burchfiel, Benjamin and Song, Shuran}, booktitle={Robotics: Science and Systems}, year={2023} } ``` # LeRobot X-VLA Soft-Fold Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/lerobot-xvla-soft-fold A Lance-formatted version of lerobot/xvla-soft-fold — a multi-camera robotics dataset from the X-VLA project — packaged as three Lance tables for efficient frame-level training, episode-level trajectory loading, and direct access to the original encoded videos. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/lerobot-xvla-soft-fold) > > Source dataset card and downloadable files for `lance-format/lerobot-xvla-soft-fold`. Available directly from the Hub at `hf://datasets/lance-format/lerobot-xvla-soft-fold/data`. * **1,542 episodes** * **2,852,512 frames** at **20 FPS** * **3 camera streams per episode** — `cam_high`, `cam_left_wrist`, `cam_right_wrist` * **Robot state and action vectors** aligned to frame timestamps ## Key features * **Three-table layout** — `frames`, `episodes`, `videos` — so frame-level training, episode-level trajectory work, and raw video access live side-by-side without scattered parquet shards or sidecar MP4 directories. * **Per-camera inline MP4 segments** in `episodes.lance`, with `from_timestamp` / `to_timestamp` bounds per camera and per episode, surfaced as lazy `BlobFile` handles via `fetch_blob_files` so metadata scans never read the bytes. * **Frame-level observations and actions** in `frames.lance` with stable `episode_index`, `frame_index`, and `index` columns for joining or temporal iteration. * **Source MP4 provenance** in `videos.lance` (`relative_path`, `filename`, `file_size_bytes`, `sha256`) alongside the raw bytes, for integrity checks or custom decode pipelines. ## Tables | Table | Rows | Purpose | | - | - | - | | `frames.lance` | 2,852,512 | Per-frame observations, actions, episode/task indices | | `episodes.lance` | 1,542 | Full per-episode trajectories plus per-camera MP4 segment blobs and timestamp bounds | | `videos.lance` | 104 | Raw source MP4 files (one row per source MP4) with file-level provenance | Use `frames.lance` for low-level training (loss-per-timestep, state-conditioned policies). Use `episodes.lance` when you need the full trajectory and the matching per-camera video segments together. Use `videos.lance` when you want direct access to the original encoded video files. ## Schemas ### `frames.lance` | Column | Type | Notes | | - | - | - | | `observation_state` | `list<float32>` | Robot state vector for that frame | | `action` | `list<float32>` | Action vector for that frame | | `time_stamp` | `float` | Original source timestamp field | | `timestamp` | `float` | Canonical frame timestamp (seconds) | | `frame_index` | `int64` | Frame index within episode | | `episode_index` | `int64` | Parent episode id | | `index` | `int64` | Global frame index | | `task_index` | `int64` | Task id | ### `episodes.lance` | Column | Type | Notes | | - | - | - | | `episode_index` | `int64` | Episode id | | `task_index` | `int64` | Task id | | `fps` | `int32` | Frame rate of the episode video segments | | `timestamps` | `list<float32>` | Per-frame timestamps | | `actions` | `list<list<float32>>` | Per-frame action vectors | | `observation_state` | `list<list<float32>>` | Per-frame robot state vectors | | `observation_images_cam_high_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_high` | | `observation_images_cam_high_from_timestamp` | `float64` | `cam_high` segment start time | | `observation_images_cam_high_to_timestamp` | `float64` | `cam_high` segment end time | | `observation_images_cam_left_wrist_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_left_wrist` | | `observation_images_cam_left_wrist_from_timestamp` | `float64` | `cam_left_wrist` segment start time | | `observation_images_cam_left_wrist_to_timestamp` | `float64` | `cam_left_wrist` segment end time | | `observation_images_cam_right_wrist_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_right_wrist` | | `observation_images_cam_right_wrist_from_timestamp` | `float64` | `cam_right_wrist` segment start time | | `observation_images_cam_right_wrist_to_timestamp` | `float64` | `cam_right_wrist` segment end time | ### `videos.lance` | Column | Type | Notes | | - | - | - | | `camera_angle` | `string` | Camera key (e.g. `cam_high`) | | `chunk_index`, `file_index` | `int32` | IDs parsed from the source path | | `relative_path`, `filename` | `string` | Provenance | | `file_size_bytes` | `int64` | Source MP4 size | | `sha256` | `string` | SHA256 of the MP4 bytes | | `video_blob` | `large_binary` (blob-encoded) | Raw source MP4 bytes | ## Pre-built indices None bundled. Build indices on a local copy if a workload calls for them — e.g., a `BTREE` on `frames.episode_index` for fast per-episode lookup, or a vector index after attaching observation embeddings via Evolve. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. Each Lance table is a separate `datasets` config. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/lerobot-xvla-soft-fold", split="frames", streaming=True) for row in hf_ds.take(3): print(row["episode_index"], row["frame_index"], row["action"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name. The same handles are used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") episodes = db.open_table("episodes") videos = db.open_table("videos") print(len(frames), len(episodes), len(videos)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access to video segments and any kind of indexed search are dramatically faster against a local copy. The full dataset is **>50 GB**, so ensure you have sufficient disk space: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/lerobot-xvla-soft-fold --repo-type dataset --local-dir ./lerobot-xvla-soft-fold > ``` > > Then point LanceDB at `./lerobot-xvla-soft-fold/data`. For most workflows, the Materialize-a-subset section at the end of this card is a better starting point than downloading the full corpus. ## Search This dataset does not ship a vector index out of the box — observation states are low-dimensional and most robotics workflows look up by index rather than by similarity. The bundled identifier columns (`episode_index`, `task_index`, `frame_index`) make exact lookups a single filtered scan. The example below pulls the first few frames of episode 30 from the frames table. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") slice_ = ( frames.search() .where("episode_index = 30 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(10) .to_list() ) for r in slice_: print(r["frame_index"], r["timestamp"], r["action"]) ``` For similarity-style search across states or actions, attach an embedding column via Evolve and build an `IVF_PQ` index on it. For visual similarity over rendered frames, the pre-extracted-frames pattern in Train below produces a table that can carry a learned image embedding alongside the pixels. ## Curate A typical curation pass for a robotics workflow starts with an episode-level filter — pick episodes with a particular task, length, or initial condition — and then either iterates frames or pulls the matching video segments. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(...)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") episodes = db.open_table("episodes") ep_rows = ( episodes.search() .where("task_index = 0 AND fps = 20", prefilter=True) .select([ "episode_index", "observation_images_cam_high_from_timestamp", "observation_images_cam_high_to_timestamp", ]) .limit(20) .with_row_id(True) .to_list() ) print(f"{len(ep_rows)} episodes selected") for r in ep_rows[:3]: print( f" ep {r['episode_index']} " f"{r['observation_images_cam_high_from_timestamp']:.2f}s → " f"{r['observation_images_cam_high_to_timestamp']:.2f}s" ) ``` Neither this scan nor any of the per-camera segment columns are read. The MP4 segments live in the blob-encoded `_video_blob` columns and stay on disk until something explicitly asks for them — which makes "find me the right episodes" a metadata-only operation against a multi-million-frame corpus. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `episode_duration` column to the episodes table from the existing `cam_high` timestamp bounds. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./lerobot-xvla-soft-fold/data") # local copy required for writes episodes = db.open_table("episodes") episodes.add_columns({ "episode_duration_s": ( "observation_images_cam_high_to_timestamp - " "observation_images_cam_high_from_timestamp" ), "is_long_episode": ( "(observation_images_cam_high_to_timestamp - " " observation_images_cam_high_from_timestamp) > 120.0" ), }) ``` The original columns and the inline video blobs are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reward labels, classifier predictions, learned observation embeddings), add the new fields and update matching rows by the appropriate key — `index` for frames or `episode_index` for episodes: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa ep_labels = pa.table({ "episode_index": pa.array([0, 1, 2]), "outcome": pa.array(["success", "partial", "success"]), }) episodes.add_columns([f for f in ep_labels.schema if f.name != "episode_index"]) episodes.merge_insert("episode_index").when_matched_update_all().execute(ep_labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a visual encoder over the decoded video frames), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for vision-language-action training is to pre-extract decoded frame pixels once into a derived LanceDB table — one row per frame, with the per-frame `action` and `observation_state` already joined in, and one column per camera holding the decoded image — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each episode's per-camera MP4 segment is randomly addressable in `episodes.lance` (the `*_from_timestamp` / `*_to_timestamp` columns give the segment bounds), so the pass can subset bytes on demand and write decoded frames into a fresh table without an external file store. Other workflows project the `*_video_blob` columns from `episodes.lance` directly and decode at the batch boundary, or skip pixels entirely and train a state-only policy on `frames.lance` — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. For a state-only policy, the frames table is already in the right shape — no pre-extraction needed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") train_ds = Permutation.identity(frames).select_columns(["observation_state", "action"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` For a vision-language-action policy, train against a pre-extracted frames-with-pixels table that joins each frame's three decoded camera images to its `action` and `observation_state`. Picking the cameras the model actually conditions on is then a column projection — `cam_high` alone, all three, or any subset: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./lerobot-xvla-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["cam_high", "cam_left_wrist", "cam_right_wrist", "observation_state", "action"] ) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) ``` The inline `_video_blob` storage and `fetch_blob_files` still earn their place outside of the training loop — visualizing an episode in a notebook, sampling for human review, one-off evaluation, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance table, whether it adds a column, merges labels, or builds an index, commits a new version. Each of `frames`, `episodes`, and `videos` is versioned independently, so a column added to `frames` does not bump the version of `episodes`. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") print("frames version:", frames.version) print("history:", frames.list_versions()) print("tags:", frames.tags.list()) ``` Once you have a local copy, tag the table for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./lerobot-xvla-soft-fold/data") local_frames = local_db.open_table("frames") local_frames.tags.create("xvla-v1", local_frames.version) ``` Reopen by tag or by version number against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames_v1 = db.open_table("frames", version="xvla-v1") frames_v5 = db.open_table("frames", version=5) ``` Pinning supports two workflows. A policy locked to `xvla-v1` keeps reproducing the same behavior while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same frames and segments, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset At >50 GB across three tables and millions of frames, few workflows want the full corpus on local disk. The practical entry point is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the per-camera `_video_blob` columns on `episodes.lance`, which stream through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") remote_episodes = remote_db.open_table("episodes") batches = ( remote_episodes.search() .where("task_index = 0 AND episode_index < 50") .select([ "episode_index", "task_index", "fps", "timestamps", "actions", "observation_state", "observation_images_cam_high_video_blob", "observation_images_cam_high_from_timestamp", "observation_images_cam_high_to_timestamp", ]) .to_batches() ) local_db = lancedb.connect("./xvla-task0-subset") local_db.create_table("episodes", batches) ``` The resulting `./xvla-task0-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/lerobot-xvla-soft-fold/data` for `./xvla-task0-subset`. The same pattern applies to `frames` and `videos` — narrow each table to the rows your workload needs, and the resulting database stays small enough to index and iterate cheaply. ## Source & license Converted from [`lerobot/xvla-soft-fold`](https://huggingface.co/datasets/lerobot/xvla-soft-fold) (LeRobot v3.0 dataset format), originally released as part of the [X-VLA](https://thu-air-dream.github.io/X-VLA/) project. Apache 2.0. ## Citation ``` @article{zheng2025xvla, title={X-VLA: Soft-Prompted Transformer as Scalable Cross-Embodiment Vision-Language-Action Model}, author={Zheng and others}, journal={arXiv preprint arXiv:2510.10274}, year={2025} } @misc{cadene2024lerobot, title={LeRobot: State-of-the-art Machine Learning for Real-World Robotics in PyTorch}, author={R{\'e}mi Cadene and Simon Alibert and Alexander Soare and Quentin Gallou{\'e}dec and Adil Zouitine and Steven Palma and Pepijn Kooijmans and Michel Aractingi and Mustafa Shukor and Martino Russi and Francesco Capuano and Caroline Pascal and Jade Choghari and Jess Moss and Thomas Wolf}, year={2024}, url={https://github.com/huggingface/lerobot} } ``` # LibriSpeech clean Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/librispeech-clean A Lance-formatted version of the LibriSpeech ASR clean configuration, sourced from openslr/librispeech_asr. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/librispeech-clean-lance) > > Source dataset card and downloadable files for `lance-format/librispeech-clean-lance`. Each row is one utterance with inline FLAC audio bytes, the reference transcript, a sentence-transformers embedding of that transcript, and speaker/chapter metadata — all available directly from the Hub at `hf://datasets/lance-format/librispeech-clean-lance/data`. ## Key features * **Inline FLAC bytes** in the `audio` column at 16 kHz mono, with no re-encoding from the upstream parquet. * **Sentence-transformers embedding of the transcript** in `text_emb` (`all-MiniLM-L6-v2`, 384-dim, cosine-normalized) with a bundled `IVF_PQ` index for semantic transcript search. * **Pre-built `INVERTED` FTS index on `text`** and `BTREE` indices on `id`, `speaker_id`, and `chapter_id` for keyword search and stable lookup by identifier. * **Per-utterance metadata** — `speaker_id`, `chapter_id`, `num_chars`, `sampling_rate` — that downstream filters can stack on. ## Splits | Split | Source config | Rows | Description | | - | - | - | - | | `dev_clean.lance` | `dev.clean` | 2,703 | Standard ASR validation set | | `test_clean.lance` | `test.clean` | 2,620 | Standard ASR test set | | `train_clean_100.lance` | `train.clean.100` | 28,539 | 100-hour clean training subset | > The 360-hour and 500-hour LibriSpeech subsets (`train.360`, `train.other.500`) are not bundled here. To extend, point `librispeech/dataprep.py` at additional splits. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | Utterance id (e.g. `1272-128104-0000`) | | `audio` | `large_binary` | Inline FLAC bytes (16 kHz mono) | | `sampling_rate` | `int32` | Always 16,000 | | `text` | `string` | Reference transcript | | `speaker_id` | `int64` | LibriVox speaker id | | `chapter_id` | `int64` | LibriVox chapter id | | `num_chars` | `int32` | Length of `text` in characters | | `text_emb` | `fixed_size_list<float32, 384>` | sentence-transformers `all-MiniLM-L6-v2` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `text_emb` — semantic transcript search (cosine) * `INVERTED` (FTS) on `text` — keyword and hybrid search * `BTREE` on `id`, `speaker_id`, `chapter_id` — fast lookup by identifier ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/librispeech-clean-lance", split="test_clean", streaming=True) for row in hf_ds.take(3): print(row["id"], row["text"][:80]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`dev_clean`, `test_clean`, `train_clean_100`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and audio decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/librispeech-clean-lance --repo-type dataset --local-dir ./librispeech-clean > ``` > > Then point LanceDB at `./librispeech-clean/data`. ## Search The bundled `IVF_PQ` index on `text_emb` makes semantic transcript retrieval a single call. In production you would encode a query string through the same sentence-transformers model used at ingest (`all-MiniLM-L6-v2`, cosine-normalized), then pass the resulting 384-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") seed = ( tbl.search() .select(["text_emb", "text"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="text_emb") .metric("cosine") .select(["id", "speaker_id", "text"]) .limit(10) .to_list() ) print("query transcript:", seed["text"][:80]) for r in hits: print(f" {r['id']} spk={r['speaker_id']} {r['text'][:80]}") ``` The `audio` blob is never touched. A top-10 semantic search moves a few kilobytes of transcript text rather than the FLAC bytes for every candidate. Because the dataset also ships an `INVERTED` index on `text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query — useful when a name or domain term must literally appear in the transcript but you still want the semantic side to rank the rest. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="text_emb") .vector(seed["text_emb"]) .text("astronomy") .select(["id", "speaker_id", "text"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['id']} spk={r['speaker_id']} {r['text'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Building a focused subset of utterances usually means combining content with structure — pick utterances by a single speaker, or above a minimum transcript length, or matching a topic. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") candidates = ( tbl.search() .where("speaker_id = 1272 AND num_chars >= 60", prefilter=True) .select(["id", "chapter_id", "num_chars", "text"]) .limit(500) .with_row_id(True) .to_list() ) print(f"{len(candidates)} utterances; first: {candidates[0]['text'][:80]}") ``` The scan never reads the `audio` column. Lance stores binary columns independently, so a metadata-only curation pass moves only the transcript text and scalar fields across the wire — even though the underlying table includes hours of inline FLAC audio. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `is_long_utterance` flag and a coarse `length_bucket`, either of which can then be used directly in `where` clauses without re-evaluating the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./librispeech-clean/data") # local copy required for writes tbl = db.open_table("train_clean_100") tbl.add_columns({ "is_long_utterance": "num_chars >= 200", "length_bucket": ( "CASE WHEN num_chars < 80 THEN 'short' " "WHEN num_chars < 200 THEN 'medium' ELSE 'long' END" ), }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (alternate transcripts, speaker embeddings, model predictions), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array(["1272-128104-0000", "1272-128104-0001"]), "wer": pa.array([0.04, 0.12]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a speaker embedding model over the FLAC bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for audio training is to pre-extract decoded features once into a derived LanceDB table — one row per training-ready window of log-mel frames or raw PCM samples — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each utterance's FLAC bytes are randomly addressable, so the pass can subset audio on demand and write decoded windows into a fresh table without an external file store. Other workflows project `audio` directly through `select_columns(...)` and decode at the batch boundary, or skip audio entirely and train on the cached transcript embeddings — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. Against a pre-extracted features table: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./librispeech-features") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["log_mel", "text", "speaker_id"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) ``` Against the cached transcript embeddings on the source table (no audio decode): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader src_db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") src_tbl = src_db.open_table("train_clean_100") train_ds = Permutation.identity(src_tbl).select_columns(["text_emb", "speaker_id"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` The inline `audio` storage and `fetch_blob_files` still earn their place around the training process — listening back to an utterance in a notebook, sampling for human review, one-off evaluation against a held-out set, and the pre-extraction pass itself. Each of those reads a small, explicit set of blobs once. What the Train section above keeps off the per-batch hot path is exactly that raw-audio decode: paying it every step is what the pre-extracted features are designed to avoid. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./librispeech-clean/data") local_tbl = local_db.open_table("train_clean_100") local_tbl.tags.create("minilm-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train_clean_100", version="minilm-v1") tbl_v5 = db.open_table("train_clean_100", version=5) ``` Pinning supports two workflows. A retrieval system locked to `minilm-v1` keeps returning stable results while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same utterances, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training pipeline benefits from a local copy with fast random access to the FLAC bytes. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the `audio` column, which streams through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") remote_tbl = remote_db.open_table("train_clean_100") batches = ( remote_tbl.search() .where("speaker_id = 1272") .select(["id", "audio", "sampling_rate", "text", "speaker_id", "chapter_id", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./librispeech-speaker-1272") local_db.create_table("train", batches) ``` The resulting `./librispeech-speaker-1272` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/librispeech-clean-lance/data` for `./librispeech-speaker-1272`. ## Source & license Converted from [`openslr/librispeech_asr`](https://huggingface.co/datasets/openslr/librispeech_asr). LibriSpeech is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) and is built from the public-domain LibriVox audiobook corpus. ## Citation ``` @inproceedings{panayotov2015librispeech, title={LibriSpeech: An ASR corpus based on public domain audiobooks}, author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev}, booktitle={IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP)}, year={2015} } ``` # MNIST Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/mnist A Lance-formatted version of the classic MNIST handwritten-digit dataset covering 70,000 28×28 grayscale digits across ten balanced classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/mnist-lance) > > Source dataset card and downloadable files for `lance-format/mnist-lance`. Each row carries inline PNG bytes, the digit label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/mnist-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so digit filters and digit-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 60,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) | | `label` | `int32` | Digit class id (0–9) | | `label_name` | `string` | Human-readable class (`"0"`..`"9"`) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the digit id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/mnist-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/mnist-lance --repo-type dataset --local-dir ./mnist-lance > ``` > > Then point LanceDB at `./mnist-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query digit through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query digit:", seed["label"]) for r in hits: print(f" id={r['id']:>5} label={r['label']}") ``` Because the embeddings are cosine-normalized and MNIST digits cluster tightly in CLIP space, near-neighbors of a seed image are dominated by the seed's own digit class — a useful sanity check before swapping in a real query encoder. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for a digit-classification workflow narrows the table to a single digit (or a small set of confusable digits like 4/9 or 3/8) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label IN (4, 9)", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} 4/9 candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_target_class` flag for binary one-vs-rest experiments and an `is_curvy_digit` flag that groups digits with curved strokes, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./mnist-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_target_class": "label = 7", "is_curvy_digit": "label IN (0, 3, 6, 8, 9)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([5, 0, 4], type=pa.int32()), "pred_conf": pa.array([0.97, 0.88, 0.82]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, normalize to [0, 1], forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./mnist-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same digits and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label IN (4, 9)") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./mnist-4-vs-9") local_db.create_table("train", batches) ``` The resulting `./mnist-4-vs-9` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/mnist-lance/data` for `./mnist-4-vs-9`. ## Source & license Converted from [`ylecun/mnist`](https://huggingface.co/datasets/ylecun/mnist). MNIST is released under the MIT license. The original dataset is by Yann LeCun, Corinna Cortes, and Christopher J.C. Burges. ## Citation ``` @article{lecun1998mnist, title={The MNIST database of handwritten digits}, author={LeCun, Yann and Cortes, Corinna and Burges, CJ}, url={http://yann.lecun.com/exdb/mnist/}, year={1998} } ``` # MS MARCO v2.1 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/ms-marco-v2 A Lance-formatted version of MS MARCO v2.1 — Microsoft's machine-reading-comprehension benchmark built from anonymized Bing query logs. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/ms-marco-v2.1-lance) > > Source dataset card and downloadable files for `lance-format/ms-marco-v2.1-lance`. Each row is one user query, the up-to-10 candidate passages Bing retrieved for it with relevance flags, and the human-written reference answers, with MiniLM query embeddings stored inline and pre-built ANN/FTS indices, available directly from the Hub at `hf://datasets/lance-format/ms-marco-v2.1-lance/data`. ## Key features * **Self-contained passage-ranking rows** — each query carries up to 10 candidate passages in parallel `passage_text` / `passage_url` / `passage_is_selected` columns, alongside the human-written `answers` and `well_formed_answers`. * **First relevant passage promoted to its own field** in `selected_passage`, so RAG / answer-evaluation workflows can read the gold context without indexing into the parallel passage lists. * **Pre-computed 384-dim query embeddings** (`query_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic query lookup. * **One columnar dataset** — scan query metadata cheaply, defer the heavy passage text reads to the rows that matter. ## Splits | Split | Rows | | - | - | | `train.lance` | 808,731 | | `validation.lance` | 101,093 | ## Schema | Column | Type | Notes | | - | - | - | | `query_id` | `int64` | MS MARCO query id | | `query` | `string` | The user's natural-language query | | `query_type` | `string` | One of `DESCRIPTION`, `NUMERIC`, `ENTITY`, `LOCATION`, `PERSON` | | `answers` | `list<string>` | Human-written reference answers | | `well_formed_answers` | `list<string>` | Reference answers re-written as full sentences | | `passage_text` | `list<string>` | Up to 10 candidate passages | | `passage_url` | `list<string>` | Source URLs for each candidate | | `passage_is_selected` | `list<int8>` | `1` if Bing labelled the passage relevant | | `selected_passage` | `string?` | First relevant passage (null if none) | | `query_emb` | `fixed_size_list<float32, 384>` | MiniLM query embedding | ## Pre-built indices * `IVF_PQ` on `query_emb` — semantic query lookup (cosine) * `INVERTED` (FTS) on `query` and `selected_passage` — keyword and hybrid search * `BTREE` on `query_id` — stable lookup by identifier * `BITMAP` on `query_type` — cheap predicate evaluation for query class ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/ms-marco-v2.1-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["query"], "->", row["answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`train`, `validation`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/ms-marco-v2.1-lance --repo-type dataset --local-dir ./ms-marco-v2.1-lance > ``` > > Then point LanceDB at `./ms-marco-v2.1-lance/data`. ## Search The bundled `IVF_PQ` index on `query_emb` makes nearest-neighbour query lookup a single call. In production you would encode an incoming user query through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["query_emb", "query"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["query_emb"], vector_column_name="query_emb") .metric("cosine") .where("query_type = 'NUMERIC'", prefilter=True) .select(["query_id", "query", "selected_passage", "answers"]) .limit(10) .to_list() ) for r in hits: print(r["query"], "->", (r["selected_passage"] or "")[:120]) ``` The result set carries only the projected columns; the 384-d `query_emb` is never read on the result side, and the full `passage_text` list is left untouched, keeping the working set small even when the underlying scan touches every row of the validation split. Because the dataset also ships an `INVERTED` index on both `query` and `selected_passage`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the gold passage. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase must literally appear in the relevant passage but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["query_emb"]) .text("determinant matrix") .select(["query", "selected_passage", "answers"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["query"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate A typical curation pass over MS MARCO starts by combining metadata filters with structural predicates over the parallel passage lists before any heavy text gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(1000)` keeps the output small enough to inspect. The example below assembles a set of numeric questions for which Bing labelled at least one passage relevant and the annotators produced a well-formed reference answer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "query_type = 'NUMERIC' " "AND selected_passage IS NOT NULL " "AND array_length(well_formed_answers) > 0 " "AND length(query) >= 30", prefilter=True, ) .select(["query_id", "query", "answers", "well_formed_answers"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['query']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `query_id`s, or hand to the Evolve and Train sections below. Neither `passage_text` nor `query_emb` is read by this scan, so a 1000-row curation pass against the Hub moves only kilobytes of metadata. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `query_length` column and a `num_selected` count over the parallel `passage_is_selected` list, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./ms-marco-v2.1-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "query_length": "length(query)", "num_selected": "array_length(passage_is_selected)", "has_well_formed": "array_length(well_formed_answers) > 0", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (cross-encoder reranker scores, generated-answer judgments, alternate embeddings from a stronger model), add the new fields and update matching rows by `query_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa reranker_scores = pa.table({ "query_id": pa.array([1185869, 9083, 524332], type=pa.int64()), "reranker_top1_score": pa.array([0.91, 0.47, 0.83]), }) tbl.add_columns([f for f in reranker_scores.schema if f.name != "query_id"]) tbl.merge_insert("query_id").when_matched_update_all().execute(reranker_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different encoder over the query text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a reader-style QA model the natural projection is the query plus the gold passage and the answer; for a query-encoder retraining loop the precomputed embedding is enough on its own. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["query", "selected_passage", "answers"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["query_emb", "passage_text", "passage_is_selected"]` to `select_columns(...)` on the next run reads only those columns, which is the right shape for training a passage reranker on cached query embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./ms-marco-v2.1-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("numeric-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="numeric-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `numeric-v1` keeps returning stable passages while the dataset evolves in parallel — newly added reranker scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same queries and passages, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "query_type = 'NUMERIC' " "AND selected_passage IS NOT NULL " "AND array_length(well_formed_answers) > 0" ) .select(["query_id", "query", "query_type", "answers", "well_formed_answers", "selected_passage", "query_emb"]) .to_batches() ) local_db = lancedb.connect("./ms-marco-numeric") local_db.create_table("train", batches) ``` The resulting `./ms-marco-numeric` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/ms-marco-v2.1-lance/data` for `./ms-marco-numeric`. ## Source & license Converted from [`microsoft/ms_marco`](https://huggingface.co/datasets/microsoft/ms_marco) (`v2.1`). MS MARCO is released under the MIT license. ## Citation ``` @article{nguyen2016ms, title={MS MARCO: A Human Generated MAchine Reading COmprehension Dataset}, author={Nguyen, Tri and Rosenberg, Mir and Song, Xia and Gao, Jianfeng and Tiwary, Saurabh and Majumder, Rangan and Deng, Li}, journal={arXiv preprint arXiv:1611.09268}, year={2016} } ``` # Natural Questions Validation Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/natural-questions-val A Lance-formatted version of the Natural Questions validation split — 7,830 real Google search queries paired with the full Wikipedia article a human used to answer them, plus 1–5 annotator labels per question. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/natural-questions-val-lance) > > Source dataset card and downloadable files for `lance-format/natural-questions-val-lance`. MiniLM question embeddings are stored inline and the dataset ships with pre-built ANN/FTS indices, all available directly from the Hub at `hf://datasets/lance-format/natural-questions-val-lance/data`. Sourced from [`google-research-datasets/natural_questions`](https://huggingface.co/datasets/google-research-datasets/natural_questions). > The NQ **train** split is 143 GB (307,373 rows); it is intentionally not bundled here. Add it via `natural_questions/dataprep.py --splits train` once disk and bandwidth allow. ## Key features * **Real Google search queries** with the full Wikipedia article that answers each one — `document_html` carries the inline UTF-8 HTML, so no sidecar files or external lookups are needed at query time. * **Annotator answer summaries** — `short_answers` aggregates and dedupes spans across all annotators, `yes_no_answer` carries the majority vote, and the `has_short_answer` / `has_long_answer` flags make annotation-coverage filters a single predicate. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question lookup. * **One columnar dataset** — scan question metadata cheaply, then read the heavy `document_html` only for the rows you actually want. ## Splits | Split | Rows | | - | - | | `validation.lance` | 7,830 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | NQ example id | | `question` | `string` | Original Google search query | | `document_title` | `string` | Wikipedia article title | | `document_url` | `string` | Wikipedia article URL | | `document_html` | `large_binary` | Full HTML of the article (inline; UTF-8 bytes) | | `short_answers` | `list<string>` | Deduped short-answer spans across all annotators | | `num_short_answers` | `int32` | Total annotator spans (incl. duplicates) | | `has_short_answer` | `bool` | At least one annotator provided a short-answer span | | `has_long_answer` | `bool` | At least one annotator selected a long-answer candidate | | `yes_no_answer` | `string` | `YES` / `NO` / `NONE` — majority vote across annotators | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM question embedding | ## Pre-built indices * `IVF_PQ` on `question_emb` — semantic question lookup (cosine) * `INVERTED` (FTS) on `question` — keyword and hybrid search * `BTREE` on `id`, `document_title` — stable lookup by identifier * `BITMAP` on `yes_no_answer`, `has_short_answer`, `has_long_answer` — cheap predicate evaluation for annotation coverage ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/natural-questions-val-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["short_answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and HTML decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/natural-questions-val-lance --repo-type dataset --local-dir ./natural-questions-val-lance > ``` > > Then point LanceDB at `./natural-questions-val-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes nearest-neighbour question lookup a single call. In production you would encode an incoming user query through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("has_short_answer = TRUE", prefilter=True) .select(["question", "short_answers", "document_title"]) .limit(10) .to_list() ) for r in hits: print(r["question"], "->", r["short_answers"]) ``` The result set carries only the projected columns; the 384-d `question_emb` is never read on the result side, and the heavy `document_html` is left untouched, keeping the working set small even though each row carries a full Wikipedia article inline. Because the dataset also ships an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the question text. LanceDB merges the two result lists and reranks them in a single call, which is useful when a named entity must literally appear in the query but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("declaration of independence") .select(["question", "short_answers", "document_title"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["question"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate A typical curation pass over NQ starts with annotation-coverage filters before any HTML gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(500)` keeps the output small enough to inspect. The example below assembles a set of factoid questions with at least one short-answer span and a non-yes/no resolution. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "has_short_answer = TRUE " "AND yes_no_answer = 'NONE' " "AND array_length(short_answers) >= 1 " "AND length(question) >= 30", prefilter=True, ) .select(["id", "question", "short_answers", "document_title", "document_url"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of NQ example ids, or hand to the Evolve and Train sections below. The large `document_html` column is not read by this scan, so a 500-row curation pass against the Hub moves only kilobytes of metadata even though each row holds an entire Wikipedia article. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length` column, a `first_short_answer_length` derived from the deduped span list, and an `is_factoid` flag that combines the annotation flags, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./natural-questions-val-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "question_length": "length(question)", "first_short_answer_length": "length(short_answers[1])", "is_factoid": "has_short_answer = TRUE AND yes_no_answer = 'NONE'", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline retriever scores, generated-answer judgments, alternate embeddings from a stronger model), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa retriever_scores = pa.table({ "id": pa.array(["797803103333068850", "5225754983651766092"]), "bm25_top1_score": pa.array([14.2, 8.7]), }) tbl.add_columns([f for f in retriever_scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(retriever_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., extracting the long-answer paragraph from `document_html`), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For an open-domain QA reader the natural projection is the question plus the full document HTML and the answer spans; for a question-encoder retraining loop the precomputed embedding is enough on its own, and skipping `document_html` keeps each batch small. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["question", "document_html", "short_answers"]) loader = DataLoader(train_ds, batch_size=4, shuffle=True, num_workers=2) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "short_answers"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the answer spans, which is the right shape for fine-tuning a retrieval head on cached embeddings without paying for the multi-megabyte `document_html` per row. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./natural-questions-val-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("factoid-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="factoid-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A QA system locked to `factoid-v1` keeps returning stable answer spans while the dataset evolves in parallel — newly added retriever scores or labels do not change what the tag resolves to. An evaluation experiment pinned to the same tag can be rerun later against the exact same questions and articles, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where( "has_short_answer = TRUE " "AND yes_no_answer = 'NONE' " "AND array_length(short_answers) >= 1" ) .select(["id", "question", "document_title", "document_url", "short_answers", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./nq-factoid") local_db.create_table("validation", batches) ``` The resulting `./nq-factoid` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/natural-questions-val-lance/data` for `./nq-factoid`. Note that this projection deliberately omits `document_html`; include it in the `.select(...)` list when the downstream task needs the article body. ## Source & license Converted from [`google-research-datasets/natural_questions`](https://huggingface.co/datasets/google-research-datasets/natural_questions). NQ is released under [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) (matching the Wikipedia source). ## Citation ``` @article{kwiatkowski2019natural, title={Natural Questions: A Benchmark for Question Answering Research}, author={Kwiatkowski, Tom and Palomaki, Jennimaria and Redfield, Olivia and Collins, Michael and Parikh, Ankur and Alberti, Chris and Epstein, Danielle and Polosukhin, Illia and Devlin, Jacob and Lee, Kenton and Toutanova, Kristina and Jones, Llion and Kelcey, Matthew and Chang, Ming-Wei and Dai, Andrew M. and Uszkoreit, Jakob and Le, Quoc and Petrov, Slav}, journal={Transactions of the Association for Computational Linguistics}, year={2019} } ``` # OpenVid-1M Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/openvid A Lance-formatted version of the OpenVid-1M corpus — 937,957 high-quality clips with inline MP4 bytes, 1024-dim video embeddings, captions, and rich per-clip quality signals — available directly from the Hub at hf://datasets/lance-format/openvid-lance/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/openvid-lance) > > Source dataset card and downloadable files for `lance-format/openvid-lance`. ![](https://huggingface.co/datasets/nkp37/OpenVid-1M/resolve/main/OpenVid-1M.png) ## Key features * **Inline MP4 bytes** in the `video_blob` column, stored in a side blob file and surfaced as lazy `BlobFile` handles via `tbl.fetch_blob_files` — metadata scans, search, and filtering never read a single byte of video data. * **Pre-computed 1024-dim video embeddings** in `embedding` with a bundled `IVF_PQ` ANN index. * **Pre-built `INVERTED` (FTS) index on `caption`** for keyword and hybrid search. * **Rich quality signals** — `aesthetic_score`, `motion_score`, `temporal_consistency_score`, `camera_motion`, `fps`, `seconds` — that downstream filters can stack on. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `video_blob` | `large_binary` (blob-encoded) | Inline MP4 bytes; stored in a separate blob file and read lazily through `tbl.fetch_blob_files` | | `video_path` | `string` | Original file path / object key | | `caption` | `string` | Text description of the clip | | `embedding` | `fixed_size_list<float32, 1024>` | Video embedding | | `aesthetic_score` | `float64` | Visual quality, roughly 0–6 | | `motion_score` | `float64` | Amount of motion, 0–1 | | `temporal_consistency_score` | `float64` | Frame-to-frame stability, 0–1 | | `camera_motion` | `string` | `pan`, `zoom`, `static`, etc. | | `fps` | `float64` | Frames per second | | `seconds` | `float64` | Clip duration | | `frame` | `int64` | Total frame count | ## Pre-built indices * `IVF_PQ` on `embedding` — video similarity (L2) * `INVERTED` (FTS) on `caption` — keyword and hybrid search ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you just want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/openvid-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and video decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/openvid-lance --repo-type dataset --local-dir ./openvid > ``` > > Then point LanceDB at `./openvid/data`. ## Search The bundled `IVF_PQ` index on `embedding` makes approximate-nearest-neighbor search a single call. In production you would encode a text prompt through a text-to-video model or a reference clip through the same video encoder used at ingest, and pass the resulting 1024-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["embedding", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["embedding"]) .metric("L2") .select(["caption", "aesthetic_score", "camera_motion", "seconds"]) .limit(10) .to_list() ) for r in hits: print(f"{r['aesthetic_score']:.2f} | {r['camera_motion']:>8} | {r['caption'][:60]}") ``` The result set carries only the projected columns. The `video_blob` column is never read, so the network traffic for a top-10 search is dominated by a few kilobytes of caption text, not by megabytes of MP4. The lazy blob fetch comes later — see Curate below. Because OpenVid also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["embedding"]) .text("sunset over the ocean") .select(["caption", "aesthetic_score", "seconds"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['aesthetic_score']:.2f} | {r['seconds']:.1f}s | {r['caption'][:60]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Curation for a video workflow almost always starts as a metadata filter — pick the dynamic, high-aesthetic, well-stabilized clips first, then decide what to do with the video bytes. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "aesthetic_score >= 4.5 " "AND motion_score >= 0.3 " "AND temporal_consistency_score >= 0.9", prefilter=True, ) .select(["caption", "camera_motion", "aesthetic_score", "fps", "seconds"]) .limit(200) .with_row_id(True) .to_list() ) print(f"{len(candidates)} clips selected") ``` The scan above never reads the `video_blob` column. Lance stores blobs in a separate side file referenced by the dataset, so column-projected reads skip them entirely until they are explicitly requested. That is what makes "find me the right clips" a metadata-only operation against a million-row video corpus. Once the candidate set is fixed, open lazy video handles with `tbl.fetch_blob_files` (requires `lancedb >= 0.41.0` for legacy blob-encoded columns). It returns one `BlobFile` per row — a seekable file-like handle that streams from inline blob storage on demand rather than reading the full clip into Python memory up front. For video specifically, this is the operation that matters: a video model trainer or a dataloader inspecting a few seconds of each clip should never have to materialize entire MP4s in memory just to inspect or decode part of them. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} row_ids = [r["_rowid"] for r in candidates[:10]] blob_files = tbl.fetch_blob_files("video_blob", row_ids) ``` Each `BlobFile` implements the file protocol, so it can be passed straight to a decoder like PyAV without first being copied through a `bytes` object. The decoder seeks and reads against the underlying handle, which means a 2-second sample from a 30-second clip moves only the bytes the decoder actually touches — not the whole MP4. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import av with av.open(blob_files[0]) as container: stream = container.streams.video[0] for seconds in (0.0, 1.0, 2.5): target = int(seconds / stream.time_base) container.seek(target, stream=stream) frame = next( (f for f in container.decode(stream) if f.time is not None and f.time >= seconds), None, ) if frame is not None: print(f" seek {seconds:.1f}s -> {frame.width}x{frame.height} @ {frame.time:.2f}s") ``` If you only need the raw bytes (e.g., to persist a hand-picked subset to disk), call `.read()` on each handle. The lazy semantics are the same; `read()` simply materializes the full blob for that one row. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for r_id, blob in zip(row_ids, blob_files): blob.seek(0) with open(f"clip_{r_id}.mp4", "wb") as f: f.write(blob.read()) ``` ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data — including the video blobs, which stay exactly where they are. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `duration_bucket` and a `is_high_quality` flag, either of which can then be used directly in `where` clauses without re-evaluating the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./openvid/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "duration_bucket": ( "CASE WHEN seconds < 5 THEN 'short' " "WHEN seconds < 15 THEN 'medium' ELSE 'long' END" ), "is_high_quality": ( "aesthetic_score >= 4.5 AND temporal_consistency_score >= 0.9" ), }) ``` The original columns and the `video_blob` side file are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, safety classifications, a second embedding from a different encoder), add the new fields and update matching rows by `video_path`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "video_path": pa.array(["s3://openvid/clips/00001.mp4", "s3://openvid/clips/00002.mp4"]), "scene_label": pa.array(["beach", "city"]), }) tbl.add_columns([f for f in labels.schema if f.name != "video_path"]) tbl.merge_insert("video_path").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative video encoder over the inline bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for video training is to pre-extract decoded frames once into a derived LanceDB table, and train against that table with the regular projection-based dataloader. `tbl.fetch_blob_files` is the mechanism that makes the extraction step tractable: each clip's MP4 is randomly addressable, so the pass can subset bytes on demand and write decoded windows into a fresh table without an external file store. Other workflows project `video_blob` directly through `select_columns(...)` and decode at the batch boundary, or skip pixels entirely and train on the cached embeddings — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. Against a pre-extracted frames table: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./openvid-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["frames", "caption", "aesthetic_score"]) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) ``` Against the cached embeddings on the source table (no pre-extraction): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader src_db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") src_tbl = src_db.open_table("train") train_ds = Permutation.identity(src_tbl).select_columns(["embedding", "caption"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` The inline `video_blob` storage and `tbl.fetch_blob_files` still earn their place outside of the training loop — random-access inspection of a clip in a notebook, sampling for human review, one-off evaluation against a held-out set, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk, with the same blob handles still valid. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./openvid/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("quality-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="quality-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `quality-v1` keeps returning stable results while the dataset evolves in parallel — newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same clips, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access into the blob file. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the `video_blob` column, which streams through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("aesthetic_score >= 4.5 AND motion_score >= 0.3") .select(["caption", "embedding", "video_blob", "aesthetic_score", "camera_motion"]) .to_batches() ) local_db = lancedb.connect("./openvid-subset") local_db.create_table("train", batches) ``` The resulting `./openvid-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/openvid-lance/data` for `./openvid-subset`. The same `fetch_blob_files` pattern from Curate also works against the local copy — and runs faster, because the blob side file is now on local disk. ## Citation ``` @article{nan2024openvid, title={OpenVid-1M: A Large-Scale High-Quality Dataset for Text-to-video Generation}, author={Nan, Kepan and Xie, Rui and Zhou, Penghao and Fan, Tiehan and Yang, Zhenheng and Chen, Zhijie and Li, Xiang and Yang, Jian and Tai, Ying}, journal={arXiv preprint arXiv:2407.02371}, year={2024} } ``` ## License Content inherits the original OpenVid-1M dataset license. Review the [upstream dataset card](https://huggingface.co/datasets/nkp37/OpenVid-1M) before downstream use. # Oxford-IIIT Pet Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/oxford-pets A Lance-formatted version of the Oxford-IIIT Pet dataset — 7,390 cat and dog photos across 37 breeds — sourced from pcuenq/oxford-pets. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/oxford-pets-lance) > > Source dataset card and downloadable files for `lance-format/oxford-pets-lance`. Each row carries the inline JPEG bytes, the breed name, a species flag distinguishing cats from dogs, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/oxford-pets-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both breed and species labels** (`label_name`, `is_dog`) so a query can target a specific breed, all dogs, or all cats by stacking simple predicates. * **Bitmap indices on both label columns** make species- and breed-based curation a cheap predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 7,390 | The `pcuenq/oxford-pets` source mirror ships a single split; the canonical Oxford-IIIT trainval/test partition is not pre-applied here. | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (quality 92) | | `label_name` | `string` | One of 37 breeds, underscore-spaced (`british_shorthair`, `golden_retriever`, …) | | `is_dog` | `bool` | `true` for dog breeds, `false` for cat breeds | | `path` | `string?` | Original filename from the source dataset | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BITMAP` on `label_name` — fast lookup by breed * `BITMAP` on `is_dog` — fast species filter ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/oxford-pets-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label_name"], row["is_dog"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/oxford-pets-lance --repo-type dataset --local-dir ./oxford-pets-lance > ``` > > Then point LanceDB at `./oxford-pets-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without a model loaded; on a clean run the first hit is expected to be the seed image itself, which is a useful sanity check on the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name", "is_dog"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name", "is_dog"]) .limit(10) .to_list() ) print(f"seed: {seed['label_name']} (is_dog={seed['is_dog']})") for r in hits: print(f" {r['id']:>5} {r['label_name']:<22} is_dog={r['is_dog']}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a fine-grained pet classifier stacks the species predicate and a breed predicate inside a single filtered scan. With bitmap indices on both `label_name` and `is_dog`, the result comes back in milliseconds, and the bounded `.limit(200)` keeps it small enough to inspect or hand off to a training run. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("is_dog = true AND label_name IN ('golden_retriever', 'beagle', 'pug')") .select(["id", "label_name", "is_dog", "path"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['label_name']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read by this query, so the network traffic is dominated by the small label fields rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below derives a `species` string from the `is_dog` boolean and adds a coarse breed-group flag for terriers, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./oxford-pets-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "species": "CASE WHEN is_dog THEN 'dog' ELSE 'cat' END", "is_terrier": "label_name LIKE '%terrier%'", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, an integer class id), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_ids = pa.table({ "id": pa.array([0, 1, 2]), "label_int": pa.array([0, 0, 17]), }) tbl.add_columns([f for f in class_ids.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_ids) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second embedding model over the JPEG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch breed classifier, project the JPEG bytes and the string breed label; for a linear probe on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label_name"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, map label_name -> int via a class list, forward, cross-entropy... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label_name"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe or a lightweight reranker. Projecting `["image", "is_dog"]` reduces the task to binary species classification on the same data. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./oxford-pets-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("is_dog = true") .select(["id", "image", "label_name", "is_dog", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./oxford-pets-dogs-subset") local_db.create_table("train", batches) ``` The resulting `./oxford-pets-dogs-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/oxford-pets-lance/data` for `./oxford-pets-dogs-subset`. ## Source & license Converted from [`pcuenq/oxford-pets`](https://huggingface.co/datasets/pcuenq/oxford-pets). Released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @inproceedings{parkhi2012cats, title={Cats and Dogs}, author={Parkhi, Omkar M. and Vedaldi, Andrea and Zisserman, Andrew and Jawahar, C. V.}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2012} } ``` # Pascal VOC 2012 Segmentation Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/pascal-voc-2012-segmentation A Lance-formatted version of the Pascal VOC 2012 semantic segmentation split, sourced from nateraw/pascal-voc-2012. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/pascal-voc-2012-segmentation-lance) > > Source dataset card and downloadable files for `lance-format/pascal-voc-2012-segmentation-lance`. Each row pairs an inline JPEG image with the per-pixel PNG segmentation mask and a cosine-normalized OpenCLIP `ViT-B-32` image embedding, so a single columnar table carries both annotation modalities and the features needed to retrieve, curate, and train against them — all available directly from the Hub at `hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data`. ## Key features * **Inline JPEG bytes and inline PNG mask bytes in the same row** — image and per-pixel segmentation travel together with no sidecar folders or mask lookups. * **Pre-computed CLIP image embeddings** (`image_emb`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for visual similarity search. * **Standard VOC class encoding** — mask pixel values are class ids in `0..20` plus `255` for void, identical to the official VOC palette. * **One columnar dataset** — scan image-level metadata cheaply, then fetch image or mask bytes only for the rows you actually want. The 20 Pascal VOC foreground classes are: `aeroplane`, `bicycle`, `bird`, `boat`, `bottle`, `bus`, `car`, `cat`, `chair`, `cow`, `diningtable`, `dog`, `horse`, `motorbike`, `person`, `pottedplant`, `sheep`, `sofa`, `train`, `tvmonitor`. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 1,464 | Official VOC 2012 segmentation train | | `validation.lance` | 1,449 | Official VOC 2012 segmentation val | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes | | `mask` | `large_binary` | Inline PNG bytes — class id per pixel (0=background, 1-20=VOC classes, 255=void) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — `metric=cosine` > Note: the small split sizes (≤1,464 rows) sit below Lance's default partition count, so the helper falls back to a smaller `num_partitions` automatically. For higher recall, rebuild the index with `num_partitions=16` against a local copy. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/pascal-voc-2012-segmentation-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["id"], len(row["image"]), len(row["mask"])) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/pascal-voc-2012-segmentation-lance --repo-type dataset --local-dir ./pascal-voc-2012-segmentation-lance > ``` > > Then point LanceDB at `./pascal-voc-2012-segmentation-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visual nearest-neighbour search a single call. In production you would encode a query image (or a class prototype) through OpenCLIP `ViT-B-32` at runtime and pass the resulting 512-d cosine-normalized vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id"]) .limit(10) .to_list() ) for r in hits: print(r["id"]) ``` Because the embeddings are cosine-normalized, `metric="cosine"` is the natural choice and the first hit is typically the seed row itself — a useful sanity check before tuning `nprobes` and `refine_factor` for recall. ## Curate A typical curation pass for a segmentation workflow combines visual similarity with a structural filter on the row. Stacking both inside a single filtered scan keeps the candidate set small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing to anything downstream. The snippet below seeds from row 42 and restricts the candidates to rows whose mask payload is non-trivially sized — a cheap proxy for masks that actually carry foreground annotation. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(42) .to_list()[0] ) candidates = ( tbl.search(seed["image_emb"]) .metric("cosine") .where("octet_length(mask) > 2000", prefilter=True) .select(["id"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `mask` columns are never read in the candidate scan, so the network traffic stays dominated by the embedding vectors rather than image or mask bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `image_bytes` size and a `has_mask` flag, both of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./pascal-voc-2012-segmentation-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "image_bytes": "octet_length(image)", "has_mask": "octet_length(mask) > 1024", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. For class-level statistics — for example, a per-row list of class ids present in the mask, or a per-class pixel count — the values cannot be derived in SQL because they require decoding the PNG. Compute them once in an external table and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_stats = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "classes_present": pa.array([[15], [7, 15], [9]], type=pa.list_(pa.int8())), }) tbl.add_columns([f for f in class_stats.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_stats) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require running a model over the image bytes (a second-pass embedding, an instance segmentation, a depth prediction), Lance also provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a segmentation run, project the JPEG bytes and the PNG mask bytes together; everything else, including the CLIP embeddings, stays on disk until you opt in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "mask"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEGs and PNGs, build (image, label) tensors, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb"]` to `select_columns(...)` on the next run skips JPEG and PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight linear probe over frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges class statistics, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./pascal-voc-2012-segmentation-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("voc2012-clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="voc2012-clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `voc2012-clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added class statistics or alternative embeddings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same image/mask pairs, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("octet_length(mask) > 2000") .select(["id", "image", "mask", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./voc-subset") local_db.create_table("train", batches) ``` The resulting `./voc-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data` for `./voc-subset`. ## Source & license Converted from [`nateraw/pascal-voc-2012`](https://huggingface.co/datasets/nateraw/pascal-voc-2012). The Pascal VOC dataset is released under [its own custom license](http://host.robots.ox.ac.uk/pascal/VOC/) — please review before redistribution. ## Citation ``` @misc{everingham2012pascal, title={The Pascal Visual Object Classes Challenge: A Retrospective}, author={Everingham, Mark and Eslami, S. M. Ali and Van Gool, Luc and Williams, Christopher K. I. and Winn, John and Zisserman, Andrew}, journal={International Journal of Computer Vision}, year={2015} } ``` # SQuAD v2 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/squad-v2 A Lance-formatted version of SQuAD v2 — the Stanford Question Answering Dataset with both answerable and deliberately unanswerable questions over Wikipedia passages — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/squad-v2-lance/data. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/squad-v2-lance) > > Source dataset card and downloadable files for `lance-format/squad-v2-lance`. ## Key features * **Span-extraction QA over Wikipedia** with 130k+ training questions and an `is_impossible` flag that cleanly separates answerable from unanswerable items. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question retrieval. * **Full-text inverted indices** on both `question` and `context` for keyword search alongside dense retrieval. * **One columnar dataset** carrying questions, contexts, answer spans, and embeddings together — project only the columns each query needs. ## Splits | Split | Rows | | - | - | | `train.lance` | 130,319 | | `validation.lance` | 11,873 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | SQuAD question id (natural join key for merges) | | `title` | `string` | Wikipedia article title | | `context` | `string` | Paragraph the question was generated from | | `question` | `string` | The question text | | `answers` | `list<string>` | Accepted answer spans (empty for impossible questions) | | `answer_starts` | `list<int32>` | Character offsets of each answer within `context` | | `is_impossible` | `bool` | `true` for SQuAD 2.0 unanswerable questions | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM embedding of `question` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `question_emb` — `metric=cosine`, vector similarity search * `INVERTED` on `question` and `context` — full-text search * `BTREE` on `id` and `title` — point lookups and prefix scans * `BITMAP` on `is_impossible` — fast filtering between answerable and unanswerable ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/squad-v2-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/squad-v2-lance --repo-type dataset --local-dir ./squad-v2-lance > ``` > > Then point LanceDB at `./squad-v2-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` turns semantic question retrieval into a single call. In production you would encode an incoming question through the same MiniLM encoder used at ingest and pass the resulting 384-dim vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in, then restricts the result to answerable items so the response always carries a usable span. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("is_impossible = false", prefilter=True) .select(["id", "title", "question", "answers"]) .limit(10) .to_list() ) for r in hits: print(f"{r['title']:30s} | {r['question'][:80]}") ``` Because the recommended setup also builds an `INVERTED` index on both `question` and `context`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges and reranks the two result lists in a single call, which is useful when a literal phrase must appear in the passage but the dense side should still drive ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("eiffel tower") .where("is_impossible = false", prefilter=True) .select(["id", "title", "question", "context", "answers"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['title']:30s} | {r['question'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate SQuAD v2 has a natural split between answerable and unanswerable questions, and the `is_impossible` boolean — backed by a `BITMAP` index — makes either subset cheap to extract. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it easy to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") impossible = ( tbl.search() .where("is_impossible = true AND length(question) >= 40", prefilter=True) .select(["id", "title", "question", "context"]) .limit(1000) .to_list() ) print(f"{len(impossible)} hard unanswerable questions; first title: {impossible[0]['title']}") ``` The mirror query — long, well-grounded answerable questions — looks identical with the boolean flipped, and the `question_emb` vector is never read by either scan. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Materialize-a-subset section below for export to a writable local copy. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length`, a `num_answers` count, and a `has_answer` flag — any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./squad-v2-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "num_answers": "array_length(answers)", "has_answer": "NOT is_impossible", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reader-model predictions, alternate embeddings, span-level labels), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa scores = pa.table({ "id": pa.array(["56be4db0acb8001400a502ec", "56be4db0acb8001400a502ed"]), "reader_score": pa.array([0.91, 0.42]), }) tbl.add_columns([f for f in scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the questions), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a reading-comprehension model the natural projection is the question, the context, and the answer spans together; for a retriever or reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["question", "context", "answers", "answer_starts", "is_impossible"] ) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; question_emb stays on disk. # tokenize question+context, build span labels from answer_starts, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb"]` (optionally with `["answers"]` for hard-negative mining) to `select_columns(...)` on the next run reads only the 384-d vectors and skips the bulky `context` strings entirely, which is the right shape for training a retrieval head or reranker on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./squad-v2-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="baseline-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `baseline-v1` keeps returning stable results while the dataset evolves in parallel — newly added reader scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and contexts, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("is_impossible = false AND length(question) >= 30") .select(["id", "title", "context", "question", "answers", "answer_starts", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./squad-v2-answerable") local_db.create_table("train", batches) ``` The resulting `./squad-v2-answerable` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/squad-v2-lance/data` for `./squad-v2-answerable`. ## Source & license Converted from [`rajpurkar/squad_v2`](https://huggingface.co/datasets/rajpurkar/squad_v2). SQuAD v2 is distributed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @article{rajpurkar2018know, title={Know What You Don't Know: Unanswerable Questions for SQuAD}, author={Rajpurkar, Pranav and Jia, Robin and Liang, Percy}, journal={Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Short Papers)}, year={2018} } ``` # Stanford Cars Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/stanford-cars A Lance-formatted version of the Stanford Cars fine-grained benchmark — 8,144 photographs across 196 make/model/year classes — sourced from Multimodal-Fatima/StanfordCars_train. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/stanford-cars-lance) > > Source dataset card and downloadable files for `lance-format/stanford-cars-lance`. Each row carries the inline JPEG bytes, the integer class id, a BLIP-generated caption inherited from the source mirror, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/stanford-cars-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **BLIP captions in `blip_caption`** with a full-text index, so keyword search on visual descriptions composes with vector search in a single query. * **A bundled scalar index on `label`** makes class-based curation a cheap predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 8,144 | The source mirror redistributes a single split; the original Stanford Cars test split is not included here. | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (quality 92) | | `label` | `int32` | Class id (0–195), one per Make Model Year combination | | `blip_caption` | `string?` | BLIP-generated caption (beam=5) carried through from the source mirror | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `INVERTED` (FTS) on `blip_caption` — keyword and hybrid search * `BTREE` on `label` — fast lookup by class id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/stanford-cars-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["blip_caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/stanford-cars-lance --repo-type dataset --local-dir ./stanford-cars-lance > ``` > > Then point LanceDB at `./stanford-cars-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "blip_caption"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "blip_caption"]) .limit(10) .to_list() ) print("seed caption:", seed["blip_caption"]) for r in hits: print(f" {r['id']:>6} label={r['label']:>3} {r['blip_caption'][:60]}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. Because the dataset also ships an `INVERTED` index on `blip_caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "red convertible" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["image_emb"]) .text("red convertible") .select(["id", "label", "blip_caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['id']:>6} label={r['label']:>3} {r['blip_caption'][:60]}") ``` ## Curate A typical curation pass for a fine-grained classifier combines a class-based filter with a content filter on the caption. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing the subset to anything downstream. The `BTREE` on `label` and the `INVERTED` index on `blip_caption` make both predicates effectively free. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") candidates = ( tbl.search("convertible OR coupe") .where("label IN (12, 47, 89)", prefilter=True) .select(["id", "label", "blip_caption"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['blip_caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 200-row candidate scan is dominated by the small caption strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. Stanford Cars class strings often encode the model year as a trailing four-digit token in the caption; the example below uses a SQL regex to lift that year into its own column, and adds a flag for vintage cars. Either can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./stanford-cars-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "caption_year": "CAST(regexp_extract(blip_caption, '(\\d{4})', 1) AS INTEGER)", "is_long_caption": "length(blip_caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, the Make Model Year strings from the original Stanford metadata), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_strings = pa.table({ "id": pa.array([0, 1, 2]), "class_name": pa.array([ "AM General Hummer SUV 2000", "Acura RL Sedan 2012", "Acura TL Sedan 2012", ]), }) tbl.add_columns([f for f in class_strings.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_strings) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second captioner over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch fine-grained classifier, project the JPEG bytes and the integer label; for a linear probe on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb and blip_caption stay on disk. # decode the JPEG bytes, forward, cross-entropy against `label`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe or a lightweight reranker. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./stanford-cars-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or captions do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search("convertible OR coupe") .select(["id", "image", "label", "blip_caption", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./stanford-cars-sports-subset") local_db.create_table("train", batches) ``` The resulting `./stanford-cars-sports-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/stanford-cars-lance/data` for `./stanford-cars-sports-subset`. ## Source & license Converted from [`Multimodal-Fatima/StanfordCars_train`](https://huggingface.co/datasets/Multimodal-Fatima/StanfordCars_train), itself a redistribution of the Stanford Cars dataset. The original dataset is for non-commercial research use; review the [archived Stanford Cars usage FAQ](https://web.archive.org/web/20210219110131/https://ai.stanford.edu/~jkrause/cars/car_dataset.html) before redistribution. ## Citation ``` @inproceedings{krause2013collecting, title={Collecting a large-scale dataset of fine-grained cars}, author={Krause, Jonathan and Stark, Michael and Deng, Jia and Fei-Fei, Li}, booktitle={Workshop on Fine-Grained Visual Categorization (CVPR)}, year={2013} } ``` # TextVQA Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/textvqa A Lance-formatted version of TextVQA — visual question answering where the question requires reading text in the image (street signs, product labels, screen captures) — sourced from lmms-lab/textvqa. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/textvqa-lance) > > Source dataset card and downloadable files for `lance-format/textvqa-lance`. Each row carries the image bytes, the question, the 10 reference annotator answers, the OCR tokens detected by the source pre-processing, OpenImages-style scene tags, and paired CLIP image and question embeddings — all available directly from the Hub at `hf://datasets/lance-format/textvqa-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files or image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (OpenCLIP ViT-B/32, 512-dim, cosine-normalized) — so cross-modal text→image retrieval is one indexed lookup. * **OCR tokens travel with the row** in `ocr_tokens`, which makes OCR-aware filtering and reranking a single SQL predicate alongside the visual and textual features. * **Pre-built ANN, FTS, and scalar indices** covering both embeddings, the question and canonical answer, and the source partition. ## Splits | Split | Rows | | - | - | | `validation.lance` | 5,000 | | `train.lance` | 34,602 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string?` | TextVQA image id | | `question_id` | `string?` | TextVQA question id | | `question` | `string` | The question text | | `answers` | `list<string>` | 10 annotator answers | | `answer` | `string` | First annotator answer (used as canonical / FTS target) | | `ocr_tokens` | `list<string>` | OCR tokens detected on the image | | `image_classes` | `list<string>` | OpenImages-style scene tags from the source | | `set_name` | `string?` | Source partition (`train`, `val`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | OpenCLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BTREE` on `image_id`, `question_id`, `set_name` — fast lookup by id and partition ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/textvqa-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/textvqa-lance --repo-type dataset --local-dir ./textvqa-lance > ``` > > Then point LanceDB at `./textvqa-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same OpenCLIP model used at ingest (ViT-B/32 `laion2b_s34b_b79k`, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question", "answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "answer", "ocr_tokens"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["answer"]) for r in hits: print(f" {r['image_id']:>14} {r['question'][:60]} ocr={r['ocr_tokens'][:5]}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased questions instead of visually similar images. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is particularly useful for TextVQA, where a brand name or sign content like "stop" must literally appear in the question (or eventually, the answer) while CLIP handles the visual side. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("brand name") .select(["image_id", "question", "answer", "ocr_tokens"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>14} {r['question'][:60]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Curation passes for TextVQA usually combine an OCR-driven structural filter (does this image actually contain a meaningful amount of detected text?) with a content predicate on the question or the canonical answer, so the candidate set is both visually interesting and topically focused. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "array_length(ocr_tokens) >= 5 AND question LIKE '%brand%' AND length(answer) > 0", prefilter=True, ) .select(["question_id", "image_id", "question", "answer", "ocr_tokens"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']} -> {candidates[0]['answer']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question, answer, and OCR-token strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `ocr_token_count`, an `is_yes_no_question` flag, and an `answer_length` integer, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./textvqa-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "ocr_token_count": "array_length(ocr_tokens)", "is_yes_no_question": "lower(answer) IN ('yes', 'no')", "answer_length": "length(answer)", "question_length": "length(question)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a stronger OCR system's tokens, a model's predicted answer, an annotator-disagreement score), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["34602", "34603"]), "model_answer": pa.array(["pepsi", "exit"]), "model_confidence": pa.array([0.88, 0.72]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternate OCR engine over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a TextVQA fine-tune that needs OCR conditioning, project the JPEG bytes, the question, the OCR tokens, and the canonical answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "ocr_tokens", "answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question and OCR tokens, forward through the VLM, # compute the loss against `answer`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./textvqa-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("openclip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="openclip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `openclip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added OCR systems or model predictions do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, questions, and OCR tokens, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_length(ocr_tokens) >= 5") .select(["question_id", "image_id", "image", "question", "answer", "ocr_tokens", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./textvqa-ocr-rich") local_db.create_table("train", batches) ``` The resulting `./textvqa-ocr-rich` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/textvqa-lance/data` for `./textvqa-ocr-rich`. ## Source & license Converted from [`lmms-lab/textvqa`](https://huggingface.co/datasets/lmms-lab/textvqa). TextVQA is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) by Singh et al. (Facebook AI Research). ## Citation ``` @inproceedings{singh2019towards, title={Towards VQA models that can read}, author={Singh, Amanpreet and Natarajan, Vivek and Shah, Meet and Jiang, Yu and Chen, Xinlei and Batra, Dhruv and Parikh, Devi and Rohrbach, Marcus}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2019} } ``` # TriviaQA Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/trivia-qa A Lance-formatted version of TriviaQA (rc.nocontext config) — a large reading-comprehension dataset of trivia questions paired with a canonical answer, accepted aliases, and entity-type metadata — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/trivia-qa-lance/data. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/trivia-qa-lance) > > Source dataset card and downloadable files for `lance-format/trivia-qa-lance`. The `rc.nocontext` slice is the standard reading-comprehension form without the multi-gigabyte `entity_pages` / `search_results` payloads, which keeps the dataset compact while preserving everything needed for closed-book QA, retrieval research, and as a search target. ## Key features * **138k+ trivia questions** with a canonical `answer_value`, normalized form for exact-match scoring, and a list of accepted `answer_aliases`. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question retrieval. * **Full-text inverted index** on `question` for keyword search and hybrid retrieval. * **One columnar dataset** carrying questions, canonical answers, aliases, types, and embeddings together — project only the columns each query needs. ## Splits | Split | Rows | | - | - | | `train.lance` | 138,384 | | `validation.lance` | 17,944 | ## Schema | Column | Type | Notes | | - | - | - | | `question_id` | `string` | TriviaQA question id (e.g. `tc_1`); natural join key for merges | | `question` | `string` | The trivia question | | `question_source` | `string` | URL or source the question came from | | `answer_value` | `string` | Canonical answer | | `answer_aliases` | `list<string>` | Other accepted phrasings (e.g. `["Sinclair Lewis", "Harry Sinclair Lewis"]`) | | `normalized_answer` | `string` | Lowercased / normalized form for exact-match scoring | | `answer_type` | `string` | TriviaQA entity type (e.g. `WikipediaEntity`, `FreebaseEntity`) | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM embedding of `question` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `question_emb` — `metric=cosine`, vector similarity search * `INVERTED` on `question` — full-text search * `BTREE` on `question_id` and `answer_value` — point lookups and prefix scans * `BITMAP` on `answer_type` — fast filtering by entity type ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/trivia-qa-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer_value"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/trivia-qa-lance --repo-type dataset --local-dir ./trivia-qa-lance > ``` > > Then point LanceDB at `./trivia-qa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` turns semantic retrieval over trivia questions into a single call. In production you would encode an incoming question through the same MiniLM encoder used at ingest and pass the resulting 384-dim vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(10) .to_list() ) for r in hits: print(f"{r['answer_value']:30s} | {r['question'][:80]}") ``` Because the recommended setup also builds an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges and reranks the two result lists in a single call, which is useful when a specific named entity must literally appear in the question but the dense side should still drive ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("sistine chapel") .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['answer_value']:30s} | {r['question'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate TriviaQA's `answer_type` column — backed by a `BITMAP` index — makes it cheap to slice the dataset by entity category, and the question text itself is a useful predicate for filtering out very short or unusually long items. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it easy to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "answer_type = 'WikipediaEntity' " "AND length(question) BETWEEN 60 AND 300", prefilter=True, ) .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first answer: {candidates[0]['answer_value']}") ``` Neither the `question_emb` vector nor the unused alias fields drive this scan, so a 1000-row curation pass against the Hub moves only the projected text columns. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Materialize-a-subset section below for export to a writable local copy. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length`, a `num_aliases` count, and a `has_aliases` flag — any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./trivia-qa-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "num_aliases": "array_length(answer_aliases)", "has_aliases": "array_length(answer_aliases) > 0", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reader-model predictions, alternate embeddings, retrieval scores from a different system), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa scores = pa.table({ "question_id": pa.array(["tc_1", "tc_2"]), "retriever_score": pa.array([0.88, 0.31]), }) tbl.add_columns([f for f in scores.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the questions), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a closed-book QA model the natural projection is the question, the canonical answer, and the alias list (the aliases serve as additional supervision targets during loss computation or evaluation); for a retriever or reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["question", "answer_value", "answer_aliases"] ) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; question_emb stays on disk. # tokenize question and answer, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "answer_value"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the canonical answer string, which is the right shape for training a retrieval head or reranker on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./trivia-qa-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="baseline-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `baseline-v1` keeps returning stable results while the dataset evolves in parallel — newly added scores or alternate embeddings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and answers, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("answer_type = 'WikipediaEntity' AND length(question) >= 60") .select( ["question_id", "question", "answer_value", "answer_aliases", "normalized_answer", "answer_type", "question_emb"] ) .to_batches() ) local_db = lancedb.connect("./trivia-qa-wiki") local_db.create_table("train", batches) ``` The resulting `./trivia-qa-wiki` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/trivia-qa-lance/data` for `./trivia-qa-wiki`. ## Source & license Converted from [`mandarjoshi/trivia_qa`](https://huggingface.co/datasets/mandarjoshi/trivia_qa) (`rc.nocontext` config). TriviaQA is released under the Apache 2.0 license. ## Citation ``` @article{joshi2017triviaqa, title={TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension}, author={Joshi, Mandar and Choi, Eunsol and Weld, Daniel S and Zettlemoyer, Luke}, journal={arXiv preprint arXiv:1705.03551}, year={2017} } ``` # VQAv2 Source: https://docs.lancedb.com/enterprise/v1-12-0/datasets/vqav2 A Lance-formatted version of VQAv2 — open-ended visual question answering on COCO images — sourced from lmms-lab/VQAv2. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/vqav2-lance) > > Source dataset card and downloadable files for `lance-format/vqav2-lance`. Each row is one `(image, question, 10 annotator answers)` triple with paired CLIP image and question embeddings drawn from the same shared space, plus the VQAv2 `question_type` / `answer_type` taxonomy and the consensus `multiple_choice_answer` — all available directly from the Hub at `hf://datasets/lance-format/vqav2-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files or image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (OpenCLIP ViT-B/32, 512-dim, cosine-normalized) — so cross-modal text→image retrieval and question-similarity retrieval both work as a single indexed lookup. * **Both raw and consensus answers** — the 10 annotator answers in `answers` alongside the canonical `multiple_choice_answer`, with parallel `answer_confidences`. * **Pre-built ANN, FTS, scalar, and bitmap indices** covering both embeddings, the question text, the answer taxonomy, and the COCO and VQAv2 ids. ## Splits | Split | Rows | | - | - | | `validation.lance` | 214,354 | The `lmms-lab/VQAv2` redistribution declares only the eval splits in its `dataset_info`, so the train shards (\~444 k rows) are not bundled here today; they can be enabled by reading `data/train-*.parquet` directly with PyArrow or by switching to `Multimodal-Fatima/VQAv2_train`. Track progress in `TRACKED_DATASETS.md`. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `int64` | COCO image id | | `question_id` | `int64` | VQAv2 question id | | `question` | `string` | Natural-language question | | `question_type` | `string` | First few tokens of the question (e.g. `what is`, `is the`) | | `answer_type` | `string` | One of `yes/no`, `number`, `other` | | `multiple_choice_answer` | `string` | Canonical (most-common) answer | | `answers` | `list<string>` | 10 annotator answers | | `answer_confidences` | `list<string>` | Parallel confidence list (`yes` / `maybe` / `no`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | OpenCLIP text embedding of the question (cosine-normalized) | Because both embeddings come from the same CLIP model, they share an embedding space and cross-modal retrieval (image→question or question→image) works without any additional alignment. ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` — keyword and hybrid search * `BITMAP` on `question_type`, `answer_type` — fast categorical filters over the VQAv2 taxonomy * `BTREE` on `image_id`, `question_id`, `multiple_choice_answer` — fast lookup by id and canonical answer ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/vqav2-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["multiple_choice_answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/vqav2-lance --repo-type dataset --local-dir ./vqav2-lance > ``` > > Then point LanceDB at `./vqav2-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same OpenCLIP model used at ingest (ViT-B/32 `laion2b_s34b_b79k`, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question", "multiple_choice_answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "multiple_choice_answer", "answer_type"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["multiple_choice_answer"]) for r in hits: print(f" {r['image_id']:>12} [{r['answer_type']}] {r['question'][:60]} -> {r['multiple_choice_answer']}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric. Swap `vector_column_name="image_emb"` for `question_emb` to do question→question retrieval against the validation set instead, which is useful for clustering paraphrases or spotting near-duplicate questions across COCO images. Because the dataset also ships an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is useful when a noun like "dog" must appear in the question text but you still want CLIP to handle visual similarity over the candidate set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("dog") .select(["image_id", "question", "multiple_choice_answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['question'][:60]} -> {r['multiple_choice_answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for VQAv2 combines a structural filter on the answer taxonomy (e.g. only yes/no questions, or only counting questions) with a content predicate on the question text or the consensus answer, so the candidate set is both categorically uniform and topically focused. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "answer_type = 'yes/no' AND question_type = 'is the' AND multiple_choice_answer IN ('yes', 'no')", prefilter=True, ) .select(["question_id", "image_id", "question", "multiple_choice_answer"]) .limit(500) .to_list() ) print(f"{len(candidates)} 'is the' yes/no candidates; first: {candidates[0]['question']} -> {candidates[0]['multiple_choice_answer']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` and embedding columns are never read, so the network traffic for a 500-row candidate scan is dominated by question and answer strings rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_binary_answer` flag, a `num_answer_tokens` count, and a `question_length` integer, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./vqav2-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_binary_answer": "multiple_choice_answer IN ('yes', 'no')", "question_length": "length(question)", "answer_length": "length(multiple_choice_answer)", "num_unique_answers": "array_length(answers)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a model's predicted answer, an annotator-agreement score, or a difficulty rating), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array([262148000, 262148001], type=pa.int64()), "model_answer": pa.array(["yes", "2"]), "model_confidence": pa.array([0.87, 0.64]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternate VLM over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a VQA fine-tune, project the JPEG bytes, the question, and the consensus answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "multiple_choice_answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question, forward through the VLM, compute the loss # against `multiple_choice_answer`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "multiple_choice_answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./vqav2-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("openclip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="openclip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `openclip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added model predictions or alternative annotations do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, questions, and consensus answers, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where("answer_type = 'number'") .select(["question_id", "image_id", "image", "question", "multiple_choice_answer", "answers", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./vqav2-counting-subset") local_db.create_table("validation", batches) ``` The resulting `./vqav2-counting-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/vqav2-lance/data` for `./vqav2-counting-subset`. ## Source & license Converted from [`lmms-lab/VQAv2`](https://huggingface.co/datasets/lmms-lab/VQAv2). VQAv2 questions and annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The underlying images come from COCO and are subject to Flickr terms of service. See the [VQAv2 download page](https://visualqa.org/download.html) for details. ## Citation ``` @inproceedings{goyal2017making, title={Making the V in VQA Matter: Elevating the Role of Image Understanding in Visual Question Answering}, author={Goyal, Yash and Khot, Tejas and Summers-Stay, Douglas and Batra, Dhruv and Parikh, Devi}, booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2017} } ``` # Large scale vector search (1.5B) Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/fineweb-edu-search Semantic search over 1.5B+ FineWeb EDU embeddings. vector-searcheducationbge-embeddings > [card] [Large Scale Vector Search (1.5B)](https://lancedb-demos.vercel.app/demo/fineweb-edu-search) > > Semantic search over curated FineWeb EDU pages, represented as 1.5B+ BGE embeddings. Inspect the > query plan to see how LanceDB serves vector search at billion scale. # Demo application gallery Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/index End-to-end applications built with LanceDB. Applications built on LanceDB, each with a live demo and a write-up of how it works. | App | What it shows | | - | - | | [Semantic.art](/enterprise/v1-12-0/demos/semantic-art) | Multimodal art discovery using feelings, phrases, and images. | | [Wikipedia 41M hybrid search](/enterprise/v1-12-0/demos/wikipedia-search) | Full-text and vector search combined, over 41M+ entries. | | [Video search](/enterprise/v1-12-0/demos/video-search) | Natural-language search across a video library. | | [Large scale vector search (1.5B)](/enterprise/v1-12-0/demos/fineweb-edu-search) | Semantic search over 1.5B+ FineWeb EDU embeddings. | | [Robot data curation (DROID)](/enterprise/v1-12-0/demos/robot-data-curation) | Searching, scoring, and selecting robotics training examples. | # Robot data curation (DROID) Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/robot-data-curation Search, score, and select robotics training examples from DROID. multimodalroboticsvector-searchfts > [card] [Robot Data Curation (DROID)](https://lancedb-demos.vercel.app/demo/robot-data-curation) > > Search robot video frames from the DROID dataset, compute features, and select training examples in LanceDB. > Add captions and quality scores as columns, then write model errors back to guide the next training run. # Semantic.art Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/semantic-art Multimodal art discovery through feelings, phrases, and images. multimodalhybrid-searchvector-searchsemantic-routing > [card] [Semantic.art](https://www.semantic.art/) > > Semantic.art turns real, human-made art discovery into a multimodal search experience using > feelings, phrases, and images. It's built with LanceDB hybrid search and semantic routing. > > > [card] [Learn how it's built](https://lancedb.com/blog/semanticdotart/) > > > > Read in detail about how Semantic.art is built in this blog post. # Video search Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/video-search Search a video library with natural language queries. multimodalvideo-searchvector-search > [card] [Video Search](https://lancedb-demos.vercel.app/demo/video-search) > > Search through a library of videos using natural language queries. This demo showcases how to use LanceDB > to perform semantic search on video content. # Wikipedia 41M hybrid search Source: https://docs.lancedb.com/enterprise/v1-12-0/demos/wikipedia-search Hybrid full-text and vector search across 41M+ Wikipedia entries. multimodalhybrid-searchvector-searchfts > [card] [Wikipedia 41M Hybrid Search](https://lancedb-demos.vercel.app/demo/wikipedia-search) > > Interactive hybrid search, full-text search (FTS) and vector search demo with 41M+ Wikipedia entries. > Explore the power of combining FTS with vector search for more relevant results. > > > [card] [Learn how it's built](https://lancedb.com/blog/feature-full-text-search/) > > > > Read in detail about how the Wikipedia 41M hybrid search demo is built in this blog post. # Agno Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/agno Build a search assistant using the Agno agent framework with LanceDB as the knowledge backend. [Agno](https://docs.agno.com/introduction) is a framework for building agentic AI applications. It supports LanceDB as a knowledge backend, allowing you to easily ingest and retrieve external content for your agents. When you pair Agno's `Knowledge` system with LanceDB, you get a clean Agentic RAG setup. We'll walk through the steps below to build a YouTube transcript-aware Agno assistant that can: * Ingest a transcript from a YouTube video via the YouTube API * Store embeddings and metadata in LanceDB * Retrieve context during responses with hybrid search * Ask questions about the video content in a CLI chat loop ## Prerequisites Install dependencies: ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install -U agno openai lancedb youtube-transcript-api beautifulsoup4 ``` ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv add agno openai lancedb youtube-transcript-api beautifulsoup4 ``` ## Step 1: Configure LanceDB-backed knowledge First, you can initialize the core `Knowledge` object that your agent will use for retrieval. It configures LanceDB as the vector store, enables hybrid search with native LanceDB FTS, and sets the embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import re from agno.agent import Agent from agno.knowledge.embedder.openai import OpenAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.models.openai import OpenAIResponses from agno.vectordb.lancedb import LanceDb, SearchType from youtube_transcript_api import YouTubeTranscriptApi if "OPENAI_API_KEY" not in os.environ: os.environ["OPENAI_API_KEY"] = "sk-..." def extract_video_id(youtube_url: str) -> str: match = re.search(r"(?<=v=)[\w-]+", youtube_url) or re.search( r"(?<=be/)[\w-]+", youtube_url ) if not match: raise ValueError("Could not parse YouTube video ID from URL") return match.group(0) knowledge = Knowledge( vector_db=LanceDb( uri="./tmp/lancedb", table_name="youtube_transcripts", search_type=SearchType.hybrid, embedder=OpenAIEmbedder(id="text-embedding-3-small"), ), ) ``` ## Step 2: Fetch and ingest the YouTube transcript Next, extract a YouTube video ID, fetch the full transcript, and flatten it into text for indexing. The snippet shown below then inserts that transcript text into the Agno knowledge base, which writes vectors and metadata to LanceDB. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} youtube_url = "https://www.youtube.com/watch?v=wl6mFyXoxos" video_id = extract_video_id(youtube_url) ytt = YouTubeTranscriptApi() transcript_segments = ytt.fetch(video_id, languages=["en", "en-US"]).to_raw_data() transcript_text = " ".join(segment["text"] for segment in transcript_segments) knowledge.insert( name=f"YouTube Transcript ({video_id})", text_content=transcript_text, metadata={"source": "youtube", "video_id": video_id, "video_url": youtube_url}, ) ``` > [!NOTE] > > This path explicitly fetches the transcript first, then inserts transcript text into LanceDB through Agno. ## Step 3: Create an Agno agent with knowledge search The next step is to construct an Agno `Agent` and attach the knowledge base you just populated. With `search_knowledge=True`, the agent performs retrieval before answering, so responses stay grounded in transcript context. In Agno, retrieval is exposed as a tool call that the model can invoke at runtime. When `search_knowledge=True`, Agno makes a knowledge-search tool (shown in output as `search_knowledge_base(...)`) available to the model; the model decides when to call it, Agno executes the tool, and the returned context is fed back into the final answer. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} agent = Agent( model=OpenAIResponses(id="gpt-5-mini"), knowledge=knowledge, search_knowledge=True, instructions="Search the transcript and answer only from retrieved context.", markdown=True, ) ``` ## Step 4: Start a CLI chat loop You can now ask an initial question and then start an interactive loop for follow-up queries. Each prompt runs through the same retrieval pipeline, so you can iteratively inspect what the transcript contains. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} agent.print_response( "Summarize the loaded video transcript in 5 concise bullet points.", stream=True, ) while True: question = input("You: ").strip() if question.lower() in {"exit", "quit", "bye"}: break agent.print_response(question, stream=True) ``` > [!NOTE] > > Want local-first inference? Replace OpenAI model/embedder classes with Agno's Ollama providers. See Agno's Ollama knowledge examples: [docs.agno.com/examples/models/ollama/chat/knowledge](https://docs.agno.com/examples/models/ollama/chat/knowledge). ### Question 1 The following question is asked in the CLI chat loop: ``` ┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ Q: What kinds of data can LanceDB handle? ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Tool Calls ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ • search_knowledge_base(query=What kinds of data can LanceDB handle?) ┃ ┃ • search_knowledge_base(query=LanceDB images audio video handle kinds of data ┃ ┃ can handle 'LanceDB can handle' 'kinds of data' 'images audio video' transcript) ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Response (19.1s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ ┃ ┃ • Images, audio, video — i.e., multimodal AI data and “all manners of things ┃ ┃ you don't put into traditional databases” (per the transcript). ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` We get the response based on the transcript's contents as expected. ### Question 2 Let's ask a more specific question about the CEO of LanceDB, which is also in the transcript: ``` You: What is the name of the CEO of LanceDB? INFO Found 10 documents ┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ What is the name of the CEO of LanceDB? ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Tool Calls ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ • search_knowledge_base(query=CEO of LanceDB) ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Response (16.7s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ ┃ ┃ • According to the retrieved YouTube transcript/title, the CEO of LanceDB is ┃ ┃ Chang She. ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` We get the response based on the transcript's contents and title as expected. ## Why this works well To start, LanceDB Embedded can run from a local directory, so transcript data can stay on your machine. * You do not need to maintain a separate transcript parser in your application code. * You do not need to hand-roll chunking and retrieval orchestration across multiple modules. * One explicit Agno `Knowledge` object, backed by LanceDB, defines both ingestion and search behavior in one place. * Fewer moving parts means the tutorial stays readable and the same pattern is easier to carry into production code. As your application needs grow, you can migrate to LanceDB [Enterprise](/enterprise/v1-12-0/index#architecture) for convenience features like automatic compaction and reindexing and the ability to scale to really large datasets. # GenKit Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/genkit ### genkitx-lancedb Genkit is an open-source framework for building end-to-end AI and RAG pipelines with a clean, TypeScript-first developer experience. The genkitx-lancedb plugin lets you use LanceDB as a high-performance vector store inside your Genkit flows, so you can index, search, and retrieve data efficiently as part of your AI applications. ### Installation ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pnpm install genkitx-lancedb ``` ### Usage Adding LanceDB plugin to your genkit instance. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { lancedbIndexerRef, lancedb, lancedbRetrieverRef, WriteMode } from "genkitx-lancedb"; import { textEmbedding004, vertexAI } from "@genkit-ai/vertexai"; import { gemini } from "@genkit-ai/vertexai"; import { z, genkit } from "genkit"; import { Document } from "genkit/retriever"; import { chunk } from "llm-chunk"; import { readFile } from "fs/promises"; import path from "path"; import pdf from "pdf-parse/lib/pdf-parse"; const ai = genkit({ plugins: [ // vertexAI provides the textEmbedding004 embedder vertexAI(), // the local vector store requires an embedder to translate from text to vector lancedb([ { dbUri: ".db", // optional lancedb uri, default to .db tableName: "table", // optional table name, default to table embedder: textEmbedding004, }, ]), ], }); ``` You can run this app with the following command: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} genkit start -- tsx --watch src/index.ts ``` This'll add LanceDB as a retriever and indexer to the genkit instance. You can see it in the GUI view ![Screenshot 2025-05-11 at 7 21 05 PM](https://github.com/user-attachments/assets/e752f7f4-785b-4797-a11e-72ab06a531b7) ### Testing retrieval on a sample table To see the raw retrieval results, open the LanceDB retriever in the Genkit Developer UI, enter a query and run it: ![Screenshot 2025-05-11 at 7 21 05 PM](https://github.com/user-attachments/assets/b8d356ed-8421-4790-8fc0-d6af563b9657) The retriever returns 5 results from the LanceDB table. Each result looks something like this: ![Screenshot 2025-05-11 at 7 21 18 PM](https://github.com/user-attachments/assets/77429525-36e2-4da6-a694-e58c1cf9eb83) ## Creating a custom RAG flow Now that we've seen how you can use LanceDB in a Genkit pipeline, let's refine the flow and create a RAG. A RAG flow will consist of an index and a retriever with its outputs postprocessed and fed into an LLM for final response ### Creating custom indexer flows You can also create custom indexer flows, using more options and features provided by LanceDB. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export const menuPdfIndexer = lancedbIndexerRef({ // Using all defaults, for dbUri, tableName, and embedder, etc }); const chunkingConfig = { minLength: 1000, maxLength: 2000, splitter: "sentence", overlap: 100, delimiters: "", } as any; async function extractTextFromPdf(filePath: string) { const pdfFile = path.resolve(filePath); const dataBuffer = await readFile(pdfFile); const data = await pdf(dataBuffer); return data.text; } export const indexMenu = ai.defineFlow( { name: "indexMenu", inputSchema: z.string().describe("PDF file path"), outputSchema: z.void(), }, async (filePath: string) => { filePath = path.resolve(filePath); // Read the pdf. const pdfTxt = await ai.run("extract-text", () => extractTextFromPdf(filePath)); // Divide the pdf text into segments. const chunks = await ai.run("chunk-it", async () => chunk(pdfTxt, chunkingConfig)); // Convert chunks of text into documents to store in the index. const documents = chunks.map((text) => { return Document.fromText(text, { filePath }); }); // Add documents to the index. await ai.index({ indexer: menuPdfIndexer, documents, options: { writeMode: WriteMode.Overwrite, } as any, }); }, ); ``` ![Screenshot 2025-05-11 at 8 35 56 PM](https://github.com/user-attachments/assets/e2a20ce4-d1d0-4fa2-9a84-f2cc26e3a29f) In your console, you can see the logs ![Screenshot 2025-05-11 at 7 19 14 PM](https://github.com/user-attachments/assets/243f26c5-ed38-40b6-b661-002f40f0423a) ### Creating custom retriever flows You can also create custom retriever flows, using more options and features provided by LanceDB. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export const menuRetriever = lancedbRetrieverRef({ tableName: "table", // Use the same table name as the indexer. displayName: "Menu", // Use a custom display name. }); export const menuQAFlow = ai.defineFlow( { name: "Menu", inputSchema: z.string(), outputSchema: z.string() }, async (input: string) => { // retrieve relevant documents const docs = await ai.retrieve({ retriever: menuRetriever, query: input, options: { k: 3, }, }); const extractedContent = docs.map((doc) => { if (doc.content && Array.isArray(doc.content) && doc.content.length > 0) { if (doc.content[0].media && doc.content[0].media.url) { return doc.content[0].media.url; } } return "No content found"; }); console.log("Extracted content:", extractedContent); const { text } = await ai.generate({ model: gemini("gemini-2.0-flash"), prompt: ` You are acting as a helpful AI assistant that can answer questions about the food available on the menu at Genkit Grub Pub. Use only the context provided to answer the question. If you don't know, do not make up an answer. Do not add or change items on the menu. Context: ${extractedContent.join("\n\n")} Question: ${input}`, docs, }); return text; }, ); ``` Now using our retrieval flow, we can ask a question about the ingested PDF ![Screenshot 2025-05-11 at 7 18 45 PM](https://github.com/user-attachments/assets/86c66b13-7c12-4d5f-9d81-ae36bfb1c346) # Hermes Agent Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/hermes-agent Use LanceDB as a persistent, semantic memory backend for Hermes Agent. Get durable recall across sessions with vector and hybrid search. [Hermes Agent](https://github.com/NousResearch/hermes-agent) is a self-hosted, open-source personal agent from [Nous Research](https://nousresearch.com). You can talk to it from a terminal UI or reach the same agent from Telegram, Discord, and Slack, and it exposes a dedicated slot for external *memory providers* that run alongside its built-in notes. The [LanceDB memory plugin](https://github.com/lancedb/hermes-agent-memory) fills that slot. It gives Hermes durable, semantic recall across sessions: state a preference or a project convention once, and the agent can retrieve it weeks later in a brand-new session, even when you ask for it in completely different words. Everything runs inside Hermes' own Python process, storing a single LanceDB table on local disk. There's no memory server to operate. > [!NOTE] > > **The mental model is clean** > > * Hermes owns the agent loop > * LanceDB manages the durable long-term memory and offers semantic recall. ## Why LanceDB fits agent memory Out of the box, Hermes remembers with a small curated notes file frozen into the system prompt, plus lexical (keyword) search over past sessions. Both are useful, but keyword search misses paraphrases of what you originally typed, the exact thing you need when recalling a fact you phrased differently months ago. LanceDB Embedded is a retrieval library that runs inside your application, which makes it a natural fit here: * **No server to stand up**: it reads and writes a table on local disk, so the plugin ships as a dependency rather than a service to operate. * **One table holds everything**: content, metadata, and embeddings live together. A memory becomes a structured row with a category, tags, timestamps, and provenance, not just a text blob. * **Query it any way you need**: vector similarity for meaning, BM25 full-text for exact names and jargon, a hybrid of the two, or plain metadata filters to keep recall scoped to the right workspace. * **It scales up**: the same table abstraction carries over to larger LanceDB deployments later, so the local setup is never a dead end. ## Install and activate > [!TIP] > > Want to try this without touching your existing Hermes setup? Run everything in an isolated > profile: `hermes profile create demo`, then add `-p demo` to the commands below. When you're > done, `rm -rf ~/.hermes/profiles/demo` removes all trace. **1. Install Hermes Agent** Skip this if you already have Hermes installed. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash ``` **2. Install the plugin** This shallow-clones the plugin into `~/.hermes/plugins/lancedb/`. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes plugins install lancedb/hermes-agent-memory ``` **3. Install runtime dependencies into Hermes' environment** Hermes loads plugins inside its own Python interpreter, so the dependencies go *there*, not into a separate virtualenv. (This interpreter is shared across profiles, so you only install once.) ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --python ~/.hermes/hermes-agent/venv/bin/python3 lancedb openai pyyaml ``` **4. Set your embeddings API key** The plugin turns conversations into embeddings, so it needs an embeddings key. By default that is OpenAI, so set `OPENAI_API_KEY` in your environment or in `~/.hermes/.env`. > [!NOTE] > > Prefer a local or non-OpenAI model? The plugin uses an OpenAI-compatible client, so you can > point it at any compatible endpoint (OpenRouter, Ollama, vLLM, …) in your config, with no code > change needed. See [Configuration](#configuration) below. **5. Activate and verify** Switch memory on and pick this plugin: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes memory setup # choose "lancedb" ``` Then confirm it's actually active before you start chatting. This is the one step worth not skipping, because Hermes quietly falls back to its built-in notes if the provider isn't set: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes memory status ``` ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} Memory status ──────────────────────────────────────── Built-in: always active Provider: lancedb Plugin: installed ✓ Status: available ✓ ``` You want to see `Provider: lancedb` with both `installed ✓` and `available ✓`. ## The memory tools Once activated, the agent has four tools for working with long-term memory: | Tool | What it does | | :- | :- | | `lancedb_recall` | Semantic (vector, the default) or hybrid search over your workspace memory. Returns matching facts with scores and provenance. | | `lancedb_remember` | Stores a durable fact when you explicitly ask. Deduplicated by content hash, so remembering the same thing twice doesn't pile up rows. | | `lancedb_read` | Fetches a single memory by ID, optionally with the original conversation messages it was distilled from. | | `lancedb_forget` | Deletes safely: previews candidates first, then deletes by exact ID, so nothing disappears by accident. | Beyond these tools, the plugin also captures durable facts from your conversations automatically: an auxiliary model distills them before context is compressed and again when a session ends, so insights survive even when the raw messages are summarized away. ## Walkthrough "*Teach it your project preferences*" Let's make this concrete with the pain we opened on: re-explaining your setup to the agent every session. We'll save a convention once and then prove a brand-new session can recall it. This example will touch all four tools along the way. ### Remember Ask Hermes to commit a convention to long-term memory. Saying "remember in long-term memory" makes sure it lands in the LanceDB store, which shows up as the `⚡ lancedb_r` (`lancedb_remember`) line below: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● Remember in long-term memory: for this project I only use uv, never pip, and I always add type hints to Python functions. ┊ 🧠 memory +memory: "For this project, the user only uses uv for Python package management, never pip, and always adds type hints to Python functions." ┊ ⚡ lancedb_r 0.0s ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── Remembered. I've stored that project convention: use uv only, never pip, and always add type hints to Python functions. ``` ### Recall First, take Hermes' built-in notes out of the picture so recall can *only* come from LanceDB (the two layers run side by side otherwise, and either could answer): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes config set memory.memory_enabled false ``` Now start a fresh session (`/new`) and ask for the convention back, worded completely differently from how you saved it: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● /new ● Look through your long-term memory for my Python project preferences. ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── I found one durable memory about Python project preferences: - Project Python tooling preference is uv; pip is not used; type hints are required. ``` This is the whole point in one exchange. You asked about your *preferences* using none of the words you stored the fact with (no *uv*, no *pip*, no *type hints*), yet a fresh session, with none of the earlier conversation in context, pulls it straight back. Semantic search matches on meaning rather than exact wording, which is precisely where keyword search falls short. > [!TIP] > > Turn the built-in layer back on for everyday use with `hermes config set memory.memory_enabled true`. > The two memory layers happily coexist. We only disabled it here to prove the recall came from > LanceDB. ### Read You can also ask where a fact came from. Hermes attributes the answer to its stored memory rather than guessing from a file in the repo (under the hood, `lancedb_read` can also return the exact source messages a fact was distilled from): ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● Where did that uv preference come from? ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── It came from the project's persistent memory, not from a codebase file I inspected. Specifically, the recalled memory says: - "For this project, the user only uses uv for Python package management, never pip, and always adds type hints to Python functions." ``` ### Forget When a preference changes, ask Hermes to drop the old fact. The tool calls tell the whole story: the two `⚡ lancedb_f` (`lancedb_forget`) lines are it previewing matches and then deleting, and the trailing `⚡ lancedb_r` is it saving the replacement in the same breath: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● I've switched from uv to pixi. Forget the uv preference. ┊ ⚡ lancedb_f uv preference python package management never pip type hints 0.3s ┊ ⚡ lancedb_f 0.0s ┊ ⚡ lancedb_r 0.2s ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── Done — I removed the uv preference from memory and replaced it with: - This project uses pixi for Python package management - Type hints on Python functions are still preferred ``` Remember, recall, read, forget: four small operations that between them cover the entire lifecycle of a durable memory. ## Retrieval modes Recall ships in `vector` mode by default: pure semantic search, which is what survives the paraphrasing you saw above. If you also need exact name or jargon matching, switch to `hybrid` (vector + BM25) and choose how the two legs are fused: RRF, a vector-biased linear blend, or a cross-encoder reranker. Mode is set per call; fusion is a config setting. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml plugins: lancedb: retrieval: mode: hybrid # vector (default) | hybrid reranker: type: rrf # how the vector + BM25 legs are fused # Swap RRF for a reranking pass (pulls in sentence-transformers + torch): # type: cross-encoder # model: cross-encoder/ettin-reranker-17m-v1 # rerank_top_n: 50 ``` The cross-encoder is the one path that pulls in a local ML stack, so it stays opt-in. It defaults to the compact 17M-parameter [ettin reranker](https://huggingface.co/cross-encoder/ettin-reranker-17m-v1). ## Inspect the store Everything lives in one table named `memories` at `~/.hermes/lancedb/memories.lance`. Because it's a plain LanceDB table, you can open it directly and see exactly what the agent has stored. A `kind` column separates extracted `fact` rows from the raw `turn` rows they were drawn from: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("~/.hermes/lancedb") tbl = db.open_table("memories") print(tbl.to_pandas()[["kind", "category", "content"]].head()) ``` ## Configuration The plugin runs on sensible defaults once activated: you don't have to configure anything. `~/.hermes/config.yaml` is purely for overrides. Two common ones: Use a cheaper model for the auxiliary fact-extraction calls: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml auxiliary: lancedb_extraction: provider: openrouter model: google/gemini-3-flash ``` Point embeddings at a fully local endpoint (for example, Ollama) so nothing leaves your machine: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml plugins: lancedb: embedding: model: nomic-embed-text base_url: http://localhost:11434/v1 api_key_env: OLLAMA_API_KEY # any value works for local Ollama ``` > [!NOTE] > > Changing the embedding model (or its dimension) against an existing store requires recreating > the table. The plugin fails loudly on a dimension mismatch rather than silently returning > nothing. Every option is documented in the plugin's [`default_config.yaml`](https://github.com/lancedb/hermes-agent-memory/blob/main/src/default_config.yaml). ## Benchmark On [LongMemEval-S](https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned), a long-conversation QA benchmark, LanceDB's semantic recall clearly beat Hermes' built-in lexical search (0.66 vs. 0.53 answer accuracy) by finding the right messages even when the question was worded differently from the original conversation. For the full methodology, the per-question-type breakdown, and a reproducible harness, see the [blog post](https://www.lancedb.com/blog/semantic-memory-for-hermes-agent-with-lancedb) and the [benchmark harness](https://github.com/lancedb/hermes-agent-memory/tree/main/benchmarks). ## Why this works well * **It's local-first and embedded.** The LanceDB memory table lives on your disk with no server to run; the plugin installs as a dependency of Hermes' own environment. * **Recall survives paraphrasing.** Semantic search matches meaning, not spelling, which is the failure mode that sinks keyword-only session search. * **Memories are structured and traceable.** Each fact is a row with metadata and a link back to the messages it came from, and `forget` always previews before it deletes. * **Nothing about it is a dead end.** As your needs grow, the same table abstraction carries over to LanceDB [Enterprise](/enterprise/v1-12-0/index#architecture) for automatic compaction, reindexing, and scale. To try it, install the plugin, enable it with `hermes memory setup`, and run the kind of workflow we walked through above. # HuggingFace Hub Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/huggingface Use LanceDB directly on Lance datasets hosted on the HuggingFace Hub for multimodal search and retrieval. **Applies to:** Embedded ✅, Enterprise ✅ [HuggingFace Hub](https://huggingface.co/datasets?format=format:lance\&sort=trending) is a popular platform for sharing machine learning datasets, models, and other resources. LanceDB can directly scan Lance datasets hosted on the [HuggingFace Hub](https://huggingface.co/datasets?format=format:lance) with `hf://` URIs. This is enabled under the hood by the [lance-huggingface](https://lance.org/integrations/huggingface/) integration that allows users to stream Lance datasets directly from HuggingFace without needing to download them first. For ML and AI engineers working in LanceDB, this capability is incredibly useful for quickly exploring multimodal datasets and reusing Lance datasets shared by others, without writing custom data loaders or preprocessing pipelines. The snippets below use the [`lance-format/laion-1m`](https://huggingface.co/datasets/lance-format/laion-1m) dataset published in Lance format. The dataset includes a million image-caption pairs, and the Lance dataset can package image embeddings alongside the metadata. This makes it useful for demonstrating LanceDB's multimodal search capabilities in combination with easy sharing via the HuggingFace Hub. The LAION table includes multimodal columns such as: * `image` (inline JPEG bytes) * `caption` (text) * `img_emb` (image embedding vector) * metadata fields such as `url` and `similarity` ## Install dependencies ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install lancedb pillow ``` ## Open the dataset with LanceDB LanceDB can open the dataset directly from the Hub, without needing to download it first. Note that in LanceDB, you need to specify the table name when opening a Lance dataset, and the HuggingFace convention is to use `train` and `test` splits for datasets. The LAION dataset is uploaded as a single split named `train`, so we specify the table name that contains the `*.lance` files when opening the dataset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") table = db.open_table("train") print(f"Opened table: {table.name}") print(f"Rows: {len(table)}") ``` ## Inspect schema and available indexes ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(table.schema) ``` This prints the schema of the LAION table. Note that there's an image embedding column that's a fixed-size list of 768-dimensional floats, and a binary column containing the raw JPEG bytes of the image. ``` image_path: string caption: string NSFW: string similarity: double LICENSE: string url: string key: string status: string error_message: null width: int64 height: int64 original_width: int64 original_height: int64 exif: string md5: string img_emb: fixed_size_list<item: float>[768] child 0, item: float image: binary ``` When inspecting Lance datasets from HuggingFace, it's also a good idea to check whether the dataset author included any pre-built indexes that you can use for search. You can check the available indexes with: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(table.list_indices()) ``` ``` [ Index(IvfPq, columns=["img_emb"], name="img_emb_idx"), Index(FTS, columns=["caption"], name="caption_idx") ] ``` In this case, we see that we have an IVF_PQ vector index on the `img_emb` column, and an FTS index on the `caption` column, which means we can directly do vector search on the image embeddings and keyword search on the captions without needing to build the indexes ourselves! > [!NOTE] > > If you see an empty list, it may be because the dataset author did not include the index files when uploading > to HuggingFace. You can download the dataset locally, and build the indexes yourself. See the [indexing guide](/enterprise/v1-12-0/indexing/) > for instructions on building different types of indexes with LanceDB. ## Projection scan Run a simple scan by projecting relevant columns to get a feel for the dataset. For example, we can run a search without any filters or input parameters to get a small subset of the data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( table.search() .select(["caption", "url", "similarity"]) .limit(3) .to_list() ) for i, row in enumerate(rows, start=1): print(f"{i}. {row['caption']}") print(f" url={row['url']}") print(f" similarity={row['similarity']}") ``` We get the first three rows and their metadata printed out, which look like this: ``` 1. Cordelia and Dudley on their wedding day last year url=https://i.dailymail.co.uk/i/pix/2012/01/05/article-2082728-0EF8956600000578-53_233x315.jpg similarity=0.2926466464996338 2. Statistics on challenges for automation in 2021 url=https://verloop.io/wp-content/uploads/2021/02/Challenges.jpg similarity=0.30174341797828674 3. Teacher Gifts / Great gifts for your child's teacher. Don't know what to get? Take a look at these gifts that the teacher in your life will love! url=https://i.pinimg.com/custom_covers/216x146/550494823141083777_1487893945.jpg similarity=0.3362061381340027 ``` ## Scan and filter data Filtered search is a common pattern to narrow down interesting subsets of the data during early exploration. Here's an example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered = ( table.search() .where("height > 600") .select(["caption", "url", "width", "height"]) .limit(3) .to_list() ) for row in filtered: print(row["caption"], row["url"], row["width"], row["height"]) ``` This prints out the metadata for large images with height greater than 600 pixels: ``` Luca Trousers, mustard stripe https://cdn.shopify.com/s/files/1/0151/5333/products/IMG_0791_1024x1024.jpg?v=1585142190 384 766 Baby Blue Fitted Short Sleeve T Shirt 3 https://cdn-img.prettylittlething.com/a/d/d/1/add198cab3ec30a61102437275573f4963642528_cmf6022_3.jpg 384 612 pattern cutting made easy pdf https://i.pinimg.com/736x/7c/6c/a7/7c6ca7361815a8929b3dd6ad34a03ab9.jpg 384 1045 ``` ## Export image bytes to local files To work with a subset of the data locally, you can export the image bytes from the table and save them as JPEG files. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pathlib import Path sample = ( table.search() .select(["image", "caption"]) .limit(3) .to_list() ) out_dir = Path("samples") out_dir.mkdir(exist_ok=True) for i, row in enumerate(sample): out_path = out_dir / f"laion_{i}.jpg" with open(out_path, "wb") as f: f.write(row["image"]) print(f"Saved {out_path} | caption={row['caption']}") ``` You can now preview the images you just exported on your local machine to get a better sense of the data. ## Vector search You can use LanceDB to run vector search directly on the data on the Hub, **without needing to download the dataset or build your own vector index**. This makes it incredibly easy to explore the dataset and iterate on your search queries before you decide to download a local copy for further experimentation on your end. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Pick an arbitrary image embedding from the dataset query_embedding = ( table.search() .select(["img_emb"]) .limit(1) .to_list()[0]["img_emb"] ) results = ( table.search(query_embedding, vector_column_name="img_emb") .select(["caption", "url", "_distance"]) .limit(3) .to_list() ) for row in results: print(row["_distance"], row["caption"]) ``` | distance | caption | | - | - | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | > [!WARNING] > > Note that the LAION dataset is known to contain a lot of duplicate images, so you may see the same image > showing up multiple times in the search results. ## Full-text search Run an FTS search query that uses BM25 ranking on the `caption` column (on which we already have an FTS index): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fts_results = ( table.search("dog running on beach", query_type="fts") .select(["caption", "url", "_score"]) .limit(3) .to_list() ) ``` | caption | url | \_score | | - | - | - | | running with dog | [https://www.doggytastic.com/wp…](https://www.doggytastic.com/wp…) | 15.73168 | | Dog Running in Water | [https://static.wixstatic.com/m…](https://static.wixstatic.com/m…) | 14.756516 | | Dogs on the run by heidiannemo… | [http://ih2.redbubble.net/image…](http://ih2.redbubble.net/image…) | 14.756516 | ## Download the full dataset > [!WARNING] > > You may hit HuggingFace rate limits when streaming large samples from `hf://`, despite using a HuggingFace token. > For repeated queries or queries that operate on the full dataset, it's recommended to > download the dataset locally and query from disk. Here's how to download the entire dataset via the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} huggingface-cli download lance-format/laion-1m --repo-type dataset --local-dir ./laion-1m ``` ## Upload your own datasets to HuggingFace in Lance format This section shows how you can upload your own Lance datasets to the HuggingFace Hub to share with the community. First, install the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) and export both `OPENAI_API_KEY` and `HF_TOKEN`. Then, create a Lance dataset using LanceDB on a local machine, and then proceed to upload it to the Hub via a CLI command. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export OPENAI_API_KEY=... export HF_TOKEN=hf_... hf auth login --token "$HF_TOKEN" ``` A typical sequence of steps is given below. ### 1. Upload your local directory to the Hub Upload the full local directory to a specified repository on the HuggingFace Hub. The command below uploads the contents of your local LanceDB directory at `/path/to/your_local_dir` to a new repository named `your_hf_org/repo_name` under your HuggingFace account. ```bash bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` > [!NOTE] > > The `upload-large-folder` command is designed for [uploading large datasets](https://huggingface.co/docs/huggingface_hub/en/guides/upload) (potentially terabytes in size) and will handle multipart uploads, retries, and resuming interrupted uploads. ### 2. Inspect dataset versions Because you can query your remote dataset directly from HuggingFace with `hf://` URIs in LanceDB, you can easily inspect the dataset versions and updates on the Hub without needing to download the data locally. This is very useful to keep track of changes to the dataset and iterate on your data collection and curation process. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("hf://datasets/your_hf_org/repo_name") table = db.open_table("table_name") versions = table.list_versions() print(versions) ``` This will print out the list of versions available for the dataset on the Hub, along with their metadata such as creation date and description. ### 3. Add a dataset card The Hub dataset card allows you to communicate the schema and usage of the dataset to other developers. It sits at the repo's root in a file named `README.md` on the Hub. This project keeps the source card text in `HF_DATASET_CARD.md`, so you can publish updates to the dataset there and upload it as `README.md` using the following command on the HF CLI: this requires a regular `hf upload` because it is a single-file upload to a specific target path (a custom commit message can be added if you wish). ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload lancedb/magical_kingdom HF_DATASET_CARD.md README.md \ --repo-type dataset \ --commit-message "Update dataset card" ``` ### 4. Update the dataset Over time, you may want to add new rows (append) or columns (backfill) to your dataset as your needs evolve. You can make the necessary updates to your local dataset using LanceDB, and then upload the updated version back to the Hub with the same `hf upload-large-folder` command. ```bash bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` The CLI will only upload the new data that has changed since the last upload, avoiding wasted I/O while making it easy to keep your dataset up-to-date on the Hub. That's it! Your dataset is now updated on the Hub with the new data and schema changes, and other users can query the latest version of the dataset directly from HuggingFace with `hf://` URIs in LanceDB. ## Explore more Lance datasets on HuggingFace The LanceDB team is actively uploading useful and interesting datasets in Lance format to the HuggingFace Hub under the [lance-format](https://huggingface.co/lance-format) organization. We actively encourage the HuggingFace and LanceDB communities to upload their own Lance datasets to the Hub to share with others! In the meantime, feel free to check out the HuggingFace Hub to discover more Lance datasets uploaded by the community. > [card] > > Click here to explore the latest trending Lance datasets on 🤗 HuggingFace! > > [Open](https://huggingface.co/datasets?format=format:lance\&sort=trending) # Kiln AI Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/kiln [**Kiln**](https://kiln.tech) is a free tool for building production-ready AI systems, combining an intuitive desktop application and an open-source Python library. It supports RAG pipelines, evaluations, agents, MCP tool-calling, synthetic data generation, and fine-tuning. Kiln provides deep integration with LanceDB for vector search, full-text search (BM25), and hybrid search. ## Quick Start: Build a RAG Pipeline in 5 Minutes with Kiln and LanceDB Watch the [quick start overview on Vimeo](https://vimeo.com/1119945690). Kiln's [app](https://kiln.tech/download) makes it easy to: * Build a RAG pipeline with a simple drag-and-drop interface * [Compare](#find-the-best-rag-pipeline-for-your-use-case) search index options (powered by LanceDB), document extractors, embedding models, and chunking strategies * Create end-to-end [evaluations](https://docs.kiln.tech/docs/evaluations) to determine which search configuration works best for your use case * Load your data from Kiln into [LanceDB Enterprise](/enterprise/v1-12-0/index#architecture) for production use * Iterate with confidence by evaluating new content, prompts, models, and embeddings in minutes instead of weeks ## Find the Best RAG Pipeline for Your Use Case There is no universal best RAG solution, only the best solution for your specific use case. Kiln makes it easy to compare state-of-the-art configurations and find which works best for you. Start with pre-configured templates for state-of-the-art RAG at various performance/quality/cost levels, or experiment with any combination of options: | Area | Technologies | Description | | :- | :- | :- | | Search Index | LanceDB | Compare LanceDB's vector search, full-text search (BM25), and hybrid search to find the best approach for your use case. | | Content | Kiln Document Library | Collaborate on a document library with your team to find the best content for your RAG. Track every revision and tag document sets. | | Document Extraction | Gemini, OpenAI GPT, Qwen VL, and more | Find the most accurate document extraction models for converting PDFs, images, audio, video, and other formats into textual data for RAG. | | Embeddings | Embedding models from Gemini, OpenAI, Nomic, Qwen, and more | Find the embedding model best suited to your use case. | | Chunking | LlamaIndex | Find the ideal chunk size and method. | ## Get Started To get started, download the [Kiln App](https://kiln.tech/download), create a project, and navigate to "Docs & Search". See the [Kiln documentation for creating a RAG system](https://docs.kiln.tech/docs/documents-and-search-rag) for details on each step of the process. ## More Information * [Kiln Homepage](https://kiln.tech) * [Download the Kiln App](https://kiln.tech/download) * [Kiln GitHub Repository](https://github.com/Kiln-AI/Kiln) * [Building RAG Systems - Kiln Documentation](https://docs.kiln.tech/docs/documents-and-search-rag) * [Python Library](https://pypi.org/project/kiln-ai/) or `pip install kiln_ai` # LangChain Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/langchain **LangChain** is a framework designed for building applications with large language models (LLMs) by chaining together various components. It supports a range of functionalities including memory, agents, and chat models, enabling developers to create context-aware applications. ![Illustration](https://raw.githubusercontent.com/lancedb/assets/refs/heads/main/docs/assets/integration/langchain_rag.png) LangChain streamlines these stages (in figure above) by providing pre-built components and tools for integration, memory management, and deployment, allowing developers to focus on application logic rather than underlying complexities. Integration of **LangChain** with **LanceDB** enables applications to retrieve the most relevant data by comparing query vectors against stored vectors, facilitating effective information retrieval. It results in better and context aware replies and actions by the LLMs. ## Quick Start You can load your document data using langchain's loaders, for this example we are using `TextLoader` and `OpenAIEmbeddings` as the embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from langchain.document_loaders import TextLoader from langchain.vectorstores import LanceDB from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter os.environ["OPENAI_API_KEY"] = "sk-..." loader = TextLoader( "../../modules/state_of_the_union.txt" ) # Replace with your data path documents = loader.load() documents = CharacterTextSplitter().split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = LanceDB.from_documents(documents, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) print(docs[0].page_content) ``` ## Documentation In the above example `LanceDB` vector store class object is created using `from_documents()` method which is a `classmethod` and returns the initialized class object. You can also use `LanceDB.from_texts(texts: List[str],embedding: Embeddings)` class method. The exhaustive list of parameters for `LanceDB` vector store are : | Name | type | Purpose | default | | :- | :- | :- | :- | | `connection` | (Optional) `Any` | `lancedb.db.LanceDBConnection` connection object to use. If not provided, a new connection will be created. | `None` | | `embedding` | (Optional) `Embeddings` | LangChain embedding model. | Provided by user. | | `uri` | (Optional) `str` | It specifies the directory location of **LanceDB database** and establishes a connection that can be used to interact with the database. | `/tmp/lancedb` | | `vector_key` | (Optional) `str` | Column name to use for vector's in the table. | `'vector'` | | `id_key` | (Optional) `str` | Column name to use for id's in the table. | `'id'` | | `text_key` | (Optional) `str` | Column name to use for text in the table. | `'text'` | | `table_name` | (Optional) `str` | Name of your table in the database. | `'vectorstore'` | | `api_key` | (Optional `str`) | API key to use for LanceDB Enterprise deployment. | `None` | | `region` | (Optional) `str` | Region to use for LanceDB Enterprise deployment. | Only for LanceDB Enterprise : `None`. | | `mode` | (Optional) `str` | Mode to use for adding data to the table. Valid values are "append" and "overwrite". | `'overwrite'` | | `table` | (Optional) `Any` | You can connect to an existing table of LanceDB, created outside of LangChain, and use it. | `None` | | `distance` | (Optional) `str` | The choice of distance metric used to calculate the similarity between vectors. | `'l2'` | | `reranker` | (Optional) `Any` | The reranker to use for LanceDB. | `None` | | `relevance_score_fn` | (Optional) `Callable[[float], float]` | LangChain relevance score function to be used. | `None` | | `limit` | `int` | Set the maximum number of results to return. | `DEFAULT_K` (it is 4) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db_url = "db://lang_test" # url of db you created api_key = "xxxxx" # your API key region = "us-east-1-dev" # your selected region vector_store = LanceDB( uri=db_url, api_key=api_key, # (dont include for local API) region=region, # (dont include for local API) embedding=embeddings, table_name="langchain_test", # Optional ) ``` ### Methods ##### `add_texts()` This method turn texts into embedding and add it to the database. | Name | Purpose | defaults | | :- | :- | :- | | `texts` | `Iterable` of strings to add to the vectorstore. | Provided by user | | `metadatas` | Optional `list[dict()]` of metadatas associated with the texts. | `None` | | `ids` | Optional `list` of ids to associate with the texts. | `None` | | `kwargs` | Other keyworded arguments provided by the user. | - | It returns list of ids of the added texts. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} vector_store.add_texts(texts=["test_123"], metadatas=[{"source": "wiki"}]) # Additionally, to explore the table you can load it into a df or save it in a csv file: tbl = vector_store.get_table() print("tbl:", tbl) pd_df = tbl.to_pandas() pd_df.to_csv("docsearch.csv", index=False) # you can also create a new vector store object using an older connection object: vector_store = LanceDB(connection=tbl, embedding=embeddings) ``` With LanceDB Enterprise, `tbl.to_pandas()` raises in the synchronous Python client; read the rows with a query instead, such as `tbl.search().limit(100).to_pandas()`. *** ##### create_index() This method creates a scalar(for non-vector cols) or a vector index on a table. | Name | type | Purpose | defaults | | :- | :- | :- | :- | | `vector_col` | `Optional[str]` | Provide if you want to create index on a vector column. | `None` | | `col_name` | `Optional[str]` | Provide if you want to create index on a non-vector column. | `None` | | `metric` | `Optional[str]` | Provide the metric to use for vector index. choice of metrics: 'l2', 'dot', 'cosine'. | `l2` | | `num_partitions` | `Optional[int]` | Number of partitions to use for the index. | `256` | | `num_sub_vectors` | `Optional[int]` | Number of sub-vectors to use for the index. | `96` | | `index_cache_size` | `Optional[int]` | Size of the index cache. | `None` | | `name` | `Optional[str]` | Name of the table to create index on. | `None` | For index creation make sure your table has enough data in it. An ANN index is usually not needed for datasets \~100K vectors. For large-scale (>1M) or higher dimension vectors, it is beneficial to create an ANN index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # for creating vector index vector_store.create_index(vector_col="vector", metric="cosine") # for creating scalar index(for non-vector columns) vector_store.create_index(col_name="text") ``` *** ##### similarity_search() This method performs similarity search based on **text query**. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | A `str` representing the text query that you want to search for in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `fts` | `Optional[bool]` | It indicates whether to perform a full-text search (FTS). | `False` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. If not provided, it uses the default table set during the initialization of the LanceDB instance. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | Return documents most similar to the query **without relevance scores**. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search(query) print(docs[0].page_content) ``` *** ##### similarity_search_by_vector() The method returns documents that are most similar to the specified **embedding (query) vector**. | Name | Type | Purpose | Default | | - | - | - | - | | `embedding` | `List[float]` | The embedding vector you want to use to search for similar documents in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. If not provided, it uses the default table set during the initialization of the LanceDB instance. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | **It does not provide relevance scores.** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search_by_vector(query) print(docs[0].page_content) ``` *** ##### similarity_search_with_score() Returns documents most similar to the **query string** along with their relevance scores. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | A `str` representing the text query you want to search for in the vector store. This query will be converted into an embedding using the specified embedding function. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. This allows you to narrow down the search results based on certain metadata attributes associated with the documents. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | It gets called by base class's `similarity_search_with_relevance_scores` which selects relevance score based on our `_select_relevance_score_fn`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search_with_relevance_scores(query) print("relevance score - ", docs[0][1]) print("text- ", docs[0][0].page_content[:1000]) ``` *** ##### similarity_search_by_vector_with_relevance_scores() Similarity search using **query vector**. | Name | Type | Purpose | Default | | - | - | - | - | | `embedding` | `List[float]` | The embedding vector you want to use to search for similar documents in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | The method returns documents most similar to the specified embedding (query) vector, along with their relevance scores. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_embedding = embeddings.embed_query("text") docs = docsearch.similarity_search_by_vector_with_relevance_scores(query_embedding) print("relevance score - ", docs[0][1]) print("text- ", docs[0][0].page_content[:1000]) ``` *** ##### max_marginal_relevance_search() This method returns docs selected using the maximal marginal relevance(MMR). Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | Text to look up documents similar to. | N/A | | `k` | `Optional[int]` | Number of Documents to return. | `4` | | `fetch_k` | `Optional[int]` | Number of Documents to fetch to pass to MMR algorithm. | `None` | | `lambda_mult` | `float` | Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. | `0.5` | | `filter` | `Optional[Dict[str, str]]` | Filter by metadata. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | Similarly, `max_marginal_relevance_search_by_vector()` function returns docs most similar to the embedding passed to the function using MMR. instead of a string query you need to pass the embedding to be searched for. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = docsearch.max_marginal_relevance_search(query="text") result_texts = [doc.page_content for doc in result] print(result_texts) # search by vector : result = docsearch.max_marginal_relevance_search_by_vector( embeddings.embed_query("text") ) result_texts = [doc.page_content for doc in result] print(result_texts) ``` *** ##### add_images() This method adds images by automatically creating their embeddings and adds them to the vectorstore. | Name | Type | Purpose | Default | | - | - | - | - | | `uris` | `List[str]` | File path to the image | N/A | | `metadatas` | `Optional[List[dict]]` | Optional list of metadatas | `None` | | `ids` | `Optional[List[str]]` | Optional list of IDs | `None` | It returns list of IDs of the added images. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} image_uris = ["./assets/image-1.png", "./assets/image-2.png"] vector_store.add_images(uris=image_uris) # here image_uris are local fs paths to the images. ``` # LlamaIndex Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/llamaIndex ## Quickstart LlamaIndex is a well-known framework for building LLM-powered agents over your data with LLMs and workflows. You can build your LlamaIndex pipeline and persist your metadata and embeddings in LanceDB via the `LanceDBVectorStore` class. First, install the LlamaIndex-LanceDB integration. pip install llama-index-vector-stores-LanceDB Run the below script as an example. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import logging import sys import textwrap import openai # Uncomment to see debug logs # logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) # logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( Document, SimpleDirectoryReader, StorageContext, VectorStoreIndex, ) from llama_index.vector_stores.lancedb import LanceDBVectorStore openai.api_key = "sk-..." documents = SimpleDirectoryReader("./data/your-data-dir/").load_data() print("Document ID:", documents[0].doc_id, "Document Hash:", documents[0].hash) ## For LanceDB Enterprise : # vector_store = LanceDBVectorStore( # uri="db://db_name", # your remote DB URI # api_key="sk_..", # lancedb enterprise api key # region="your-region" # the region you configured # host_override="https://your-host.com" # if you have a custom host, otherwise omit this # ) vector_store = LanceDBVectorStore( uri="./lancedb", mode="overwrite", query_type="vector" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents(documents, storage_context=storage_context) lance_filter = "metadata.file_name = 'paul_graham_essay.txt' " retriever = index.as_retriever(vector_store_kwargs={"where": lance_filter}) response = retriever.retrieve("What did the author do growing up?") ``` The vector store connector will open an existing LanceDB directory or create the directory if it does not exist. ### Filtering For metadata filtering, you can use a Lance SQL-like string filter as demonstrated in the example above. Additionally, you can also filter using the `MetadataFilters` class from LlamaIndex: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from llama_index.core.vector_stores import ( FilterCondition, FilterOperator, MetadataFilter, MetadataFilters, ) query_filters = MetadataFilters( filters=[ MetadataFilter( key="creation_date", operator=FilterOperator.EQ, value="2024-05-23" ), MetadataFilter(key="file_size", value=75040, operator=FilterOperator.GT), ], condition=FilterCondition.AND, ) ``` ### Hybrid Search For complete documentation, refer [here](/enterprise/v1-12-0/search/hybrid-search). This example uses the `colbert` reranker. Make sure to install necessary dependencies for the reranker you choose. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.rerankers import ColbertReranker reranker = ColbertReranker() vector_store._add_reranker(reranker) query_engine = index.as_query_engine( filters=query_filters, vector_store_kwargs={ "query_type": "hybrid", }, ) response = query_engine.query("How much did Viaweb charge per month?") ``` In the snippet above, you can change/specify `query_type` when creating the engine/retriever to use different search strategies, such as vector search or FTS. ## API reference > [card] [LlamaIndex Vector Stores API reference](https://developers.llamaindex.ai/python/framework-api-reference/storage/vector_store/lancedb/) > > See the official LlamaIndex Vector Stores API reference for more details. # PromptTools Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/prompttools [PromptTools](https://github.com/hegelai/prompttools) offers a set of free, open-source tools for testing and experimenting with models, prompts, and configurations. The core idea is to enable developers to evaluate prompts using familiar interfaces like code and notebooks. You can use it to experiment with different configurations of LanceDB, and test how LanceDB integrates with the LLM of your choice. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/prompttools-eval-prompts/main.ipynb) ![Alt text](https://prompttools.readthedocs.io/en/latest/_images/demo.gif "a title") # Meta Llama Synthetic Data Kit Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/synthetic-data-kit Use Meta Llama's Synthetic Data Kit with LanceDB to generate high-quality synthetic datasets for LLM fine-tuning and training. [Synthetic Data Kit](https://github.com/meta-llama/synthetic-data-kit) is a tool from Meta LLAMA that helps you generate high-quality synthetic datasets for fine-tuning large language models (LLMs). It simplifies the process of preparing data for fine-tuning by providing a command-line interface (CLI) with a modular four-command flow. One of the key features of the `synthetic-data-kit` is its use of the Lance format for storing and ingesting datasets. This allows for efficient storage and retrieval of data, which is crucial when working with large datasets. ### Key Features: * **Data Ingestion:** The toolkit can ingest various file formats, including PDF, HTML, YouTube transcripts, DOCX, PPT, and TXT. * **Fine-tuning Format Creation:** It can create different fine-tuning formats, such as question-answer (QA) pairs, QA pairs with Chain-of-Thought (CoT), and summarization formats. * **Data Curation:** The tool uses Llama as a judge to curate high-quality examples, ensuring the quality of the generated dataset. * **Flexible Saving Options:** You can save the generated datasets in various formats compatible with your fine-tuning workflow, including HuggingFace, JSONL, and JSON. ### How it Works: The synthetic-data-kit follows a simple four-step process: 1. **Ingest:** Import your input files into the toolkit. The data is stored in the Lance format for efficient processing. 2. **Create:** Generate diverse fine-tuning datasets, such as reasoning, summarization, and QA pairs, from the ingested documents. 3. **Curate:** Use Llama to filter and select high-quality examples from the generated dataset. 4. **Save-as:** Export the curated dataset in your preferred format. ### Usage The `synthetic-data-kit` uses Lance format to store and manage the data that you ingest. The workflow is a series of commands that build on each other, starting with the `ingest` command. Here is an example of the end-to-end workflow: 1. **Ingest Data into a LanceDB dataset** This command reads a source document and creates a Lance dataset from it. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit ingest docs/report.pdf --multimodal # This will create a Lance dataset at data/parsed/report.lance # with 'text' and 'image' columns. ``` 2. **Create fine-tuning data** This command uses the Lance dataset created in the previous step to generate multimodal question-answer pairs. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit create data/parsed/report.lance --type multimodal-qa # This writes data/generated/report.json ``` 3. **Curate the data** This step uses a language model to curate the generated data and ensure its quality. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit curate data/generated/report.json # This writes data/curated/report_cleaned.json ``` 4. **Save the final dataset** Finally, save the curated data in the format you need: `jsonl`, `alpaca`, `ft` or `chatml`. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit save-as data/curated/report_cleaned.json -f jsonl -o ./my_finetuning_data.jsonl ``` This workflow allows you to go from a collection of documents to a high-quality, fine-tuning dataset with just a few commands. The use of LanceDB in the background makes the process efficient and scalable. ### Getting Started: To get started with the synthetic-data-kit, you can clone the [GitHub Repository](https://github.com/meta-llama/synthetic-data-kit) and install the necessary dependencies. > **Note:** You will also need access to a Llama model, either running locally or via a hosted API. # VS Code extensions Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/ai/vscode Embed LanceDB in a VS Code extension to search a workspace by meaning, with no server, and bundle and package its native binaries correctly. A VS Code extension runs in the *extension host*, a Node.js process, so LanceDB's TypeScript SDK (`@lancedb/lancedb`) runs inside it like any other npm package. There's no database server to start: the extension opens a table on local disk and queries it in-process. That makes LanceDB a good fit for features such as semantic search over a workspace, retrieval for an AI assistant, or a cache of embeddings that survives restarts. The extension host differs from a plain Node.js script in three ways that trip people up: * **Where you can write.** Relative paths resolve against the extension host's working directory, not the workspace, and that directory may be read-only. * **Bundling.** The default extension template bundles everything with esbuild, which can't bundle LanceDB's native `.node` binary. * **Packaging.** LanceDB installs a native binary for the current platform only, so a VSIX built on one OS doesn't run on another. This guide builds a small extension that handles all three. It indexes the Markdown files in a workspace and searches them by meaning, using a local embedding model, so no API key is needed. > [!NOTE] > > **What you'll build** > > * **LanceDB: Index Markdown in Workspace** splits every `*.md` file into paragraphs and stores > them in a LanceDB table, with embeddings from `Xenova/all-MiniLM-L6-v2` run locally through > Transformers.js. > * **LanceDB: Search Markdown** embeds your query, shows the five closest paragraphs, and opens > the one you pick. ## Create the extension **1. Scaffold a TypeScript extension** Use the official generator. Choose **New Extension (TypeScript)** and **esbuild** as the bundler. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx --package yo --package generator-code -- yo code ``` **2. Install LanceDB** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb apache-arrow@18.1.0 ``` Your code imports Arrow types directly, so add `apache-arrow` as a dependency, pinned inside LanceDB's peer dependency range (`>=15.0.0 <=18.1.0`). If the project already depends on a newer `apache-arrow`, installing LanceDB fails with `ERESOLVE`. LanceDB also needs `@types/node` 22 or later. The generator's template already uses a recent version; an old one causes `Cannot find module 'node:stream'` errors. You don't need to install `@huggingface/transformers` yourself. LanceDB pins it as an optional dependency, and installing a different version gives your code a copy that LanceDB doesn't use. **3. Skip type checking of dependencies** The type declarations of `apache-arrow` and the ONNX runtime used by Transformers.js refer to browser types such as `ReadableStreamReadResult` and `HTMLCanvasElement`. The template's `tsconfig.json` doesn't include the DOM library, so `tsc` reports errors inside `node_modules`. Turn on `skipLibCheck`: ```json tsconfig.json icon="brackets-curly" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "compilerOptions": { "skipLibCheck": true } } ``` ## Store the database in extension storage Give LanceDB an absolute path inside the storage VS Code reserves for your extension: * `context.storageUri`: a folder for the current workspace. It's `undefined` when no folder is open. Use it for anything derived from the workspace, such as this index. * `context.globalStorageUri`: a folder shared by all workspaces. Use it for things like downloaded models. Neither folder is guaranteed to exist, so create it before connecting. Both live outside the user's project, so the index never shows up in their files or in version control. Don't pass a relative path such as `lancedb.connect("data")`. It resolves against the extension host's working directory, which isn't the workspace and may be read-only: this causes the `Read-only file system (os error 30)` error on macOS. Put the LanceDB code in its own module, `src/search.ts`: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as path from "node:path"; import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/transformers"; import { Int32, Utf8 } from "apache-arrow"; ``` ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Pass an absolute directory, such as `context.storageUri.fsPath`. A relative // path resolves against the extension host's working directory, which is not // your workspace and may be read-only (on macOS it is usually `/`). export async function openDatabase(storageDir: string) { return lancedb.connect(path.join(storageDir, "lancedb")); } ``` ## Index and search Split each file into paragraphs, and keep the line each one starts on so a result can open the file at the right place: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export type Chunk = { path: string; line: number; text: string }; // Split a Markdown file into paragraphs, keeping the line each one starts on // so a search result can jump straight to it. export function chunkMarkdown(filePath: string, content: string): Chunk[] { const lines = content.split(/\r?\n/); const chunks: Chunk[] = []; let start = 0; for (let i = 0; i <= lines.length; i++) { if (i === lines.length || lines[i].trim() === "") { const text = lines.slice(start, i).join("\n").trim(); if (text) { chunks.push({ path: filePath, line: start, text }); } start = i + 1; } } return chunks; } ``` Create the table with LanceDB's built-in `huggingface` [embedding function](/enterprise/v1-12-0/embedding/quickstart). Because the `text` column is declared as the function's source field, LanceDB computes the `vector` column for you as the rows are written: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) { // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed. const embedder = (await lancedb.embedding .getRegistry() .get("huggingface") ?.create()) as lancedb.embedding.EmbeddingFunction; const schema = lancedb.embedding.LanceSchema({ path: new Utf8(), line: new Int32(), text: embedder.sourceField(new Utf8()), vector: embedder.vectorField(), }); // LanceDB fills in the `vector` column from `text` as the rows are written. return db.createTable("chunks", chunks, { schema, mode: "overwrite" }); } ``` The table remembers its embedding function, so you can search it with plain text after VS Code restarts: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export async function searchChunks( db: lancedb.Connection, query: string, limit = 5, ) { // The table stores its embedding function in its metadata, so a text query // is embedded with the same model that embedded the rows. const table = await db.openTable("chunks"); return table .search(query) .select(["path", "line", "text", "_distance"]) .limit(limit) .toArray(); } ``` `mode: "overwrite"` rebuilds the index each time, which is fine for a few thousand paragraphs. For larger workspaces, update only the files that changed with [`mergeInsert`](/enterprise/v1-12-0/ingestion/merge-insert). ## Wire up the commands Declare the two commands in `package.json`: ```json package.json icon="brackets-curly" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} "contributes": { "commands": [ { "command": "lancedbSearch.index", "title": "Index Markdown in Workspace", "category": "LanceDB" }, { "command": "lancedbSearch.search", "title": "Search Markdown", "category": "LanceDB" } ] } ``` Then register them in `src/extension.ts`: ```typescript src/extension.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as vscode from "vscode"; import { type Chunk, chunkMarkdown, indexChunks, openDatabase, searchChunks, } from "./search"; export async function activate(context: vscode.ExtensionContext) { // One index per workspace. `storageUri` is undefined when no folder is open. const storage = context.storageUri ?? context.globalStorageUri; // Transformers.js downloads the embedding model on first use. Keep it in // global storage so every workspace shares one copy and it survives // extension updates. Use `import()`: LanceDB loads the ES module build, and // `require()` would return a separate copy whose settings LanceDB never sees. const { env } = await import("@huggingface/transformers"); env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, "models").fsPath; context.subscriptions.push( vscode.commands.registerCommand("lancedbSearch.index", async () => { const files = await vscode.workspace.findFiles( "**/*.md", "**/node_modules/**", ); const chunks: Chunk[] = []; for (const file of files) { const bytes = await vscode.workspace.fs.readFile(file); // Store the file's URI, not a path relative to its folder: in a // multi-root workspace `findFiles` searches every folder, and only the // URI says which one a result came from. chunks.push( ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)), ); } if (chunks.length === 0) { vscode.window.showWarningMessage("No Markdown files to index."); return 0; } await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: `Indexing ${files.length} Markdown files`, }, async () => { await vscode.workspace.fs.createDirectory(storage); await indexChunks(await openDatabase(storage.fsPath), chunks); }, ); vscode.window.showInformationMessage( `Indexed ${chunks.length} paragraphs from ${files.length} files.`, ); return chunks.length; }), // Called with a query (for example from a test or another extension), the // command returns the matching rows instead of showing a picker. vscode.commands.registerCommand( "lancedbSearch.search", async (query?: string) => { const text = query ?? (await vscode.window.showInputBox({ prompt: "Search Markdown by meaning", })); if (!text) { return []; } const results = await searchChunks( await openDatabase(storage.fsPath), text, ); if (query !== undefined) { return results; } const picked = await vscode.window.showQuickPick( results.map((row) => { const uri = vscode.Uri.parse(row.path); return { label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`, description: `distance ${row._distance.toFixed(3)}`, detail: row.text, uri, line: row.line, }; }), { placeHolder: text, matchOnDetail: true }, ); if (picked) { const editor = await vscode.window.showTextDocument(picked.uri); const start = new vscode.Position(picked.line, 0); editor.selection = new vscode.Selection(start, start); editor.revealRange( new vscode.Range(start, start), vscode.TextEditorRevealType.InCenter, ); } return results; }, ), ); } export function deactivate() {} ``` A few details in this file are specific to running inside VS Code: * The index goes in `storageUri`, so each workspace gets its own table. * The embedding model (about 90 MB) downloads on first use. By default Transformers.js caches it inside `node_modules` in the installed extension, which is replaced on every update. Setting `env.cacheDir` keeps it in global storage. Load the module with `import()`, not `require()`: LanceDB loads the ES module build of `@huggingface/transformers`, and `require()` returns a separate copy whose settings LanceDB never sees. * Each paragraph is stored with its file's URI, not a path relative to a workspace folder. In a multi-root workspace, `findFiles` searches every folder and two folders can hold the same relative path, so only the URI opens the right file. `asRelativePath` turns it back into a short label, which names the folder when there's more than one. * When another extension or a test passes a query to `lancedbSearch.search`, it returns the rows instead of opening a picker. That's how the results below were produced, with each URI shown through `asRelativePath`. ## Sample results Here are the results of running the extension in VS Code against a small workspace of six Markdown files that document a fictional CLI. The columns are the vector distance (lower is closer), the file and line, and the paragraph. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query: my credentials were exposed, what should I do? 33.100 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. 40.091 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. 42.334 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. 43.105 docs/auth.md:3 Acme uses personal access tokens. Create one under Settings > Tokens. 45.664 README.md:5 Install it with `npm install -g acme-cli`, then run `acme login`. query: uploads are stuck behind the company firewall 38.420 docs/troubleshooting.md:3 If `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443. 39.212 docs/sync.md:3 Run `acme sync` to upload changed notes. Only files modified since the last sync are sent. 40.859 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. 42.537 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. 45.853 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. ``` Neither top result shares a keyword with its query: "credentials were exposed" matches "a token leaks", and "stuck behind the company firewall" matches "hangs … proxy". Picking a result in the search box opens the file at that paragraph. ## Bundle with esbuild The template bundles your code and its dependencies into `dist/extension.js`. esbuild can't bundle native binaries, so building with LanceDB fails with `No loader is configured for ".node" files`. Mark the packages that load native code as external so they're loaded from `node_modules` at runtime: ```javascript esbuild.js icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} external: [ "vscode", "@lancedb/lancedb", "@huggingface/transformers", // LanceDB loads apache-arrow from node_modules anyway; bundling it ships a second copy. "apache-arrow", ], ``` External packages must be in the VSIX, but the template's `.vscodeignore` excludes `node_modules/**`. Delete that line. `vsce` then includes your production dependencies and leaves out the dev dependencies. If you skip this step, the packaged extension fails to activate with `Cannot find module '@lancedb/lancedb'`, and its commands report `command 'lancedbSearch.index' not found`. ## Package a VSIX for each platform npm installs LanceDB's native binary only for the machine it runs on, such as `@lancedb/lancedb-win32-x64-msvc` on 64-bit Windows. Build one VSIX per platform, each on a matching machine or CI runner, and publish them all. The Marketplace serves each user the right one. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx @vscode/vsce package --target win32-x64 ``` | `vsce` target | LanceDB native package | | :- | :- | | `win32-x64` | `@lancedb/lancedb-win32-x64-msvc` | | `win32-arm64` | `@lancedb/lancedb-win32-arm64-msvc` | | `linux-x64` | `@lancedb/lancedb-linux-x64-gnu` | | `linux-arm64` | `@lancedb/lancedb-linux-arm64-gnu` | | `alpine-x64` | `@lancedb/lancedb-linux-x64-musl` | | `alpine-arm64` | `@lancedb/lancedb-linux-arm64-musl` | | `darwin-arm64` | `@lancedb/lancedb-darwin-arm64` | LanceDB doesn't publish a binary for Intel Macs (`darwin-x64`). The table covers LanceDB's own binaries. This sample's local model also needs `onnxruntime-node`, which Transformers.js loads when the extension activates. Its Linux binaries link against glibc and it publishes no musl build, so the sample as written doesn't run on Alpine, whatever `--target` you pass. To ship the `alpine-*` targets, embed with a hosted API or use [full-text search](/enterprise/v1-12-0/search/full-text-search) instead, or build ONNX Runtime for musl yourself. > [!TIP] > > Native binaries make the VSIX large: the `win32-x64` build of this extension is about 200 MB. > `onnxruntime-node`, which Transformers.js uses, ships binaries for every platform. Excluding > the ones a target doesn't need brings the `win32-x64` build to about 150 MB. Keep one ignore > file per target and pass it with `--ignoreFile`: > > ```text .vscodeignore.win32-x64 theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > node_modules/onnxruntime-node/bin/napi-v3/darwin/** > node_modules/onnxruntime-node/bin/napi-v3/linux/** > node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/** > ``` > > If you don't need a local model, embed text with a hosted API instead, or use > [full-text search](/enterprise/v1-12-0/search/full-text-search), which needs no model at all. ## Keep the extension host responsive All extensions share one extension host, and loading the model and computing embeddings in it can stall the others. While the sample indexes, VS Code may briefly report that the extension host is unresponsive. That's fine for a handful of files. For a large workspace, move indexing into a [worker thread](https://nodejs.org/api/worker_threads.html) or a child process, and index in batches as files change instead of all at once. ## Troubleshooting | Error | Cause | Fix | | :- | :- | :- | | `Read-only file system (os error 30)` | A relative database path resolved against the extension host's working directory | Connect to an absolute path under `context.storageUri` or `context.globalStorageUri` | | `No loader is configured for ".node" files` | esbuild tried to bundle a native binary | Mark `@lancedb/lancedb` and `@huggingface/transformers` as `external` | | `Cannot find module '@lancedb/lancedb'`, or `command '…' not found` | The VSIX doesn't contain `node_modules` | Remove `node_modules/**` from `.vscodeignore` | | A native module isn't found on another OS | The VSIX was built on a different platform | Package one VSIX per `--target` on a matching machine | | `Cannot find module 'node:stream' or its corresponding type declarations` | `@types/node` is too old | Use `@types/node` 22 or later | | `Cannot find name 'HTMLCanvasElement'` and similar errors in `node_modules` | Dependency typings refer to DOM types | Set `"skipLibCheck": true` | | `ERESOLVE` with `peer apache-arrow@">=15.0.0 <=18.1.0"` | The project depends on a newer `apache-arrow` | Install `apache-arrow@18.1.0` | | The model downloads again after an update | Transformers.js caches inside the extension's `node_modules` | Set `env.cacheDir` through `import("@huggingface/transformers")` | # dlt Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/dlt [dlt](https://dlthub.com/docs/intro) is an open-source library that you can add to your Python scripts to load data from various and often messy data sources into well-structured, live datasets. dlt's [integration with LanceDB](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb) lets you ingest data from any source (databases, APIs, CSVs, dataframes, JSONs, and more) into LanceDB with a few lines of simple python code. The integration enables automatic normalization of nested data, schema inference, incremental loading and embedding the data. dlt also has integrations with several other tools like dbt, airflow, dagster etc. that can be inserted into your LanceDB workflow. ## How to ingest data into LanceDB In this example, we will be fetching movie information from the [Open Movie Database (OMDb) API](https://www.omdbapi.com/) and loading it into a local LanceDB instance. To implement it, you will need an API key for the OMDb API (which can be created freely [here](https://www.omdbapi.com/apikey.aspx)). 1. **Install `dlt` with LanceDB extras:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install dlt[lancedb] ``` 2. **Inside an empty directory, initialize a `dlt` project with:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dlt init rest_api lancedb ``` This will add all the files necessary to create a `dlt` pipeline that can ingest data from any REST API (ex: OMDb API) and load into LanceDB. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ├── .dlt │ ├── config.toml │ └── secrets.toml ├── rest_api ├── rest_api_pipeline.py └── requirements.txt ``` dlt has a list of pre-built [sources](https://dlthub.com/docs/dlt-ecosystem/verified-sources/) like [SQL databases](https://dlthub.com/docs/dlt-ecosystem/verified-sources/sql_database), [REST APIs](https://dlthub.com/docs/dlt-ecosystem/verified-sources/rest_api), [Google Sheets](https://dlthub.com/docs/dlt-ecosystem/verified-sources/google_sheets), [Notion](https://dlthub.com/docs/dlt-ecosystem/verified-sources/notion) etc., that can be used out-of-the-box by running `dlt init <source_name> lancedb`. Since dlt is a python library, it is also very easy to modify these pre-built sources or to write your own custom source from scratch. 3. **Specify necessary credentials and/or embedding model details:** To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB Embedded or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. dlt's LanceDB integration also allows you to automatically embed the data during ingestion. Depending on the embedding model chosen, you may need to paste the necessary credentials inside `.dlt/secrets.toml`: ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [sources.rest_api] api_token = "api_token" # Enter the API key for the OMDb API [destination.lancedb] embedding_model_provider = "sentence-transformers" embedding_model = "all-MiniLM-L6-v2" [destination.lancedb.credentials] uri = ".lancedb" api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB Embedded. embedding_model_provider_api_key = "embedding_model_provider_api_key" # Not needed for providers that don't need authentication (ollama, sentence-transformers). ``` See [here](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb#configure-the-destination) for more information and for a list of available models and model providers. 4. **Write the pipeline code inside `rest_api_pipeline.py`:** The following code shows how you can configure dlt's REST API source to connect to the [OMDb API](https://www.omdbapi.com/), fetch all movies with the word "godzilla" in the title, and load it into a LanceDB table. The REST API source allows you to pull data from any API with minimal code, to learn more read the [dlt docs](https://dlthub.com/docs/dlt-ecosystem/verified-sources/rest_api). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Import necessary modules import dlt from rest_api import rest_api_source # Configure the REST API source movies_source = rest_api_source( { "client": { "base_url": "https://www.omdbapi.com/", "auth": { # authentication strategy for the OMDb API "type": "api_key", "name": "apikey", "api_key": dlt.secrets[ "sources.rest_api.api_token" ], # read API credentials directly from secrets.toml "location": "query", }, "paginator": { # pagination strategy for the OMDb API "type": "page_number", "base_page": 1, "total_path": "totalResults", "maximum_page": 5, }, }, "resources": [ # list of API endpoints to request { "name": "movie_search", "endpoint": { "path": "/", "params": { "s": "godzilla", "type": "movie", }, }, } ], } ) if __name__ == "__main__": # Create a pipeline object pipeline = dlt.pipeline( pipeline_name="movies_pipeline", destination="lancedb", # this tells dlt to load the data into LanceDB dataset_name="movies_data_pipeline", ) # Run the pipeline load_info = pipeline.run(movies_source) # pretty print the information on data that was loaded print(load_info) ``` The script above will ingest the data into LanceDB as it is, i.e. without creating any embeddings. If we want to embed one of the fields (for example, `"Title"` that contains the movie titles), then we will use dlt's `lancedb_adapter` and modify the script as follows: * Add the following import statement: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from dlt.destinations.adapters import lancedb_adapter ``` * Modify the pipeline run like this: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} load_info = pipeline.run( lancedb_adapter( movies_source, embed="Title", ) ) ``` This will use the embedding model specified inside `.dlt/secrets.toml` to embed the field `"Title"`. 5. **Install necessary dependencies:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install -r requirements.txt ``` Note: You may need to install the dependencies for your embedding models separately. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install sentence-transformers ``` 6. **Run the pipeline:** Finally, running the following command will ingest the data into your LanceDB instance. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python rest_api_pipeline.py ``` For more information and advanced usage of dlt's LanceDB integration, read [the dlt documentation](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb). # DuckDB Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/duckdb Learn how to use the DuckDB-Lance extension to query Lance tables with SQL. LanceDB integrates with [DuckDB](https://duckdb.org/) through the [Lance extension](https://github.com/lance-format/lance-duckdb) for DuckDB. In this page, we'll show how LanceDB manages table lifecycle, and DuckDB provides SQL analytics (including joins) and search over those tables. Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for LanceDB Embedded tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. ## Install Install the DuckDB CLI as per [their docs](https://duckdb.org/install) and alternatively, their Python package with `pip install duckdb`. Then, open the DuckDB CLI and install and load the Lance extension as follows: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSTALL lance; LOAD lance; ``` ## Attach the directory namespace in DuckDB Attach the LanceDB root directory as a Lance namespace: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH './local_lancedb' AS lance_ns (TYPE LANCE); ``` In this page, tables are referenced using `lance_ns.main.<table_name>`, so the table path is `lance_ns.main.lance_duck`. ## Write Lance table Create the `lance_duck` table using SQL and populate it with sample data: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE OR REPLACE TABLE lance_ns.main.lance_duck AS SELECT * FROM ( VALUES ('duck', 'quack', [0.9, 0.7, 0.1]::FLOAT[]), ('horse', 'neigh', [0.3, 0.1, 0.5]::FLOAT[]), ('dragon', 'roar', [0.5, 0.2, 0.7]::FLOAT[]) ) AS t(animal, noise, vector); ``` This table is the source of truth for all DuckDB queries below. > [!NOTE] > > The examples below show SQL entered in the DuckDB CLI. You can run the same SQL from > Python as well, using LanceDB and DuckDB's Python clients in your application code. ## Query the table with SQL ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM lance_ns.main.lance_duck LIMIT 5; ``` ## Vector search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _distance FROM lance_vector_search( 'lance_ns.main.lance_duck', 'vector', [0.8, 0.7, 0.2]::FLOAT[], k = 1, prefilter = true ) ORDER BY _distance ASC; ``` ## Full-text search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _score FROM lance_fts( 'lance_ns.main.lance_duck', 'animal', 'the brave knight faced the dragon', k = 1, prefilter = true ) ORDER BY _score DESC; ``` ## Hybrid search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _hybrid_score, _distance, _score FROM lance_hybrid_search( 'lance_ns.main.lance_duck', 'vector', [0.8, 0.7, 0.2]::FLOAT[], 'animal', 'the duck surprised the dragon', k = 2, prefilter = false, alpha = 0.5, oversample_factor = 4 ) ORDER BY _hybrid_score DESC; ``` ## Directory namespace model A directory namespace maps a LanceDB namespace root -- there's no catalog in Embedded -- to namespace-qualified table identifiers in DuckDB. This keeps table discovery and table naming stable as your project grows. To learn more about the namespace and catalog model, see [Namespaces and the Catalog Model](/enterprise/v1-12-0/management/namespace). ## Advanced usage See the [docs](https://github.com/lance-format/lance-duckdb) directory in the Lance-DuckDB extension repo for more advanced usage on SQL and REST API clients. # Pandas and PyArrow Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/pandas_and_pyarrow **Applies to:** Embedded ✅, Enterprise ✅ Because Lance is built on top of [Apache Arrow](https://arrow.apache.org/), LanceDB fits naturally into Pandas-first workflows. You can ingest a `DataFrame`, query it with LanceDB's vector operators, and keep working in Pandas without any glue code. ## Create a dataset Start by importing LanceDB alongside your usual Pandas utilities and connect to a temporary database. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import asyncio import tempfile from pathlib import Path import lancedb import pandas as pd ``` Use the familiar `pd.DataFrame` API to prepare your rows, then pass the entire frame to `db.create_table`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb pandas_df = pd.DataFrame( [ {"id": "1", "text": "dragon", "vector": [0.9, 0.1, 0.3]}, {"id": "2", "text": "griffin", "vector": [0.4, 0.5, 0.2]}, {"id": "3", "text": "phoenix", "vector": [0.7, 0.3, 0.6]}, ] ) pandas_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pandas-demo")) pandas_table = pandas_db.create_table("creatures", data=pandas_df, mode="overwrite") ``` ## Vector search Queries can return Pandas frames as well, so you can immediately inspect the results or pipe them into downstream analytics. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pandas_results = ( pandas_table.search([0.9, 0.1, 0.3]) .select(["text", "_distance"]) .limit(1) .to_pandas() ) print(pandas_results) ``` ## Async API For web services or background jobs that already rely on `asyncio`, use the asynchronous helpers to keep everything non-blocking. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb async def run_pandas_async_example() -> pd.DataFrame: async_db = await lancedb.connect_async( str(Path(tempfile.mkdtemp()) / "pandas-async") ) async_df = pd.DataFrame( [ {"id": "10", "text": "sage", "vector": [0.6, 0.4, 0.8]}, {"id": "11", "text": "bard", "vector": [0.2, 0.7, 0.3]}, ] ) async_table = await async_db.create_table( "creatures_async", data=async_df, mode="overwrite" ) # An async search returns its query builder from an await query = await async_table.search([0.6, 0.4, 0.8]) async_results = await query.select(["text", "_distance"]).limit(1).to_pandas() print(async_results) return async_results async_results = asyncio.run(run_pandas_async_example()) ``` # Polars Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/polars_arrow **Applies to:** Embedded ✅, Enterprise ✅ LanceDB supports [Polars](https://github.com/pola-rs/polars), a blazingly fast DataFrame library for Python written in Rust. Under the hood, both Lance and Polars speak Arrow, so passing data back and forth stays zero-copy and ergonomic. ## Create and Query a Table Import the required libraries, including the optional Pydantic helpers if you plan to define schemas. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import polars as pl from lancedb.pydantic import LanceModel, Vector ``` Build a Polars `DataFrame`, convert it to Arrow, and use it directly when creating a LanceDB table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb birds = pl.DataFrame( { "text": ["phoenix", "sparrow"], "vector": [ [0.1, 0.2, 0.3], [0.8, 0.6, 0.5], ], } ) polars_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "polars-demo")) polars_table = polars_db.create_table( "birds", data=birds.to_arrow(), mode="overwrite" ) ``` Run vector search and keep the results as a Polars `DataFrame` for further processing or visualization. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} polars_results = ( polars_table.search([0.1, 0.2, 0.3]) .select(["text", "_distance"]) .limit(1) .to_polars() ) print(polars_results) ``` ## Work with LazyFrames When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for LanceDB Embedded tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lazy_frame = polars_table.to_polars().lazy() print(lazy_frame.select(["text"]).collect()) ``` ## Define Schemas with Pydantic You can also describe your table via `LanceModel` and continue ingesting data from Polars. This is useful when multiple teams share a schema or when you want validation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BirdModel(LanceModel): text: str vector: Vector(3) schema_table = polars_db.create_table( "birds_schema", schema=BirdModel, mode="overwrite" ) schema_table.add(birds.to_dicts()) ``` # Pydantic Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/pydantic **Applies to:** Embedded ✅, Enterprise ✅ [Pydantic](https://docs.pydantic.dev/latest/) is a data validation library in Python. LanceDB integrates with Pydantic for schema inference, data ingestion, and query result casting. Using `lancedb.pydantic.LanceModel`, users can seamlessly integrate Pydantic with the rest of the LanceDB APIs. First, import the necessary LanceDB and Pydantic modules: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.pydantic import LanceModel, Vector ``` Next, define your Pydantic model by inheriting from `LanceModel` and specifying your fields including a vector field: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class LanceDocs(LanceModel): text: str vector: Vector(2) ``` Set the database connection URL: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pydantic-docs")) ``` Now you can create a table, add data, and perform vector search operations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("docs", schema=LanceDocs, mode="overwrite") table.add( [ {"text": "hello world", "vector": [1.0, 0.0]}, {"text": "goodbye world", "vector": [0.0, 1.0]}, ] ) results = table.search([1.0, 0.0]).limit(1).to_pydantic(LanceDocs) print(results[0].text) # hello world ``` ## Vector Field LanceDB provides a `lancedb.pydantic.Vector` method to define a vector Field in a Pydantic Model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pydantic from lancedb.pydantic import Vector, pydantic_to_schema class MyModel(pydantic.BaseModel): id: int url: str embeddings: Vector(768) schema = pydantic_to_schema(MyModel) assert schema == pa.schema( [ pa.field("id", pa.int64(), False), pa.field("url", pa.utf8(), False), pa.field("embeddings", pa.list_(pa.float32(), 768)), ] ) ``` This example demonstrates how LanceDB automatically converts Pydantic field types to their corresponding Apache Arrow data types. The `pydantic_to_schema()` function takes a Pydantic model and generates an Arrow schema where: * `int` fields become `pa.int64()` (64-bit integers) * `str` fields become `pa.utf8()` (UTF-8 encoded strings) * `Vector(768)` becomes `pa.list_(pa.float32(), 768)` (fixed-size list of 768 float32 values) * The `False` parameter indicates that the fields are not nullable ## Type Conversion LanceDB automatically convert Pydantic fields to [Apache Arrow DataType](https://arrow.apache.org/docs/python/generated/pyarrow.DataType.html#pyarrow.DataType). Current supported type conversions: | Pydantic Field Type | PyArrow Data Type | | - | - | | `int` | `pyarrow.int64` | | `float` | `pyarrow.float64` | | `bool` | `pyarrow.bool` | | `str` | `pyarrow.utf8()` | | `list` | `pyarrow.List` | | `BaseModel` | `pyarrow.Struct` | | `Vector(n)` | `pyarrow.FixedSizeList(float32, n)` | LanceDB supports to create Apache Arrow Schema from a `pydantic.BaseModel` via `lancedb.pydantic.pydantic_to_schema` method. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import List, Optional import pyarrow as pa import pydantic from lancedb.pydantic import Vector, pydantic_to_schema class FooModel(pydantic.BaseModel): id: int s: str vec: Vector(1536) # fixed_size_list<item: float32>[1536] li: List[int] schema = pydantic_to_schema(FooModel) assert schema == pa.schema( [ pa.field("id", pa.int64(), False), pa.field("s", pa.utf8(), False), pa.field("vec", pa.list_(pa.float32(), 1536)), pa.field("li", pa.list_(pa.int64()), False), ] ) ``` This example shows a more complex Pydantic model with various field types and demonstrates how LanceDB handles: * Basic types: `int` and `str` fields * Vector fields: `Vector(1536)` creates a fixed-size list of 1536 float32 values * List fields: `List[int]` becomes a variable-length list of int64 values * Schema generation: The `pydantic_to_schema()` function automatically converts all these types to their Arrow equivalents # Voxel51 Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/data/voxel51 # FiftyOne [FiftyOne](https://docs.voxel51.com/) is an open source toolkit that enables users to curate better data and build better models. It includes tools for data exploration, visualization, and management, as well as features for collaboration and sharing. Any developers, data scientists, and researchers who work with computer vision and machine learning can use FiftyOne to improve the quality of their datasets and deliver insights about their models. ![example](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/integrations/voxel.gif?s=e115c947bf296a57b588fe6366194696) **FiftyOne** provides an API to create LanceDB tables and run similarity queries, both **programmatically in Python** and via **point-and-click in the App**. Let's get started and see how to use **LanceDB** to create a **similarity index** on your FiftyOne datasets. ## Overview [Embeddings](/enterprise/v1-12-0/embedding/) are foundational to all of the **vector search** features. In FiftyOne, embeddings are managed by the [**FiftyOne Brain**](https://docs.voxel51.com/user_guide/brain.html) that provides powerful machine learning techniques designed to transform how you curate your data from an art into a measurable science. > *Have you ever wanted to find the images most similar to an image in your dataset?* The **FiftyOne Brain** makes computing **visual similarity** really easy. You can compute the similarity of samples in your dataset using an embedding model and store the results in the **brain key**. You can then sort your samples by similarity or use this information to find potential duplicate images. We'll be doing the following : 1. **Create Index** - To run similarity queries against our media, we need to **index** the data. We can do this via the `compute_similarity()` function. * In the function, specify the **model** you want to use to generate the embedding vectors, and what **vector search engine** you want to use on the **backend** (here LanceDB). > [!TIP] > > You can also give the similarity index a name(`brain_key`), which is useful if you want to run vector searches against multiple indexes. 2. **Query** - Once you have generated your similarity index, you can query your dataset with `sort_by_similarity()`. The query can be any of the following: * An ID (sample or patch) * A query vector of same dimension as the index * A list of IDs (samples or patches) * A text prompt (search semantically) ## Prerequisites: install necessary dependencies 1. **Create and activate a virtual environment** Install virtualenv package and run the following command in your project directory. python -m venv fiftyone\_ From inside the project directory run the following to activate the virtual environment. source fiftyone\_/Scripts/activate fiftyone\_/Scripts/activate 2. **Install the following packages in the virtual environment** To install FiftyOne, ensure you have activated any virtual environment that you are using, then run pip install fiftyone ## Understand basic workflow The basic workflow shown below uses LanceDB to create a similarity index on your FiftyOne datasets: 1. Load a dataset into FiftyOne. 2. Compute embedding vectors for samples or patches in your dataset, or select a model to use to generate embeddings. 3. Use the `compute_similarity()` method to generate a LanceDB table for the samples or object patches embeddings in a dataset by setting the parameter `backend="lancedb"` and specifying a `brain_key` of your choice. 4. Use this LanceDB table to query your data with `sort_by_similarity()`. 5. If desired, delete the table. ## Quick Example Let's jump on a quick example that demonstrates this workflow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone as fo import fiftyone.brain as fob import fiftyone.zoo as foz # Step 1: Load your data into FiftyOne dataset = foz.load_zoo_dataset("quickstart") ``` Make sure you install torch ([guide here](https://pytorch.org/get-started/locally/)) before proceeding. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Steps 2 and 3: Compute embeddings and create a similarity index lancedb_index = fob.compute_similarity( dataset, model="clip-vit-base32-torch", brain_key="lancedb_index", backend="lancedb", ) ``` > [!NOTE] > > Running the code above downloads the CLIP model (2.6 GB). Once the similarity index has been generated, we can query our data in FiftyOne by specifying the `brain_key`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Step 4: Query your data query = dataset.first().id # query by sample ID view = dataset.sort_by_similarity( query, brain_key="lancedb_index", k=10, # limit to 10 most similar samples ) ``` The returned result are of type - `DatasetView`. > [!NOTE] > > `DatasetView` does not hold its contents in-memory. Views simply store the rule(s) that are applied to extract the content of interest from the underlying Dataset when the view is iterated/aggregated on. > > This means, for example, that the contents of a `DatasetView` may change as the underlying Dataset is modified. > *Can you query a view instead of dataset?* Yes, you can also query a view. Performing a similarity search on a `DatasetView` will only return results from the view; if the view contains samples that were not included in the index, they will never be included in the result. This means that you can index an entire Dataset once and then perform searches on subsets of the dataset by constructing views that contain the images of interest. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Step 5 (optional): Cleanup # Delete the LanceDB table lancedb_index.cleanup() # Delete run record from FiftyOne dataset.delete_brain_run("lancedb_index") ``` ## Using LanceDB backend By default, calling `compute_similarity()` or `sort_by_similarity()` will use an sklearn backend. To use the LanceDB backend, simply set the optional `backend` parameter of `compute_similarity()` to `"lancedb"`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone.brain as fob # Re-run similarity creation using the LanceDB backend explicitly fob.compute_similarity( dataset, model="clip-vit-base32-torch", brain_key="lancedb_index", backend="lancedb", ) ``` Alternatively, you can configure FiftyOne to use the LanceDB backend by setting the following environment variable. In your terminal, set the environment variable using: export FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND=lancedb \$Env:FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND="lancedb" //powershell set FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND=lancedb //cmd > [!WARNING] > > This will only run during the terminal session. Once terminal is closed, environment variable is deleted. Alternatively, you can **permanently** configure FiftyOne to use the LanceDB backend creating a `brain_config.json` at `~/.fiftyone/brain_config.json`. The JSON file may contain any desired subset of config fields that you wish to customize. ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "default_similarity_backend": "lancedb" } ``` This will override the default `brain_config` and will set it according to your customization. You can check the configuration by running the following code : ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone.brain as fob # Print your current brain config print(fob.brain_config) ``` ## LanceDB config parameters The LanceDB backend supports query parameters that can be used to customize your similarity queries. These parameters include: | Name | Purpose | Default | | :- | :- | :- | | **table_name** | The name of the LanceDB table to use. If none is provided, a new table will be created | `None` | | **metric** | The embedding distance metric to use when creating a new table. The supported values are ("cosine", "euclidean") | `"cosine"` | | **uri** | The database URI to use. In this Database URI, tables will be created. | `"/tmp/lancedb"` | There are two ways to specify/customize the parameters: 1. **Using `brain_config.json` file** ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "similarity_backends": { "lancedb": { "table_name": "your-table", "metric": "euclidean", "uri": "/tmp/lancedb" } } } ``` 2. **Directly passing to `compute_similarity()` to configure a specific new index** : ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lancedb_index = fob.compute_similarity( dataset, model="clip-vit-base32-torch", backend="lancedb", brain_key="lancedb_index", table_name="your-table", metric="euclidean", uri="/tmp/lancedb", ) ``` For a much more in depth walkthrough of the integration, visit the LanceDB x Voxel51 [docs page](https://docs.voxel51.com/integrations/lancedb.html). # Superlinked Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/superlinked [Superlinked](https://superlinked.com) is a self-hosted inference engine (SIE) for embedding, reranking, and extraction. The `sie-lancedb` package registers SIE as a first-class embedding function in LanceDB's embeddings registry, so embeddings are computed automatically on insert and search. You need a running SIE instance - see the [Superlinked quickstart](https://superlinked.com/docs) for deployment options. ## Installation ```bash Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install sie-lancedb ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @superlinked/sie-lancedb @lancedb/lancedb ``` ## Registered functions Importing `sie_lancedb` registers two embedding functions in LanceDB's registry: | Name | Purpose | | - | - | | `"sie"` | Dense text embeddings | | `"sie-multivector"` | ColBERT-style late interaction with MaxSim scoring | Supported parameters on `.create()`: | Parameter | Type | Description | | - | - | - | | `model` | `str` | Any of 85+ SIE-supported models (e.g. `BAAI/bge-m3`, `NovaSearch/stella_en_400M_v5`, `jinaai/jina-colbert-v2`) | | `base_url` | `str` | URL of the SIE endpoint (e.g. `http://localhost:8080`) | ## Usage ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector import sie_lancedb # registers "sie" and "sie-multivector" sie = get_registry().get("sie").create( model="BAAI/bge-m3", base_url="http://localhost:8080", ) class Documents(LanceModel): id: int text: str = sie.SourceField() vector: Vector(sie.ndims()) = sie.VectorField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "superlinked-demo")) table = db.create_table("docs", schema=Documents) table.add([ {"id": 1, "text": "Machine learning is a subset of AI."}, {"id": 2, "text": "Neural networks use multiple layers."}, {"id": 3, "text": "Python is popular for ML development."}, ]) results = table.search("What is deep learning?").limit(3).to_list() ``` LanceDB handles embedding generation for both inserts and queries automatically, based on the `SourceField` / `VectorField` declarations on the schema. The `id` column gives each document a stable key, which [entity extraction](#entity-extraction) uses to merge its results back. ## Hybrid search with reranker `SIEReranker` plugs into LanceDB's hybrid search pipeline. It uses SIE's cross-encoder `score()` to rerank combined vector + full-text search results. You need a full-text search index on the column first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from sie_lancedb import SIEReranker # Create FTS index for hybrid search table.create_fts_index("text", replace=True) results = ( table.search("What is deep learning?", query_type="hybrid") .rerank(SIEReranker(model="jinaai/jina-reranker-v2-base-multilingual")) .limit(5) .to_list() ) for r in results: print(f"{r['_relevance_score']:.3f} {r['text']}") ``` The reranker also works with pure vector or pure FTS search via `.rerank()`. ## ColBERT and multivector `SIEMultiVectorEmbeddingFunction` (registered as `"sie-multivector"`) works with LanceDB's native `MultiVector` type and MaxSim scoring for ColBERT and ColPali models. In LanceDB Python 0.40.0, a multivector that LanceDB generates on insert is stored as null unless the document's token count happens to equal the per-token dimension, so this example computes the document multivectors with `compute_source_embeddings()` and passes them in the `vector` column. LanceDB still generates the query multivector automatically: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import MultiVector sie_colbert = get_registry().get("sie-multivector").create( model="jinaai/jina-colbert-v2", base_url="http://localhost:8080", ) class ColBERTDocs(LanceModel): text: str = sie_colbert.SourceField() vector: MultiVector(sie_colbert.ndims()) = sie_colbert.VectorField() table = db.create_table("colbert_docs", schema=ColBERTDocs) # Compute the document multivectors and store them with their text texts = ["Machine learning is a subset of AI."] vectors = sie_colbert.compute_source_embeddings(texts) table.add([{"text": text, "vector": vector} for text, vector in zip(texts, vectors)]) # MaxSim search - query and document multivectors compared token-by-token results = table.search("What is ML?").limit(5).to_list() ``` ## Entity extraction `SIEExtractor` adds entity extraction to LanceDB's data-enrichment workflows. Extract entities from a text column and merge the results back as a structured Arrow column - enabling filtered search on extracted entities. This example enriches the `docs` table from [Usage](#usage), matching rows on its `id` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from sie_lancedb import SIEExtractor extractor = SIEExtractor( base_url="http://localhost:8080", model="urchade/gliner_multi-v2.1", ) docs = db.open_table("docs") extractor.enrich_table( docs, source_column="text", target_column="entities", labels=["person", "technology", "organization"], id_column="id", ) ``` The `entities` column stores structured Arrow data (`list<struct<text, label, score, start, end, bbox>>`), so you can filter on extracted entities in queries. ## Links * [`sie-lancedb` on PyPI](https://pypi.org/project/sie-lancedb/) * [`@superlinked/sie-lancedb` on npm](https://www.npmjs.com/package/@superlinked/sie-lancedb) * [Superlinked on GitHub](https://github.com/superlinked/sie) * [Superlinked docs](https://superlinked.com/docs) # Voyage AI Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/embedding/voyageai Voyage AI provides cutting-edge embedding and rerankers. Using voyageai API requires voyageai package, which can be installed using `pip install voyageai`. Voyage AI embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `VOYAGE_API_KEY` environment variable to use the Voyage AI API. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export VOYAGE_API_KEY="your-api-key" ``` Supported models are: * voyage-4-large (best retrieval quality, 1024 default dimensions, supports 256/512/1024/2048) * voyage-4 (balanced general-purpose, 1024 default dimensions, supports 256/512/1024/2048) * voyage-4-lite (optimized for latency/cost, 1024 default dimensions, supports 256/512/1024/2048) * voyage-context-3 * voyage-3.5 * voyage-3.5-lite * voyage-3 * voyage-3-lite * voyage-finance-2 * voyage-multilingual-2 * voyage-law-2 * voyage-code-2 * voyage-multimodal-3.5 (multimodal - supports text, images, and video) > [!NOTE] > > **Multimodal Model:** `voyage-multimodal-3.5` supports text, images, and video inputs. It outputs 1024-dimensional embeddings by default, configurable via the `output_dimension` parameter (256, 512, 1024, 2048). See the [Voyage AI multimodal embeddings documentation](https://docs.voyageai.com/docs/multimodal-embeddings) for more details. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `None` | The model ID of the model to use. Supported models: voyage-4-large, voyage-4, voyage-4-lite, voyage-3, voyage-3-lite, voyage-3.5, voyage-3.5-lite, voyage-context-3, voyage-finance-2, voyage-multilingual-2, voyage-law-2, voyage-code-2, voyage-multimodal-3.5 | | `input_type` | `str` | `None` | Type of the input text. Default to None. Other options: query, document. | | `truncation` | `bool` | `True` | Whether to truncate the input texts to fit within the context length. | | `output_dimension` | `int` | `None` | Output embedding dimension. Only supported by `voyage-multimodal-3.5`. Valid options: 256, 512, 1024 (default), 2048. | For text models, `compute_source_embeddings()` accepts a single string, a list of strings, a one-dimensional NumPy array, or a PyArrow `Array` or `ChunkedArray`. Batch inputs retain their order. Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector voyageai = ( EmbeddingFunctionRegistry.get_instance().get("voyageai").create(name="voyage-3") ) class TextModel(LanceModel): text: str = voyageai.SourceField() vector: Vector(voyageai.ndims()) = voyageai.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` ### Multimodal Example The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, local `pathlib.Path` objects, raw image bytes, or PIL Image objects. For source embeddings, PIL images and images loaded from bytes or local paths are converted to RGB and encoded as JPEG. This supports RGBA, grayscale with alpha, and palette images; transparency is discarded. Composite transparent images onto your chosen background before embedding if the background color matters. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector # Create multimodal embedding function with custom dimension voyageai = ( EmbeddingFunctionRegistry.get_instance() .get("voyageai") .create(name="voyage-multimodal-3.5", output_dimension=512) ) class ImageModel(LanceModel): image_uri: str = voyageai.SourceField() vector: Vector(voyageai.ndims()) = voyageai.VectorField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-multimodal")) tbl = db.create_table("images", schema=ImageModel, mode="overwrite") # Add images using URLs tbl.add( [ { "image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png" }, ] ) # Search with text query results = tbl.search("dice").limit(1).to_list() print(results) ``` # LeRobotDataset Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/lerobotdataset Train LeRobot policies straight from object storage, and curate, search and visualize robotics datasets as Lance tables. [LeRobot](https://huggingface.co/docs/lerobot/index) is HuggingFace's open-source robotics stack. Since [lerobot#4363](https://github.com/huggingface/lerobot/pull/4363) it reads Lance datasets natively, and `lerobot-lancedb` wraps that into a ready-made dataset class for video features: same items, same training pipeline. Image-backed features are not supported -- re-encode them as video first. What you get: * **Train from object storage while keeping your GPUs fed.** Lance reads random frames straight from S3, GCS, the HF Hub or HF Storage Buckets, fetching only the bytes each batch needs, so every batch is a global shuffle: any frame, from anywhere in the dataset. In the table below (samples/s, 8 workers, batch 64), Lance and upstream local both draw every batch from the whole dataset. Upstream streaming does a reservoir shuffle, reading the dataset in order and drawing each batch from a pool of recently seen frames, so those two columns are not the same job: | dataset | window shuffle, Lance from object store | window shuffle, upstream streaming from the Hub | Lance (object store) vs upstream streaming | RAM, Lance | RAM, streaming | global shuffle, Lance from object store | global shuffle, upstream from local NVMe | Lance (object store) vs upstream (local NVMe) | | - | - | - | - | - | - | - | - | - | | DROID | 904 | 478 | 1.9x | 8 GB | 122 GB | 257 | 224 | 1.1x | | roboturk | 778 | 152 | 5.1x | 6 GB | 9 GB | 1,074 | 983 | 1.1x | | aloha_mobile_cabinet | 772 | 51 | 15.2x | 9 GB | 30 GB | 693 | 573 | 1.2x | | koch_pick_place_5_lego | 701 | 54 | 13.0x | 8 GB | 15 GB | 876 | 526 | 1.7x | | pusht | 5,340 | 648 | 8.2x | 3 GB | 7 GB | 5,508 | 4,224 | 1.3x | | aloha_static_cups_open | 597 | 45 | 13.2x | 10 GB | 38 GB | 575 | 483 | 1.2x | The shuffle window is 0.05% of the dataset, at least 5,000 frames: 5,000 on the small sets, 13,815 on DROID. Streaming DROID at that window in upstream default needs 122 GB, so those two runs used a 256 GB machine with the same decode speed. The DROID pair is noisy: Lance 684 and 1,124, streaming 303 and 653. Same batches: Lance from an object store is 1.9x faster than upstream streaming on DROID and 5x to 15x on the other datasets, with 8 GB of RAM against 122 GB on DROID. Global shuffle: Lance with nothing downloaded is 1.1x to 1.7x faster than upstream reading local NVMe after the download. berkeley_rpt, toto and soarm101 are left out because their metadata lists frames the videos do not have; `lerobot-lance-doctor` reports that before you train. * **Faster iteration, end to end.** 10,000 steps of SmolVLA on DROID, 8xH100, lerobot's default `num_workers=4`, same seed: | | Lance, S3, nothing downloaded | upstream, local NVMe after a 384 GB download | | - | - | - | | wall clock | **1 h 27 m** | 2 h 00 m | | steady rate | 495 samples/s | 361 samples/s | | of each step spent waiting on data | 1.7% | 37.4% | | final loss | 0.2380 | 0.2380 | Same model, same loss, 33 minutes sooner, and no 384 GB download first. The difference is time the GPUs spend waiting on data, so it grows with the run: at 100k steps it is over five hours, and every re-run and sweep point pays it again. * **The training table is also the index.** Parquet has no secondary indexes, so finding frames instead of scanning them usually means another system per question: a vector database for embeddings, a search service for instructions, a feature store for scores. With Lance those are columns and indexes on the same table the DataLoader reads. One query spans all of them, at a version the trainer can reopen. ## Install ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lerobot[lancedb]" # the reader, inside lerobot itself pip install lerobot-lancedb # the converter ``` ## Convert a dataset Any LeRobot v3.0 dataset, from the Hub or a local directory: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-lance-convert --repo-id lerobot/pusht --out ./pusht-lance ``` **Migration costs about as much as a file copy.** Videos are stored as blobs without re-encoding, so items are bit-identical to the source: 392,578 frames convert in 10 seconds, DROID's 27.6M in 34 minutes. Nothing about your recording or training code changes. The output keeps `meta/` as is and adds three Lance tables (`frames`, `videos`, `meta`). `lerobot-lance-doctor` audits the result and often finds problems in the source: DROID carries 44% orphaned rows, and three of eight public datasets we converted have frame-count defects that only random access exposes. Host the result anywhere: an HF dataset repo (`hf upload`, tag it `v3.0`), an HF Storage Bucket (`hf buckets sync`), or any object store (`aws s3 sync`). ## Load and train `lerobot-lancedb` provides one map-style dataset class for both image and video features, reading from a local path or an `s3://`, `gs://` or `hf://` URI with nothing downloaded up front. Pair it with `lance_mp_context()` so multi-worker `DataLoader`s share Lance's own multiprocessing context instead of the default one: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lerobot_lancedb import LanceDBDataset, lance_mp_context from torch.utils.data import DataLoader dataset = LanceDBDataset(root="hf://datasets/lance-format/pusht-lance") sample = dataset[0] print(sample["observation.state"].shape) print(sample["action"].shape) loader = DataLoader( dataset, batch_size=32, num_workers=8, multiprocessing_context=lance_mp_context(), ) ``` Items are bit-exact with `LeRobotDataset`, and `delta_timestamps` configures temporal windows the same way. Or from the CLI. Held-out evaluation on a remote dataset needs random access, so it only works on the Lance path: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-train \ --dataset.repo_id=my-org/my-bucket/pusht-lance \ --dataset.repo_type=bucket \ --dataset.eval_split=0.02 \ --policy.type=act ``` ## Visualize TB-scale datasets in Foxglove LeRobot's dataset viewer can serve an episode to [Foxglove](https://foxglove.dev) over its WebSocket protocol ([lerobot#4542](https://github.com/huggingface/lerobot/pull/4542)), and with a Lance dataset it works wherever the data lives: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-dataset-viz --repo-id lance-format/pusht-lance --episode-index 3 --display-mode foxglove ``` Open the Foxglove app, connect to `ws://localhost:8765`, and scrub. Cameras, joint state and actions show up as topics you can lay out however you like: ![Foxglove showing episode 7 of DROID served from S3: three camera panels and the joint state, scrubbed to 19.4 s](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/integrations/lerobot-foxglove-droid.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=9a2f88314bfd363b3d2a3ba02547555e) Frames are fetched as you scrub, so looking at one episode of the 373 GB DROID from S3 moves a few MB, not the dataset. No MCAP export, no download, and nothing new to install on the dataset side: this is the same reader the trainer uses. ## Query, curate, enrich The frames table is a LanceDB table like any other: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pusht-lance") frames = db.open_table("frames") videos = db.open_table("videos") print(len(frames), len(videos)) print(frames.schema) ``` Filter with SQL over any feature, using the indexes built at conversion: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frame_rows = ( frames.search() .where("episode_index = 0 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action"]) .limit(10) .to_list() ) for row in frame_rows: print(row["episode_index"], row["frame_index"], row["timestamp"]) ``` From here it is standard LanceDB. The examples below are from our DROID walkthrough, all on the table the trainer reads. **Feature engineering costs nothing until you use it.** With [Geneva](/enterprise/v1-12-0/geneva/udfs/udfs), `add_columns` registers a `@udf` function and its input columns as a new column and computes nothing; `backfill` computes and stores the values later, in parallel. No copy of the dataset, and the videos are never touched: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.float32(), input_columns=["action_joint_velocity"]) def jerk_score(v): # per-frame motion roughness ... tbl.add_columns({"jerk_score": jerk_score}) # nothing computed yet tbl.backfill("jerk_score", concurrency=8) # 610,403 rows in 16.7 s ``` Embeddings work the same way, reading frames straight from the video blobs in the `videos` table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 768), num_gpus=1, input_columns=["episode_index", "frame_index"]) class EmbedFromBlob: # SigLIP2 loads once per worker def __call__(self, episode_index, frame_index): blob = self.videos.fetch_blob_files("video_bytes", [video_row_id])[0] frame = VideoDecoder(blob).get_frames_at([pos]).data[0] ... ``` **Deduplication** removes near-static runs before they skew curation or training. A stopped gripper holding one pose for a few seconds produces many frames whose `emb_siglip2` vectors are nearly identical; LanceDB Enterprise's native [`dedupe`](/enterprise/v1-12-0/sql/dql/dedupe) collapses them into one representative per cluster, directly over the index, without a pairwise scan: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'emb_siglip2', distance_threshold => 0.01 ) """) ``` Every column survives the dedup unchanged -- `jerk_score`, the episode and camera metadata, the video blob reference -- since `dedupe` returns full rows, not just which ones matched. Wrap it in a materialized view, as above, to keep the deduplicated set current as new episodes land; see [Materialized views](/enterprise/v1-12-0/feature-engineering/materialized-views). **Search** is an index on those columns: a vector index over the embeddings built in 29.7 s across 27.6M rows, a full-text index over the instructions in 7.0 s, queries in 10 to 54 ms. **Curation** is one query across all of it. Semantic search with a predicate on the derived score, no join, no second system: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( tbl.search(vec("a gripper closing on an object"), vector_column_name="emb_siglip2") .where("jerk_score > 1.2875") # the roughest 1% of frames .limit(4) .to_arrow() ) ``` **Mining** is the same query pointed at the rare cases. `tbl.search().where("jerk_score > 1.2875 AND success = false")` pulls the rough, failed frames out of 27.6M rows in milliseconds, ready to become a fine-tuning set or a labeling queue. **EDA** is a scan of the tabular columns: a pass over all 27.6M rows reads 2.52 GB in 190 s and decodes no video. Then drop what you found from training with `episodes=[...]` instead of rewriting files. The reader ignores columns it does not know, and the table is versioned, so curation and training share one copy of the data at a version you can reopen. > [!NOTE] > > Lance datasets are read-only in LeRobot: record and edit in the default format, then convert. Public examples to try everything above: [`lance-format/pusht-lance`](https://huggingface.co/datasets/lance-format/pusht-lance) and friends under the [`lance-format`](https://huggingface.co/lance-format) org. # Answer.AI Rerankers Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/answerdotai Use AnswerDotAI's lightweight reranking library with LanceDB. Features unified API for common reranking models, configurable model selection, and comprehensive scoring options. # Answer.AI Rerankers This integration uses [AnswersDotAI's rerankers](https://github.com/AnswerDotAI/rerankers) to rerank the search results, providing a lightweight, low-dependency, unified API to use all common reranking and cross-encoder models. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import AnswerdotaiRerankers embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "answerdotai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = AnswerdotaiRerankers() # Run vector search with a reranker result = tbl.search("hello").rerank(reranker=reranker).to_list() # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() # Run hybrid search with a reranker result = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_type` | `str` | `"colbert"` | The type of model to use. Supported model types can be found here: [https://github.com/AnswerDotAI/rerankers](https://github.com/AnswerDotAI/rerankers). | | `model_name` | `str` | `"answerdotai/answerai-colbert-small-v1"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Cohere Reranker Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/cohere Integrate Cohere's powerful reranking API with LanceDB for enhanced search results. Supports English and multilingual models with configurable scoring options for vector, FTS, and hybrid search. # Cohere Reranker This reranker uses the [Cohere](https://cohere.ai/) API to rerank the search results. You can use this reranker by passing `CohereReranker()` to the `rerank()` method. Note that you'll either need to set the `COHERE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install cohere ``` Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import CohereReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cohere-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = CohereReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"rerank-english-v2.0"` | The name of the reranker model to use. Available cohere models are: rerank-english-v2.0, rerank-multilingual-v2.0 | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Cohere API. If not provided, the `COHERE_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`) | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`) | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`) | # ColBERT Reranker Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/colbert Enhance search results with ColBERT's contextual reranking in LanceDB. Features efficient model deployment, device optimization, and flexible scoring options for vector, FTS, and hybrid search. # ColBERT Reranker This reranker uses ColBERT model to rerank the search results. You can use this reranker by passing `ColbertReranker()` to the `rerank()` method. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import ColbertReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "colbert-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = ColbertReranker() # Run vector search with a reranker result = tbl.search("hello").rerank(reranker=reranker).to_list() # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() # Run hybrid search with a reranker result = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"colbert-ir/colbertv2.0"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `device` | `str` | `None` | The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu". | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Jina Reranker Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/jina Integrate Jina's multilingual reranking API with LanceDB for improved search results. Features model selection, API key management, and flexible scoring options for all search types. # Jina Reranker This reranker uses the [Jina](https://jina.ai/reranker/) API to rerank the search results. You can use this reranker by passing `JinaReranker()` to the `rerank()` method. Note that you'll either need to set the `JINA_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import JinaReranker os.environ["JINA_API_KEY"] = "your-api-key" embedder = get_registry().get("jina").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = JinaReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"jina-reranker-v2-base-multilingual"` | The name of the reranker model to use. You can find the list of available models in [https://jina.ai/reranker](https://jina.ai/reranker). | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Jina API. If not provided, the `JINA_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # OpenAI Reranker (Experimental) Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/openai Explore experimental search reranking using OpenAI's GPT models in LanceDB. Features configurable model selection, API key management, and comprehensive scoring options for all search types. # OpenAI Reranker (Experimental) This reranker uses OpenAI chat model to rerank the search results. You can use this reranker by passing `OpenaiReranker()` to the `rerank()` method. > **Note:** Supported query types: Hybrid, Vector, and FTS. > **Warning:** This reranker is experimental. OpenAI does not have a dedicated reranking model, so it uses a chat model under the hood. Replace `your-api-key` with your provider API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import OpenaiReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "openai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = OpenaiReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"gpt-5.6-sol"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | | `api_key` | `str` | `None` | The API key to use. If None, will use the OPENAI_API_KEY environment variable. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Voyage AI Reranker Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/voyageai Integrate Voyage AI's cutting-edge reranking models with LanceDB. Features model selection, API key management, and comprehensive scoring options for all search types. # Voyage AI Reranker Voyage AI provides cutting-edge embedding and rerankers. This reranker uses the [Voyage AI](https://docs.voyageai.com/docs/) API to rerank the search results. You can use this reranker by passing `VoyageAIReranker()` to the `rerank()` method. Note that you'll either need to set the `VOYAGE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. Replace `your-api-key` with your provider API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import VoyageAIReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = VoyageAIReranker(api_key="your-api-key", model_name="rerank-2") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `None` | The name of the reranker model to use. Available models are: rerank-2, rerank-2-lite | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Voyage AI API. If not provided, the `VOYAGE_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | | `truncation` | `bool` | `None` | Whether to truncate the input to satisfy the "context length limit" on the query and the documents. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ❌ Not Supported | Returns have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`) | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ✅ Supported | Returns have vector(`_distance`) along with Hybrid Search score(`_relevance_score`) | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ✅ Supported | Returns have FTS(`score`) along with Hybrid Search score(`_relevance_score`) | # Watsonx Reranker Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/reranking/watsonx Rerank LanceDB search results with the IBM watsonx.ai text rerank API. Supports vector, FTS, and hybrid search with configurable models, projects, and spaces. # Watsonx Reranker This reranker uses the [IBM watsonx.ai](https://cloud.ibm.com/docs/apis/watsonx-ai#text-rerank) text rerank API to reorder search results. Pass `WatsonxReranker()` to the `rerank()` method on a query. Credentials come from the `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` (or `WATSONX_SPACE_ID`) environment variables, or can be passed explicitly as arguments. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install ibm-watsonx-ai ``` Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import WatsonxReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "watsonx-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) # Supply your API key and project ID (or use space_id instead of project_id). reranker = WatsonxReranker( api_key="your-api-key", project_id="your-project-id", ) # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"cross-encoder/ms-marco-minilm-l-12-v2"` | The rerank model ID. See [supported rerank models](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx#rerank). | | `column` | `str` | `"text"` | The name of the table column to use as document input. | | `top_n` | `int` | `None` | The number of results to return. If `None`, all results are returned. | | `return_score` | `str` | `"relevance"` | Options are `"relevance"` or `"all"`. Controls which score columns are kept on the result. | | `api_key` | `str` | `None` | IBM Cloud API key. Falls back to the `WATSONX_API_KEY` environment variable. | | `project_id` | `str` | `None` | watsonx.ai project ID. Falls back to `WATSONX_PROJECT_ID`. Mutually exclusive with `space_id`. | | `space_id` | `str` | `None` | watsonx.ai deployment space ID. Falls back to `WATSONX_SPACE_ID`. Mutually exclusive with `project_id`. | | `url` | `str` | `"https://us-south.ml.cloud.ibm.com"` | watsonx.ai service URL. | | `truncate_input_tokens` | `int` | `None` | Truncate each document to this many tokens before scoring. | > [!NOTE] > > You must supply exactly one of `project_id` or `space_id` (either as an argument or via its environment variable). Setting both, or neither, raises a `ValueError`. ## Supported scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Stable World Model Source: https://docs.lancedb.com/enterprise/v1-12-0/integrations/stable-worldmodel Use Stable World Model with LanceDB-backed datasets for reproducible world model research, fast data loading, and compact storage. [Stable World Model](https://github.com/galilai-group/stable-worldmodel) is a research platform for collecting data, training world models, and evaluating policies with model-predictive control across standardized environments. The LanceDB integration is built into Stable World Model's data format registry. Lance is the default backend for collected datasets, so a path ending in `.lance` gives you an append-friendly LanceDB table with episode-contiguous rows and fast indexed reads. Random access speed is the bottleneck for world model training, since the loop repeatedly samples temporal windows from high-dimensional observations, actions, and rewards. The faster those windows arrive, the more GPU time goes into training rather than waiting on the data loader. ## Install ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install stable-worldmodel ``` Datasets and checkpoints are stored under `$STABLEWM_HOME`, which defaults to `~/.stable_worldmodel/`. ## Collect data into Lance Stable World Model uses Lance by default when you collect to a `.lance` path. Replace `your_expert_policy` with the expert or scripted policy you use to collect demonstrations. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import stable_worldmodel as swm world = swm.World("swm/PushT-v1", num_envs=8) world.set_policy(your_expert_policy) world.collect("data/pusht_demo.lance", episodes=100, seed=0) ``` Every writer accepts a `mode` argument such as `append`, `overwrite`, or `error`. The default is append, so re-running collection extends the existing dataset. ## Load a Lance dataset for training The dataset loader autodetects the Lance format from the path. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dataset = swm.data.load_dataset("data/pusht_demo.lance", num_steps=16) batch = dataset[0] print(batch.keys()) ``` Your model code stays focused on the world model objective while LanceDB handles the storage layout and read path. ## Evaluate with model-predictive control After training a world model on the Lance-backed dataset, Stable World Model can evaluate it with planning solvers such as CEM. Replace `world_model` with the trained model object from your training loop. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from stable_worldmodel.policy import PlanConfig, WorldModelPolicy from stable_worldmodel.solver import CEMSolver solver = CEMSolver(model=world_model, num_samples=300) policy = WorldModelPolicy(solver=solver, config=PlanConfig(horizon=10)) world.set_policy(policy) results = world.evaluate(episodes=50) print(f"Success Rate: {results['success_rate']:.1f}%") ``` ## Convert between formats Stable World Model can convert between registered dataset formats. A common workflow is to collect in Lance for fast training reads, then export to the video layout for compact inspection artifacts. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} swm.data.convert( "data/pusht_demo.lance", "data/pusht_video", dest_format="video", fps=30, ) ``` ## Throughput The Stable World Model README reports the following PushT benchmark results from `scripts/benchmark/compare_h5_lance.py`: | Format | Source | Cache | samples/s | ms/step | | :- | :- | :- | -: | -: | | HDF5 | local | no-cache | 1,416.1 | 45.2 | | HDF5 | local | cached | 1,474.0 | 43.4 | | LanceDB | local | no-cache | 4,814.8 | 13.3 | | LanceDB | local | cached | 4,431.3 | 14.4 | | Video | local | - | 1,330.6 | 48.1 | | LanceDB | s3 | no-cache | 3,183.7 | 20.1 | | LanceDB | s3 | cached | 3,253.2 | 19.7 | | HDF5 | s3 | no-cache | 9.1 | 7,032.5 | | HDF5 | s3 | cached | 756.5 | 84.6 | In that benchmark, local LanceDB reached about **3.4x** the no-cache throughput of local HDF5, while S3-backed LanceDB reached about **350x** the no-cache throughput of S3-backed HDF5. Even with cache enabled, S3-backed LanceDB was about **4.3x** faster than S3-backed HDF5. These numbers come from the Stable World Model project's own benchmark setup, so they're best read as a reproducible directional baseline that may shift across environments, models, and storage configurations. ## Storage The same README reports these local storage sizes for the benchmark dataset: | Format | Local size | | :- | -: | | HDF5 | 43.12 GB | | LanceDB | 13.31 GB | | Video | 496.29 MB | LanceDB used about **69% less local storage than HDF5** in the reported benchmark, while preserving a table interface built for fast training reads and append-heavy collection. ## More resources > [card] [Stable World Model README](https://github.com/galilai-group/stable-worldmodel/blob/main/README.md) > > Installation, quick start, supported formats, benchmarks, environments, solvers, and citation. > [card] [Stable World Model docs](https://galilai-group.github.io/stable-worldmodel/) > > Full upstream documentation with tutorials, API references, and guides. # Object Detection for AV Perception Source: https://docs.lancedb.com/enterprise/v1-12-0/training/object-detection End-to-end fine-tuning of a Faster R-CNN object detector on curated dashcam slices, using LanceDB as the data backbone from raw frames to checkpoints. This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) (riders, nighttime pedestrians, and distant pedestrians) using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/enterprise/v1-12-0/training/permutation) API, and pinning checkpoints to an exact data version. ## What you get Fine-tuning Faster R-CNN ResNet50 FPN v2 for 10 epochs on each curated slice (batch size 64, AMP, A100), starting from the same COCO-pretrained checkpoint and evaluating on the matching validation view: | Failure mode | Metric | Baseline (COCO) | Fine-tuned | Δ% | | - | - | - | - | - | | **Nighttime pedestrian** | mAP\@0.5 | 0.4025 | **0.5192** | **+29.0%** | | | Recall | 0.5923 | **0.7570** | **+27.8%** | | **Rider** | mAP\@0.5 | 0.5563 | **0.6676** | **+20.0%** | | | Recall | 0.6788 | **0.7847** | **+15.6%** | | **Distant pedestrian** | mAP\@0.5 | 0.4746 | **0.5788** | **+22.0%** | | | Recall | 0.6794 | **0.8024** | **+18.1%** | No external data added, only training-distribution correction via SQL filters over a single Lance table. Each panel below shows the same frame with three overlaid predictions: **green** = ground truth · **red** = pretrained COCO baseline · **blue** = fine-tuned model. ![Rider detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/training/rider_04.jpg?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=43fee6b6b5080a43c3457f3faa355bd8) ![Nighttime pedestrian detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/training/nighttime_person_01.jpg?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=b92570541aab89d419c45f8db5449119) ![Distant pedestrian detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/training/distant_person_00.jpg?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=a71970150a0aef864c0cde7a138b9c27) The rest of the page walks through the pipeline that produced these checkpoints. ## The failure modes A perception model fine-tuned on a generic dataset typically misses the long-tail scenarios that matter most in deployment. Three common failure modes drive this example: | Failure mode | Curation signal | | - | - | | **Riders** (person on bike/motorcycle) | `has_rider = true` | | **Nighttime pedestrians** | `timeofday = 'night' AND has_person = true` | | **Distant pedestrians** | `has_person = true AND person_bbox_area_pct < 30.0` | Each curated slice becomes a [Geneva materialized view](/enterprise/v1-12-0/geneva/jobs/materialized-views) (a named, refreshable SQL filter over the source table), and the training script loads it by name. New footage flows in through `add()` → `backfill()` → `refresh()`; no manifests, no exports, no reshuffling on disk. ## 1. Schema The source table holds raw image bytes alongside structured annotations. Bounding boxes are stored as a parallel list (one element per box) rather than a nested struct so they remain directly queryable with SQL. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa BDD_SCHEMA = pa.schema([ pa.field("image_id", pa.string()), pa.field("split", pa.string()), # "train" | "val" pa.field("image_bytes", pa.large_binary()), # raw JPEG pa.field("width", pa.int32()), pa.field("height", pa.int32()), # scene metadata pa.field("weather", pa.string()), pa.field("scene", pa.string()), pa.field("timeofday", pa.string()), # annotations — parallel lists, one element per box pa.field("ann_categories", pa.list_(pa.string())), pa.field("ann_bboxes", pa.list_(pa.list_(pa.float32()))), pa.field("ann_occluded", pa.list_(pa.bool_())), ]) ``` Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Lance table, with no intermediate preprocessing job. The table can live on local disk, S3, GCS, or Azure; everything downstream (backfills, views, the training loader) opens it in place via `lancedb.connect("s3://...")` with no local copy step. ## 2. Backfill curation features with Geneva Curation signals are added as columns on the same table using [Geneva backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling). Backfills are incremental and checkpointed: re-running the command after new footage arrives only computes the new rows. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva.transformer import udf # Tier 1 — CPU, derived from annotations alone @udf(data_type=pa.bool_(), input_columns=["ann_categories"]) def has_rider(ann_categories: list[str]) -> bool: return "rider" in (ann_categories or []) # Tier 2 — GPU, runs a Faster R-CNN to find the largest detected person # as a percentage of frame area. <30% = a distant or small pedestrian, # the hard case we want to upweight in training. @udf(data_type=pa.float32(), input_columns=["image_bytes", "width", "height"], cuda=True, num_gpus=1) class PersonBboxAreaPct: def __init__(self): self._model = None def __call__(self, image_bytes, width, height): # lazy model load — runs once per Ray worker, then reused ... ``` Run the backfill against the live table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva gconn = geneva.connect("data/bdd100k/lancedb") tbl = gconn.open_table("bdd100k") tbl.add_columns({"has_rider": has_rider}) tbl.add_columns({"person_bbox_area_pct": PersonBboxAreaPct()}) with gconn.local_ray_context(): tbl.backfill("has_rider") tbl.backfill("person_bbox_area_pct") ``` > [!NOTE] > > Because the curation features are flat scalar columns on the same table, all four retrieval modes (SQL, full-text search, vector search, and SQL-filtered vector search) work directly without joins or exports. See [Geneva backfilling](/enterprise/v1-12-0/geneva/jobs/backfilling) for how a backfill fills only the rows that lack values. ## 3. Define training splits as materialized views A training split is a named SQL filter, not a CSV manifest. Each view stays in sync with the source table and bumps its `version` on every refresh. That version is the link between a checkpoint and the exact data that produced it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva gconn = geneva.connect("data/bdd100k/lancedb") gtbl = gconn.open_table("bdd100k") VIEWS = { "bdd100k_rider_train": "has_rider = true AND split = 'train'", "bdd100k_rider_val": "has_rider = true AND split = 'val'", "bdd100k_nighttime_person_train": "timeofday = 'night' AND has_person = true AND split = 'train'", "bdd100k_nighttime_person_val": "timeofday = 'night' AND has_person = true AND split = 'val'", "bdd100k_distant_person_train": "has_person = true AND person_bbox_area_pct < 30.0 AND split = 'train'", "bdd100k_distant_person_val": "has_person = true AND person_bbox_area_pct < 30.0 AND split = 'val'", } with gconn.local_ray_context(): for name, sql_filter in VIEWS.items(): query = gtbl.search().where(sql_filter) mv = gconn.create_materialized_view(name, query) mv.refresh() print(f"[{name}] {mv.count_rows()} rows (version {mv.version})") ``` ## 4. PyTorch DataLoader via the Permutation API The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/enterprise/v1-12-0/training/permutation) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch import torchvision.io as tio from lancedb.permutation import Permutation DETECTION_COLS = ["image_bytes", "ann_categories", "ann_bboxes"] class LanceDetectionDataset(torch.utils.data.Dataset): def __init__(self, uri: str, table_name: str): self.uri, self.table_name = uri, table_name self._perm = None self.length = len(lancedb.connect(uri).open_table(table_name)) def __len__(self): return self.length def __getstate__(self): # Permutation holds Rust async state — zero it so each worker reopens state = self.__dict__.copy() state["_perm"] = None return state def _ensure_open(self): if self._perm is None: tbl = lancedb.connect(self.uri).open_table(self.table_name) self._perm = ( Permutation.identity(tbl) .select_columns(DETECTION_COLS) .with_format("arrow") # zero-copy ) def __getitems__(self, indices: list[int]): self._ensure_open() return self._perm.__getitems__(indices) ``` The collate function decodes JPEG bytes and converts BDD category strings into COCO class IDs (so the comparison against the pretrained checkpoint is valid): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} BDD_LABEL_MAP = { "person": 1, "rider": 1, "bicycle": 2, "car": 3, "motorcycle": 4, "bus": 6, "train": 7, "truck": 8, "traffic light": 10, } def detection_collate(batch): images, targets = [], [] for raw, cats, bboxes in zip( batch.column("image_bytes").to_pylist(), batch.column("ann_categories").to_pylist(), batch.column("ann_bboxes").to_pylist(), ): buf = torch.frombuffer(bytearray(raw), dtype=torch.uint8) images.append(tio.decode_image(buf, tio.ImageReadMode.RGB).float() / 255.0) valid_boxes, valid_labels = [], [] for cat, box in zip(cats or [], bboxes or []): lid = BDD_LABEL_MAP.get(cat) if lid is None or box[2] <= box[0] or box[3] <= box[1]: continue valid_boxes.append(box) valid_labels.append(lid) targets.append({ "boxes": torch.tensor(valid_boxes or [], dtype=torch.float32).reshape(-1, 4), "labels": torch.tensor(valid_labels or [], dtype=torch.int64), }) return images, targets ``` Wire it into a standard `torch.utils.data.DataLoader`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): dataset = LanceDetectionDataset(uri, table_name) sampler = torch.utils.data.RandomSampler(dataset) if shuffle else None return torch.utils.data.DataLoader( dataset, batch_size=batch_size, sampler=sampler, num_workers=num_workers, collate_fn=detection_collate, pin_memory=torch.cuda.is_available(), persistent_workers=(num_workers > 0), multiprocessing_context="spawn" if num_workers > 0 else None, ) ``` > [!NOTE] > > `with_format("arrow")` keeps batches as zero-copy `pa.RecordBatch`es: no per-row Python boxing, no pickling between worker and main. Each DataLoader worker reopens its own `Permutation` after fork (the Rust async handle is cleared in `__getstate__`), so reads scale with `num_workers` and stream straight from the underlying object store. JPEG decode overlaps with GPU compute via `pin_memory` + `prefetch_factor`, which is what keeps the loader from becoming the bottleneck on a fast GPU. ## 5. Fine-tune Faster R-CNN The training loop is plain PyTorch: the Lance integration ends at the loader. Mixed precision is enabled on CUDA for \~2× speedup on Ampere GPUs. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import time import torch from torchvision.models.detection import ( fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") use_amp = device.type == "cuda" # COCO pretrained weights — head left intact since BDD uses a subset of COCO IDs model = fasterrcnn_resnet50_fpn_v2( weights=FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1 ).to(device) train_loader = make_loader("data/bdd100k/lancedb", "bdd100k_rider_train", batch_size=64, num_workers=14, shuffle=True) val_loader = make_loader("data/bdd100k/lancedb", "bdd100k_rider_val", batch_size=64, num_workers=14) optimizer = torch.optim.SGD( [p for p in model.parameters() if p.requires_grad], lr=0.04, momentum=0.9, weight_decay=1e-4, ) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) scaler = torch.cuda.amp.GradScaler() if use_amp else None for epoch in range(1, 11): model.train() t0 = time.time() for images, targets in train_loader: images = [img.to(device) for img in images] targets = [{k: v.to(device) for k, v in t.items()} for t in targets] if all(t["labels"].numel() == 0 for t in targets): continue with torch.cuda.amp.autocast(enabled=use_amp): losses = sum(model(images, targets).values()) optimizer.zero_grad() if use_amp: scaler.scale(losses).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) scaler.step(optimizer) scaler.update() else: losses.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) optimizer.step() scheduler.step() print(f"epoch {epoch} ({time.time() - t0:.1f}s)") ``` ## 6. Pin the checkpoint to a data version Every Lance table, including a materialized view, exposes a monotonically increasing `version`. Logging it next to the weights gives a permanent, deterministic link between a checkpoint and the exact data snapshot that produced it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import json from pathlib import Path train_tbl = lancedb.connect("data/bdd100k/lancedb").open_table("bdd100k_rider_train") out = Path("checkpoints/rider") out.mkdir(parents=True, exist_ok=True) torch.save(model.state_dict(), out / "fasterrcnn_bdd_finetuned.pt") with open(out / "metadata.json", "w") as f: json.dump({ "train_table": train_tbl.name, "table_version": train_tbl.version, "row_count": len(train_tbl), }, f, indent=2) ``` To reproduce a run, [time-travel](/enterprise/v1-12-0/management/table#versioning) the view to the recorded version before opening the loader: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = lancedb.connect("data/bdd100k/lancedb").open_table("bdd100k_rider_train") tbl.checkout(version=7) # exact snapshot the checkpoint was trained on ``` ## 7. Continuous updates When new footage arrives, the same three calls update every downstream view (no view definitions change, no training-script edits required): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1. ingest the new footage into the source table table.add(new_record_batches) # 2. backfill computes only the new rows (incremental, checkpointed) with gconn.local_ray_context(): tbl.backfill("has_rider") tbl.backfill("person_bbox_area_pct") # 3. refresh appends qualifying new rows to every materialized view for view_name in gconn.table_names(): if view_name == "bdd100k": continue mv = gconn.open_table(view_name) before = mv.count_rows() mv.refresh() print(f"[{view_name}] {before} → {mv.count_rows()} rows (version {mv.version})") ``` The next training run picks up the new data automatically and pins itself to the new `version`. ## Full source The complete code, including a synthetic-data mode for pipeline verification (`--synthetic 500`), GPU UDFs for CLIP embeddings and dHash deduplication, and the EDA notebook, is in this [GitHub repository](https://github.com/lancedb/training/tree/main/object-detection). # Fine-tuning a VLM on TextVQA Source: https://docs.lancedb.com/enterprise/v1-12-0/training/vlm-finetuning End-to-end fine-tuning of Qwen2.5-VL on a curated TextVQA slice, using LanceDB and Geneva to materialize expensive vision-language features once and train from cached columns. This example walks through a vision-language model (VLM) fine-tuning pipeline for [TextVQA](https://textvqa.org/), where the task is to answer questions that require reasoning over text *inside an image*. The base model is `Qwen2.5-VL-3B-Instruct`, fine-tuned with the [QLoRA](https://arxiv.org/abs/2305.14314) method. The data backbone is one Lance table that evolves from raw multimodal rows into training-ready features. The key idea is simple: in this QLoRA fine-tuning setup, we freeze the VLM's image encoder and train only a small adapter on the language-model side. We call that encoder the **vision tower** in this example: it is the part of the model that turns image pixels into visual hidden states before the language model reads them alongside the text prompt. Because the vision tower's weights do not change during fine-tuning, its output for a given image also does not change. That means the pipeline can compute those visual hidden states once, store them as a fixed-size Lance column, and reuse them in every epoch instead of recomputing them in every training step. This also helps the run fit comfortably on a small GPU, because the training job does not need to keep the vision encoder active or pay for its forward pass on every batch. > [card] [Open the Colab demo](https://colab.research.google.com/github/lancedb/training/blob/vlm-textvqa/examples/vlm-textvqa/notebooks/colab_textvqa_lance.ipynb) > > Run the Colab-sized workflow on a free T4: download the pre-baked Lance subset, explore it, benchmark Lance vs Parquet, fine-tune with QLoRA, and evaluate base vs tuned answers. > [card] [View the full demo source](https://github.com/lancedb/tmls-2026-demo) > > Full demo repository with the notebook, Geneva UDFs, direct backfill fallback, dataloader, training loop, and evaluation scripts. The Colab notebook uses a pre-baked subset of the TextVQA dataset: it downloads a curated Lance subset whose expensive feature columns have already been computed. This page explains the complete end-to-end pipeline that produced that subset, then shows how the notebook applies it to produce a fine-tuned model that improves performance on the TextVQA task. ## What you get On the curated `text_dense` TextVQA slice, the demo fine-tunes `Qwen2.5-VL-3B-Instruct` with QLoRA and evaluates on held-out images: | Setup | TextVQA accuracy | | - | - | | Base model | 0.799 | | LoRA-tuned model | **0.820** | | Lift | **+2.1 percentage points** | The larger point is not the absolute score, because you could just as well fine-tune a better base model on more data. The main takeaways are the workflow and quality-of-life improvements that you get when you combine LanceDB and Geneva: 1. **Add expensive features** as new columns without rewriting the raw dataset. 2. **Read fixed-size model features efficiently** for shuffled PyTorch batches. 3. **Iterate quickly** from feature idea to scalable CPU/GPU backfill, using Geneva UDFs. ## Why LanceDB fits this workflow VLM fine-tuning pipelines spend a lot of time between "I have an experiment idea" and "I trained the model." LanceDB shortens that loop in three places. > [card] Cheap feature evolution > > Lance can append derived columns such as `ocr_token_count`, `dhash`, `vision_tower_hiddens`, and tokenized SFT prompts without rewriting the existing image/question/answer columns or managing sidecar files. > [card] Efficient training reads > > Lance is optimized for scans and random access over fixed-size lists, which are common in model training: embeddings, hidden states, token IDs, masks, and labels. > [card] Fast experiment turnaround > > Geneva lets AI engineers express feature work as UDFs, run those UDFs across CPU or GPU workers, and materialize the results directly into the same Lance table. In this pipeline, those three properties combine into the core optimization: compute the VLM vision features once, store them cheaply, then train by reading only the cached columns the model needs. ## Pipeline overview The runnable demo uses the exact Colab subset hosted at [`lance-format/textvqa-lance-colab`](https://huggingface.co/datasets/lance-format/textvqa-lance-colab). It is derived from the Lance-formatted TextVQA corpus and stores inline JPEG bytes, questions, answers, OCR tokens, object classes, CLIP image/question embeddings, and the cached training features used by this example. The full demo pipeline adds three tiers of derived features on top. > [card] Tier 1: text features > > Cheap CPU columns such as `question_length`, `answer_length`, `question_type`, and `ocr_token_count`. > [card] Tier 2: light image features > > Image-derived columns such as `dhash`, computed by decoding the JPEG once and storing a perceptual hash. > [card] Tier 3: VLM training features > > GPU-heavy columns: `vision_tower_hiddens` plus SFT token fields (`input_ids`, `attention_mask`, `labels`). The Colab notebook's workflow starts after all three tiers have been computed. It downloads a small curated subset and runs the training/evaluation path without needing to run Geneva or the vision-tower backfill on the notebook GPU. ## 1. Start with a multimodal LanceDB table The base schema comes from the TextVQA Lance dataset. One row contains the image bytes, natural-language question, reference answers, OCR tokens, scene tags, and retrieval embeddings. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa BASE_SCHEMA = pa.schema([ pa.field("id", pa.int64()), pa.field("image", pa.large_binary()), pa.field("image_id", pa.string()), pa.field("question_id", pa.string()), pa.field("question", pa.string()), pa.field("answers", pa.list_(pa.string())), pa.field("answer", pa.string()), pa.field("image_emb", pa.list_(pa.float32(), 512)), pa.field("question_emb", pa.list_(pa.float32(), 512)), pa.field("ocr_tokens", pa.list_(pa.string())), pa.field("image_classes", pa.list_(pa.string())), pa.field("set_name", pa.string()), ]) ``` Because the raw image, text, OCR, and embedding features live together, the same table supports curation, retrieval, feature engineering, and training. For example, the notebook can run a text-to-image retrieval demo by searching `image_emb` with a question embedding that already exists in the row. ## 2. Add feature columns with Geneva Geneva turns feature engineering into UDF definitions plus backfills. The UDFs can be simple text functions, image-processing functions, or stateful GPU model calls. The Tier 1 features are ordinary CPU UDFs: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import re import pyarrow as pa from geneva.transformer import udf _QUESTION_TYPE_PATTERNS = [ ("how_many", re.compile(r"^\s*how\s+many\b", re.IGNORECASE)), ("what_brand", re.compile(r"^\s*what\s+(is\s+the\s+)?(brand|company|make)\b", re.IGNORECASE)), ("what", re.compile(r"^\s*what\b", re.IGNORECASE)), ] @udf(data_type=pa.string(), input_columns=["question"]) def question_type(question: str) -> str: for label, pattern in _QUESTION_TYPE_PATTERNS: if pattern.search(question or ""): return label return "other" @udf(data_type=pa.int32(), input_columns=["ocr_tokens"]) def ocr_token_count(ocr_tokens: list[str] | None) -> int: return len(ocr_tokens) if ocr_tokens else 0 ``` The Tier 3 feature is heavier: run Qwen2.5-VL's frozen vision tower once, then store the merged visual hidden states as a fixed-size fp16 list. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} IMAGE_PX = 560 LLM_TOKENS_PER_IMAGE = 400 VISION_HIDDEN = 2048 @udf( data_type=pa.list_(pa.float16(), LLM_TOKENS_PER_IMAGE * VISION_HIDDEN), input_columns=["image"], ) class VisionTowerEmbedder: def __init__(self): self._model = None self._processor = None def _lazy_load(self): if self._model is not None: return import torch from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration self._torch = torch self._model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-3B-Instruct", torch_dtype=torch.bfloat16, device_map="cuda:0", ).model.visual.eval() self._processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct") def __call__(self, image: bytes) -> list[float]: self._lazy_load() # Decode image, resize to IMAGE_PX, run the frozen vision tower, # and return fp16[400, 2048] flattened as one fixed-size list. ... ``` The fixed shape matters. With `IMAGE_PX = 560`, Qwen2.5-VL produces 400 merged visual tokens, each with hidden size 2048. That becomes one `fp16[400 * 2048]` column per row. Training can scan and randomly access that column without decoding images or running the vision tower in the hot loop, saving GPU compute at training time. Run the tiered backfill with Geneva: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -m vlm.backfill_geneva --tier 1 # CPU text columns python -m vlm.backfill_geneva --tier 2 # image decode + dhash python -m vlm.backfill_geneva --tier 3 # vision tower + SFT tokens ``` > [!TIP] > > The same Tier 3 work can be done manually by creating PyArrow batches and calling Lance's column-evolution APIs directly. The demo repo includes [`backfill_direct.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_direct.py) for that path. Geneva is the preferred abstraction when you want to scale the same feature code across CPU or GPU workers and keep backfills incremental. See the full UDF registry in [`vlm/geneva_udfs.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/geneva_udfs.py) and the backfill driver in [`vlm/backfill_geneva.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_geneva.py). ## 3. Curate a training slice The demo uses a `text_dense` slice: TextVQA examples whose images contain many OCR tokens. The slice was chosen empirically because it gave the clearest LoRA lift over the already-strong base model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} TEXT_DENSE_OCR_THRESHOLD = 16 def matches_text_dense(row: dict) -> bool: return len(row.get("ocr_tokens") or []) >= TEXT_DENSE_OCR_THRESHOLD ``` The Colab-ready bake ingests a small train split, backfills Tier 3 on that train table, ingests a held-out validation split, and optionally pushes the result to HuggingFace: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -m vlm.colab_prepare \ --out data/colab \ --slice text_dense \ --train-rows 600 \ --val-rows 400 \ --hf-repo lance-format/textvqa-lance-colab \ --push ``` The train table contains cached Tier 3 columns because training reads them directly. The validation table keeps raw images because evaluation should run the full VLM on unseen images. ## 4. Explore the prepared table Before training, it helps to look at the actual task. Each row pairs an image with a question whose answer is often visible as text in the image: a product label, phone screen, sign, book spine, or package. > [card] Q: what is the name of the airline on the sugar packet? > > **A:** TWA > > **OCR:** 7h the Finest... 74 1E TWA 8 SALT REESE PEPPER > [card] Q: what time is displayed? > > **A:** 12:39 am > > **OCR:** AT\&T 12:39 AM TV CS WATCH P PANDORA YouTube Ustream > [card] Q: what brand of building block is this? > > **A:** lego > > **OCR:** LEGO CITY Ages/edades 5-12 POLICE B-403 4473 112 112 pcs > [card] Q: what is printed in red? > > **A:** warning > > **OCR:** WARNING Controlled Area Itis unlawf enter thisre without permission nstallation The notebook downloads the public pre-baked subset: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from huggingface_hub import snapshot_download import os local = snapshot_download( repo_id="lance-format/textvqa-lance-colab", repo_type="dataset", local_dir="data/colab", ) def open_tbl(path: str): name = os.path.basename(path).removesuffix(".lance") return lancedb.connect(os.path.dirname(path)).open_table(name) train_tbl = open_tbl(f"{local}/textvqa_colab_train.lance") val_tbl = open_tbl(f"{local}/textvqa_colab_val.lance") ``` Because the table also ships CLIP embeddings, you can run cross-modal retrieval without loading a model: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np seed = ( train_tbl.search() .select(["question", "question_emb"]) .limit(40) .to_arrow() .to_pylist()[11] ) hits = ( train_tbl.search( np.asarray(seed["question_emb"], dtype=np.float32), vector_column_name="image_emb", ) .select(["image", "question", "answer", "_distance"]) .limit(5) .to_arrow() .to_pylist() ) ``` This is the same table that later feeds training. There is no separate feature store, image directory, Parquet export, or manifest to keep synchronized. ## 5. Benchmark Lance vs Parquet-style reads Many training pipelines start with Parquet. Parquet is excellent for columnar analytics, but training commonly needs shuffled batches and fixed-size tensor columns. The notebook compares Lance and Parquet on two access patterns: | Column group | Why it matters | | - | - | | `image`, `question`, `answer` | Raw multimodal rows: the baseline "decode and tokenize during training" path. | | `vision_tower_hiddens` | Cached fixed-size fp16 VLM features: the optimized training path. | The notebook mirrors those column groups to uncompressed Parquet, then measures sequential scans and shuffled random batches: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} RAW = ["image", "question", "answer"] VEC = ["vision_tower_hiddens"] BATCH = 8 lance_ds = train_tbl.to_lance() n = train_tbl.count_rows() def seq(ds, cols): t0 = time.time() for _ in ds.to_batches(columns=cols, batch_size=BATCH): pass return n / (time.time() - t0) def shuf(ds, cols, num_batches=20): batches = [ sorted(rng.choice(n, BATCH, replace=False).tolist()) for _ in range(num_batches) ] t0 = time.time() for idx in batches: ds.take(idx, columns=cols) return (num_batches * BATCH) / (time.time() - t0) ``` One Colab run produced the following throughput: | Throughput, rows/s | LanceDB | Parquet | | - | -: | -: | | `image` + `question` + `answer`, sequential | 2,603 | 8,311 | | `image` + `question` + `answer`, shuffled | 2,613 | 352 | | `vision_tower_hiddens` fp16, sequential | 1,452 | 90 | | `vision_tower_hiddens` fp16, shuffled | 2,149 | -- | The takeaways are workload-specific: * For a traditional sequential scan over raw image/question/answer columns, Parquet is faster in this run: 8,311 rows/s vs 2,603 rows/s. * For shuffled raw multimodal batches, Lance is faster because training reads scattered rows repeatedly instead of streaming the file once. * For cached fp16 fixed-size arrays, Lance is about 16x faster than Parquet on the sequential scan. This is the training-relevant path in this example: the model reads `vision_tower_hiddens`, token IDs, masks, and labels as fixed-size columns. * The benchmark intentionally skips the Parquet fp16 shuffled case. Parquet would re-decode whole row groups for each random batch, which is slow enough to distract from the real use case. The sequential fp16 row already shows the layout gap, while Lance shuffled reads remain fast. The numbers shown above are central to the example. The Tier 3 feature is only useful if the storage format can read it efficiently in the way a trainer actually needs: projected columns, repeated scans, and shuffled batches. **Lance specializes in exactly that access pattern**, including fixed-size list columns stored on disk. ## 6. Load cached columns with the Permutation API The training DataLoader projects only the columns needed by the cached training loop: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation CACHED_COLS = [ "vision_tower_hiddens", "input_ids", "attention_mask", "labels", ] class LancePermutationDataset(torch.utils.data.Dataset): def __init__(self, uri: str, table_name: str): self.uri = uri self.table_name = table_name self._perm = None self.length = len(lancedb.connect(uri).open_table(table_name)) def __len__(self): return self.length def __getstate__(self): state = self.__dict__.copy() state["_perm"] = None return state def _ensure_open(self): if self._perm is None: tbl = lancedb.connect(self.uri).open_table(self.table_name) self._perm = ( Permutation.identity(tbl) .select_columns(CACHED_COLS) .with_format("arrow") ) def __getitems__(self, indices: list[int]): self._ensure_open() return self._perm.__getitems__(indices) ``` Each worker opens its own `Permutation`, reads Arrow batches directly from Lance, and avoids per-row Python object conversion until the collate function converts arrays into tensors. The training batch contains: | Field | Shape | | - | - | | `vision_hiddens` | `fp16[B, 400, 2048]` | | `input_ids` | `int64[B, 512]` | | `attention_mask` | `int64[B, 512]` | | `labels` | `int64[B, 512]` | ## 7. Fine-tune without loading the vision tower The training process loads the language-model side of Qwen2.5-VL in 4-bit, deletes the vision tower, and wraps the LLM projections with LoRA adapters. During the forward pass, the model embeds the token IDs, finds the `<|image_pad|>` positions, and inserts the cached visual hidden states into those positions: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def forward_cached(model, batch, image_pad_id: int): base = model.get_base_model() if hasattr(model, "get_base_model") else model inner = base.model inputs_embeds = inner.get_input_embeddings()(batch.input_ids) _, _, hidden_dim = inputs_embeds.shape mask = ( (batch.input_ids == image_pad_id) .unsqueeze(-1) .expand_as(inputs_embeds) ) vision_flat = batch.vision_hiddens.to(inputs_embeds.dtype).reshape(-1, hidden_dim) inputs_embeds = inputs_embeds.masked_scatter(mask, vision_flat) return model( inputs_embeds=inputs_embeds, attention_mask=batch.attention_mask, labels=batch.labels, ).loss ``` At this point, the LanceDB integration is done. The rest is plain PyTorch: optimizer, gradient accumulation, checkpointing, and saving the LoRA adapter. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} loader = make_cached_loader( "data/colab/textvqa_colab_train.lance", batch_size=2, shuffle=True, ) for batch in loader: batch = batch.to(device) loss = forward_cached(model, batch, image_pad_id) (loss / grad_accum).backward() ... ``` This produces a training log like the following. The loss falls as the adapter learns from the cached features, and peak VRAM stays at 5.3 GB because QLoRA trains without keeping the vision tower active: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} step 10/300 loss=2.6694 5.9 samples/s step 20/300 loss=2.3133 6.1 samples/s . . . step 290/300 loss=0.0359 6.3 samples/s step 300/300 loss=0.4750 6.3 samples/s saved adapter to runs/colab_lora/lora | peak VRAM 5.3 GB ``` The training loop pays zero per-step cost for image decode, vision-tower forward, or prompt tokenization. Those costs were moved into feature engineering, where LanceDB and Geneva make them durable, incremental, and reusable. ## 8. Evaluate on held-out images Evaluation uses the held-out validation table and loads the full VLM, including the vision tower. That is intentional: inference should see raw unseen images, not the cached train features. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( val_tbl.search() .select(["image", "question", "answer", "answers"]) .limit(256) .to_arrow() .to_pylist() ) base_model, processor = load_model(adapter_dir=None, load_4bit=True) tuned_model, processor = load_model(adapter_dir="runs/colab_lora/lora", load_4bit=True) base_score = score_textvqa(base_model, processor, rows) tuned_score = score_textvqa(tuned_model, processor, rows) ``` In this end-to-end example, the held-out curated validation split produced: | Model | TextVQA accuracy | | - | -: | | Base `Qwen2.5-VL-3B-Instruct` | 0.799 | | QLoRA-tuned adapter | **0.820** | | Lift | **+2.1 percentage points** | The tuned adapter is not meant to be a state-of-the-art TextVQA checkpoint. It is the proof point for the pipeline: the same Lance table supports curation, feature engineering, efficient training reads, and evaluation on held-out raw images. The notebook renders side-by-side examples: image, question, base answer, tuned answer, and ground truth. This closes the loop from feature idea to trained model while keeping the source data, derived features, training batches, and evaluation split in Lance. ## Full source The complete demo implementation with helper scripts and usage instructions is in [this repo](https://github.com/lancedb/tmls-2026-demo). > [card] [Notebook](https://github.com/lancedb/training/blob/vlm-textvqa/examples/vlm-textvqa/notebooks/colab_textvqa_lance.ipynb) > > The runnable Colab workflow: download, explore, benchmark, train, and evaluate. > [card] [UDF registry](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/geneva_udfs.py) > > Tier 1, Tier 2, and Tier 3 feature definitions. > [card] [Backfill driver](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_geneva.py) > > Feature materialization for the tiers above. > [card] [Training loop](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/train_qwen25vl_lora.py) > > QLoRA training from cached Lance columns. # Agentic RAG Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/agentic-rag Several agents collaborating to retrieve and answer. Builds a RAG system where multiple agents collaborate (retrieving information, checking it, and generating answers) rather than a single retrieve-then-generate pass. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Agentic_RAG/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/Agentic_RAG) > > Read the source. # Contextual RAG Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/contextual-rag Prepend LLM-generated context to each chunk before embedding it. Addresses the "lost in the middle" problem in retrieval. An LLM generates a succinct piece of context for each document chunk, which is prepended to the chunk before embedding, so a chunk carries enough surrounding meaning to be retrieved for the right queries. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Contextual-RAG/Anthropic_Contextual_RAG.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Contextual-RAG) > > Read the source. # HyDE: hypothetical document embeddings Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/hyde Generate a hypothetical answer, then retrieve documents similar to it. An LLM writes a hypothetical document answering the query, and that document, not the query, is embedded and used for retrieval. It works because a plausible answer sits nearer the real answers in embedding space than a question does. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Advance-RAG-with-HyDE/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Advance-RAG-with-HyDE) > > Read the source. # Late chunking Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/late-chunking Retrieve whole documents first, chunk them afterwards. Inverts the usual order: documents are retrieved first and chunked just before synthesis. Chunking late preserves context that pre-chunking discards, since a chunk is cut with knowledge of the query it is answering. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Advanced_RAG_Late_Chunking/Late_Chunking_\(Chunked_Pooling\).ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Advanced_RAG_Late_Chunking) > > Read the source. # Matryoshka embeddings Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/matryoshka-embeddings Nested, variable-size embeddings with LanceDB and LlamaIndex. A RAG pipeline built on Matryoshka embeddings with LlamaIndex. The embeddings nest, so one model serves several dimensionalities: store the full vector and retrieve with a truncated one when the cheaper comparison is good enough. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/RAG-with_MatryoshkaEmbed-Llamaindex/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/RAG-with_MatryoshkaEmbed-Llamaindex) > > Read the source. # Multimodal Agent Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/multimodal-agent/index Build an AI agent that understands both text and images to help users find recipes using LanceDB and PydanticAI [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) Ever wanted to combine the power of text and images in a single AI agent? In this tutorial, you'll build an agent that can understand both text and images to help users discover recipes that are relevant to them. The approach shown combines LanceDB's multimodal capabilities with [Pydantic AI](https://ai.pydantic.dev/) for the agentic workflow. ## Key Technologies * **LanceDB**: Embedded retrieval library and multimodal lakehouse for efficient storage and retrieval * **PydanticAI**: Modern AI agent framework with type safety * **Sentence Transformers**: Text embeddings for semantic search * **CLIP**: Vision-language model for image understanding * **Streamlit**: Interactive web application framework ## Tutorial Overview ### Option 1: Notebook The notebook shows how to work through the steps and prepare a small sample recipe dataset, generate both text and image embeddings, store everything efficiently in LanceDB, and then build a PydanticAI agent with custom tools to query it. You'll finish by testing the agent against a few example questions to see the full multimodal flow end to end. > [card] [Notebook](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) > > This simple tutorial provides a step-by-step workflow with a small demo dataset of 4 examples. > No local setup required - just click and start learning about multimodal agents. > [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) ### Option 2: Demo Application (Local Setup) The demo application is the full codebase: you'll download and process a real recipe dataset with thousands of items, run a Streamlit chat interface that supports image upload, and follow a structure that includes production-minded touches like error handling, logging, and monitoring. Everything you need to deploy is included. > [card] [Download Tutorial Files](https://github.com/lancedb/vectordb-recipes/tree/main/applications/multimodal-recipe-agent) > > Download the files for the full demo application here. ### Dataset Information * **Source**: [Kaggle Recipe Dataset](https://www.kaggle.com/datasets/pes12017000148/food-ingredients-and-recipe-dataset-with-images) * **Size**: Thousands of recipes with images * **Format**: CSV file with recipe data and image references ### Setup ```bash bash icon="code" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1. Extract the downloaded files to a folder # 2. Navigate to the folder in terminal cd multimodal-recipe-agent # 3. Install dependencies with uv uv sync # 4. Download the Kaggle dataset # Visit: https://www.kaggle.com/datasets/pes12017000148/food-ingredients-and-recipe-dataset-with-images # Extract recipes.csv to the data/ folder # 5. Import the dataset uv run python import.py # 6. Run the complete Streamlit chat application uv run streamlit run app.py ``` # NVIDIA RAG Blueprint with LanceDB Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/nvidia-rag-blueprint/index Use LanceDB as the retrieval layer for NVIDIA RAG Blueprint with a Docker-first, retrieval-only reference integration. ## What this tutorial shows If you are using [NVIDIA RAG Blueprints](https://build.nvidia.com/blueprints) and want to evaluate LanceDB in that stack, this tutorial gives you a concrete starting point. It shows how to use LanceDB as the retrieval layer for a Docker-based NVIDIA RAG deployment with a small, script-driven reference integration where LanceDB Embedded runs directly in the NVIDIA containers, the collection is prepared ahead of time, and the RAG server retrieves from it for search and generation. The example is intentionally retrieval-only, but it also includes hybrid search and reranker selection so you can see how LanceDB fits into a realistic NVIDIA retrieval workflow. > [!TIP] > > The runnable example for this tutorial lives in the > [VectorDB recipes repository](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb). ## How NVIDIA organizes vector databases NVIDIA's [RAG Blueprint documentation](https://docs.nvidia.com/rag/latest/readme.html) effectively describes three different patterns for vector database support. 1. There are built-in backends such as Milvus, where NVIDIA already owns both ingestion and retrieval. 2. There are built-in alternatives such as Elasticsearch, where NVIDIA still owns the end-to-end flow but switches the backend through configuration. 3. Then, there is the custom vector database path, where you implement a `VDBRag` backend yourself and register it in NVIDIA's factory. The LanceDB example shown below fits into the third category. More specifically, it follows NVIDIA's **retrieval-only** custom backend path: the data is prepared in LanceDB ahead of time, and NVIDIA RAG Blueprint is then pointed at that existing collection for search and generation. It does not yet teach NVIDIA's ingestor how to write new documents into LanceDB automatically. ## Deployment model This reference integration uses **LanceDB Embedded as an embedded retrieval library**, not as a separate database service. In practice, `APP_VECTORSTORE_NAME` is set to `lancedb`, `APP_VECTORSTORE_URL` points to a local filesystem path inside the NVIDIA containers, the LanceDB collection is prepared ahead of time, and the NVIDIA RAG server loads the LanceDB adapter to retrieve directly from that local dataset. ## What the recipe contains The recipe at [`examples/nvidia-rag-blueprint-lancedb`](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb) is organized around a small number of practical pieces. The data-prep script builds a demo LanceDB collection from scratch, generates embeddings through the LanceDB embedding registry, and creates a full-text index so hybrid retrieval works immediately. The adapter file shows the retrieval-only integration point for NVIDIA RAG Blueprint, while the Docker override and NVIDIA change guide show the minimal configuration and source changes needed to run the example against NVIDIA's containers. ## End-to-end flow ### 1. Prepare the LanceDB collection From the [recipe directory](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv sync uv run prepare_lancedb.py --embedder demo-keyword --reranker mrr ``` That script creates: * a local LanceDB dataset under `data/` * a collection named `nvidia_blueprint_demo` * automatic embeddings generated at ingest time * an FTS index for hybrid search The default embedder is an offline demo embedder so the example stays easy to run. If you want a more realistic setup, the same script can switch to a sentence-transformers embedder. ### 2. Patch the NVIDIA blueprint Follow the instructions in the recipe's [`nvidia_blueprint_changes.md`](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb/nvidia_blueprint_changes.md). The essential changes are: * add LanceDB dependencies to the NVIDIA environment * copy `lancedb_vdb.py` into the NVIDIA source tree * register the `lancedb` branch in NVIDIA's VDB factory NVIDIA's [RAG blueprint documentation](https://docs.nvidia.com/rag/latest/readme.html) and custom-VDB guide provide useful background if you want more context before applying the LanceDB-specific changes. ### 3. Start the Docker deployment Set the absolute path to the recipe directory: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_RECIPE_DIR=/absolute/path/to/vectordb-recipes/examples/nvidia-rag-blueprint-lancedb ``` Then from the NVIDIA repo root: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docker compose \ -f deploy/compose/docker-compose-rag-server.yaml \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ up -d --build docker compose \ -f deploy/compose/docker-compose-ingestor-server.yaml \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ up -d --build ``` The key environment values are: * `APP_VECTORSTORE_NAME=lancedb` * `APP_VECTORSTORE_URL=/opt/lancedb-recipe/data` * `COLLECTION_NAME=nvidia_blueprint_demo` * `APP_VECTORSTORE_SEARCHTYPE=hybrid` * `LANCEDB_RERANKER=mrr` ## Verifying the integration ### Search ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X POST http://localhost:8081/v1/search \ -H 'Content-Type: application/json' \ -d '{ "query": "How do I replace Milvus in the NVIDIA RAG blueprint with LanceDB?", "use_knowledge_base": true, "collection_names": ["nvidia_blueprint_demo"], "vdb_top_k": 3, "reranker_top_k": 0 }' ``` ### Generate ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -N -X POST http://localhost:8081/v1/generate \ -H 'Content-Type: application/json' \ -d '{ "messages": [{"role":"user","content":"Summarize the LanceDB integration approach."}], "use_knowledge_base": true, "collection_names": ["nvidia_blueprint_demo"], "vdb_top_k": 3, "reranker_top_k": 0 }' ``` ## Hybrid retrieval and rerankers This example is meant to prove more than a trivial vector lookup. * LanceDB hybrid retrieval combines vector search with full-text search * the recipe creates the FTS index as part of dataset prep * the adapter supports `RRFReranker`, `MRRReranker`, and `CrossEncoderReranker` * the default example uses `MRRReranker`, not a plain weighted linear combination Hybrid retrieval is important for NVIDIA partner workloads because product names, storage platforms, and technical jargon often need exact lexical matching as well as semantic retrieval. ## How this can be extended The current example follows NVIDIA's **custom retrieval-only backend** path. In practice, that means the LanceDB collection is created ahead of time and NVIDIA RAG Blueprint is then pointed at that existing collection for search and generation. The sample data in `prepare_lancedb.py` exists only to make that flow runnable end to end: it creates a small local collection, inserts a few documents, generates embeddings, and builds an FTS index so the NVIDIA side has something real to query. A fuller integration is possible. NVIDIA's custom `VDBRag` interface also supports the pattern used by built-in backends such as Milvus and Elasticsearch, where NVIDIA owns both ingestion and retrieval. To make LanceDB work that way, a complete LanceDB backend would need to implement the ingestion methods NVIDIA documents, especially `create_collection` and `write_to_index`, along with the retrieval and collection-management methods expected by the rest of the stack. The open work is in defining how NVIDIA's ingestor should write records into LanceDB, how that storage is shared between the ingestor and the RAG server, and how document and collection metadata should be exposed so the broader NVIDIA APIs behave correctly. Until those pieces exist, this example should be read as: prepare LanceDB first, then let NVIDIA retrieve from it. # Time-Travel RAG with versioned data Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/agents/time-travel-rag/index Build a RAG example that retrieves documents from a selected table version. > [!TIP] > > All the scripts and code for this tutorial are available in the > [vectorDB recipes](https://github.com/lancedb/vectordb-recipes/tree/main/examples/time-travel-rag) repository. ## Use case: Financial services regulatory knowledge base Imagine you're a major investment bank. Your team is tasked with building a critical Retrieval-Augmented Generation (RAG) system. This system must provide instant, accurate answers to compliance officers about ever-changing financial regulations. A wrong or out-of-date answer isn't just an inconvenience: it could lead to multi-million dollar fines, reputational damage, and regulatory audits. Your knowledge base is a living entity, constantly evolving with: * Daily regulatory updates from government bodies. * New internal policy documents and interpretations. * A/B testing of different embedding models and text chunking strategies to improve accuracy. This dynamic environment creates a series of high-stakes challenges that traditional vector databases are ill-equipped to handle. ## Pain points solved by LanceDB 1. "Our RAG gave different answers yesterday versus today. Which version was used in the official compliance report?" Without versioning, you can't prove what the AI knew at a specific point in time, making audits impossible. 2. "The new embedding model we deployed corrupted half the vectors. Can we instantly roll back our 10TB dataset?" With traditional systems, a rollback means a painful, hours-long (or days-long) process of re-indexing from a backup, leading to significant downtime. 3. "Regulators want to audit an AI-assisted decision from three months ago. How can we prove what data the model had access to at that exact moment?" Reproducibility is key for compliance. You must be able to reconstruct the exact state of the knowledge base for any historical query. 4. "We need to A/B test a new chunking strategy, but we can't disrupt the production system or duplicate the entire dataset." Experimentation is vital for improvement, but it can't come at the cost of production stability or a massive infrastructure bill. LanceDB's [column-based data evolution](/enterprise/v1-12-0/management/table#schema) and [time-travel capabilities](/enterprise/v1-12-0/management/table#versioning) help preserve the dataset used for a particular answer. This tutorial demonstrates versioned retrieval; production auditing also needs application logs, retention policies and access controls. ## Dataset: The U.S. Federal Register To make this use case realistic, we'll use a perfect real-world dataset: The U.S. Federal Register, the official daily journal of the United States Government. It contains all new rules, proposed rules, and notices from federal agencies. It is the canonical source for regulatory changes, and it's updated every business day. It even has a public API, allowing us to simulate the real-time ingestion of new documents. An example output of the workflow defined in main.py is shown below. ```bash main.py expandable icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} --- Initializing Database Environment --- Removed old database at ./lancedb Loading embedding model: all-MiniLM-L6-v2... --- STEP 1: Initial Data Ingestion --- Fetching 500 documents for publication date: 2024-08-19... Successfully fetched 86 documents. Embedding 86 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 7.12it/s] Successfully embedded 86 documents. Creating table 'federal_register'... ✅ Table 'federal_register' created. Version: 1, Rows: 86 --- STEP 2: Simulating Sequential Daily Updates --- Fetching 500 documents for publication date: 2024-08-20... Successfully fetched 102 documents. Embedding 102 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 10.66it/s] Successfully embedded 102 documents. ✅ Data added to 'federal_register'. New Version: 2, Total Rows: 188 Fetching 500 documents for publication date: 2024-08-21... Successfully fetched 114 documents. Embedding 114 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 10.19it/s] Successfully embedded 114 documents. ✅ Data added to 'federal_register'. New Version: 3, Total Rows: 302 ======================================================== = PART 1: AUDITING KNOWLEDGE BASE ACROSS TIME = ======================================================== Running audit for query: 'cybersecurity reporting requirements for public companies' Attempting to open 'federal_register' and checkout version 1... ✅ Successfully checked out Version 1 of 'federal_register'. Total rows: 86 Querying table 'federal_register' (Version 1)... --- Top Result for Version: V1 (all-MiniLM-L6-v2) --- 📄 Title: Public Company Accounting Oversight Board; Extension of Approval Periods for Proposed Rules on a Firm's System of Quality Control and Related Amendments to PCAOB Standards, Proposed Rules on Amendments Related to Aspects of Designing and Performing Audit Procedures That Involve Technology-Assisted Analysis of Information in Electronic Form, and Proposed Rules on Amendment to PCAOB Rule 3502 Governing Contributory Liability 🗓️ Date: 2024-08-19 📏 Distance: 1.1667 📝 Abstract: [No abstract available for this document] -------------------------------------- Attempting to open 'federal_register' and checkout version 2... ✅ Successfully checked out Version 2 of 'federal_register'. Total rows: 188 Querying table 'federal_register' (Version 2)... --- Top Result for Version: V2 (all-MiniLM-L6-v2) --- 📄 Title: Information Collection Being Reviewed by the Federal Communications Commission Under Delegated Authority 🗓️ Date: 2024-08-20 📏 Distance: 1.1436 📝 Abstract: As part of its continuing effort to reduce paperwork burdens, and as required by the Paperwork Reduction Act (PRA) of 1995, the Federal Communications Commission (FCC or the Commission) invites the general public and other Federal agencies to take this opportunity to comment on the following information collection. Comments are requested concerning: whether the proposed collection of information is necessary for the proper performance of the functions of the Commission, including whether the information shall have practical utility; the accuracy of the Commission's burden estimate; ways to enhance the quality, utility, and clarity of the information collected; ways to minimize the burden of the collection of information on the respondents, including the use of automated collection techniques or other forms of information technology; and ways to further reduce the information collection burden on small business concerns with fewer than 25 employees. The FCC may not conduct or sponsor a collection of information unless it displays a currently valid control number. No person shall be subject to any penalty for failing to comply with a collection of information subject to the PRA that does not display a valid Office of Management and Budget (OMB) control number. -------------------------------------- Attempting to open 'federal_register' and checkout version 3... ✅ Successfully checked out Version 3 of 'federal_register'. Total rows: 302 Querying table 'federal_register' (Version 3)... --- Top Result for Version: V3 (all-MiniLM-L6-v2) --- 📄 Title: Equipment, Systems, and Network Information Security Protection 🗓️ Date: 2024-08-21 📏 Distance: 1.0942 📝 Abstract: This proposed rulemaking would impose new design standards to address cybersecurity threats for transport category airplanes, engines, and propellers. The intended effect of this proposed action is to standardize the FAA's criteria for addressing cybersecurity threats, reducing certification costs and time while maintaining the same level of safety provided by current special conditions. -------------------------------------- ✅ Date-based audit complete. Results show how knowledge evolves over time. This demonstrates LanceDB's powerful [versioning capabilities](/tutorials/tables/consistency#versioning) for maintaining audit trails. ============================================================= = PART 2: A/B TESTING DIFFERENT EMBEDDING MODELS = ============================================================= Loading embedding model: all-mpnet-base-v2... Embedding 302 documents... Batches: 100%|█████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:03<00:00, 2.55it/s] Successfully embedded 302 documents. Creating table 'federal_register_experimental'... ✅ Table 'federal_register_experimental' created. Version: 1, Rows: 302 Comparing search results for the same data with different models: Querying table 'federal_register' (Version 3)... --- Top Result for Version: Latest Prod V3 (all-MiniLM-L6-v2) --- 📄 Title: Equipment, Systems, and Network Information Security Protection 🗓️ Date: 2024-08-21 📏 Distance: 1.0942 📝 Abstract: This proposed rulemaking would impose new design standards to address cybersecurity threats for transport category airplanes, engines, and propellers. The intended effect of this proposed action is to standardize the FAA's criteria for addressing cybersecurity threats, reducing certification costs and time while maintaining the same level of safety provided by current special conditions. -------------------------------------- Querying table 'federal_register_experimental' (Version 1)... --- Top Result for Version: Experimental (all-mpnet-base-v2) --- 📄 Title: Commission Information Collection Activities (FERC-725B); Comment Request; Extension 🗓️ Date: 2024-08-20 📏 Distance: 1.0827 📝 Abstract: In compliance with the requirements of the Paperwork Reduction Act of 1995, the Federal Energy Regulatory Commission (Commission or FERC) is soliciting public comment on the currently approved information collection, FERC-725B, Mandatory Reliability Standards, Critical Infrastructure Protection (CIP) (Update for CIP-012-1 to version CIP-012-02) Cyber Security--Communications between Control Centers. The 60-day notice comment period ended on July 23, 2024, with no comments received. -------------------------------------- ✅ A/B test complete. Notice the difference in relevance (distance score) between models. This showcases how LanceDB enables [experimentation with different embedding models](/docs/embeddings/) without disrupting production systems. ``` # Feature engineering 101 Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/feature-engineering/feature-engineering-101 Add derived feature columns to an existing table. Adds new derived features to a table, the pattern documented under [computed columns](/enterprise/v1-12-0/feature-engineering/add-computed-column). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/feature-engineering/feature-engineering-101.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/feature-engineering/feature-engineering-101.ipynb) > > Read the source. # Materialized views Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/feature-engineering/materialized-views Persist query results as physical tables and keep them current. Creates [materialized views](/enterprise/v1-12-0/management/materialized-view): query results persisted as physical tables, brought up to date by a [refresh](/enterprise/v1-12-0/feature-engineering/refresh-materialized-view). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/feature-engineering/materialized-views.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/feature-engineering/materialized-views.ipynb) > > Read the source. # Tutorials Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/index Worked examples of building with LanceDB, grouped by what they build. Every tutorial is one page in the sidebar, grouped by what it builds. The documentation explains how a feature works; these show it doing something. Examples marked as notebooks live in the [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository and are runnable in Colab; the rest are written up here. ## Where to start > [card] [Search](/enterprise/v1-12-0/tutorials/search/hybrid-search-beir) > > Vector, multi-vector, hybrid and full-text retrieval. > [card] [RAG](/enterprise/v1-12-0/tutorials/agents/contextual-rag) > > Retrieval-augmented generation and agent applications. > [card] [Feature engineering](/enterprise/v1-12-0/tutorials/feature-engineering/feature-engineering-101) > > Deriving columns and materialized views. > [card] [Training](/enterprise/v1-12-0/training/object-detection) > > Curating data and training models directly on a table. ## The features these use | Feature | What it covers | | :- | :- | | [Vector search](/enterprise/v1-12-0/search/vector-search) | Similarity search, distance metrics, and tuning it. | | [Full-text search](/enterprise/v1-12-0/search/full-text-search) | Keyword search over text columns. | | [Hybrid search](/enterprise/v1-12-0/search/hybrid-search) | Keyword and vector search combined. | | [Multi-vector search](/enterprise/v1-12-0/search/vector-search) | Several embeddings per document. | | [Reranking](/enterprise/v1-12-0/reranking) | Reordering results to improve the top-k. | | [Feature engineering](/enterprise/v1-12-0/feature-engineering) | Deriving columns and tables from data already stored. | | [Materialized views](/enterprise/v1-12-0/management/materialized-view) | A table defined by a query, brought up to date by each refresh. | | [Training](/enterprise/v1-12-0/training/data-loading) | Reading a table into a data loader. | # Hybrid search and reranking on BEIR Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/hybrid-search-beir Combine semantic and keyword search on the BEIR benchmark, then rerank the results. Uses LanceDB's built-in [hybrid search](/enterprise/v1-12-0/search/hybrid-search), which combines the strengths of semantic and full-text search. Working against the BEIR dataset, it shows how searching for both the meaning of a query and the specific keywords in it produces more relevant results than either alone, and how a [reranker](/enterprise/v1-12-0/reranking) refines what comes back. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Inbuilt-Hybrid-Search/Inbuilt_Hybrid_Search_with_LanceDB.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Inbuilt-Hybrid-Search) > > Read the source. # Finding the Needle in a Haystack: Comparing Multi-vector Search Strategies Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/multivector-needle-in-a-haystack Tutorial on token-level retrieval with LanceDB multivector search. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-1.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=75175ce9a9ec25fd77aad7ca4f8d7298) In the development of advanced search and retrieval systems, moving from keyword matching to semantic understanding is a critical step. However, a key distinction exists between finding a relevant document and locating a specific piece of information within that document with precision. While there are techniques that perform well for retrieving documents, most of them work by extracting summarized semantic meaning of the document. This can be seen as these models trying to understand the "gist" of the documents. Both single-vector search and late-interaction approaches work well for these conditions with various tradeoffs involved. But there's another type of problem where the goal is not just to understand the overall topic of a document in general, but to also specifically account for the requested detail within the document. This "needle in a haystack" problem is a significant challenge, and addressing it is essential for building high-precision retrieval systems. This guide provides a technical analysis of multivector search for high-precision information retrieval. We will examine various optimization strategies and analyze their performance. This guide should be seen as complementary to resources like [this blog post by Answer.AI](https://www.answer.ai/posts/colbert-pooling.html) on ColBERT pooling, which explains how pooling strategies can be effective for document-level retrieval. Here, we will demonstrate why those same techniques can be counterproductive when precision at an intra-document, token level is the primary objective. To reproduce the work below, see the code [here](https://github.com/lancedb/research/tree/main/multivector-needle-haystack-bench). ## The Dataset This task is different from benchmarks like BEIR, which focus on text-based doc retrieval, finding the most relevant documents from a large collection. Here, we want *intra-document localization*, where the goal is to find a precise piece of information within a single, dense document, in a multimodal setting. ### The Task: The Document Haystack Dataset Our benchmark is built on the **[AmazonScience/document-haystack](https://huggingface.co/datasets/AmazonScience/document-haystack)** dataset, which contains 25 visually complex source documents (e.g., financial reports, academic papers). To create a rigorous test, our evaluation follows a per-document methodology: * We process each of the 25 source documents independently. * **Table Creation:** For a single source document (e.g., "AIG"), we ingest all pages from all of its page-length variants (from 5 to 200 pages long). This creates a temporary LanceDB table containing approximately 1,230 pages. * **The Task:** We then query this table using a set of "needle" questions, where the goal is to retrieve the **exact page number** containing the answer. A successful retrieval means the correct page number is within the top K results. * **Target metric:** We measure both retrieval accuracy (Hit\@K) and the average search latency for each query against this table. **Dataset example** The documents contain "text needles" like these ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-2.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=2a0ab7d22b1dfba5915c10887718b66c) ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-3.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=c7f5f7b5ad49098e0b9f92d341439078) During evaluation, the queries processed are somewhat like this: ``` What is the secret currency in the document? What is the secret object #3 in the document? ``` The intention of this task is to find the page which has the text needle that answers this questions ## Models and Architectures Our testbed includes a baseline single-vector model and a family of advanced multivector models. ### Single-Vector (Bi-Encoder) Baseline: CLIP ViT-Base-Patch32 A bi-encoder maps an entire piece of content (a query, a document page) to a *single* vector. The search process is simple: pre-compute one vector for every page, and at query time, find the page vector closest to the query vector. * **Strength:** Speed and simplicity. * **Weakness:** This creates an **information bottleneck**. All the nuanced details, keywords, and semantic relationships on a page must be compressed into a single, fixed-size vector. For finding a needle, this is like trying to describe a specific person's face using only one word. ### Multi-vector (Late-Interaction) Models Multi-vector models, pioneered by ColBERT, take a different approach. Instead of one vector per page, they generate a *set of vectors* for each page: one for every token (or image patch). * **Mechanism (MaxSim):** The search process is more sophisticated. For each token in the query, the system finds the most similar token on the page. These maximum similarity scores are then summed up to get the final relevance score. This "late-interaction" preserves fine-grained, token-level details. * **The Models:** We used several vision-language models adapted for this architecture, including `ColPali`, `ColQwen2`, and `ColSmol`. While their underlying transformer backbones differ, they all share the ColBERT philosophy of representing documents as a bag of contextualized token embeddings. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-4.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=fc693f01bebcd2a7980283ea87b27328) ## Different Retrieval Strategies Used A full multivector search is powerful but computationally intensive. Here are five strategies for managing it, complete with LanceDB implementation details. ### 1. `base`: The Gold Standard (Full Multi-vector Search) This is the pure, baseline late-interaction search. It offers the highest potential for accuracy by considering every token. **LanceDB also integrates with ConteXtualized Token Retriever (XTR)** , an advanced retrieval model that prioritizes the most semantically important document tokens during search. This integration enhances the quality of search results by focusing on the most relevant token matches. **LanceDB Implementation:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa # Schema for multivector data # Assumes embeddings are 128-dimensional schema = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.list_(pa.float32(), 128))) ]) db = lancedb.connect("./lancedb") tbl = db.create_table("document_pages_base", schema=schema) # Ingesting multi-token embeddings for a page # multi_token_embeddings is a NumPy array of shape (num_tokens, 128) tbl.add([{"page_num": 1, "vector": multi_token_embeddings.tolist()}]) # Searching with a multi-token query # query_multi_vector is also shape (num_query_tokens, 128) results = tbl.search(query_multi_vector).limit(5).to_list() ``` ### 2. `flatten`: Mean Pooling This strategy "flattens" the set of token vectors into a single vector by averaging them. This transforms the search into a standard, fast approximate nearest neighbor (ANN) search. **LanceDB Implementation:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema for single-vector data schema_flat = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.float32(), 128)) ]) tbl_flat = db.create_table("document_pages_flat", schema=schema_flat) # Ingesting the mean-pooled vector mean_vector = multi_token_embeddings.mean(axis=0) tbl_flat.add([{"page_num": 1, "vector": mean_vector.tolist()}]) # Searching with a single averaged query vector query_mean_vector = query_multi_vector.mean(axis=0) results = tbl_flat.search(query_mean_vector).limit(5).to_list() ``` ### 3. Max pooling This is a variation of `flatten`. `max_pooling` takes the element-wise max across all token vectors instead of the mean. The implementation is identical to `flatten`, just with a different aggregation method (`.max(axis=0)`). ### 4. `flatten and multivector rerank`: The Hybrid Optimization This two-stage strategy aims for the best of both worlds. First, use a fast, pooled-vector search to find a set of promising candidates. Then, run the full, accurate multivector search on *only* those candidates. **LanceDB Implementation:** This requires a table with two vector columns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema with both flat and multivector columns schema_rerank = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector_flat", pa.list_(pa.float32(), 128)), pa.field("vector_multi", pa.list_(pa.list_(pa.float32(), 128))) ]) tbl_rerank = db.create_table("document_pages_rerank", schema=schema_rerank) # Ingest both vectors tbl_rerank.add([ { "page_num": 1, "vector_flat": multi_token_embeddings.mean(axis=0).tolist(), "vector_multi": multi_token_embeddings.tolist() } ]) # --- Two-Stage Search --- # Stage 1: Fast search on the flat vector query_flat = query_multi_vector.mean(axis=0) candidates = tbl_rerank.search(query_flat, vector_column_name="vector_flat") \ .limit(100) \ .with_row_id(True) \ .to_pandas() # Stage 2: Precise multivector search on candidates candidate_ids = tuple(candidates["_rowid"].to_list()) final_results = tbl_rerank.search(query_multi_vector, vector_column_name="vector_multi") \ .where(f"_rowid IN {candidate_ids}") \ .limit(5) \ .to_list() ``` ### 5. `hierarchical token pooling`: Compressing the Haystack This is an indexing-time strategy that aims to reduce the storage footprint and computational cost of multivector search by reducing the number of vectors per document. Instead of using every token vector, it clusters semantically similar tokens together and replaces them with a single, averaged vector. * **Mechanism:** For each document, it computes the similarity between all token vectors, performs hierarchical clustering to group them, and then mean-pools the vectors within each cluster. This results in a smaller, more compact set of token vectors representing the document. * **Goal:** To reduce memory and disk usage while attempting to preserve the most important semantic information, potentially offering a middle ground between the high accuracy of `base` search and the speed of pooled methods. **LanceDB Implementation:** The schema is identical to the `base` multivector search, but the data is pre-processed before ingestion. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from utils import pool_embeddings_hierarchical import numpy as np # Schema is the same as the base multivector schema schema = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.list_(pa.float32(), 128))) ]) tbl_hierarchical = db.create_table("document_pages_hierarchical", schema=schema) # Pool the embeddings before ingestion # multi_token_embeddings is a NumPy array of shape (num_tokens, 128) pooled_embeddings = pool_embeddings_hierarchical( multi_token_embeddings, pool_factor=4 # Reduce vector count by a factor of 4 ) # Ingest the smaller set of multi-token embeddings # pooled_embeddings is now shape (approx. num_tokens / 4, 128) tbl_hierarchical.add([{"page_num": 1, "vector": pooled_embeddings.tolist()}]) # Search is identical to the base multivector search results = tbl_hierarchical.search(query_multi_vector).limit(5).to_list() ``` ## The Results For a "needle in a haystack" task, retrieval accuracy is the primary metric of success. The benchmark results reveal a significant performance gap between the full multivector search strategy and common optimization techniques. ### Baseline Performance: Single-Vector Bi-Encoder First, we establish a baseline using a standard single-vector bi-encoder model, `openai/clip-vit-base-patch32`. This represents a common approach to semantic search but, as the data shows, is ill-suited for this task's precision requirements. | Model | Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | :- | | `openai/clip-vit-base-patch32` | `base` | 1.6% | 4.7% | 11.8% | **0.008 s** | With a Hit\@20 rate of just under 12%, the baseline model struggles to reliably locate the correct page. This performance level is insufficient for applications requiring high precision. ### Multi-vector Model Performance We now examine the performance of multivector models using different strategies. The following table compares the `base` (full multivector), `flatten` (mean pooling), and `rerank` (hybrid) strategies across several late-interaction models. | Model | Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | :- | | `vidore/colqwen2-v1.0` | `flatten` | 1.9% | 5.5% | 11.9% | 0.010 s | | `vidore/colqwen2-v1.0` | `flatten and multivector rerank` | 0.3% | 1.5% | 7.3% | 0.692 s | | **`vidore/colqwen2-v1.0`** | **`hierarchical token pooling`** | **13.7%** | **60.5%** | **91.6%** | **0.144 s** | | **`vidore/colqwen2-v1.0`** | **`base`** | **14.0%** | **65.4%** | **95.5%** | 0.668 s | | `vidore/colpali-v1.3` | `flatten` | 1.7% | 4.5% | 9.3% | 0.008 s | | `vidore/colpali-v1.3` | `flatten and multivector rerank` | 0.6% | 2.3% | 6.9% | 0.949 s | | **`vidore/colpali-v1.3`** | **`hierarchical token pooling`** | **10.8%** | **41.7%** | **64.8%** | **0.189 s** | | **`vidore/colpali-v1.3`** | **`base`** | **11.3%** | **42.3%** | **65.6%** | 0.936 s | | `vidore/colSmol-256M` | `flatten` | 1.6% | 4.7% | 10.5% | 0.008 s | | `vidore/colSmol-256M` | `flatten and multivector rerank` | 0.3% | 1.6% | 7.0% | 0.853 s | | **`vidore/colSmol-256M`** | **`base`** | **14.4%** | **64.0%** | **91.7%** | 0.848 s | The data shows a consistent pattern: the `base` strategy outperforms all other techniques. The flattned pooling and reranking strategies perform no better than the single-vector baseline. However, hierarchical token pooling seems like a decent alternative to base considering speed vs accuracy tradeoff. Let's look at the numbers in detail. ### In-Depth Analysis of Pooling Strategies To further understand the failure of optimization techniques, we compared different methods for pooling token vectors into a single vector: `mean` (`flatten`), `max`. | Model & Pooling Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | | `vidore/colqwen2-v1.0` (`mean_pooling`) | 1.9% | 5.5% | 11.9% | 0.010 s | | `vidore/colqwen2-v1.0` (`max_pooling`) | 1.4% | 4.2% | 11.2% | 0.011 s | | **`vidore/colqwen2-v1.0` (`base`)** | **14.0%** | **65.4%** | **95.5%** | 0.668 s | All flattened pooling methods perform poorly, confirming that the aggregation of token vectors into a single representation loses the fine-grained detail required for this task. **Finding the Right Trade-Off** ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-5.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=d52ebfe28a2945e94bd792bbc6ae33c0) 1. **The Failure of Simple Pooling:** The `flatten` (mean pooling) and `max_pooling` strategies fail to improve upon the baseline. This is because their aggressive compression **destroys the essential localization signal**. The resulting single vector represents the *topic* of the page, not the *specific needle* on it. 2. **The Failure of `flatten and multivector rerank`:** This hybrid strategy is the *worst-performing* of all. The reason is a fundamental flaw in its design for this task: the first stage uses a simple pooled vector to retrieve candidates. Since this pooling eliminates the localization signal, the initial candidate set is effectively random. 3. **`hierarchical token pooling`:** By clustering and pooling tokens at indexing time, it reduces the number of vectors per page (in our case, by a factor of 4). This intelligently compresses the data, while preserving enough token-level detail in multivector setting. It achieves a **Hit\@20 of 91.6%**, only slightly behind the `base` strategy's 95.5%, but is significantly faster. 4. **`base` multivector Search:** The vanilla, un-optimized `base` multivector search remains the most accurate strategy. Preserving every token vector provides the highest guarantee of finding the needle, but this comes at the highest computational cost. ### Latency: ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/enterprise/v1-12-0/static/assets/images/search/multivector/multivector-6.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=35321a8c16636ebdb952a9c58eceacfd) The "optimizations" are not all created equal. While simple pooling is fast, its inaccuracy makes it unusable. Hierarchical pooling, however, offers a compelling balance of speed and accuracy. | Strategy (on `vidore/colqwen2-v1.0`) | Avg. Search Latency (s) | Hit\@20 Accuracy | | :- | :- | :- | | `flatten` (Fast but Ineffective) | **0.010 s** | 11.9% | | `flatten and multivector rerank` (Slower and Ineffective) | 0.692 s | 7.3% | | **`hierarchical token pooling` (Accurate & Fast)** | **0.144 s** | **91.6%** | | `base` (Most Accurate) | 0.668 s | **95.5%** | | *Latency reported is as seen on NVIDIA H100 GPUs* | | | ## Practical Considerations The accuracy of `base` multivector search is impressive, but its computational intensity has historically limited its use. `hierarchical token pooling` as a viable strategy creates a new, practical sweet spot on the accuracy-latency curve, making high-precision search accessible for a wider range of applications. ### Search Latency and Computational Complexity As the benchmark data shows, the search latency for `base` multivector search is orders of magnitude higher than for single-vector (or pooled-vector) search. It's important to note that the reported \~670ms latency is an average from per-document evaluations. In this benchmark, each of the 25 documents is processed independently. All pages from a single document's variants (ranging from 5 to 200 pages) are ingested into a temporary table, resulting in a table size of approximately **1,230 rows (pages)** per evaluation. The search is performed on this table, and then the table is discarded. This highlights a significant performance cost even on a relatively small, per-document scale. This stems from a fundamental difference in computational complexity: * **Modern ANN Search (for single vectors):** Algorithms like HNSW (Hierarchical Navigable Small World) provide sub-linear search times, often close to `O(log N)`, where `N` is the number of items in the index. This allows them to scale to billions of vectors with millisecond-level latency. * **Late-Interaction Search (Multi-vector):** The search process is far more intensive. For each query, it must compute similarity scores between query tokens and the tokens of many candidate documents. The complexity is closer to `O(M * Q * D)`, where `M` is the number of candidate documents to score, `Q` is the number of query tokens, and `D` is the average number of tokens per document. `Hierarchical token pooling` directly attacks this problem by reducing `D`, leading to a significant reduction in search latency. ### When to Use Multi-Vector Search Given these constraints, the choice of strategy depends on the specific requirements of the application. * **For Maximum Precision (`base`):** In domains where the cost of missing the needle is extremely high, the full `base` search is the most reliable option. * **For a Balance of Precision and Performance (`hierarchical token pooling`):** This is the ideal choice for many applications. It makes high-precision search practical for larger datasets and more interactive use cases where the sub-second latency of the `base` search may be too high. It significantly lowers the barrier to entry for adopting multivector search. It should still not be seen as a drop-in replacement for ANN, as it still requires more computational resources than single-vector search. * **For General-Purpose Document Retrieval (`flatten` / single-vector):** For large-scale retrieval where understanding the "gist" is sufficient or where in cases where large-context text-based models suffice, single-vector search remains the most practical and scalable solution. ## Appendix: Full Benchmark Results The full benchmark results are shown below. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} | name | _runtime | _step | _timestamp | _wandb | avg_inference_latency | avg_search_latency | hit_rates | model_name | strategy | |:--------------------------------------------|-----------:|--------:|--------------:|:-------------------|------------------------:|---------------------:|:------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------|:---------------------| | vidore/colqwen2-v0.1_base | 13410 | 0 | 1.75873e+09 | {'runtime': 13410} | 0.0418646 | 0.751151 | {'1': 0.1355151515151515, '10': 0.888, '20': 0.9597575757575758, '3': 0.3936969696969697, '5': 0.6349090909090909} | vidore/colqwen2-v0.1 | base | | vidore/colqwen2-v1.0_rerank | 13008 | 0 | 1.75873e+09 | {'runtime': 13008} | 0.0426252 | 0.692482 | {'1': 0.003393939393939394, '10': 0.03296969696969697, '20': 0.07296969696969698, '3': 0.010666666666666666, '5': 0.015272727272727271} | vidore/colqwen2-v1.0 | rerank | | vidore/colpali-v1.3_flatten | 2998 | 0 | 1.75872e+09 | {'runtime': 2998} | 0.0296511 | 0.00833224 | {'1': 0.017454545454545455, '10': 0.06448484848484848, '20': 0.09333333333333334, '3': 0.034666666666666665, '5': 0.04509090909090909} | vidore/colpali-v1.3 | flatten | | vidore/colqwen2-v0.1_rerank | 13512 | 0 | 1.75873e+09 | {'runtime': 13512} | 0.0418855 | 0.662372 | {'1': 0.002909090909090909, '10': 0.026424242424242423, '20': 0.05987878787878788, '3': 0.0075151515151515155, '5': 0.014545454545454544} | vidore/colqwen2-v0.1 | rerank | | vidore/colqwen2-v1.0_base | 12933 | 0 | 1.75873e+09 | {'runtime': 12933} | 0.0416839 | 0.667898 | {'1': 0.14012121212121212, '10': 0.8846060606060606, '20': 0.9553939393939394, '3': 0.4111515151515152, '5': 0.6538181818181819} | vidore/colqwen2-v1.0 | base | | vidore/colpali-v1.3_rerank | 12090 | 0 | 1.75873e+09 | {'runtime': 12090} | 0.0310783 | 0.949047 | {'1': 0.006060606060606061, '10': 0.03878787878787879, '20': 0.06933333333333333, '3': 0.014545454545454544, '5': 0.022787878787878788} | vidore/colpali-v1.3 | rerank | | vidore/colqwen2-v1.0_flatten | 4846 | 0 | 1.75874e+09 | {'runtime': 4846} | 0.0504031 | 0.010443 | {'1': 0.018666666666666668, '10': 0.07854545454545454, '20': 0.11903030303030304, '3': 0.041212121212121214, '5': 0.055030303030303034} | vidore/colqwen2-v1.0 | flatten | | vidore/colqwen2-v0.1_base | 10838 | 0 | 1.75874e+09 | {'runtime': 10838} | 0.04627 | 0.692836 | {'1': 0.13575757575757577, '10': 0.8870303030303031, '20': 0.96, '3': 0.3941818181818182, '5': 0.6351515151515151} | vidore/colqwen2-v0.1 | base | | vidore/colqwen2-v0.1_flatten | 4828 | 0 | 1.75874e+09 | {'runtime': 4828} | 0.0486335 | 0.0103028 | {'1': 0.018424242424242423, '10': 0.07224242424242425, '20': 0.10521212121212122, '3': 0.03903030303030303, '5': 0.05212121212121213} | vidore/colqwen2-v0.1 | flatten | | vidore/colpali-v1.3_base | 10253 | 0 | 1.75874e+09 | {'runtime': 10253} | 0.0312334 | 0.93611 | {'1': 0.11272727272727272, '10': 0.551030303030303, '20': 0.6555151515151515, '3': 0.29987878787878786, '5': 0.4232727272727273} | vidore/colpali-v1.3 | base | | vidore/colqwen2-v0.1_flatten | 4745 | 0 | 1.75874e+09 | {'runtime': 4745} | 0.0472825 | 0.00990508 | {'1': 0.018424242424242423, '10': 0.07296969696969698, '20': 0.10496969696969696, '3': 0.03951515151515152, '5': 0.05236363636363636} | vidore/colqwen2-v0.1 | flatten | | vidore/colqwen2.5-v0.2_base | 17218 | 0 | 1.75875e+09 | {'runtime': 17218} | 0.0540356 | 0.694855 | {'1': 0.11903030303030304, '10': 0.7127272727272728, '20': 0.8366060606060606, '3': 0.336, '5': 0.5258181818181819} | vidore/colqwen2.5-v0.2 | base | | vidore/colqwen2.5-v0.2_rerank | 16859 | 0 | 1.75875e+09 | {'runtime': 16859} | 0.0518383 | 0.71693 | {'1': 0.0026666666666666666, '10': 0.025212121212121213, '20': 0.060848484848484846, '3': 0.006787878787878788, '5': 0.01187878787878788} | vidore/colqwen2.5-v0.2 | rerank | | vidore/colqwen2-v0.1_rerank | 9484 | 0 | 1.75875e+09 | {'runtime': 9484} | 0.0445599 | 0.691609 | {'1': 0.005333333333333333, '10': 0.030545454545454542, '20': 0.064, '3': 0.010666666666666666, '5': 0.017696969696969697} | vidore/colqwen2-v0.1 | rerank | | vidore/colSmol-256M_flatten | 6822 | 0 | 1.75875e+09 | {'runtime': 6822} | 0.0404544 | 0.00822329 | {'1': 0.01575757575757576, '10': 0.06836363636363636, '20': 0.10496969696969696, '3': 0.03442424242424243, '5': 0.04678787878787879} | vidore/colSmol-256M | flatten | | vidore/colSmol-500M_base | 12681 | 0 | 1.75875e+09 | {'runtime': 12681} | 0.0408026 | 0.850902 | {'1': 0.136, '10': 0.8029090909090909, '20': 0.8993939393939394, '3': 0.3806060606060606, '5': 0.5975757575757575} | vidore/colSmol-500M | base | | vidore/colSmol-500M_rerank | 13066 | 0 | 1.75876e+09 | {'runtime': 13066} | 0.0440974 | 0.927632 | {'1': 0.003636363636363637, '10': 0.028606060606060607, '20': 0.07054545454545455, '3': 0.00896969696969697, '5': 0.015030303030303033} | vidore/colSmol-500M | rerank | | vidore/colSmol-256M_rerank | 12646 | 0 | 1.75876e+09 | {'runtime': 12646} | 0.0391553 | 0.853279 | {'1': 0.003393939393939394, '10': 0.02909090909090909, '20': 0.07006060606060606, '3': 0.008727272727272728, '5': 0.015515151515151517} | vidore/colSmol-256M | rerank | | vidore/colqwen2.5-v0.2_flatten | 6348 | 0 | 1.75876e+09 | {'runtime': 6348} | 0.0509971 | 0.00772653 | {'1': 0.017696969696969697, '10': 0.06545454545454546, '20': 0.09284848484848485, '3': 0.03515151515151515, '5': 0.045575757575757575} | vidore/colqwen2.5-v0.2 | flatten | | vidore/colSmol-256M_base | 11554 | 0 | 1.75876e+09 | {'runtime': 11554} | 0.0366467 | 0.848463 | {'1': 0.1435151515151515, '10': 0.8426666666666667, '20': 0.9173333333333332, '3': 0.40824242424242424, '5': 0.6404848484848484} | vidore/colSmol-256M | base | | vidore/colSmol-500M_flatten | 6395 | 0 | 1.75876e+09 | {'runtime': 6395} | 0.0384664 | 0.00716238 | {'1': 0.018424242424242423, '10': 0.07345454545454545, '20': 0.11393939393939394, '3': 0.03903030303030303, '5': 0.05090909090909091} | vidore/colSmol-500M | flatten | | openai/clip-vit-base-patch32_base | 815 | 0 | 1.75876e+09 | {'runtime': 815} | 0.00533487 | 0.00794629 | {'1': 0.016, '10': 0.07636363636363637, '20': 0.11757575757575756, '3': 0.03296969696969697, '5': 0.04703030303030303} | openai/clip-vit-base-patch32 | base | | vidore/colqwen2-v0.1_max_pooling | 8758 | 0 | 1.7595e+09 | {'runtime': 8758} | 0.0985753 | 0.0106716 | {'1': 0.015515151515151517, '10': 0.07296969696969698, '20': 0.11248484848484848, '3': 0.032484848484848484, '5': 0.04703030303030303} | vidore/colqwen2-v0.1 | max_pooling | | vidore/colpali-v1.3_max_pooling | 4728 | 0 | 1.75949e+09 | {'runtime': 4728} | 0.0718573 | 0.0103053 | {'1': 0.011393939393939394, '10': 0.05672727272727273, '20': 0.08872727272727272, '3': 0.02666666666666667, '5': 0.03709090909090909} | vidore/colpali-v1.3 | max_pooling | | vidore/colqwen2-v1.0_max_pooling | 8760 | 0 | 1.7595e+09 | {'runtime': 8760} | 0.0981102 | 0.0106316 | {'1': 0.013575757575757576, '10': 0.06933333333333333, '20': 0.112, '3': 0.02812121212121212, '5': 0.041939393939393936} | vidore/colqwen2-v1.0 | max_pooling | | vidore/colqwen2-v0.1_max_pooling | 7696 | 0 | 1.7595e+09 | {'runtime': 7696} | 0.105203 | 0.011907 | {'1': 0.016242424242424242, '10': 0.07321212121212121, '20': 0.1132121212121212, '3': 0.03442424242424243, '5': 0.04945454545454545} | vidore/colqwen2-v0.1 | max_pooling | | vidore/colSmol-256M_max_pooling | 13982 | 0 | 1.75951e+09 | {'runtime': 13982} | 0.0999708 | 0.0121211 | {'1': 0.00993939393939394, '10': 0.05818181818181818, '20': 0.09187878787878788, '3': 0.025212121212121213, '5': 0.037575757575757575} | vidore/colSmol-256M | max_pooling | | vidore/colSmol-500M_max_pooling | 14191 | 0 | 1.75951e+09 | {'runtime': 14191} | 0.111858 | 0.0121703 | {'1': 0.012363636363636365, '10': 0.07539393939393939, '20': 0.13187878787878787, '3': 0.02787878787878788, '5': 0.0416969696969697} | vidore/colSmol-500M | max_pooling | | vidore/colqwen2-v0.1_hierarchical_pooling | 4507 | 0 | 1.7599e+09 | {'runtime': 4507} | 0.0320023 | 0.133653 | {'1': 0.1296969696969697, '10': 0.8504242424242424, '20': 0.9343030303030304, '3': 0.37527272727272726, '5': 0.6041212121212122} | vidore/colqwen2-v0.1 | hierarchical_pooling | | vidore/colpali-v1.3_hierarchical_pooling | 5816 | 0 | 1.7599e+09 | {'runtime': 5816} | 0.0217625 | 0.188727 | {'1': 0.10763636363636364, '10': 0.5372121212121213, '20': 0.6482424242424243, '3': 0.29333333333333333, '5': 0.4167272727272727} | vidore/colpali-v1.3 | hierarchical_pooling | | vidore/colqwen2.5-v0.2_hierarchical_pooling | 8430 | 0 | 1.75991e+09 | {'runtime': 8430} | 0.043073 | 0.141276 | {'1': 0.11103030303030303, '10': 0.6892121212121212, '20': 0.8203636363636364, '3': 0.3185454545454545, '5': 0.4989090909090909} | vidore/colqwen2.5-v0.2 | hierarchical_pooling | | vidore/colqwen2-v1.0_hierarchical_pooling | 5685 | 0 | 1.75991e+09 | {'runtime': 5685} | 0.0343824 | 0.144062 | {'1': 0.13745454545454547, '10': 0.822060606060606, '20': 0.9156363636363636, '3': 0.3856969696969697, '5': 0.6050909090909091} | vidore/colqwen2-v1.0 | hierarchical_pooling | ``` # Multi-vector search with XTR Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/multivector-xtr Represent a document with many vectors, and speed retrieval with ConteXtualized Token Retrieval. Covers [multi-vector search](/enterprise/v1-12-0/search/vector-search) enhanced by XTR (ConteXtualized Token Retriever): representing complex data with several vectors for more nuanced meaning, and using XTR to speed retrieval by prioritizing the most important tokens. For a comparison of retrieval strategies on a token-level benchmark, see [Needle in a haystack](/enterprise/v1-12-0/tutorials/search/multivector-needle-in-a-haystack). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/multivector_xtr/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/multivector_xtr) > > Read the source. # NER-powered vector search Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/ner-search Extract named entities and embed them to sharpen retrieval. Uses Named Entity Recognition to power vector search. Extracting entities (people, places, organizations) and embedding them alongside the text improves accuracy when queries are about specific things rather than general topics. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/NER-powered-Semantic-Search/NER_powered_Semantic_Search_with_LanceDB.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/NER-powered-Semantic-Search) > > Read the source. # Reddit concept summarizer Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/reddit-summarizer An end-to-end pipeline from Reddit text to embeddings to summarization and search. A complete pipeline: acquire text from Reddit, turn it into embeddings, store and manage those vectors in LanceDB, then build summarization and semantic search on top. Useful as a shape for any ingest-embed-serve workflow. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Reddit-summarization-and-search/subreddit_summarization_querying.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Reddit-summarization-and-search) > > Read the source. # Semantic result merging Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/vector-arithmetic Add and subtract embeddings to steer a query toward or away from a concept. Explores vector arithmetic: manipulating embeddings to capture relationships a single query vector cannot. Adding or subtracting the vector representation of a concept shifts the query, which makes searches more nuanced than a literal similarity lookup. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Vector-Arithmetic-with-LanceDB/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Vector-Arithmetic-with-LanceDB) > > Read the source. # Semantic search across videos Source: https://docs.lancedb.com/enterprise/v1-12-0/tutorials/search/video-search Embed video with V-JEPA and search it by similarity. Builds a video search application on V-JEPA (Video Joint Embedding Predictive Architecture). Generates vector embeddings for video content and uses [vector search](/enterprise/v1-12-0/search/vector-search) to find visually similar clips: a multimodal case where the searchable column is not text. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/v-jepa-video-search/intra-video.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/v-jepa-video-search) > > Read the source. # Create a materialized view Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/materializedview/create-a-materialized-view /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/materialized_view/{id}/create Create a materialized view at identifier `id`. The view may be query-backed, UDTF-backed, or chunker-backed, controlled by the `kind` discriminator. # Trigger an async materialized view refresh Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/materializedview/trigger-an-async-materialized-view-refresh /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/materialized_view/{id}/refresh Trigger an asynchronous refresh job for materialized view `id`. Returns a job ID for tracking. # Add new columns to table schema Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/add-new-columns-to-table-schema /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/add_columns Add new columns to table `id` using SQL expressions or default values. # Analyze query execution plan Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/analyze-query-execution-plan /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/analyze_plan Analyze the query execution plan for a query against table `id`. Returns detailed statistics and analysis of the query execution plan. REST NAMESPACE ONLY REST namespace returns the response as a plain string instead of the `AnalyzeTableQueryPlanResponse` JSON object. # Atomically commit a batch of mixed table operations Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/atomically-commit-a-batch-of-mixed-table-operations /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/batch-commit Atomically commit a batch of table operations. This is a generalized version of `BatchCreateTableVersions` that supports mixed operation types within a single atomic transaction at the metadata layer. Supported operation types: - `DeclareTable`: Declare (reserve) a new table - `CreateTableVersion`: Create a new version entry for a table - `DeleteTableVersions`: Delete version ranges from a table - `DeregisterTable`: Deregister (soft-delete) a table All operations are committed atomically: either all succeed or none are applied. # Atomically create versions for multiple tables Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/atomically-create-versions-for-multiple-tables /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/version/batch-create Atomically create new version entries for multiple tables. This operation is atomic: either all table versions are created successfully, or none are created. If any version creation fails (e.g., due to conflict), the entire batch operation fails. Each entry in the request specifies the table identifier and version details. This supports `put_if_not_exists` semantics for each version entry. # Count rows in a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/count-rows-in-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/count_rows Count the number of rows in table `id` REST NAMESPACE ONLY REST namespace returns the response as a plain integer instead of the `CountTableRowsResponse` JSON object. The REST response maps to the `CountTableRowsResponse` model as follows: - the integer response body maps to `count` - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Create a new branch Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-a-new-branch /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/create Create a new branch for table `id` starting from a source ref (another branch and/or version), defaulting to the latest version of the main branch. # Create a new table version Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-a-new-table-version /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/create Create a new version entry for table `id`. This operation supports `put_if_not_exists` semantics. The operation will fail with 409 Conflict if the version already exists. # Create a new tag Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-a-new-tag /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/create Create a new tag for table `id` that points to a specific version. # Create a scalar index on a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-a-scalar-index-on-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create_scalar_index Create a scalar index on a table field for faster filtering operations. Supports scalar indexes (BTREE, BITMAP, LABEL_LIST, FTS, etc.). This is an alias for CreateTableIndex specifically for scalar indexes. Index creation is handled asynchronously. Use the `ListTableIndices` and `DescribeTableIndexStats` operations to monitor index creation progress. # Create a table with the given name Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-a-table-with-the-given-name /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create Create table `id` in the namespace with the given data in Arrow IPC stream. The schema of the Arrow IPC stream is used as the table schema. If the stream is empty, the API creates a new empty table. REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `CreateTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `mode`: pass through query parameter of the same name - `properties`: serialize as a single JSON-encoded query parameter such as `properties={"user":"alice","team":"eng"}`; these are business logic properties managed by the namespace implementation outside Lance context - `storage_options`: serialize as a single JSON-encoded query parameter such as `storage_options={"aws_region":"us-east-1","timeout":"30s"}`; these configure write-time overrides for data and metadata written during table creation # Create an index on a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/create-an-index-on-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create_index Create an index on a table field for faster search operations. Supports vector indexes (IVF_FLAT, IVF_HNSW_SQ, IVF_PQ, etc.) and scalar indexes (BTREE, BITMAP, FTS, etc.). Index creation is handled asynchronously. Use the `ListTableIndices` and `DescribeTableIndexStats` operations to monitor index creation progress. # Declare a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/declare-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/declare Declare a table with the given name without touching storage. This is a metadata-only operation that records the table existence and sets up aspects like access control. For DirectoryNamespace implementation, this creates a `.lance-reserved` file in the table directory to mark the table's existence without creating actual Lance data files. # Delete a branch Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/delete-a-branch /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/delete Delete an existing branch from table `id`. # Delete a tag Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/delete-a-tag /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/delete Delete an existing tag from table `id`. # Delete rows from a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/delete-rows-from-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/delete Delete rows from table `id`. # Delete table version records Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/delete-table-version-records /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/delete Delete version metadata records for table `id`. This operation deletes version tracking records, NOT the actual table data. It supports deleting ranges of versions for efficient bulk cleanup. Special range values: - `start_version: 0` with `end_version: -1` means delete ALL version records # Describe a specific table version Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/describe-a-specific-table-version /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/describe Describe the detailed information for a specific version of table `id`. Returns the manifest path and metadata for the specified version. # Drop a specific index Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/drop-a-specific-index /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/{index_name}/drop Drop the specified index from table `id`. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `DropTableIndexRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `index_name`: pass through path parameter of the same name # Get query execution plan explanation Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/get-query-execution-plan-explanation /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/explain_plan Get the query execution plan for a query against table `id`. Returns a human-readable explanation of how the query will be executed. REST NAMESPACE ONLY REST namespace returns the response as a plain string instead of the `ExplainTableQueryPlanResponse` JSON object. # Get table index statistics Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/get-table-index-statistics /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/{index_name}/stats Get statistics for a specific index on a table. Returns information about the index type, distance type (for vector indices), and row counts. # Get table statistics Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/get-table-statistics /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/stats Get statistics for table `id`, including row counts, data sizes, and column statistics. # Get version for a specific tag Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/get-version-for-a-specific-tag /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/version Get the version number that a specific tag points to for table `id`. # Insert records into a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/insert-records-into-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/insert Insert new records into table `id`. For tables that have been declared but not yet created on storage (is_only_declared=true), this operation will create the table with the provided data. REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `InsertIntoTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `mode`: pass through query parameter of the same name # List all branches for a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/list-all-branches-for-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/list List all branches that have been created for table `id`. Returns a map of branch names to their contents. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableBranchesRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List all tags for a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/list-all-tags-for-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/list List all tags that have been created for table `id`. Returns a map of tag names to their corresponding version numbers and metadata. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableTagsRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List all versions of a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/list-all-versions-of-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/list List all versions (commits) of table `id` with their metadata. Use `descending=true` to guarantee versions are returned in descending order (latest to oldest). Otherwise, the ordering is implementation-defined. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableVersionsRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `descending`: pass through query parameter of the same name # List indexes on a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/list-indexes-on-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/list List all indices created on a table. Returns information about each index including name, columns, status, and UUID. # Merge insert (upsert) records into a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/merge-insert-upsert-records-into-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/merge_insert Performs a merge insert (upsert) operation on table `id`. This operation updates existing rows based on one or more matching columns and inserts new rows that don't match. It returns the number of rows inserted and updated. For tables that have been declared but not yet created on storage (is_only_declared=true), this operation will create the table with the provided data (since there are no existing rows to merge with). REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `MergeInsertIntoTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `on`: pass through query parameter of the same name, repeated once per field path - `when_matched_update_all`: pass through query parameter of the same name - `when_matched_update_all_filt`: pass through query parameter of the same name - `when_not_matched_insert_all`: pass through query parameter of the same name - `when_not_matched_by_source_delete`: pass through query parameter of the same name - `when_not_matched_by_source_delete_filt`: pass through query parameter of the same name # Modify existing columns Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/modify-existing-columns /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/alter_columns Modify existing columns in table `id`, such as renaming or changing data types. # Query a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/query-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/query Query table `id` with vector search, full text search and optional SQL filtering. Returns results in Arrow IPC file or stream format. REST NAMESPACE ONLY REST namespace returns the response as Arrow IPC file binary data instead of the `QueryTableResponse` JSON object. The REST response maps to the `QueryTableResponse` model as follows: - the Arrow IPC file binary body maps to `data` - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Remove columns from table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/remove-columns-from-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/drop_columns Remove specified columns from table `id`. # Trigger an async column backfill job Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/trigger-an-async-column-backfill-job /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/backfill_column Trigger an asynchronous backfill job for a computed column on table `id`. The column must be a virtual (UDF-backed) column or a computed column declared with an expression binding. Returns a job ID for tracking. # Update a tag to point to a different version Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/update-a-tag-to-point-to-a-different-version /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/update Update an existing tag for table `id` to point to a different version. # Update per-field metadata Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/update-per-field-metadata /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/update_field_metadata Update the Arrow field (column) metadata for table `id`. Each entry targets a field by `path` and merges the provided key-value pairs into that field's existing metadata, or replaces it when `replace` is true. A null metadata value deletes that key. # Update rows in a table Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/update-rows-in-a-table /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/update Update existing rows in table `id`. # Update table schema metadata Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/table/update-table-schema-metadata /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/table/{id}/schema_metadata/update Replace the schema metadata for table `id` with the provided key-value pairs. REST NAMESPACE ONLY REST namespace uses a direct object (map of string to string) as both request and response body instead of the wrapped `UpdateTableSchemaMetadataRequest` and `UpdateTableSchemaMetadataResponse`. # Alter information of a transaction. Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/transaction/alter-information-of-a-transaction /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/transaction/{id}/alter Alter a transaction with a list of actions such as setting status or properties. The server should either succeed and apply all actions, or fail and apply no action. # Describe information about a transaction Source: https://docs.lancedb.com/enterprise/v1-12-0/api-reference/rest/transaction/describe-information-about-a-transaction /enterprise/v1-12-0/api-reference/rest/openapi.yaml post /v1/transaction/{id}/describe Return a detailed information for a given transaction # About this version Source: https://docs.lancedb.com/oss/v0-41-0/about-this-version The release and sources of the LanceDB Embedded 0.41.0 documentation. These pages document LanceDB Embedded 0.41.0. They were saved from the sources below when this edition was prepared. * **Release:** LanceDB Embedded 0.41.0 * **Enterprise pages:** the Enterprise documentation of LanceDB Enterprise 1.12.0 * **REST API specification:** `lance-format/lance-namespace` `v0.13.0` The Enterprise pages are included so that the navigation is complete. They come from the Enterprise documentation named above, pinned when this edition was prepared. # Agentic skills Source: https://docs.lancedb.com/oss/v0-41-0/basics/agentic-skills Give a coding agent a current, maintained reference for the LanceDB APIs. A coding agent writing LanceDB code from memory writes whatever was in its training data: often an older API, sometimes one that never existed. The LanceDB agent plugin fixes that by supplying the current reference at the point the agent needs it. ## The plugin It ships as the `lancedb` plugin in the [lancedb-agent-plugins](https://github.com/lancedb/lancedb-agent-plugins) repository, which is also a plugin marketplace. Install it with your agent's plugin manager: ```text Claude Code theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} /plugin marketplace add lancedb/lancedb-agent-plugins /plugin install lancedb@lancedb ``` ```bash Codex icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} codex plugin marketplace add lancedb/lancedb-agent-plugins codex plugin add lancedb@lancedb ``` ```bash Other agents icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx plugins add lancedb/lancedb-agent-plugins ``` The [`plugins`](https://www.npmjs.com/package/plugins) installer shown under **Other agents** is a cross-tool option. It detects which agent CLIs are on your `PATH` (Cursor, GitHub Copilot CLI, VS Code, Grok Build, and Kimi Code, as well as Claude Code and Codex) and installs through each one's native plugin system. The plugin supplements the agent's training data with current LanceDB instructions. To pick up later revisions, refresh the marketplace: ```text Claude Code theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} /plugin marketplace update lancedb ``` ```bash Codex icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} codex plugin marketplace upgrade ``` ```bash Other agents icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx plugins add lancedb/lancedb-agent-plugins ``` > [accordion] Where the plugin gets installed > > Each plugin manager clones the repository, reads its marketplace manifest to find > the `lancedb` plugin, and hands the plugin to the agent's own plugin store rather > than copying files into your project. Claude Code and Codex keep it under > `~/.claude/plugins` and `~/.codex/plugins` respectively, so the plugin is available > in every project on the machine. > > The `npx plugins` installer defaults to the same user-wide scope. Pass > `--scope project` to record the plugin in the current repository instead, so that > everyone working in it gets the same plugin, or `-t <target>` to install for a > single agent rather than every one it detects: > > ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > npx plugins add lancedb/lancedb-agent-plugins --scope project -t cursor > ``` > > Not every agent supports project scope; `npx plugins targets` lists what it > found and what each target supports. ## Automated prompt catalog Explore the prompts covered by automated agent evaluations. Each prompt uses example data and may require existing tables, indexes, metadata, branches, version history, or running jobs. Replace the test fixtures and connection details with your own before using a prompt. The evaluations run against a LanceDB Enterprise test database, with and without the agent plugin. Evaluation coverage does not guarantee success for every agent or model. Prompts are reproduced verbatim, including the answer formats used by automated grading. Table names, local files, and placeholders in these prompts refer to test fixtures. Supply your own data, database connection, and timestamps when adapting them. 66 prompts. ### Tables and schema design > [accordion] 101: list tables by prefix > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Some tables in this database came from a legacy load and are named with the prefix `eval_lt_`. Find every table whose name starts with `eval_lt_` and report them. This is a read-only check. End your answer with one line per table, each of exactly this form: > > TABLE: <table_name> > ``` > [accordion] 102: describe table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Give me an overview of the `eval_describe` table: its columns with their types, and how many rows it holds. This is a read-only check — do not modify anything. End your answer with one line per column, then two final lines, of exactly these forms. Write each `<type>` exactly as the API reports it, not as a synonym; for a nested type, write the outer type name with its element type and length in angle brackets (a 4-element vector of 8-bit ints would read `fixed_size_list<int8, 4>`): > > COLUMN: <column_name> = <type> > ROWS: <row_count> > COLUMNS: <number_of_columns> > ``` > [accordion] 103: table storage stats > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How is the `eval_table_stats` table laid out in storage? Report its total size on disk and its fragment layout. This is a read-only check. End your answer with two lines of exactly this form: > > BYTES: <total_size_in_bytes> > FRAGMENTS: <number_of_fragments> > ``` > [accordion] 104: create table with data > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a new table called `eval_created_products` in this database with three columns: `sku` (string), `name` (string), and `price` (float64). Populate it with exactly these 4 rows: > > | sku | name | price | > |---------|------------------|--------| > | SKU-001 | Espresso Machine | 249.99 | > | SKU-002 | Milk Frother | 39.5 | > | SKU-003 | Coffee Grinder | 89.0 | > | SKU-004 | Digital Scale | 24.95 | > ``` > [accordion] 105: create empty table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a new, empty table called `eval_empty_events` in this database, ready for an event-logging pipeline to start writing into later. It needs three columns: `event_name` (string), `severity` (int64), and `payload` (string) — and no rows yet. > ``` > [accordion] 107: drop table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_drop_me` table was created by a test run and is no longer needed. Drop it from the database — and nothing else. > ``` > [accordion] 108: design tables from joined schema > > ````text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > My current DB has these 5 tables that join; how should I set up my tables in LanceDB? > > ``` > products (product_id BIGINT PK, name TEXT, description TEXT, price NUMERIC(10,2), category_id BIGINT FK, brand_id BIGINT FK) > categories (category_id BIGINT PK, name TEXT) > brands (brand_id BIGINT PK, name TEXT, country TEXT) > reviews (review_id BIGINT PK, product_id BIGINT FK, rating SMALLINT, body TEXT) > order_items (order_id BIGINT, product_id BIGINT FK, quantity INT, unit_price NUMERIC(10,2)) > ``` > > In LanceDB the app will run one query: semantic search over product descriptions, filtered by category name and brand name, where every hit shows the product's name, price, category name, brand name, and average review rating. Order analytics stays in our warehouse. Description embeddings are 384-dimensional float32 vectors. > > Set the tables up in this database as you recommend: create them empty (schema only, no rows). Name the table the product search runs against `eval_schema_search`, and give any other table you create the `eval_schema_` prefix. Explain your design in your answer. > ```` ### Data ingestion and updates > [accordion] 201: insert rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Append these 5 new products to the `eval_insert_rows` table (the embedding columns can be left null): > > | id | title | category | price_usd | relevance_score | > |-----|--------------|-----------|-----------|-----------------| > | 100 | Clearance A | clearance | 9.99 | 0.1 | > | 101 | Clearance B | clearance | 10.99 | 0.1 | > | 102 | Clearance C | clearance | 11.99 | 0.1 | > | 103 | Clearance D | clearance | 12.99 | 0.1 | > | 104 | Clearance E | clearance | 13.99 | 0.1 | > ``` > [accordion] 202: delete rows by filter > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > All 'toys' products have been discontinued. Delete every row in category `toys` from the `eval_delete_rows` table — and nothing else. > ``` > [accordion] 203: delete all rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_purge` table was loaded from a corrupted export and every row in it is suspect. Clear out all of its rows — but keep the table itself (and its schema) in place so it can be reloaded. > ``` > [accordion] 204: update rows by filter > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Editorial flagged every 'books' product in the `eval_update_rows` table for re-review: set `relevance_score` to 0 for all rows in category `books`. Don't touch any other rows. > ``` > [accordion] 205: update with expression > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Run a flash sale on the `eval_discount` table: cut the price of every product in category `electronics` by 10% — each one's `price_usd` becomes 90% of its current value. Leave every other category's prices alone. > ``` > [accordion] 206: upsert rows > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Sync the `eval_upsert` table with this batch of refurbished products, matching on `id`: update the row if the id already exists, insert it if not — as one upsert operation, not separate update and insert passes. The embedding columns can be left null. > > | id | title | category | price_usd | relevance_score | > |-----|-----------------------|----------|-----------|-----------------| > | 2 | Refurbished Product 2 | refurb | 19.99 | 0.5 | > | 6 | Refurbished Product 6 | refurb | 29.99 | 0.5 | > | 200 | Refurb Special A | refurb | 15.0 | 0.5 | > | 201 | Refurb Special B | refurb | 18.0 | 0.5 | > ``` > [accordion] 207: add column backfill > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Analytics needs integer cents. Add a `price_cents` integer column to the `eval_add_column` table, backfilled for every existing row as the price in cents (`price_usd` × 100, rounded to the nearest integer). > ``` > [accordion] 208: rename column > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Rename the `price_usd` column of the `eval_rename_column` table to `price`, in place, keeping the data — do not rebuild or rewrite the table. > ``` > [accordion] 209: drop column > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The legacy `image_clip_v1` embedding column of the `eval_drop_column` table is superseded and wasting storage. Remove that column — keep everything else. > ``` > [accordion] 210: cast column type > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Downstream tooling needs 64-bit floats: change the type of the `relevance_score` column in the `eval_cast_column` table from float32 to float64, in place, keeping the values. > ``` > [accordion] 211: performant batch ingest > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Make sure my ingest pattern will be performant. My ingest script is `ingest.py` in your working directory; it creates the table `eval_ingest_events` in this database and loads the day's 1,000 events into it. Fix whatever would make the ingest slow or hurt the table, keeping the same table name, schema, and rows, then run it against this database so the table ends up holding exactly those 1,000 events. > ``` ### Queries and search > [accordion] 301: filtered count > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How many products in the `eval_filter_count` table are in category `books` with a price above $100? This is a read-only check. End your answer with a line of exactly this form: > > COUNT: <n> > ``` > [accordion] 302: filtered ids > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Which products in the `eval_filter_ids` table are in category `electronics` and priced under $50? This is a read-only check. End your answer with one line per matching product, each of exactly this form: > > ID: <id> > ``` > [accordion] 303: lookup row by id > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Look up the product with id 12 in the `eval_lookup_row` table and report its title. This is a read-only check. End your answer with a line of exactly this form: > > TITLE: <title> > ``` > [accordion] 304: top k cheapest > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What are the 3 cheapest products in the `eval_cheapest` table? This is a read-only check. End your answer with a line of exactly this form, ids ordered from cheapest up: > > CHEAPEST: <id>,<id>,<id> > ``` > [accordion] 305: paginated read > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our storefront lists the `eval_pagination` table's products cheapest-first, 3 to a page. A customer is looking at page 2 — which products do they see? This is a read-only check. End your answer with a line of exactly this form, the three ids in display (price-ascending) order: > > PAGE2: <id>,<id>,<id> > ``` > [accordion] 306: pick column for image search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > I have a LanceDB table called `eval_pick_column`. I want to let users upload a photo and find visually similar products. Which column should the similarity search run against? If there's more than one candidate, tell me which one to use and why. This is a read-only check — do not modify the table, its rows, or its metadata. End your answer with a line of exactly this form, naming the single column to use: > > RECOMMENDATION: <column_name> > ``` > [accordion] 307: vector search similar > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A shopper is viewing product 5 in the `eval_vector_search` table and we want a 'similar items' shelf. Using product 5's `image_clip_v2` embedding as the query, find the single most visually similar OTHER product. This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 308: vector search filtered > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Same 'similar items' feature, but constrained to a department: using product 8's `image_clip_v2` embedding as the query on the `eval_vector_filtered` table, find the single most similar product in category `books` (product 8 itself is not in that category). This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 309: full text search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A customer remembers a product description mentioning 'waterproof'. Using full-text search on the `eval_fts_search` table, find which product that is. This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 310: fts multi match > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Marketing wants a list of every product in the `eval_fts_multi` table whose description mentions 'wireless'. Use full-text search to find them all. This is a read-only check. End your answer with one line per matching product, each of exactly this form: > > ID: <id> > ``` > [accordion] 311: hybrid search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Find the product in the `eval_hybrid_search` table most relevant to a shopper who typed the keyword 'solar' and whose taste profile is product 4's `image_clip_v2` embedding — i.e. combine keyword relevance and vector similarity (a hybrid search). This is a read-only check. End your answer with a line of exactly this form: > > MATCH: <id> > ``` > [accordion] 312: explain query plan > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Before we ship a price filter on the `eval_explain_plan` table, confirm from the server's query plan whether a filter on `price_usd` (for example `price_usd < 50`) is served by an index or by scanning the table. This is a read-only check — do not build or drop anything. End your answer with exactly one of these lines: > > PLAN: index > PLAN: scan > ``` ### Index management > [accordion] 401: build index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Queries that filter the `eval_build_index` table by `category` are slow. Build the appropriate index to speed them up. > ``` > [accordion] 402: create vector index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Vector similarity queries against the `image_clip_v2` column of the `eval_vector_index` table are running as brute-force scans. Build an ANN index on that column using cosine distance, and make sure it finishes building. > ``` > [accordion] 403: create fts index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Enable keyword (full-text) search over the `body_text` column of the `eval_fts_index` table, and make sure the index finishes building. > ``` > [accordion] 404: inspect indexes > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Audit the indexes on the `eval_index_report` table: what indexes exist, and how many rows does the index on `category` cover? This is a read-only check. End your answer with one line per index plus one final line, of exactly these forms: > > INDEX: <index_name> > INDEXED_ROWS: <rows covered by the category index> > ``` > [accordion] 405: index coverage > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The scalar index on `price_usd` of the `eval_index_coverage` table was built a while ago, and data has landed in the table since. Check the index's coverage: how many rows does it currently cover, and how many rows are not yet indexed? This is a read-only check — do not rebuild or modify anything. End your answer with two lines of exactly this form: > > INDEXED: <rows covered by the index> > UNINDEXED: <rows not yet covered> > ``` > [accordion] 406: drop index > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The index on `price_usd` in the `eval_drop_index` table was an experiment and is slowing down writes. Drop that index. > ``` ### Version history and tags > [accordion] 501: version history > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > How many versions does the `eval_versions` table have? This is a read-only check — do not create new versions. End your answer with a line of exactly this form: > > VERSIONS: <n> > ``` > [accordion] 502: time travel read > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Without modifying the `eval_timetravel` table, compare it to its past: how many rows did it have at version 1, and how many does it have now? End your answer with two lines of exactly this form: > > THEN: <rows at version 1> > NOW: <rows now> > ``` > [accordion] 503: restore version > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Someone ran a bad cleanup against the `eval_restore` table and rows went missing. Roll the table back to the version immediately before the deletion, so the missing rows are back. > ``` > [accordion] 504: tag version > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We're about to run a risky migration on the `eval_tag_create` table. Tag its current version as `prod-baseline` so we can refer back to it later. > ``` > [accordion] 505: read at tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_tag_read` table's version tagged `release-v1` is what we shipped. Without modifying the table, compare then and now: how many rows did it have at the `release-v1` tag, and how many does it have now? End your answer with two lines of exactly this form: > > TAGGED: <rows at the release-v1 tag> > NOW: <rows now> > ``` > [accordion] 506: move tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `latest` tag on the `eval_tag_move` table still points at an old version, but the table has moved on since. Update the `latest` tag so it points at the table's current version. Leave any other tags alone. > ``` > [accordion] 507: delete tag > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `deprecated` tag on the `eval_tag_delete` table is obsolete. Remove that tag — leave any other tags alone. > ``` > [accordion] 508: compare two versions > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Compare version 3 and version 7 of the `eval_history_compare` table and explain, in plain English, what happened to it in between — cover the schema, the indexes, and the data. This is a read-only investigation: do not modify the table. > > Report only what changed AFTER version 3, up to and including version 7 — version 3 is the starting point, so whatever happened at version 3 itself is not one of the changes. > > End your answer with three lines of exactly these forms. The first two are comma-separated lists of column names (or NONE): the columns added in that range, and the columns that gained an index in that range. The third is exactly one of the five words offered, describing the row-level data changes in that range: > > COLUMNS_ADDED: <column_name>[, <column_name>...] > INDEXES_ADDED: <column_name>[, <column_name>...] > DATA_CHANGES: APPEND_THEN_DELETE | DELETE_THEN_APPEND | APPEND_ONLY | DELETE_ONLY | NONE > ``` > [accordion] 509: changes since date > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our last schema review of the `eval_history_since` table signed off at {cutoff}. Did any schema or index changes happen to that table since then? Explain in plain English what you find, and say which changes were not schema or index changes so we know they were considered. This is a read-only investigation: do not modify the table. > > This table also has columns and indexes that predate that timestamp — those are not what the review is asking about, so report only what changed at or after it. > > End your answer with four lines of exactly these forms: every table version at or after that timestamp that changed the schema or an index — version numbers only, comma-separated, ascending (or NONE); the column added by a schema change at or after that timestamp (or NONE); the column covered by an index built at or after that timestamp (or NONE); and every table version at or after that timestamp whose change was NOT a schema or index change — version numbers only, comma-separated, ascending (or NONE): > > CHANGED_VERSIONS: <version>[, <version>...] > COLUMN_ADDED: <column_name> > INDEX_ADDED: <column_name> > OTHER_CHANGES: <version>[, <version>...] > ``` > [accordion] 510: trace column to job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Someone added a column called `foo` to the `eval_history_column_job_{db}` table and nobody wrote down why. Find the exact version where `foo` appeared, then find the background job that was pinned to that same table version and report what it is doing and its current state. There are several jobs on this table, pinned to different versions of it, so make sure the one you report is the one pinned to that version. This is a read-only investigation: do not cancel or modify anything. > > End your answer with four lines of exactly these forms (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose: > > VERSION: <version_number> > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` ### Column metadata and lineage > [accordion] 601: add all metadata types > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Document the two image-embedding columns in the `eval_add_metadata` table: write a clear description for each, tag each with its field type, the model that produced it, and its version, mark the newer one as the latest, and group both under a single logical column. > ``` > [accordion] 602: delete one metadata key > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `model` tag on the `image_clip_v1` column of `eval_delete_metadata` is wrong. Remove just that tag — leave the column's description and other tags alone. > ``` > [accordion] 603: explain column origin > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Some columns in the `eval_lin_origin` table were generated by the platform rather than loaded with the data. Investigate the column `title_sentiment`: is it produced by a UDF or by a SQL expression, what produces it, and which columns does it read? This is a read-only investigation: do not modify the table. > > End your answer with lines of exactly these forms — one INPUT line per input column. Write the generator exactly as the table's own metadata records it (the UDF's registered name, or the SQL expression), not a paraphrase: > > KIND: <udf or expression> > GENERATOR: <udf name or SQL expression> > INPUT: <input_column_name> > ``` > [accordion] 604: find downstream dependents > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We want to drop the `price_usd` column from the `eval_lin_deps` table, but some of the table's generated columns are derived from other columns. Find every column that depends on `price_usd` — directly, or indirectly through another generated column. This is a read-only investigation: do not modify the table. > > End your answer with one line per dependent column, each of exactly this form (do not list `price_usd` itself): > > DEPENDENT: <column_name> > ``` > [accordion] 605: trace column refresh job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The generated column `discounted_price` in the `eval_lin_job_{db}` table is filled in by a background refresh job, and we need to know which job that is. There is more than one job on this table (a long-lived database can also hold finished or cancelled leftovers), so make sure the one you report is the currently-running job that refreshes `discounted_price`. This is a read-only investigation: do not cancel or modify anything. > > End your answer with three lines of exactly these forms (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose: > > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` ### Namespaces > [accordion] 701: create namespace > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a namespace called `analytics` in this database, ready for new tables to be organized under it. > ``` > [accordion] 702: create table in namespace > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Under the `staging` namespace of this database, create a table called `sessions` with columns `session_id` (string) and `duration_s` (float64), holding exactly these 2 rows: > > | session_id | duration_s | > |------------|------------| > | a1b2 | 12.5 | > | c3d4 | 3.25 | > ``` > [accordion] 703: list namespace tables > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What tables live inside the `warehouse` namespace of this database? This is a read-only check. End your answer with one line per table, each of exactly this form: > > TABLE: <table_name> > ``` > [accordion] 704: query namespace table > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Our SRE dashboards read from the `ops` namespace of this database, which holds a `latency` table of per-service p99 latency readings. Which service has the highest `p99_ms`, and what is that value? This is a read-only check. End your answer with two lines of exactly this form: > > SERVICE: <service_name> > P99: <p99_ms value> > ``` ### Table branches > [accordion] 801: create branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Create a branch called `experiment-reindex` on the `eval_create_branch` table, off its current state. > ``` > [accordion] 802: switch branch and write > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Switch to the `wip-branch` branch of the `eval_switch_branch` table and add a description to its `category` column. The change should land on `wip-branch`, not on main. > ``` > [accordion] 803: cherry pick branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `ready-to-cherry-pick` branch of the `eval_cherry_pick` table has been reviewed and approved. Cherry-pick it onto main so its changes land on the main table. > ``` > [accordion] 804: delete branch > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We no longer need the `stale-2024` branch on the `eval_delete_branch` table. Delete it. > ``` ### Background jobs > [accordion] 901: list running jobs > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > What jobs are currently running against the `eval_job_list_{db}` table? Give each one's type and current state. This is a read-only check — do not cancel or modify anything. End your answer with one line per currently-running job, each of exactly this form (full job id, no truncation). Write `<job_type>` and `<current_state>` exactly as the API reports them, not as synonyms or prose — a compaction job that had failed would read `RUNNING: j1-xy-0ab-cdef | table_compaction | failed`: > > RUNNING: <job_id> | <job_type> | <current_state> > ``` > [accordion] 902: describe job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > An automated maintenance job was recently started against the `eval_job_describe_{db}` table. Find it and report what kind of job it is and its current status. Do not cancel or modify it. End your answer with lines of exactly these forms (full job id, no truncation). Write the type and state exactly as the API reports them, not as synonyms or prose — a compaction job that had failed would read `TYPE: table_compaction` and `STATE: failed`: > > JOB: <job_id> > TYPE: <job_type> > STATE: <current_state> > ``` > [accordion] 903: cancel job > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > A cache-prewarm job against the `eval_job_cancel_{db}` table is hogging resources. Cancel it, and leave every other job alone. End your answer with a line of exactly this form (the full id of the job you cancelled, no truncation): > > CANCELLED: <job_id> > ``` ### Multi-step workflows > [accordion] 1001: create embed search > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Set up a small semantic-search demo from scratch in this database. Create a new table called `eval_embed_search` with exactly three columns: `id` (int64), `text` (string), and `embedding` — a fixed-size vector of floats holding an embedding of `text`, computed with the `all-MiniLM-L6-v2` sentence-transformers model (embed each `text` exactly as written; use that same model for every row and for the query below). Populate it with exactly these 8 rows: > > | id | text | > |----|------| > | 1 | Espresso machine with a 15-bar pump for rich, crema-topped coffee | > | 2 | Burr coffee grinder for fresh, evenly ground espresso beans | > | 3 | Pour-over coffee kettle with a gooseneck spout for slow brewing | > | 4 | Reusable coffee filter for drip brewers and pour-over cones | > | 5 | Waterproof hiking boots for rocky mountain trails | > | 6 | Lightweight hiking backpack with a hydration sleeve for day trails | > | 7 | Trekking poles for steep mountain trail descents | > | 8 | Merino wool hiking socks for long days on the trail | > > Then run two vector searches against the table, both using cosine distance: (1) a 'similar items' search using row 2's own stored embedding as the query, returning the 3 nearest OTHER rows; (2) a text search — embed the query `gear for a mountain hike` with the same model and return the 3 nearest rows. End your answer with two lines of exactly this form, ids comma-separated, nearest first: > > NEAREST: <id>,<id>,<id> > QUERY_HITS: <id>,<id>,<id> > ``` > [accordion] 1002: build all indexes > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > The `eval_index_all` table is about to back our product search page. The page will run: visual similarity search on the `image_clip_v2` embeddings (cosine distance), keyword search over `body_text`, exact-match filters on `category`, and range filters on `price_usd` — often combined with the searches. Today the table has no indexes at all. Build all the indexes this table will need to make search fast, and make sure every one of them finishes building. Don't build indexes the page won't use — each one costs build time and slows writes — and note that `image_clip_v1` is a legacy column nothing queries anymore. Do not modify the table's rows or schema. > ``` > [accordion] 1003: embedding models in branches > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > We're choosing an embedding model for the `body_text` column of the `eval_embed_branches` table (24 product descriptions) and want to compare 3 candidates side by side without touching the production data. The candidates: `all-MiniLM-L6-v2`, `bge-small-en-v1.5`, and `gte-small`. Run the experiment on branches: for each candidate, create a branch of the table off main and, on that branch only, add a fixed-size float vector column called `body_embedding` holding that model's embedding of every row's `body_text` (embed the text exactly as stored). Then run the same search on each branch, using cosine distance — the 3 products most similar to the query `a paperback novel to read on the beach`, embedded with that branch's model — so we can compare what each model returns. Main must be left exactly as it is: no new column, no new rows, no other writes. End your answer with one line per branch, each of exactly this form (the model named the way its provider does, e.g. `all-MiniLM-L6-v2`; the three ids comma-separated, most similar first): > > BRANCH: <branch_name> | <embedding_model> | <id>,<id>,<id> > ``` > [accordion] 1004: parquet to lance embed > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > Convert this Parquet dataset to Lance and add a vector column from the description field. The dataset is `products.parquet` in your working directory. Load it into a new table called `eval_parquet_products` in this database, keeping every Parquet column and row exactly as they are, and add a column `description_embedding`: a fixed-size vector of floats holding an embedding of each row's `description`, computed with a text-embedding model of your choice (the same model for every row). > ``` # LanceDB Lakehouse Source: https://docs.lancedb.com/oss/v0-41-0/basics/catalog LanceDB Lakehouse objects are organized into a catalog of databases, namespaces and tables -- connect to a database to work with them. ## Catalog Hierarchy A catalog keeps track of named data objects, such as tables and views, so applications can discover and access them. In LanceDB Enterprise, the catalog is the top-level entry point: it organizes databases, which in turn organize namespaces and tables -- similar to a catalog in Postgres, Snowflake, or other database systems. The catalog itself has no name of its own -- it's just the root -- and an Enterprise deployment's catalog is identified by its endpoint, not a name like the objects beneath it. LanceDB Embedded has no catalog at all. Connect directly to a [database](#connecting-to-database) instead of going through a catalog. A database contains namespaces that group related tables and views. Namespaces can also contain other namespaces, letting teams organize data by project, environment or purpose. For example, a search application can keep production and staging data in separate namespaces within the same database, with `prod` further split into a nested `search` namespace: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD catalog["root catalog"] --> database["ai_data · database"] database --> prod["prod · namespace"] database --> staging["staging · namespace"] prod --> search["search · namespace"] search --> search_docs["documents · table"] search --> search_view["recent_documents · view"] search --> search_fn["embed · function"] staging --> staging_docs["documents · table"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` | Object | What it represents | | - | - | | [Catalog](/oss/v0-41-0/management/catalog) | The unnamed root of an Enterprise deployment, identified by its endpoint; lists, creates and drops databases. Not present in Embedded. | | [Database](/oss/v0-41-0/management/database) | A container for namespaces and their data objects. | | [Namespace](/oss/v0-41-0/management/namespace) | A named group of catalog objects -- tables, views, secrets, functions, storage integrations, or nested namespaces -- addressed by its namespace path. | | [Table](/oss/v0-41-0/management/table) | Data stored as rows and columns. | | [View](/oss/v0-41-0/management/view) | A saved query, evaluated when read. Available in Enterprise. | | [Materialized view](/oss/v0-41-0/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. | | [Secret](/oss/v0-41-0/management/secret) | A named credential that a Function binds by reference. Available in Enterprise. | | [Storage integration](/oss/v0-41-0/management/storage-integration) | A named credential for reading or importing from storage outside the deployment's own tables, such as an S3 prefix or a HuggingFace repository. Available in Enterprise. | | [Function](/oss/v0-41-0/management/function) | Registered code used to compute column values. Available in Enterprise. | ### Namespace name and path A namespace's **name** is just its own component, such as `search`. Its **path** is the full sequence of names from the database down to it: in the diagram above, `search` sits inside `prod`, so its path is the sequence `prod`, `search`. A namespace path is never written by joining those names with `.` -- a dot is a valid character inside a name, so a dot-joined path couldn't always be split back into its components unambiguously. The two forms below are how SQL actually writes one. ### Schema SQL addresses a namespace path as a **schema**, the ANSI standard's term for the same concept: a nested path collapses into one identifier, its components joined by `$` instead of `.`. The path's length changes what the schema looks like: | Path | Schema | | - | - | | `[]` (the database root) | `public` -- the reserved name for the empty path | | `["prod"]` | `prod` -- one component needs no joining | | `["prod", "search"]` | `` `prod$search` `` -- joined, and backtick-quoted because `$` isn't a bare-identifier character | `$` can't appear in an ordinary name, so a schema can always be split back into its exact path, unlike a dot-joined one. (This "schema" is the namespace path as a SQL identifier -- distinct from a table's Arrow schema, its column names and types.) ### Object identifier An object -- a table, view, function, secret, or storage integration -- is addressed in SQL by the ANSI three-part identifier `database.schema.name`, where `schema` is exactly the `$`-joined path above. The `documents` table in `search`, nested inside `prod`, in database `ai_data`, is ``ai_data.`prod$search`.documents``. One directly under the database root uses `public`: `ai_data.public.documents`. See [Namespace](/oss/v0-41-0/sql/ddl/namespace) for the full `CREATE`/`ALTER`/`DROP` syntax. ## Connecting You always run table and query operations within a **database**; cross-database operations go through SQL instead. The same Python, TypeScript and Rust SDKs reach a database and the catalog separately. ### Connecting to Catalog `connect_catalog(endpoint)` connects to Enterprise's root catalog, which can list, create and drop databases across the whole deployment. Its `connect_database(name)` and `create_database(name)` then return the same kind of database connection `lancedb.connect()` does. This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a database, never directly against the catalog. Local filesystem and object-store deployments have no catalog to connect to -- each is already scoped to one database. ### Connecting to Database `lancedb.connect(uri)` opens one database in a single call -- a local directory, an object-storage path, or (with a `db://` URI) a specific Enterprise database. The table below shows which URI reaches which kind of database directly. | URI | Mode | Where queries run | | - | - | - | | A local path, such as `./data` | Embedded | In your process | | `s3://`, `gs://` or `az://` | Embedded | In your process, reading object storage | | `db://` | Enterprise | On your cluster | #### A local directory Embedded in your application, LanceDB reads and writes the tables in a directory on disk. ```python Python (sync) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" db = lancedb.connect(uri) ``` ```python Python (async) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" async_db = await lancedb.connect_async(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("ex_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("ex_lancedb").execute().await?; ``` #### Object storage With an object storage URI the library is still embedded: your process runs every query and reads and writes the bucket directly, with credentials from its environment or its connection's `storage_options`. ```python Python (sync) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". db = lancedb.connect(uri) ``` ```python Python (async) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". async_db = await lancedb.connect_async(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". const db = await lancedb.connect(uri); ``` In Rust, pass the same URI to `connect`. LanceDB supports these object storage backends: | Backend | URI scheme | Credentials | | - | - | - | | AWS S3, and S3-compatible stores (MinIO, Tigris, ...) | `s3://` | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, or `storage_options`. Compatible stores also need `endpoint` and `region`. | | Google Cloud Storage | `gs://` | `GOOGLE_SERVICE_ACCOUNT` (path to a service account JSON), or `storage_options` | | Azure Blob Storage | `az://` | `AZURE_STORAGE_ACCOUNT_NAME` + `AZURE_STORAGE_ACCOUNT_KEY` (or a SAS token), or `storage_options` | | Tencent COS | `cos://` | `TENCENTCLOUD_SECRET_ID` / `TENCENTCLOUD_SECRET_KEY`, or `storage_options` | | GooseFS (a cache layer over COS or S3) | `goosefs://` | Reads from the GooseFS client environment | Pass credentials as environment variables (uppercase), or as a `storage_options` dict at connection or table level (lowercase keys); a table's `storage_options` inherit the connection's and override on a per-key basis. Choosing among these is a tradeoff between latency, scalability, cost and operational complexity, before you even pick a cloud-specific backend: object storage (S3, GCS, Azure Blob) has the highest latency but is the cheapest and scales storage effectively without limit; networked file storage (EFS, Filestore, Azure Files) and third-party stores (MinIO, WekaFS) sit in between; block storage (EBS, Persistent Disk, Managed Disk) and local NVMe are the fastest but tie data to one instance, so scaling means sharding or copying it yourself. ##### S3-compatible stores ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://bucket/path", storage_options={ "region": "us-east-1", "endpoint": "http://minio:9000", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3Minio() { const db = await lancedb.connect("s3://bucket/path", { storageOptions: { region: "us-east-1", endpoint: "http://minio:9000", }, }); return db; } ``` If the endpoint is `http://` (common in local development), also set `ALLOW_HTTP=true` or pass `allow_http=True` in `storage_options`. ##### S3 Express ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://my-bucket--use1-az4--x-s3/path", storage_options={ "region": "us-east-1", "s3_express": "true", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3Express() { const db = await lancedb.connect( "s3://my-bucket--use1-az4--x-s3/path", { storageOptions: { region: "us-east-1", s3Express: "true", }, }, ); return db; } ``` Consult AWS's networking requirements for S3 Express before enabling it. ##### Server-side encryption with KMS Set `aws_server_side_encryption` to `aws:kms` and `aws_sse_kms_key_id` to the key ID or ARN to encrypt at rest with an AWS KMS key. The same options apply at connection or table level, and combine with bucket-level default encryption. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( "s3://bucket/path", storage_options={ "aws_server_side_encryption": "aws:kms", "aws_sse_kms_key_id": "<your-kms-key-id-or-arn>", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function storageS3SseKms() { const db = await lancedb.connect("s3://bucket/path", { storageOptions: { awsServerSideEncryption: "aws:kms", awsSseKmsKeyId: "<your-kms-key-id-or-arn>", }, }); return db; } ``` The IAM principal needs `kms:Encrypt`, `kms:Decrypt` and `kms:GenerateDataKey` on the configured KMS key. > [!NOTE] > > **Tencent COS and GooseFS build availability.** Both are bundled by > default in the Python wheel. In the Node binding, GooseFS is bundled by > default but COS is not -- build with the `cos` Cargo feature enabled to > use it there. In Rust, neither is in the default feature set; build with > the `cos` or `goosefs` Cargo feature enabled to use either one. #### LanceDB Enterprise A `db://` URI connects directly to one database in LanceDB Enterprise, where your cluster runs queries and background work. Get the database URI, API key, region and endpoint from your administrator, then replace the placeholders below. Use your cluster's region in place of `us-east-1`. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` In Rust, enable the crate's `remote` feature; the connection builder then takes the same settings through `api_key`, `region` and `host_override`. To use OAuth instead of an API key, see [Authentication](/oss/v0-41-0/enterprise/authentication); for every connection option, see [Database](/oss/v0-41-0/management/database#deployment). ## Organization and access control * **Separate projects and environments.** Keep production and staging tables in distinct namespaces, even when they use the same table names. * **Find shared datasets.** Give teams a consistent place to discover and access the data they work with. * **Control access in Enterprise.** Use permissions on databases, namespaces and tables to manage who can access shared data and what they can do with it. ## Learn more * [Catalog](/oss/v0-41-0/management/catalog): initial access to a new deployment, and the superuser bootstrap. * [Databases](/oss/v0-41-0/management/database): connect to and manage a database. * [Namespaces](/oss/v0-41-0/management/namespace): create groups and address tables within them. * [Tables](/oss/v0-41-0/management/table): create, inspect and manage your data. * [Views](/oss/v0-41-0/management/view) and [materialized views](/oss/v0-41-0/management/materialized-view): work with query-defined data. * [Secrets](/oss/v0-41-0/management/secret): store a credential that a Function can bind by reference. * [Storage integrations](/oss/v0-41-0/management/storage-integration): read or import from storage outside your own tables. * [Authorization](/oss/v0-41-0/governance/authorization): configure Enterprise access permissions. # Embedded vs Enterprise Source: https://docs.lancedb.com/oss/v0-41-0/basics/embedded-vs-enterprise A feature-by-feature comparison between LanceDB Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. [LanceDB Enterprise](/oss/v0-41-0/enterprise/index) distributes query execution, indexing, maintenance and refresh work across a cluster of many machines, outside your application. Both are built on the same [Lance](/oss/v0-41-0/basics/lance) columnar file format, so moving data from one edition to the other does not require a data conversion step. See [Architecture](/oss/v0-41-0/index#architecture) for how each one's components fit together. ## How they differ | Dimension | LanceDB Embedded | LanceDB Enterprise | What the difference means | | :- | :- | :- | :- | | **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | | **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/oss/v0-41-0/search/vector-search#expected-performance) and [full-text search](/oss/v0-41-0/search/full-text-search#expected-performance) for representative measurements. | | **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/oss/v0-41-0/enterprise/data-page-cache). | | **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/oss/v0-41-0/indexing/). | | **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | | **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | | **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/oss/v0-41-0/curation) over SQL. See [SQL reference](/oss/v0-41-0/sql). | | **Native vector dedup** | Not available | `dedupe()` / `duplicate_pairs()` | Index-partition deduplication as a SQL table function, with no full pairwise scan. See [DEDUPE](/oss/v0-41-0/sql/dql/dedupe). | | **Materialized views** | Not available | Server-side, distributed compute | Enterprise derives and refreshes a table from a query as a background job. See [Materialized views](/oss/v0-41-0/feature-engineering/materialized-views). | ## Compare features | Area | Feature | Embedded | Enterprise | | - | - | :-: | :-: | | **Data Ingestion** | [Insert data](/oss/v0-41-0/ingestion/insert) | ✅ | ✅ | | | [RTE Write (Upsert)](/oss/v0-41-0/ingestion/realtime-write) | ✅ | ✅ | | | [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write) | ❌ | ✅ | | | [Attach Database](/oss/v0-41-0/ingestion/migrate-from-embedded) | ❌ | ✅ | | | [Import Datasets](/oss/v0-41-0/ingestion/import) | ❌ | ✅ | | | [Distributed Write](/oss/v0-41-0/enterprise/distributed-write) | ❌ | ✅ | | **Search** | [Vector search](/oss/v0-41-0/search/vector-search) | ✅ | ✅ | | | [Full-text search](/oss/v0-41-0/search/full-text-search) | ✅ | ✅ | | | [Hybrid search](/oss/v0-41-0/search/hybrid-search) | ✅ | ✅ | | | [Filtering](/oss/v0-41-0/search/filtering) | ✅ | ✅ | | | [Reranking](/oss/v0-41-0/reranking) | ✅ | ✅ | | | [Distributed Search](/oss/v0-41-0/enterprise/distributed-search) | ❌ | ✅ | | | [RTE Read](/oss/v0-41-0/search/realtime-read) | ✅ | ✅ | | | [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read) | ❌ | ✅ | | | [Cache Prewarm](/oss/v0-41-0/enterprise/cache-prewarm) | ❌ | ✅ | | **Data Curation** | [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) | ❌ | ✅ | | | [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) | ❌ | ✅ | | | [Selective Sampling](/oss/v0-41-0/curation/selective-sampling) | ✅ | ✅ | | | [Aggregation and profiling](/oss/v0-41-0/curation/aggregate) | ❌ | ✅ | | | [Joins](/oss/v0-41-0/curation/join) | ❌ | ✅ | | | [Blob Late Materialization](/oss/v0-41-0/curation/blob-late-materialization) | ❌ | ✅ | | | [Ranking](/oss/v0-41-0/curation/windowing) | ❌ | ✅ | | | [Near-duplicate detection](/oss/v0-41-0/curation/dedupe) | ❌ | ✅ | | | [Chunking](/oss/v0-41-0/curation/chunking) | ❌ | ✅ | | | [Changes since a version](/oss/v0-41-0/curation/changes) | ❌ | ✅ | | **Feature Engineering** | [Computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) | ❌ | ✅ | | | [Incremental Refresh](/oss/v0-41-0/enterprise/incremental-refresh) | ❌ | ✅ | | | [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) | ❌ | ✅ | | | [Checkpointing](/oss/v0-41-0/enterprise/checkpointing) | ❌ | ✅ | | | [Adaptive Execution](/oss/v0-41-0/enterprise/adaptive-execution) | ❌ | ✅ | | | [Refresh Materialized View](/oss/v0-41-0/feature-engineering/refresh-materialized-view) | ❌ | ✅ | | | [Embedding registry](/oss/v0-41-0/embedding) | ✅ | ✅ | | **Training** | [PyTorch data loader](/oss/v0-41-0/training/data-loading) | ✅ | ✅ | | | [Training Cache](/oss/v0-41-0/training/training-cache) | ❌ | ✅ | | | [Permutations](/oss/v0-41-0/training/permutation) | ✅ | ✅ | | | [Distributed training](/oss/v0-41-0/training/distributed-training) | ✅ | ✅ | | | [Observability](/oss/v0-41-0/training/observability) | ✅ | ✅ | | | [Checkpointing](/oss/v0-41-0/training/checkpointing) | ✅ | ✅ | | | [Resuming](/oss/v0-41-0/training/resuming) | ✅ | ✅ | | **Management** | [Catalog](/oss/v0-41-0/management/catalog) | ❌ | ✅ | | | [Database](/oss/v0-41-0/management/database) | ✅ | ✅ | | | [Namespace](/oss/v0-41-0/management/namespace) | ✅ | ✅ | | | [Table](/oss/v0-41-0/management/table) | ✅ | ✅ | | | [View](/oss/v0-41-0/management/view) | ❌ | ✅ | | | [Materialized view](/oss/v0-41-0/management/materialized-view) | ❌ | ✅ | | | [Secret](/oss/v0-41-0/management/secret) | ❌ | ✅ | | | [Function](/oss/v0-41-0/management/function) | ❌ | ✅ | | | [Storage integration](/oss/v0-41-0/management/storage-integration) | ❌ | ✅ | | | [Console](/oss/v0-41-0/enterprise/console) | ❌ | ✅ | | **Maintenance** | [Intelligent Auto-Maintenance](/oss/v0-41-0/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | | | [Vector Indexing](/oss/v0-41-0/indexing/vector-index) | ✅ | ✅ | | | [FTS Indexing](/oss/v0-41-0/indexing/fts-index) | ✅ | ✅ | | | [Scalar Indexing](/oss/v0-41-0/indexing/scalar-index) | ✅ | ✅ | | | [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing) | ✅ | ✅ | | | [Distributed Indexing](/oss/v0-41-0/enterprise/distributed-indexing) | ❌ | ✅ | | | [GPU Indexing](/oss/v0-41-0/indexing/gpu-indexing) | ✅ | ✅ | | | [Compaction](/oss/v0-41-0/maintenance/compaction) | ✅ | ✅ | | | [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction) | ❌ | ✅ | | | [Garbage Collection](/oss/v0-41-0/maintenance/cleanup) | ✅ | ✅ | | | [Distributed Compaction](/oss/v0-41-0/enterprise/distributed-compaction) | ❌ | ✅ | | | [Advanced Conflict Resolution](/oss/v0-41-0/enterprise/advanced-conflict-resolution) | ❌ | ✅ | | **Security** | [Authentication](/oss/v0-41-0/enterprise/authentication) | ❌ | ✅ | | | [Authorization](/oss/v0-41-0/governance/authorization) | ❌ | ✅ | | | [Audit Log](/oss/v0-41-0/governance/audit-log) | ❌ | ✅ | | **Deployment** | [Horizontal Scaling](/oss/v0-41-0/enterprise/horizontal-scaling) | ❌ | ✅ | | | [OpenTelemetry](/oss/v0-41-0/deployment/opentelemetry) | ✅ | ✅ | | | [Kubernetes](/oss/v0-41-0/enterprise/deployment/kubernetes) | ❌ | ✅ | | | [Multicloud](/oss/v0-41-0/deployment/multicloud) | ❌ | ✅ | | | [Slurm](/oss/v0-41-0/deployment/slurm) | ❌ | ✅ | ## Usage differences between Enterprise and Embedded The [quickstart](/oss/v0-41-0/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...` connections. Once connected to LanceDB, the table API is largely the same: create a table, search, filter, evolve the schema, and store multimodal records. However, there are some semantic differences worth understanding when your code is talking to LanceDB Enterprise. ### 1. Connection model In LanceDB Enterprise, your app connects via a `db://...` URI and sends requests to the cluster API. The cluster executes table operations on your behalf. Your code is coupled to a **managed service endpoint**, whereas LanceDB Embedded is directly coupled to local or object-storage paths. ### 2. Returned table type Connecting to an Enterprise table via `open_table(...)` returns a `RemoteTable`, unlike LanceDB Embedded, which returns a `LanceTable`. `RemoteTable` is a catalog-backed table accessed through a server/cluster, and does not support all the same methods as `LanceTable` (see below). ### 3. Materialization APIs For Python users working with LanceDB Enterprise, `RemoteTable` does not support table-level materialization methods like `table.to_arrow()` or `table.to_pandas()`. This protects users from accidentally materializing tables that are too large to fit in memory. Instead, materialize results through query/search builders, for example `table.search(...).limit(...).to_pandas()` for a vector or full-text search, or `table.search().where(...).limit(...).to_arrow()` for a filtered scan. For quick previews, use `table.head()`. ### 4. Maintenance lifecycle In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and `cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients reject `optimize()` as not supported. That means maintenance is managed by platform behavior and cluster configuration, not by explicit per-table maintenance calls in your application code. ### 5. Guardrails and limits Enterprise can enforce platform-level guardrails, such as index/table limits and safety checks around operations like `merge_insert` when too many rows are unindexed. LanceDB Embedded mostly exposes storage/format-level behavior, and you tune many lifecycle tasks yourself. This means an operation in LanceDB Enterprise can fail due to service-level policy, not just because of local table shape or schema mismatch. > [!NOTE] > > As a rule of thumb, all you need to remember is this: treat `db://...` as a network service boundary, > use query builders to fetch results, and otherwise interact with your tables as you would in LanceDB > Embedded. ## Which one should I use? [It's very simple to get started with LanceDB Embedded](/oss/v0-41-0/quickstart/): Get started with `pip install lancedb` and begin ingesting your data and vectors into LanceDB. LanceDB Embedded (open source) makes sense when your dataset fits on one machine, traffic is still modest, and your team is comfortable handling maintenance tasks such as compaction or reindexing itself. Move to LanceDB Enterprise when retrieval becomes shared infrastructure for your business: your data or traffic has outgrown a single machine, you need private deployment options, or you want platform support for monitoring, security, and large-scale feature workflows. If these sound like your use cases, [reach out to us](https://www.lancedb.com/contact) and we can help you scope your workload and arrange an Enterprise proof of concept. # Guarantees Source: https://docs.lancedb.com/oss/v0-41-0/basics/guarantees Understand table commits, concurrent writes and the boundaries of recovery. ## Atomic table writes A table transaction commits its changes atomically: readers see the committed table version, not a partially applied transaction. For example, a committed append adds its rows together. This boundary is one table transaction. A workflow that updates several tables or runs a background job can contain multiple commits. Do not assume the whole workflow is atomic. Schema changes are also part of table history. Changing a column's type can rewrite data; adding a derived column can write the new column independently. ## Consistent reads A read of a table uses a consistent snapshot. A consistent snapshot can still be older than another writer's latest commit. [Consistency](/oss/v0-41-0/tables/consistency) explains how LanceDB Embedded and LanceDB Enterprise choose the version a reader sees. For an experiment that must keep using the same data, select a specific retained table version rather than relying on a connection's default freshness. ## Concurrent writes Lance uses optimistic concurrency control. Writers prepare changes, then check compatibility with intervening commits. Compatible changes can be committed; conflicts may be retried or returned as errors. Applications must handle failed writes. Concurrent appends are compatible, but that does not promise success through storage failures or exhausted retries. Do not rely on a particular ordering between independent writers. The [Lance transaction specification](https://lance.org/format/table/transaction/) describes commit behavior and compatibility between operations. ## Storage durability A committed table version is stored in the table’s configured storage. LanceDB Embedded uses your local filesystem or object store; LanceDB Enterprise uses the cluster’s configured storage. Table version history does not replace backups. Configure storage redundancy and backups to meet your recovery requirements. ## Background job completion In LanceDB Enterprise, operations such as index builds and column refreshes can run as background jobs. Receiving a job handle confirms submission. Wait for the job to succeed before relying on its result. Some operations save results in batches. If a job fails or is cancelled, batches already committed can remain in the table. Each operation’s guide explains whether it can leave partial results. ## Writes after a client timeout If a client times out while waiting for a write, the write may already have committed. Retrying an append can therefore insert the same records again. Check whether the intended records were written before retrying. For an operation submitted as a background job, check its status using the job handle. ## Version history and recovery Retained table versions let you inspect earlier data or restore a table to a previous version. Cleanup can remove those versions and their underlying files, so configure retention to cover the history you need. Dropping a table is different from deleting records. Table version history cannot undo `drop_table`. ## Learn more * [Consistency](/oss/v0-41-0/tables/consistency): control when reads observe updates. * [Table versioning](/oss/v0-41-0/management/table#versioning): inspect and restore history. * [Garbage Collection](/oss/v0-41-0/maintenance/cleanup): configure retention and understand protected versions. * [Job Framework](/oss/v0-41-0/basics/jobs): distinguish submission, completion and cancellation. * [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column): understand partial progress. * [Architecture](/oss/v0-41-0/index#architecture): understand storage and background maintenance. # Job Framework Source: https://docs.lancedb.com/oss/v0-41-0/basics/jobs Track background work from submission to completion. **Applies to:** Embedded ❌, Enterprise ✅ ## Job handles A job handle lets you track an operation, such as an index build or a computed column refresh. Use it to check progress, wait for completion and inspect failures. Methods such as Python's `create_index_async` and TypeScript's `createIndexAsync` return job handles. In LanceDB Embedded, the work runs in your application process; in Enterprise, it runs on server workers or through the SQL query backend. A returned handle can represent an operation that has already finished, so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = tbl.create_index_async("vector", replace=True) print(job.id) print(job.job_type) print(job.status()) ``` ## Submit and wait for a job 1. **Submit the operation.** Keep the returned job handle. For an Enterprise registry job, also keep its ID if another process needs to look it up later. 2. **Check progress.** Read the current status while the operation runs. 3. **Wait for completion.** Check that the job succeeded before using its result. If it failed or was cancelled, inspect the failure details and any results it committed before stopping. In Python, `job.status()` reports the current state and `job.wait()` waits for completion, raising if the job fails or is cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. If the timeout expires while disconnected, the wait raises `ConnectionError` with the job ID and instructions to resume waiting. A timeout while connected raises `TimeoutError`. The job may still be running; timing out does not cancel it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb.exceptions import JobFailedError, JobCancelledError job = tbl.create_index_async("vector", replace=True) job_id = job.id # Save the ID to reopen an Enterprise registry job later. try: result = job.wait(timeout=timedelta(minutes=10)) except JobFailedError: print(f"job failed: {job.failure}") except JobCancelledError: print("job was cancelled") except ConnectionError as exc: print(exc) # The job may still be running on the server. except TimeoutError: print(f"still running: {job.status()}") ``` After connectivity returns, reopen an Enterprise registry job by its saved ID and continue waiting on the existing operation: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.open_job(job_id) result = job.wait(timeout=timedelta(minutes=10)) ``` For SQL-backed jobs, call `wait()` again on the original handle. These jobs cannot be reopened with `db.open_job()`; see [SQL-backed job handles](#sql-backed-job-handles). ## Inspect and cancel jobs | Task | What to do | | - | - | | Inspect progress | Check status and refresh the handle to retrieve details. Enterprise job events can help explain ongoing work or failures. | | Reattach from another process | Open an existing server job with its ID, such as Python's `db.open_job(job_id)`. The server must still retain the job record. | | Diagnose a failure | Inspect failure details and relevant events. Enterprise SQL also provides `SHOW ERRORS`. | | Request cancellation | Call the job's cancellation method. Cancellation may take time, and work already committed is not rolled back. | Reopening a job retrieves the existing operation; it does not restart failed work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.open_job(job_id) # raises JobNotFoundError if unknown job.refresh() # pull the latest status from the server print(job.status()) events = job.events(limit=100) print(events.to_pylist()) job.cancel() ``` List jobs on a connection, paging through the results: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for info in db.list_jobs(page_limit=50): print(info.job_id, info.job_type, info.state) ``` Event responses have [row limits](/oss/v0-41-0/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. ## Embedded and Enterprise execution The following table describes LanceDB Embedded operations and registry jobs on LanceDB Enterprise. SQL-backed job handles follow the query lifecycle described below. | | Embedded | Enterprise registry job | | - | - | - | | Execution | In your application process | On server workers | | Job identity | No server ID | A server ID for looking up the job | | Event history | No server event history | Available through the jobs API | | Reattaching after a client restart | No server job to reopen | Reopen by ID while the record is retained | ### SQL-backed job handles On Enterprise, several catalog operations return a job handle backed by the SQL query engine rather than the job registry: | Operation | SDK methods | Behavior | | - | - | - | | Materialized views | `create_materialized_view_async()`, `refresh_async()`, `drop_materialized_view_async()` | Synchronous variants wait on the same SQL execution. Drop removes the catalog binding immediately; physical cleanup continues in the background. | | Functions | Registration, `drop_function_async()` | Registration waits for catalog publication before returning the immutable FunctionVersion. Drop confirms catalog removal while cleanup continues separately. | | Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. | | Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. | All of these report `job.job_type` as `"query"`, with `job.id` holding the connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect one. Unlike registry handles, they don't expose event history, can't be reopened through `open_job()` or reattached after a client restart, and cancellation depends on the SQL server's support for it. ### Object teardown The "physical cleanup continues in the background" behavior above, for a dropped table, view, materialized view, Secret or Function, is a job type of its own: `drop_object` deletes the dropped object's content, then clears it from the database's cleanup backlog. You trigger it indirectly, by dropping one of those objects or a [namespace](/oss/v0-41-0/management/namespace) -- it runs as this job rather than inline with the call. Whether a dropped table runs as `drop_object` or as [`drop_table`](/oss/v0-41-0/management/table#drop), which fences the table's directory with its own marker instead, depends on how the deployment stores its catalog. ## Learn more * [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing): submit index work. * [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column): populate derived values. * [SQL job commands](/oss/v0-41-0/sql/ddl/job): list jobs and inspect errors. * [SDKs](/oss/v0-41-0/basics/sdk): find the job API for your client. # Lance format Source: https://docs.lancedb.com/oss/v0-41-0/basics/lance The open format for multimodal data behind LanceDB. ## Lance format overview [Lance](https://lance.org/) is an open-source, columnar format designed for multimodal AI. It defines how data is stored and organized into versioned tables. LanceDB Embedded and LanceDB Enterprise both use Lance as their storage foundation. The format is developed as an independent open-source project, with its own specification and tools. ## Multimodal data A Lance table can hold images, video, audio, text, embeddings and structured metadata together. For example, a video dataset can keep each clip alongside its caption, labels and embeddings, so applications can search and work with those fields together. ## Data access, versioning and column updates * **Efficient data access.** Read individual rows for retrieval and training, or scan columns for analytics. * **Versioned data.** Read an earlier table version to reproduce an experiment or inspect previous results, while that version is retained. * **Independent column updates.** Add embeddings or other derived features without rewriting the existing image, video or text columns. ## Opening Lance datasets in Python Any `.lance` dataset directory is a LanceDB table. Pass the parent directory to `lancedb.connect()` and open the table by its directory stem: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("/data") # pass storage_options=... for S3, GCS or Azure tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a version ``` Use `lancedb` for search, retrieval, data curation, multimodal blob access and application code. Install `pylance` (`import lance`) only when building query engines or connectors, calling format-level fragment APIs directly, or converting plain-scan lazy blob handles or legacy blob bytes with `to_pandas()`. See [Multimodal data and blobs](/oss/v0-41-0/management/table#multimodal) for native v2 blob conversions that do not require `pylance`. | `pylance` (`import lance`) | `lancedb` (`import lancedb`) | | - | - | | `lance.dataset("/data/frames.lance")` | `lancedb.connect("/data").open_table("frames")` | | `lance.write_dataset(data, "/data/frames.lance")` | `lancedb.connect("/data").create_table("frames", data)` | | `lance.vector.vec_to_table(mat)` | `db.create_table(name, pa.table({"vector": list(mat)}))` | | `lance.blob_field("video")` | `lancedb.blob("video")` | | `ds.take_blobs("video", ids=row_ids)` | `tbl.fetch_blob_files("video", row_ids)` (seekable handles) or `tbl.fetch_blobs("video", row_ids)` (`pa.LargeBinaryArray`) | | `ds.to_table(columns=cols, filter=expr, limit=n)` | `tbl.search().where(expr).select(cols).limit(n).to_arrow()` | | `ds.to_batches(batch_size=k)` | `tbl.search().to_batches(k)` | | `ds.take(offsets)` | `tbl.__getitems__(offsets)` (preserves offset order) or `tbl.take_offsets(offsets).to_arrow()` (unordered) | | `ds.versions()`, `ds.checkout_version(v)`, `ds.restore()` | `tbl.list_versions()`, `tbl.checkout(v)`, `tbl.restore()` | | `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(compaction_options=..., cleanup_older_than=...)` | ## Learn more * [Lance format specification](https://lance.org/format): how the format works. * [Multimodal data and blobs](/oss/v0-41-0/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. * [Table versioning](/oss/v0-41-0/management/table#versioning): read and manage table versions. * [Computed columns](/oss/v0-41-0/feature-engineering/add-computed-column): add derived features to your data. * [Architecture](/oss/v0-41-0/index#architecture): how LanceDB Embedded and Enterprise build on Lance. # LanceDB Embedded Source: https://docs.lancedb.com/oss/v0-41-0/basics/lancedb-embedded The open-source, embedded retrieval library that runs inside your application process. **LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database server to deploy. It reads and writes tables on local disk or in object storage from inside your application process, on the same [Lance](/oss/v0-41-0/basics/lance) format and table model that [LanceDB Enterprise](/oss/v0-41-0/enterprise/index) builds on. ![LanceDB Embedded architecture](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/overview/lancedb-embedded.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=8ea6fa772b094329812645eb31cc448b) LanceDB Embedded: the LanceDB SDK and the Lance format run in your application, reading and writing tables on local disk or in object storage. ## Why use LanceDB Embedded? LanceDB Embedded fits local retrieval applications, notebooks, development, and single-node data pipelines, where your application controls its own compute resources and [table maintenance](/oss/v0-41-0/maintenance/compaction). * **No infrastructure to run** -- the library runs inside your process. There is no server to deploy, configure, or keep available. * **Free and open source** -- `pip install lancedb` (or the TypeScript or Rust equivalent) and start reading and writing tables, with no account or service to set up first. * **Full local control** -- your application decides where table data lives, when maintenance such as compaction and indexing runs, and how much compute each operation gets. * **The same table format as Enterprise** -- Embedded and [Enterprise](/oss/v0-41-0/enterprise/index) share the same Lance format and table model, so moving to a distributed deployment later does not require a data conversion step. ## Get started > [card] [Quickstart](/oss/v0-41-0/quickstart) > > Create a table, add data, and run your first search in a few lines of code. > [card] [Choose an SDK](/oss/v0-41-0/basics/sdk) > > Pick between the Python, TypeScript, and Rust SDKs. When your data or traffic outgrows a single machine, or you need managed infrastructure, private deployment, or platform support, see [LanceDB Enterprise](/oss/v0-41-0/enterprise/index) and the [feature-by-feature comparison](/oss/v0-41-0/basics/embedded-vs-enterprise). # Limits Source: https://docs.lancedb.com/oss/v0-41-0/basics/limits Find fixed constraints, configurable bounds and what happens when you reach them. This page lists limits for job events, SQL error reports, sampling and full-text indexing. Each table identifies the affected API and what happens when a request reaches its limit. SQL and server job limits apply to Enterprise. [Naming Rules](/oss/v0-41-0/basics/naming) is the reference for name lengths, characters and namespace depth. Client and server versions can differ in which rules they enforce. ## Fixed API limits | Operation | Scope | Limit and behavior | | - | - | - | | Job event retrieval | Enterprise | At most 10,000 rows per response. Results can be truncated without a truncation indicator. | | `SHOW ERRORS ... LIMIT` | Enterprise SQL | Accepts 1 through 100,000. Values outside the range are rejected. | | `SHOW ERRORS` without `FOR JOB` | Enterprise SQL | Inspects up to the 32 most recent failed jobs. Use `FOR JOB` to inspect a specific job. | | Percentage sampling | Enterprise SQL | `TABLESAMPLE` accepts percentages from 0 through 100. Values outside the range are rejected. | | Row-count sampling | Enterprise SQL | `TABLESAMPLE (... ROWS)` requires a whole number. | See [SQL job commands](/oss/v0-41-0/sql/ddl/job#errors) and [Sampling](/oss/v0-41-0/sql/dql/sampling) for syntax and restrictions on supported table types. Data-type and index constraints belong to the operation you choose. Check [Data types](/oss/v0-41-0/sql/data-types) and [Vector indexes](/oss/v0-41-0/indexing/vector-index) before choosing a schema or index. For materialized views, confirm your source table meets your deployment's requirements with your administrator before creating one over it. ## Configurable limits | Setting | What it controls | | - | - | | Job event `limit` | Requests more or fewer event rows. The default is 1,000; the 10,000-row maximum still applies. | | FTS `max_token_length` | The maximum indexed token length. The default is 40; longer tokens are excluded from the index. | | Enterprise capacity and quotas | Storage, request rate and concurrency are governed by your deployment's resources and configuration. Confirm these with your administrator or LanceDB support. | ## Handling rejected or incomplete results * **Rejected requests:** correct the input before retrying, such as a sampling percentage outside the accepted range. * **Truncated responses:** do not assume that a returned event list is the full history. Increasing `limit` cannot exceed the maximum; use filters to narrow the events you inspect. * **Excluded data:** an FTS token-length setting can affect which words are searchable. Choose it for your text and indexing requirements. ## Learn more * [Naming Rules](/oss/v0-41-0/basics/naming): choose portable names and paths. * [Job Framework](/oss/v0-41-0/basics/jobs): track work and inspect events. * [Full-text indexes](/oss/v0-41-0/indexing/fts-index): configure tokenization. * [SQL](/oss/v0-41-0/basics/sql) and [SDKs](/oss/v0-41-0/basics/sdk): check interface support. * [Enterprise support](/oss/v0-41-0/deployment/support): discuss deployment capacity. # Naming rules Source: https://docs.lancedb.com/oss/v0-41-0/basics/naming Choose portable names for your data objects and namespace paths. ## Naming rules Databases, namespaces, tables and views all have names. Choose names that describe their purpose, such as `documents`, `prod` or `training_2026`. Consistent names make data easier to find and application code easier to read. Use the following rules for names that work across LanceDB Embedded and LanceDB Enterprise. | Object | Characters | Length | | - | - | - | | Table, materialized view, view | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Namespace component | ASCII letters and digits, `-`, `_`, `.` | 1 to 64 characters; at most 10 components in a path | | Database | ASCII letters and digits, `-`, `_`, `.`, with `/` between components | 1 to 64 characters for the whole name | | Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Function | ASCII letters and digits, `_` | 1 to 128 characters | * Names and individual namespace or database components must not be empty. * Table, view, namespace and database components cannot be `.` or `..`. * Secret names cannot be `.` or `..`. * Avoid `$` and `:` because they separate parts of qualified identifiers. * A namespace path beginning with `public` cannot contain another component. ## Namespace paths A namespace path is a list of names. `["prod", "search"]` identifies the `search` namespace within `prod`. A table named `documents` belongs to that namespace; its table name remains `documents`. Use the SDK's namespace-path argument to supply the list. A period inside an SDK name is a character in that name, not a separator that creates another namespace. SQL uses its own qualified-name syntax; see [SQL namespace paths](/oss/v0-41-0/sql/dql/select#namespaces). The empty path `[]` identifies the root namespace. ## Examples | Name or path | Guidance | | - | - | | `documents`, `user-events.v2`, `train_2026` | Portable table names | | `["prod", "search"]` | A two-component namespace path | | `my table` | Use `my_table` instead of a space | | `orders$2026` | Use `orders_2026`; `$` is reserved | | `résumés` | Use an ASCII name such as `resumes` | | `["public", "search"]` | Invalid nesting under `public`; use a different parent namespace | ## Learn more * [Namespaces](/oss/v0-41-0/management/namespace): create namespaces and address tables. * [Limits](/oss/v0-41-0/basics/limits): check other constraints before designing your schema. # SDKs Source: https://docs.lancedb.com/oss/v0-41-0/basics/sdk Choose a LanceDB SDK and find the API reference for your language. Use a LanceDB SDK to create tables, add data, build indexes and run searches from your application. Python, TypeScript and Rust work with both LanceDB Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. LanceDB Enterprise distributes query execution, indexing, maintenance and refresh work across the service, outside your application. The [quickstart](/oss/v0-41-0/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see [Connect to LanceDB](/oss/v0-41-0/basics/catalog). ## Client versions for these guides The database release and the client SDK version are separate choices. These guides use the following client baselines: | Client | Embedded 0.41.0 | Enterprise 1.12.0 | | - | - | - | | Python | `lancedb==0.41.0` | `lancedb==0.42.0b8` from the LanceDB preview index | | TypeScript | `@lancedb/lancedb@0.41.0` | `@lancedb/lancedb@0.42.0-beta.8` | | Rust | `lancedb` 0.41.0 for the general API; standalone quickstart examples pin 0.31.0 | Enable `remote`; examples use the pinned client revision below | Install the Python or TypeScript client used by the Enterprise examples: ```bash Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --extra-index-url https://pypi.fury.io/lancedb/ "lancedb==0.42.0b8" ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb@0.42.0-beta.8 ``` The Rust Function examples use the client revision bundled with Enterprise 1.12.0: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cargo add lancedb --git https://github.com/lancedb/lancedb \ --rev bff93ff314eee34f625d05bd92b73d95867fe787 --features remote ``` The released Rust 0.41.0 crate also includes APIs for registering, listing, fetching and dropping Functions. The source pin above selects the bundled client as the example baseline. A newer SDK does not add server capabilities: these guides still describe the limits of server 1.12.0. ## Official SDKs | SDK | API reference | | - | - | | Python | [Python reference](https://lancedb.github.io/lancedb/python/python/) | | TypeScript | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | | Rust | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | Guides show the available language examples together. Use the API reference for method signatures and options; SDKs do not expose every feature through the same methods. In Rust, enable the `remote` feature to connect to Enterprise. For SQL joins, aggregations and window functions, use [SQL](/oss/v0-41-0/basics/sql). Python provides a SQL client, and applications in other languages can use a Flight SQL client. TypeScript's table query API does not provide a SQL execution method. ## Lance Namespace SDKs LanceDB Enterprise's catalog and table operations follow the [Lance Namespace Client SDK Specification](https://lance.org/format/namespace), an open specification for describing access to tables in a multimodal lakehouse. Any client that implements it can integrate with LanceDB this way, not only the official SDKs above -- useful for a language or tool without a LanceDB SDK. For SQL queries, connect through [Flight SQL](/oss/v0-41-0/basics/sql) instead. | Language | Package | Used by | | - | - | - | | Java | `org.lance:lance-namespace-core` | Spark, Flink, Kafka, Trino, Presto; also LanceDB's Java client | | Python | `lance-namespace` | Core interface and connect functionality | | Rust | `lance-namespace` | Core interface, in [lance-format/lance](https://github.com/lance-format/lance) | LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated `LanceNamespace` interface talking to Enterprise's Namespace endpoint. The [real time engine](/oss/v0-41-0/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of the Lance Namespace Client SDK Specification. See [lance.org/format/namespace](https://lance.org/format/namespace) for the full specification and its other catalog implementations (Directory, Apache Polaris, Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more). ## Community SDKs These clients are maintained by the community. Check each project's supported features, installation instructions and releases before choosing one. | Language | Project | | - | - | | Go | [lancedb-go](https://pkg.go.dev/github.com/lancedb/lancedb-go/pkg/lancedb) | | Ruby | [Lancelot](https://github.com/scientist-labs/lancelot) | | Swift | [LanceDbSwiftKit](https://github.com/RyanLisse/LanceDbSwiftKit) | | R | [lancedb](https://github.com/CathalByrneGit/lancedb) | | Flutter | [flutter_lancedb](https://github.com/Alexcn/flutter_lancedb) | ## Related guides > [card] [SQL](/oss/v0-41-0/basics/sql) > > Query Enterprise tables with SQL from Python or a Flight SQL client. > [card] [PyTorch Data Loader](/oss/v0-41-0/training/data-loading) > > Use LanceDB tables in a DataLoader, including multiple worker processes. > [card] [Agentic Skills](/oss/v0-41-0/basics/agentic-skills) > > Use the LanceDB plugin to help a coding agent work with your data. # SQL Source: https://docs.lancedb.com/oss/v0-41-0/basics/sql Query LanceDB Enterprise with SQL from Python or an Arrow Flight SQL client. Use SQL in LanceDB Enterprise to filter records, join tables, calculate aggregates, and prepare datasets. SQL queries work with the same Lance tables you create and update through the SDKs, without exporting the data to another system. This guide starts with when to reach for SQL instead of SDK table operations, then covers the three ways to run SQL, connection settings, a first query, parameterized queries, and how to read and manage the results. ## Choose SQL or SDK table operations An SDK gives you a programming-language-specific API for invoking LanceDB's functionality: create a table, insert rows, build an index, run a vector search, each its own method call. Every one of those functionalities also has a corresponding SQL operation. SQL covers a wider surface than any one SDK method and lets you chain operations together in a single statement -- running a vector search and then joining the results with another table, for example -- where SDK methods stay separate calls. Use **SQL** for joins, aggregations, window functions, analytical queries, and whenever you want to chain operations together. Use **SDK table operations** to build applications around table management, ingestion, filtering, and search, including applications that run with LanceDB Embedded, where SQL is not available. You can combine them. For example, create and populate a table with an SDK, then query it with SQL to prepare a training dataset. In Python, both workflows can use the same Enterprise connection. Both interfaces work with the same Lance tables, through the same Arrow schema. Applications in different languages can work with the same tables: connect to the same database and namespace, use the appropriate credentials, and account for [read consistency](/oss/v0-41-0/tables/consistency) when another process writes data. A fixed-size vector column stores vectors of a consistent dimension; see the [data types reference](/oss/v0-41-0/sql/data-types) for the supported element types and other column types. ### Common SQL operations Several tasks are available through both interfaces, but the methods and SQL statements do not have identical coverage. SDK support also differs by language. These SQL reference pages describe the supported statements: | Task | SQL reference | | - | - | | Create a table | [CREATE TABLE](/oss/v0-41-0/sql/ddl/table) | | Insert or change rows | [INSERT](/oss/v0-41-0/sql/dml/insert), [UPDATE](/oss/v0-41-0/sql/dml/update), [DELETE](/oss/v0-41-0/sql/dml/delete) | | Build an index | [CREATE INDEX](/oss/v0-41-0/sql/ddl/index) | | Join and aggregate data | [SELECT](/oss/v0-41-0/sql/dql/select) | | Save a query as a view | [CREATE VIEW](/oss/v0-41-0/sql/ddl/view) | [Computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) store SQL expressions whose values are populated by a refresh. They are separate from registered Python Functions. See the computed-column and [materialized-view](/oss/v0-41-0/management/materialized-view) guides for their SDK and SQL operations and Enterprise setup requirements. ## Access LanceDB with SQL There are three ways to run SQL against LanceDB Enterprise, all against the same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) endpoint, returning results as Arrow record batches: 1. **`db.execute_query()`** on the Python SDK's Enterprise connection, shown below, or **`Connection::execute_query_async()`** on the Rust SDK's. These are LanceDB's native SQL execution methods, and we recommend them for the best performance -- see [Adaptive query execution](#adaptive). 2. **An Arrow Flight SQL client.** Use this from TypeScript, whose LanceDB SDK does not expose a SQL execution method, or from any tool with its own Flight SQL integration. A LanceDB-specific SDK is not required to submit SQL. 3. **The LanceDB CLI.** Open an interactive SQL shell, or run a statement or file, directly from the command line with no code at all. The [SQL reference](/oss/v0-41-0/sql#connecting) shows a query from Python. See [SDKs](/oss/v0-41-0/basics/sdk) for the LanceDB language clients. ### Adaptive query execution A standard Flight SQL client calls `GetFlightInfo` to plan a query and then `DoGet` to fetch rows -- two round trips every time, even when the server could stream results back immediately. `execute_query()` skips that extra round trip when it can. It calls `DoGet` directly for a query with no parameters, or `DoExchange` when [binding parameters](#parameters), and sends a `lancedb-sql-protocol: adaptive-v1` header. The server decides per query whether to stream results on that same call or defer execution and return a poll ticket; when it defers, `execute_query()` follows up with `PollFlightInfo` automatically, with no extra code on your side. A generic Flight SQL client does not send that header, so it always takes the slower `GetFlightInfo` path. ### Connection settings Get the following values from your Enterprise administrator: * Database URI, such as `db://your-database`. * API key and region. * API endpoint for `host_override`. * Flight SQL endpoint for `sql_host_override`, including its scheme and port. The Flight SQL endpoint must be enabled and reachable from your client. Pass it explicitly as `sql_host_override` in Python, as in the example below. The API and SQL endpoints may use different hosts or ports. See [Connect to Enterprise](/oss/v0-41-0/basics/catalog#enterprise) for other connection options. SQL runs in Enterprise. Connections to a local directory or an object-storage bucket use LanceDB Embedded and cannot execute SQL statements. Use SDK table operations to query those tables. ## Run a query in Python Install the SDK with `pip install lancedb`. Replace the connection placeholders with your Enterprise settings, including the region and both endpoint URLs. This example reads an existing `frames` table, with a `video_id` and a `caption` column describing each frame. Change the query to match your table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect( "db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-api-endpoint", sql_host_override="https://your-sql-endpoint:443", ) reader = db.execute_query("SELECT frame_id, video_id, caption FROM frames LIMIT 10") table = reader.read_all() print(table.to_pylist()) ``` In application code, load credentials from environment variables or a secrets manager. The [connection guide](/oss/v0-41-0/basics/catalog#enterprise) shows that setup. `execute_query()` returns a blocking Arrow reader; see [Adaptive query execution](#adaptive) for how it starts streaming. The example above uses `read_all()` to collect the small result in memory. For larger results, or to track and cancel a running query, see [Read and manage results](#results). To submit a query and check its status separately, use `execute_query_async()`. ## Parameters in SQL queries Pass a `parameters` argument to bind values into a query, instead of formatting them into the SQL string: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np reader = db.execute_query( "SELECT id FROM docs ORDER BY distance(vector, $1) LIMIT $2", parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) ``` Values travel as Arrow, not interpolated SQL text, so a vector binds as a fixed-size list with no manual formatting and no injection risk. Reference a parameter with `$1`, `$2`, ... for positional binding, or `$name` for named binding: * A list or tuple binds positionally, in order, to `$1`, `$2`, ... * A dict binds by key to `$name`. * A one-row `pyarrow.RecordBatch` or `Table` binds its columns, by name and by position. * A 1-D NumPy or Arrow array becomes a single fixed-size-list value -- use this form for a vector argument, as shown above. > [!NOTE] > > `parameters` is a LanceDB-specific mechanism, separate from the Flight SQL > protocol's `PREPARE`/bind step, which a deployment does not implement; see > [Prepared statements](#prepared-statements) below. Bind values with > `parameters` from the Python SDK; a generic Flight SQL client has no > equivalent. ## Prepared statements A Flight SQL client can prepare a statement before it runs it. A deployment accepts that, but it keeps no plan between runs and does not accept the parameter values described above at this protocol layer. > [!WARNING] > > There is no SQL `PREPARE` / `EXECUTE` here. Preparation is part of the > **Arrow Flight SQL protocol**, so you reach it through your client rather than > by sending a statement. A script containing `PREPARE name AS SELECT ...` will > not run. A Flight SQL client takes these steps, whatever it calls them: 1. **Prepare:** send the SQL and get back a handle and the result schema. The statement is parsed and planned at this point, so a syntax or name error surfaces here rather than at execution. 2. **Execute:** run the handle and read the result. The deployment plans the statement again each time it runs, so reusing a handle does not save planning time. 3. **Close:** release the handle. A client that binds values to placeholders such as `$1` and `$2` at this protocol layer gets a "not implemented" error when it executes the statement. Use `parameters` [above](#parameters) instead; do not put untrusted input directly into prepared statement text, since quoting it does not protect the statement the way binding a parameter would. Prepare a statement when your client requires it, or to get a statement's result schema and catch syntax and name errors without running it. Preparing does not make a repeated statement faster. To give a reusable query a name, create a [view](/oss/v0-41-0/management/view). To store its result for later queries, create a [materialized view](/oss/v0-41-0/management/materialized-view). ## Read and manage results * **Collect the results** when you want a list, Arrow table or DataFrame that fits in memory. Use a result limit and select only the columns you need. * **Read batches** when you want to process a large result incrementally. Reading batches avoids loading the entire result into application memory. It does not guarantee that the query can return its first batch immediately. ### Asynchronous clients An async client lets your application do other work while a request is waiting. That is separate from whether you collect results or read them in batches. Python offers synchronous and asynchronous clients; TypeScript uses async APIs. Check the SDK reference for the methods available in your client. ### Query handles and background jobs An Enterprise SQL query handle lets you inspect query execution and request cancellation. Background operations such as index builds return a [job](/oss/v0-41-0/basics/jobs) handle instead. Use the API for the returned handle to check status and retrieve results. ## Query plans Use query plans to understand how LanceDB reads data, applies filters and uses indexes. `explain_plan()` shows the planned operations. `analyze_plan()` runs the query and adds measurements, including execution time and rows processed. ### Inspect a plan or measure execution | Operation | Python / Rust | TypeScript | | :- | :- | :- | | Inspect the plan without executing the query | `explain_plan()` | `explainPlan()` | | Execute the query and report runtime measurements | `analyze_plan()` | `analyzePlan()` | Use the first to inspect query structure and the second to investigate work actually performed. Operator names and available measurements can differ between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/oss/v0-41-0/sql/dql/explain). > [accordion] Explain and analyze a query in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > query = table.search([1.0, 0.0]).select(["id", "text", "_distance"]).limit(2) > print("Plan:", query.explain_plan()) > print("Measured execution:", query.analyze_plan()) > rows = query.to_list() > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const query = table > .vectorSearch([1.0, 0.0]) > .select(["id", "text", "_distance"]) > .limit(2); > console.log("Plan:", await query.explainPlan()); > console.log("Measured execution:", await query.analyzePlan()); > const rows = await query.toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > println!("Plan: {}", query.explain_plan(false).await?); > println!("Measured execution: {}", query.analyze_plan().await?); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > This tiny table demonstrates the API, not a performance benchmark. The plan > uses a scan because the example has no vector index. The following larger > example illustrates how to read scans, filters and index operations. ### Read scans, filters and result retrieval The recorded example below uses 1.2 million rows sampled from the [Wikipedia dataset](https://huggingface.co/datasets/wikimedia/wikipedia). The counts describe that run. The table initially has no indexes, so the plan shows a scan. This Enterprise plan includes `RemoteTake` and hides storage paths as `uri=***`. A local plan shows the dataset path instead, and fetches the result rows with Lance's `Take` or, depending on the library version, a second `LanceRead` whose `source` is `stream(_rowid)`. Let's examine a vector search query that: * Filters rows where `identifier` is between 0 and 1,000,000 * Returns the top 100 matches * Projects specific columns: `chunk_index`, `title`, and `identifier` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # explain_plan query_explain_plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .explain_plan(True) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // explain_plan const explainPlan = await table .search(queryEmbed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .explainPlan(true); ``` #### Execution Plan Components > [accordion] Read the recorded vector plan operator by operator > > The execution plan reveals the sequence of operations performed to execute your query. Let's examine each component: > > ``` > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" > CoalesceBatchesExec: target_batch_size=1024 > GlobalLimitExec: skip=0, fetch=100 > FilterExec: _distance@3 IS NOT NULL > SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false] > KNNVectorDistance: metric=l2 > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 > LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false > ``` > > ##### 1. Base Layer (LanceScan) > > * Initial data scan loading only specified columns to minimize I/O > * Unordered scan enabling parallel processing > > ``` > LanceScan: > - projection=[vector, identifier] > - row_id=true, row_addr=false, ordered=false > ``` > > ##### 2. First Filter > > * Apply requested filter on `identifier` column > * Reduces the number of vectors that need KNN computation > > ``` > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 > ``` > > ##### 3. Vector Search > > * Computes squared L2 distances between query vector and all vectors that passed the filter > > ``` > KNNVectorDistance: metric=l2 > ``` > > ##### 4. Results Processing > > * Filters out null distance results > * Sorts by distance and takes top 100 results > * Coalesces output into batches targeting 1,024 rows in this plan > > ``` > SortExec: TopK(fetch=100) > - expr=[_distance@3 ASC NULLS LAST] > - preserve_partitioning=[false] > FilterExec: _distance@3 IS NOT NULL > GlobalLimitExec: skip=0, fetch=100 > CoalesceBatchesExec: target_batch_size=1024 > ``` > > ##### 5. Data Retrieval > > * `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version > * Handles efficient data retrieval from remote storage locations > * Fetches specific rows and columns needed for the final output > * Optimizes network bandwidth by only retrieving required data > > ``` > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" > ``` > > ##### 6. Final Output > > * Returns only requested columns and maintains column ordering > > ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] > ``` > > This plan demonstrates a basic search without index optimizations: it performs a full scan and filter before vector search. ### Non-vector queries Query plans also cover filters and full-text search. Python can show both sub-plans of a hybrid query. Check where a filter runs and how many rows flow through each operator; a separate `FilterExec` does not by itself establish that the plan is inefficient or that an index is missing. #### FTS queries ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} plan = ( table.search("puppy", query_type="fts") .where("category = 'animals'", prefilter=True) .limit(10) .explain_plan(True) ) print(plan) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const plan = await table .query() .fullTextSearch("puppy") .where("category = 'animals'") .limit(10) .explainPlan(true); ``` Look for the text-index operation and any scan of unindexed rows. A scan can be needed to include records written after the index was built. Use index coverage and execution measurements to determine whether that extra work matters. Check filter placement separately from text-index use. #### Hybrid queries For hybrid queries, `explain_plan` returns the reranker label followed by the vector and FTS sub-plans, indented for readability: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} plan = ( table.search("flower moon", query_type="hybrid") .where("category = 'film'", prefilter=True) .limit(10) .explain_plan(True) ) print(plan) # RRFReranker(...) # <vector sub-plan> # <FTS sub-plan> ``` `analyze_plan` executes both sub-queries and labels them `Vector Search Plan:` and `FTS Search Plan:`. Compare their filter placement and execution measurements. `analyze_plan` executes the query and returns the physical plan annotated with runtime metrics such as elapsed time, rows produced, bytes read and index comparisons. Where [`explain_plan`](#inspect-a-query-plan) tells you what a query intends to do, analysis shows the work performed. > [!NOTE] > > The SQL equivalent is [`EXPLAIN ANALYZE`](/oss/v0-41-0/sql/dql/explain). ### Read execution measurements Executes the query and provides detailed runtime metrics, including: * Operation duration (`_elapsed_compute_`) * Data processing statistics (`_output_rows_`, `_bytes_read_`) * Index effectiveness (`_index_comparisons_`, `_indices_loaded_`) * Resource utilization (`_iops_`, `_requests_`) ### Measure the example query Let's use `analyze_plan` to run the query and analyze the query performance, which will help us identify potential bottlenecks: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # analyze_plan query_analyze_plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .analyze_plan() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // analyze_plan const analyzePlan = await table .search(queryEmbed) .where("identifier > 0 AND identifier < 1000000") .select(["chunk_index", "title", "identifier"]) .limit(100) .analyzePlan(); ``` #### Performance Metrics Analysis > [accordion] Inspect the recorded execution measurements > > ``` > ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance], metrics=[output_rows=100, elapsed_compute=1.424µs] > RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title", metrics=[output_rows=100, elapsed_compute=175.53097ms, output_batches=1, remote_takes=100] > CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=100, elapsed_compute=2.748µs] > GlobalLimitExec: skip=0, fetch=100, metrics=[output_rows=100, elapsed_compute=1.819µs] > FilterExec: _distance@3 IS NOT NULL, metrics=[output_rows=100, elapsed_compute=10.275µs] > SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false], metrics=[output_rows=100, elapsed_compute=39.259451ms, row_replacements=546] > KNNVectorDistance: metric=l2, metrics=[output_rows=1099508, elapsed_compute=56.783526ms, output_batches=1076] > FilterExec: identifier@1 > 0 AND identifier@1 < 1000000, metrics=[output_rows=1099508, elapsed_compute=17.136819ms] > LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1200000, elapsed_compute=21.348178ms, bytes_read=1852931072, iops=78, requests=78] > ``` > > ##### 1. Data Loading (LanceScan) > > * Scanned 1,200,000 rows from the LanceDB table > * Read 1.86GB of data in 78 I/O operations > * Only loaded necessary columns (`vector` and `identifier`) > * Unordered scan for parallel processing > > ##### 2. Filtering and Search > > * Applied prefilter condition (`identifier > 0 AND identifier < 1000000`) > * Reduced dataset from 1.2M to 1,099,508 rows > * KNN search used L2 (Euclidean) distance metric > * Vector comparisons processed in 1076 batches > > ##### 3. Results Processing > > * KNN results sorted by distance (TopK with fetch=100) > * Null distances filtered out > * Batches coalesced to target size of 1024 rows > * Additional columns fetched for final results > * Remote take operation for 100 results > * Final projection of required columns #### Distributed metrics on LanceDB Enterprise Enterprise When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers: | Mode | What it shows | When to use it | | :- | :- | :- | | `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. | | `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. | | `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. | Python exposes this option through `distributed_metrics`. In TypeScript, pass the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python queries on LanceDB Embedded ignore the distributed mode and return single-node measurements. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Show a per-worker breakdown for a query on LanceDB Enterprise plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") .limit(100) .analyze_plan(distributed_metrics="per_worker") ) print(plan) ``` > [!NOTE] > > Use `per_worker` or `full` sparingly; the plan output grows with the size of your worker pool. Stick with the default `aggregate` mode for routine tuning. #### Identify expensive operations * The query computes distances for 1,099,508 vectors; inspect timings to assess its contribution to latency * The scan reads 1.86 GB in this recorded run * Full table scan due to lack of indices * Compare this scan with an indexed plan using the same query ### Compare the query after adding indexes > [accordion] Compare the recorded indexed and unindexed plans > > The recorded query after adding vector and scalar indexes produced this plan: > > ``` > ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] > RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" > CoalesceBatchesExec: target_batch_size=1024 > GlobalLimitExec: skip=0, fetch=100 > SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] > ANNSubIndex: name=vector_idx, k=100, deltas=1 > ANNIvfPartition: uuid=83916fd5-fc45-4977-bad9-1f0737539bb9, nprobes=20, deltas=1 > ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) > ``` > > #### Optimized Plan Analysis > > ##### 1. Scalar Index Query > > ``` > ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) > metrics=[ > output_rows=2 > index_comparisons=2,301,824 > indices_loaded=2 > output_batches=1 > parts_loaded=562 > elapsed_compute=86.979354ms > ] > ``` > > * Range filter using scalar index > * Only 2 index files and 562 scalar index parts loaded > * 2.3M index comparisons for matches > > ##### 2. Vector Search > > ``` > ANNSubIndex: name=vector_idx, k=100, deltas=1 > metrics=[ > output_rows=2,000 > index_comparisons=25,893 > indices_loaded=0 > output_batches=20 > parts_loaded=20 > elapsed_compute=111.849043ms > ] > ``` > > * IVF index with 20 probes > * Only 20 index parts loaded > * 25,893 vector comparisons > * 2,000 matching vectors > > ##### 3. Results Processing > > ``` > SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] > GlobalLimitExec: skip=0, fetch=100 > CoalesceBatchesExec: target_batch_size=1024 > ``` > > * Sorts by distance > * Limits to top 100 results > * Batches into groups of 1024 > > ##### 4. Data Fetching > > ``` > RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" > metrics=[output_rows=100, elapsed_compute=113.491859ms, output_batches=1, remote_takes=100] > ``` > > * Single output batch > * One remote take per row > > ##### 5. Final Projection > > ``` > ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] > ``` > > * Returns specified columns: chunk_index, title, identifier, and distance > > #### Performance Improvements > > ##### 1. Initial Data Access > > ``` > ScalarIndexQuery metrics: > - indices_loaded=2 > - parts_loaded=562 > - output_batches=1 > ``` > > * Before: Full table scan of 1.2M rows, 1.86GB data > * After: Only 2 indices and 562 scalar index parts loaded > * Benefit: Eliminated table scans for prefilter > > ##### 2. Vector Search Efficiency > > ``` > ANNSubIndex: > - index_comparisons=25,893 > - indices_loaded=0 > - parts_loaded=20 > - output_batches=20 > ``` > > * Before: L2 calculations on 1,099,508 vectors > * After: > * About 97.6% fewer vector comparisons (25,893 versus 1,099,508) > * Decreased output batches from 1,076 to 20 > > ##### 3. Data Retrieval Optimization > > ``` > RemoteTake: > - remote_takes=100 > - output_batches=1 > ``` > > * RemoteTake operation remains consistent ### Choose a change to measure #### 1. Index Implementation ##### When to Create Indices * Columns used in WHERE clauses * Vector columns for similarity searches * Join columns used in `merge_insert` ##### Index Type Selection | Data Type | Recommended Index | Use Case | | - | - | - | | Vector | IVF_PQ/IVF_HNSW_SQ/IVF_HNSW_FLAT | Approximate nearest neighbor search | | Scalar | B-Tree | Equality and range filters | | Categorical | Bitmap | Multi-value filters and set operations | | `List` | Label_list | Multi-label classification and filtering | > [card] Index Coverage Monitoring > > Use `table.index_stats()` to monitor index coverage. > Unindexed rows can add scan work. Use their count alongside query measurements > to decide when index maintenance is needed. #### 2. Query Plan Optimization ##### Common Patterns and Fixes | Plan Pattern | Optimization | | - | - | | Scan with high bytes read or I/O count | Check index coverage and whether the query can use an index | | | Use `select()` to limit returned columns | | | Check whether the dataset has been compacted | | Multiple filters | Check their placement and row counts; compare the plan after changing the query | > [!NOTE] > > Regularly analyze your query plans to identify and address performance > bottlenecks. The `analyze_plan` output provides detailed metrics to guide > optimization efforts. #### 3. Getting Started with Optimization Keep the query, data and result limit fixed while changing one factor. Compare rows processed, bytes read, timings and returned results. For ANN changes, measure recall too: doing less work is useful only if retrieval quality meets your application's needs. See [vector indexes](/oss/v0-41-0/indexing/vector-index) and [scalar indexes](/oss/v0-41-0/indexing/scalar-index) for index choices. ## Vector and full-text search SQL vector search support depends on the Enterprise server version and query form. Versions that support `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan can plan indexed or flat vector search. Check that your server version supports this form, then use [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain) to inspect the query plan. The [SDK vector search API](/oss/v0-41-0/search/vector-search) is also available in LanceDB Enterprise and LanceDB Embedded. Use it when you prefer the SDK query builder or need to search embedded tables. For full-text search in SQL, use the [`fts()`](/oss/v0-41-0/sql/dql/fts) table function or the [`contains_tokens`](/oss/v0-41-0/sql/dql/contains-tokens) predicate. ## SQL syntax and API references The [SQL reference](/oss/v0-41-0/sql) documents statement syntax, supported expressions, and data types. For SDK methods and their arguments, use the [Python](https://lancedb.github.io/lancedb/python/python/), [TypeScript](https://lancedb.github.io/lancedb/js/), or [Rust](https://docs.rs/lancedb/latest/lancedb/index.html) API reference. > [card] [SQL Reference](/oss/v0-41-0/sql) > > Statement syntax, expressions, and data types for LanceDB SQL. ## Next steps > [card] [Quickstart](/oss/v0-41-0/quickstart) > > Run a complete create, insert and search example. > [card] [Search](/oss/v0-41-0/search) > > Choose vector, full-text or hybrid retrieval. > [card] [Filtering](/oss/v0-41-0/search/filtering) > > Narrow results with predicates. > [card] [SDKs](/oss/v0-41-0/basics/sdk) > > Compare language clients and find their API references. # Profiling a dataset Source: https://docs.lancedb.com/oss/v0-41-0/curation/aggregate Measure coverage, missing values and class balance before selecting a dataset. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL aggregates to summarize a dataset: count records, find missing values, and compare groups. These summaries help you understand the data before selecting records for search, evaluation or training. ## Example data Connect with an [Enterprise SQL client](/oss/v0-41-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Count records and missing values Use `count(*)` to count rows and `count(column)` to count non-null values. Add `DISTINCT` to count unique values: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*) AS records, count(DISTINCT doc_id) AS documents, count(caption) AS captioned, count(*) FILTER (WHERE caption IS NULL) AS missing_caption FROM curation_documents; ``` The example returns **6 records, 4 documents, 4 populated captions and 2 missing captions**. `count(column)` excludes null values; it does not check whether a string is empty or whether a value is useful for the task. ## Group records by label Use `GROUP BY` to calculate a summary for each label: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT label, count(*) AS documents FROM curation_labels GROUP BY label ORDER BY documents DESC, label; ``` There are **2 cats and 1 dog** in the label table. Document 40 is absent, so this query does not measure labeling coverage across all source documents. Use a [left join](/oss/v0-41-0/curation/join#join-type) to find documents without labels. Decide whether the distribution matches your intended use. A uniform random sample tends to preserve the source distribution; it does not balance classes. To cap the number selected per label, use [ranking within a group](/oss/v0-41-0/curation/windowing#per-group). ## Count records that match a condition ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT source, count(*) AS records, count(*) FILTER (WHERE score >= 0.9) AS high_score, count(*) FILTER (WHERE caption IS NULL) AS missing_caption FROM curation_documents GROUP BY source ORDER BY source; ``` `FILTER` applies a condition to one aggregate. Here, `books` has 2 records, 1 high-score record and no missing captions. `web` has 4 records, 1 high-score record and 2 missing captions. Counts are per record, so repeated document IDs still contribute more than once. ## Group numeric values into ranges Use `count(DISTINCT column)` for the number of distinct non-null values. For numeric fields, group by a range or summarize their distribution. For example, this query counts records in score buckets of width 0.1: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT floor(score * 10) / 10 AS score_bucket, count(*) AS records FROM curation_documents GROUP BY score_bucket ORDER BY score_bucket; ``` For time-based data, group by the time interval relevant to the task. The [aggregation reference](/oss/v0-41-0/sql/dql/aggregation) and [scalar function reference](/oss/v0-41-0/sql/dql/scalar-functions) cover additional summaries, including approximate counts and percentiles. Use an approximate aggregate when an estimate is sufficient; use an exact count when the result must be precise. ## Aggregate over a Function's result An aggregate can summarize a [Function](/oss/v0-41-0/curation/create-function)'s output the same as any other expression -- the engine computes the Function once per row, then aggregates. Register `caption_quality` the same way any other curation Function is registered: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT source, avg(caption_quality(caption)) AS avg_quality FROM curation_documents WHERE caption IS NOT NULL GROUP BY source ORDER BY source; ``` Filtering out null captions first avoids calling the Function on rows with nothing to score. ## Profile a sample A [sample](/oss/v0-41-0/curation/statistical-sampling) can help you explore a large dataset before a full scan. Report the sample size and method alongside the result. A sample can miss rare classes, and fragment sampling can reflect the order in which records were written. Before accepting a curated dataset, check its required fields and key constraints directly rather than inferring them from a small sample. ## Continue curating Use these measurements to choose a [sample](/oss/v0-41-0/curation/statistical-sampling), [attach missing metadata](/oss/v0-41-0/curation/join), or [select one record per document](/oss/v0-41-0/curation/windowing). See [Aggregation](/oss/v0-41-0/sql/dql/aggregation) for complete SQL syntax. # Blob Late Materialization Source: https://docs.lancedb.com/oss/v0-41-0/curation/blob-late-materialization Deferring a wide BlobV2 or vector column's read until after a join has already narrowed down which rows survive. **Applies to:** Embedded ❌, Enterprise ✅ A join that includes a wide column -- a [BlobV2](/oss/v0-41-0/management/table#managed-blobs) or an embedding -- can multiply that column's read far past the result's own row count: a naive plan reads the wide column for every candidate row the join considers, then throws most of that work away once the join condition filters non-matches. Blob late materialization is the optimizer rewrite that avoids this, deferring the wide read until after the join has already settled which rows survive. ## The two plan shapes ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph Naive["Naive: wide column read before filtering"] direction TB N1["Scan wide column<br/>for every row"] --> N2["Join"] N2 --> N3["Rows that didn't match<br/>are discarded --<br/>their wide read was wasted"] end subgraph Deferred["Late materialization: wide column read after filtering"] direction TB D1["Scan only the join key<br/>(+ early columns)"] --> D2["Join on the key"] D2 --> D3["RemoteTake:<br/>fetch the wide column,<br/>once per surviving row"] end classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class D3 accent ``` In the naive plan, the wide column is read once per **candidate** row -- every row either side of the join could possibly produce -- before the join has thrown any of them away. In the rewritten plan, the join operates on a narrowed schema (the key, any small "early" columns, and a row id), and a `RemoteTake` node fetches the wide column afterward, once per row that actually **survived** the join. ## Eligibility This is a physical-plan optimizer rewrite, not something you opt into with special syntax -- the optimizer decides whether a given join qualifies. It applies to a plain inner equi-join (a single `ON left_col = right_col` condition, no additional filter fused into the join, no `LIMIT` fused into it) where one side -- and only one side -- bottoms out at a single, otherwise-unfiltered table scan: no existing row filter, scan range, fragment subset, deleted-row handling, or [RTE write](/oss/v0-41-0/ingestion/realtime-write) tier. If both sides would otherwise qualify, the side with a BlobV2 column is preferred over the other; if neither or both sides have one, the rewrite declines rather than guessing which to narrow. Which columns actually get deferred differs by which side of the join is narrowed: * **The side that builds the join's hash table:** every column beyond the join key is deferred, regardless of size. The hash table holds everything this side reads for the lifetime of the join, so even a modestly-sized column adds up across every row the join holds in memory at once. * **The side that probes the hash table:** only columns wide enough to cross a size heuristic are deferred; small columns stay in the initial scan, since reading them eagerly doesn't carry the same memory risk. A BlobV2 column's **descriptor** (small, pointer-like) is early and stays in the scan either way -- only the raw **bytes** of the blob are late and deferred, so narrowing doesn't lose track of which rows have a blob at all, just postpones reading its payload. ## Where the deferred read actually happens The take itself runs through the same replica-group-aware routing as any other distributed table read (see [Horizontal Scaling](/oss/v0-41-0/enterprise/horizontal-scaling)) -- it is not shipped back to the query node to be joined there directly. Routing is resolved once per query and reused across every batch the take processes, rather than re-resolved per batch, which is what keeps repeated takes in the same query hitting a cache that's already warm instead of bouncing between replica groups. Where the executing node already holds the needed data, the take can also resolve natively without a separate network round trip at all. ## Confirming it happened A join written this way is a **candidate** for the rewrite, not a guarantee -- confirm it per query with [`EXPLAIN`](/oss/v0-41-0/basics/sql#query-plans). A `Take` or `RemoteTake` node by itself isn't proof either way -- it's the general operator that fetches columns for selected rows from remote storage, and shows up in an ordinary, join-free query just as it does here (see the [recorded vector-search plan](/oss/v0-41-0/basics/sql#5-data-retrieval)); the rewrite itself inserts a plain `Take`, which only a later, separate pass turns into `RemoteTake`. What confirms the deferral specifically is a `Take`/`RemoteTake` node sitting above a `HashJoinExec`, fetching a column set that includes `__join_late_materialization_key` -- that key column only exists when this rewrite fired. Join on a narrow, selective key and project the wide columns only in the final select list, rather than alongside the join condition: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT s.frame_id, f.image, f.embedding FROM selected AS s JOIN frames AS f ON f.frame_id = s.frame_id ``` `selected` is narrow -- just the frame IDs an earlier curation step already kept. `frames` is wide -- a BlobV2 `image` and a vector `embedding` alongside its key. Neither a passing query nor an `EXPLAIN` that omits `RemoteTake` tells you how much I/O a plan did or did not save on its own -- use [`EXPLAIN ANALYZE`](/oss/v0-41-0/sql/dql/explain) for the plan's actual row and byte counts, since plain `EXPLAIN` shows the planned shape without executing the query. ## What to read next > [card] [Joining datasets](/oss/v0-41-0/curation/join) > > Join types, duplicate keys, and calling a Function across a join. > [card] [Joins](/oss/v0-41-0/sql/dql/join) > > Join syntax and semantics in the SQL reference. > [card] [Query plans](/oss/v0-41-0/basics/sql#query-plans) > > Reading `EXPLAIN` output in general. > [card] [Horizontal Scaling](/oss/v0-41-0/enterprise/horizontal-scaling) > > The replica-group routing a RemoteTake's read goes through. # Scope curation to what changed Source: https://docs.lancedb.com/oss/v0-41-0/curation/changes Process only the rows added since your last curation run, instead of rescanning the whole table. **Applies to:** Embedded ❌, Enterprise ✅ A curation task you run repeatedly -- chunking, deduplication, profiling -- does not need to rescan rows it already processed. `CHANGES` reads only the rows appended to a table since an earlier [version](/oss/v0-41-0/management/table#versioning), so a recurring job can scope itself to what is new. ## Example data `curation_batches` gets a batch of new documents appended periodically, with no updates or deletes between appends: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR); INSERT INTO curation_batches VALUES (1, 'web', 'A cat on a chair'), (2, 'web', 'A dog in a field'); -- note the version after this insert, for example 5 INSERT INTO curation_batches VALUES (3, 'books', 'A bird in a tree'), (4, 'books', 'A cat by a window'); -- the table is now at a later version, for example 7 ``` ## Read only what is new `CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)` reads the rows appended after version 5 -- documents 3 and 4 -- without rescanning 1 and 2: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` Record the table's version after each curation run, then start the next run's `CHANGES` from it. See [Versioning](/oss/v0-41-0/management/table#versioning) for the APIs that read a table's current version. ## Chain it into a curation task `CHANGES` is a relation, like any other table reference, so it composes with the rest of this page: chunk, dedupe, or join only the new rows, instead of the whole table. Materializing the result keeps a running, append-only table of work already done: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSERT INTO curated_batches SELECT doc_id, source, text FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) WHERE source = 'books' ``` A [chunker Function](/oss/v0-41-0/curation/chunking) or a [`dedupe`](/oss/v0-41-0/sql/dql/dedupe) call works the same way: put the `CHANGES` relation where the source table would otherwise go, and only the new rows flow through it. ## Strictly append-only The clause is named for what it requires, not just what it does. If anything other than a pure append happened to the table between the starting version and the current one -- an update, a delete, a merge -- the query is refused rather than silently returning an incomplete or wrong result: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- refused if any row in curation_batches was updated or deleted after version 5 SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` When that happens, either re-run from a later starting version that is itself after the non-append write, or read the table in full instead of incrementally for that run. See [Changes since a version](/oss/v0-41-0/sql/dql/changes#strict) for the complete set of refused forms. ## What to read next > [card] [CHANGES](/oss/v0-41-0/sql/dql/changes) > > The full SQL syntax, placement rules, and unsupported forms. > [card] [Table](/oss/v0-41-0/management/table#versioning) > > How table versions work, and how to find one to start from. # Chunk records into multiple rows Source: https://docs.lancedb.com/oss/v0-41-0/curation/chunking Expand one source row into many derived rows -- documents into passages, videos into clips, images into tiles. **Applies to:** Embedded ❌, Enterprise ✅ Every other curation task on this page keeps the row count the same or smaller: profiling, sampling, joining, deduplicating. Chunking goes the other way -- one source row becomes many derived rows, each carrying its parent's columns along with it. Use it to split a document into passages for embedding, a video into clips, or an image into tiles. ## Define a chunking Function A Function that returns a `list` produces more than one value per input row. A chunker is a Function whose output is a list -- of structs, of strings, of anything -- registered like any other Function. See [Create a Function](/oss/v0-41-0/curation/create-function) for CPU, GPU and remote-service Functions, and scalar versus batch calling, if you have not registered one before. A function that splits text into fixed-size passages turns a `documents` table into one row per passage. Registration details, environment and dependency declarations, and how a version stays immutable once rows are filled from it, are the same for a chunker as for any other Function -- register it from Python, or the same function from SQL with [`CREATE FUNCTION`](/oss/v0-41-0/sql/ddl/function#create): **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is a method of..." (long text) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb.functions import function @function( output_schema=pa.list_( pa.struct([ pa.field("chunk_index", pa.int64(), nullable=False), pa.field("chunk_text", pa.utf8(), nullable=False), ]) ), ) def split_into_passages(text: str) -> list[dict]: size = 200 return [ {"chunk_index": i, "chunk_text": text[i : i + size]} for i in range(0, len(text), size) ] version = db.create_function_async(split_into_passages).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION split_into_passages(text utf8) RETURNS list<struct<chunk_index: int64, chunk_text: utf8>> LANGUAGE python AS ' def split_into_passages(text): size = 200 return [ {"chunk_index": i, "chunk_text": text[i:i+size]} for i in range(0, len(text), size) ] ' ``` ## Explode it in a query Wrap the function call in `UNNEST` in the `SELECT` list, with an alias: it yields one row per element of the list the function returns, with every other selected column repeated. Reference the exploded struct's fields through that alias in a query over this one: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH exploded AS ( SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p FROM documents ) SELECT doc_id, title, p.chunk_index, p.chunk_text FROM exploded ``` A document with five 200-character passages becomes five output rows, each carrying `doc_id` and `title` from its parent. This is the fastest way to check a chunker before committing to a materialized view: run it over a few rows and inspect the output shape. ## Video into frames Chunking a blob column is the same shape, with the chunker producing timestamps rather than text spans, and a second Function pulling the actual frame for each one. `videos` holds raw clips in a [Blob v2](/oss/v0-41-0/management/table#managed-blobs) column, with each row's duration already known: **Source: `videos`** | video_id | video | duration_seconds | | - | - | - | | "clip-1" | (Blob v2 bytes) | 12.0 | A chunker that samples one timestamp per second needs no blob access at all \-- it only looks at `duration_seconds`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function( output_schema=pa.list_( pa.struct([ pa.field("frame_index", pa.int64(), nullable=False), pa.field("ts", pa.float64(), nullable=False), ]) ), ) def sample_frame_timestamps(duration_seconds: float) -> list[dict]: every = 1.0 # one frame per second count = int(duration_seconds // every) return [{"frame_index": i, "ts": i * every} for i in range(count)] version = db.create_function_async(sample_frame_timestamps).wait() ``` A second Function reads the blob -- incrementally, through a `BlobReader`, rather than loading the whole clip -- and returns one JPEG per call: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb import BlobReader @function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], input_schema=pa.schema([ lancedb.blob("video"), pa.field("ts", pa.float64(), nullable=False), ]), output_schema=lancedb.blob("jpeg", nullable=False), ) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # decode the frame at ts, encode as JPEG, return its bytes extract_version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) ``` Compose both in one query: explode `videos` into one row per sampled timestamp, then call `extract_frame` on each row to produce its image: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH sampled AS ( SELECT video_id, video, UNNEST(sample_frame_timestamps(duration_seconds)) AS f FROM videos ) SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg FROM sampled ``` A 12-second clip becomes 12 output rows, each with its own extracted JPEG. A Function in `FROM` position yields one row per list element the same way regardless of what the list holds; whether the second step produces a blob, a plain value, or another struct does not change the explosion. ## Persist it as a materialized view Wrap either query in [`CREATE MATERIALIZED VIEW`](/oss/v0-41-0/sql/ddl/materialized-view) to keep a real table that stays current as the source changes, instead of recomputing the explosion on every query: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW chunks AS WITH exploded AS ( SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p FROM documents ) SELECT doc_id, title, p.chunk_index, p.chunk_text FROM exploded ``` **Derived: `chunks`** (1:N expansion) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning is a method..." | | 1 | "Intro to AI" | 1 | "...of teaching computers..." | The view refreshes like any other materialized view: new source rows are chunked and inserted, deleted source rows drop their children, and an updated row's old children are replaced by freshly chunked ones on the next [refresh](/oss/v0-41-0/feature-engineering/refresh-column). A single `UNNEST(...)` -- whether unnesting a Function's list output directly, as above, or an existing list column -- is the only lateral expansion a materialized view can carry, and it can't be combined with `GROUP BY`, so keep aggregation or further curation in a second step over the chunked table. ## Chunk, then curate A freshly chunked table is a normal table: [dedupe](/oss/v0-41-0/curation/dedupe) it to collapse near-identical chunks, [sample](/oss/v0-41-0/curation/statistical-sampling) it for a quick look, or [profile it](/oss/v0-41-0/curation/aggregate) to check how many chunks each source row produced. Continue with [choosing a curation task](/oss/v0-41-0/curation#questions). # Cluster records by index partition Source: https://docs.lancedb.com/oss/v0-41-0/curation/clustering Group records by the partition an existing IVF vector index already assigns them to, without training a new clustering model. **Applies to:** Embedded ❌, Enterprise ✅ `ivf_partition` groups records by the partition a vector falls into, using the centroids of an IVF-family vector index you already built for search -- no separate clustering model to train or maintain. Use it as a `GROUP BY` key to aggregate per cluster, or to sample across clusters instead of across rows. ## Example data Connect with an [Enterprise connection](/oss/v0-41-0/basics/catalog#enterprise). > [accordion] Create the example table > > Use the same `curation_embeddings` fixture as [dedupe](/oss/v0-41-0/curation/dedupe#example-data) > \-- eight records, where rows 10 and 20 are near-identical, 30, 40 and 50 > form one looser cluster, and 60, 70 and 80 are each distinct and > increasingly far apart -- but build the index with more partitions. > Clustering wants partitions fine-grained enough to tell the two clusters > apart; deduplication only needs a distance threshold within one: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.create_index("embedding", config=IvfFlat(num_partitions=5, distance_type="l2")) > table.wait_for_index(["embedding_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > await table.createIndex("embedding", { > config: lancedb.Index.ivfFlat({ numPartitions: 5, distanceType: "l2" }), > }); > await table.waitForIndex(["embedding_idx"], 300); > ``` > > ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::time::Duration; > > use lancedb::index::vector::IvfFlatIndexBuilder; > use lancedb::index::Index; > use lancedb::DistanceType; > > table > .create_index( > &["embedding"], > Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(5).distance_type(DistanceType::L2)), > ) > .execute() > .await?; > table.wait_for_index(&["embedding_idx"], Duration::from_secs(300)).await?; > ``` > > `ivf_partition` reads an existing index's trained centroids; it does not > train one. The column needs an up-to-date, single-segment IVF-family index > before the function runs, the same requirement [`dedupe`](/oss/v0-41-0/curation/dedupe#example-data) > has. ## Group records by partition `ivf_partition(column)` returns the partition each row's vector falls into. Rows closer to the same centroid than to any other land in the same partition, so the near-identical cat photos (10, 20) group together, the three dog photos (30, 40, 50) group together, and the three increasingly distant photos (60, 70, 80) are more likely to each keep their own partition: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids, count(*) AS n FROM curation_embeddings GROUP BY cluster ORDER BY cluster ``` The exact partition numbers depend on how the index's centroids were trained, but rows that are close together in embedding space consistently land in the same group. Aggregate anything per cluster this way -- `count(*)` for cluster sizes, `avg(score)` for a per-cluster quality signal, or `array_agg(id)` to collect candidate rows for a downstream pass. ## Sample across clusters instead of across rows Pass a selection mode to group by only a subset of the index's partitions, instead of all of them: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- The first 2 partitions, deterministically SELECT ivf_partition(embedding, 'first', 2) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster; -- 2 partitions chosen at random, reproducible via the seed SELECT ivf_partition(embedding, 'random', 2, 42) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster; ``` `'first'` takes the first `count` partitions and accepts no seed, since the result is already deterministic. `'random'` requires a seed, so the same call reproduces the same partitions. Either way, the result is a spatially-stratified sample across the embedding space: one that covers each selected region of the data, rather than a plain row sample that can easily pick many near-duplicate rows from a dense cluster and miss a sparse one entirely. ## Keep a clustering current with a materialized view Wrap a `GROUP BY ivf_partition(...)` query in a [materialized view](/oss/v0-41-0/management/materialized-view) so the grouping stays current as new records arrive: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW curation_embeddings_clustered AS SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids FROM curation_embeddings GROUP BY cluster ``` A refresh reassigns every row's partition from the index's current centroids, so retraining the index with [`replace=True`](/oss/v0-41-0/feature-engineering/add-computed-column) regroups the view on the next refresh. See [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) for manual and automatic refresh options. ## A typical use case: deduplication Near-duplicate records are close together in embedding space, so they consistently land in the same or a neighboring partition. Grouping by `ivf_partition` first, then comparing distances only within each group, finds near-duplicate candidates without a full pairwise scan across the whole table. This is exactly the approach [`dedupe` and `duplicate_pairs`](/oss/v0-41-0/curation/dedupe) use internally, packaged as a table function with a `distance_threshold` instead of a `GROUP BY` clause to write yourself. Reach for those directly for deduplication; use `ivf_partition` when the task is a different kind of per-cluster grouping or sampling, not deduplication specifically. ## Related guides > [card] [IVF_PARTITION](/oss/v0-41-0/sql/dql/ivf-partition) > > The full function signature: arguments, sampling modes, and positional syntax. > [card] [Deduplicate near-duplicates](/oss/v0-41-0/curation/dedupe) > > The packaged table function for the deduplication use case above. > [card] [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) > > Row-level and fragment-level sampling, without clustering. # Create a Function Source: https://docs.lancedb.com/oss/v0-41-0/curation/create-function Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/oss/v0-41-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Early access Some curation steps cannot be written as a SQL expression: an embedding model, an image decode, a call to an external service. A Function is a Python callable registered with the database, versioned, and then applied as a column or called in a query -- the code runs where the data is, not pulled into your process first. This page covers how to shape one; later curation tasks such as [Chunking](/oss/v0-41-0/curation/chunking) assume you have read it. The full registration, listing, refresh and drop lifecycle is covered on the [Function management reference](/oss/v0-41-0/management/function); the examples below focus on shaping a Function for common curation tasks. ## Scalar: once per row The plain form takes one row's values and returns one result. Types are inferred from the annotations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col, function @function(pip=["numpy==2.2.0"]) def score(value: float) -> float: return value * 2 version = db.create_function_async(score).wait() table.add_columns({"doubled": version(value=col("value"))}) ``` `pip` declares the worker's dependencies; they are part of the function's immutable version, so changing one produces a new version rather than altering rows a previous version already filled. ## Batch: once per call, many rows at a time A function is called once per batch instead of once per row when its parameters are annotated `pyarrow.Array`, or when it takes a single `pyarrow.RecordBatch` parameter to read more than one column together. The same doubling logic, vectorized over a whole batch at once: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pyarrow.compute as pc from lancedb import function @function( pip=["numpy==2.2.0"], batch_size=32, row_timeout_seconds=90, input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.float64(), ) def score_batch(value: pa.Array) -> pa.Array: return pc.multiply(value, 2) ``` Batching amortizes per-call overhead across many rows, which matters most once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. `batch_size` caps the number of input rows in each execution batch; actual batches may be smaller. `row_timeout_seconds` bounds each Python call: one row for scalar Functions or the entire batch for vectorized Functions. It does not include the instance's `__init__`. Both settings are part of the registered version. Enterprise 1.12.0 does not support a per-Function call-concurrency setting. Batch annotations such as `pa.Array` do not specify element types. Supply both `input_schema` and `output_schema`, as above. ## Stateful Functions: load once, call many times A `@function`-decorated **class** is the same callable with state. Each remote instance calls `__init__` once, calls `__call__` for every row or batch it processes, and calls `close()`, if defined, once when it retires: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import function @function class scale: def __init__(self, factor: float, offset: float = 0.0): self.factor = factor self.offset = offset def __call__(self, value: float) -> float: return value * self.factor + self.offset ``` Constructor parameters are **initialization fields**, bound once per binding rather than read per row -- mixed with per-row columns in the same call: `version(value=col("value"), factor=2.0)`. Load models, open clients, and build rate limiters in `__init__`; every batch the instance serves then reuses them, since an instance's state is shared across its own batches but never across other instances or workers. This is the pattern GPU inference and remote-API Functions both build on below. ## GPU: batch inference, loaded once `db.list_gpu_classes()` lists the GPU classes configured for the deployment. Each record reports the operator's hardware description and limits; it does not mean a GPU is currently free. Listing requires the System Usage permission. Pass a returned class name to `gpu_class` to fix that placement in the Function version. `gpu=True` remains required: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb import function gpu_class = next( gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G" ) @function( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), output_schema=pa.list_(pa.float32(), list_size=384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): import torch from sentence_transformers import SentenceTransformer device = "cuda" if torch.cuda.is_available() else "cpu" self.model = SentenceTransformer(model_name, device=device) def __call__(self, text: pa.Array) -> pa.Array: texts = [t or "" for t in text.to_pylist()] embeddings = self.model.encode(texts) return pa.array(embeddings.tolist(), type=pa.list_(pa.float32(), list_size=384)) version = db.create_function_async(embed_text).wait() table.add_columns({"embedding": version(text=col("caption"))}) ``` Older servers that do not implement `GET /v1/gpu/classes` raise `NotImplementedError`. Without `gpu_class`, the deployment's default GPU class is used. The class is immutable with the Function version; set a per-refresh class or aggregate GPU budget through [`refresh_column_async`](/oss/v0-41-0/feature-engineering/refresh-column#resources). The model loads once per worker instance, in `__init__`; `__call__` only encodes the batch it was handed. Registering the same logic as a plain function instead would reload the model on every single row. ## Calling a remote service A function that calls an external API needs a credential without putting it in the function's source. A Secret is a database-scoped named credential: `db.create_secret` stores the value once, and binding it at registration time puts it in the environment variable the function reads, without ever returning it from any API or recording it in the function's own definition. Combine it with the stateful form so the HTTP client -- and any rate limiter around it -- is built once, not reopened on every row. There is no built-in retry or per-row error-skip policy -- a function that calls a flaky service should handle timeouts and retries itself, inside `__call__`. See [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret#specify) for the full worked example, how the bound value actually reaches a running evaluation, and how that differs from rotating or revoking it later. ## Read and produce blobs A Function can bind a [Blob v2 column](/oss/v0-41-0/management/table#managed-blobs) and return another blob, including a blob nested inside a struct field, not only at the top level. In row mode, a top-level blob parameter arrives as Python `bytes`, or `None` for a nullable input, after the worker has read the payload. Return bytes and let the destination table store the Managed payload and descriptor. This section extracts a frame from a stored video and captions it, continuing as one example across chaining, persisting and incremental reads below. `videos` holds raw clips in a `video` Blob v2 column; `frames` names one timestamp per clip to extract, with a `selected` flag to skip some: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa videos = db.create_table("videos", schema=pa.schema([ pa.field("id", pa.utf8(), nullable=False), lancedb.blob("video", nullable=False), ])) frames = db.create_table("frames", [ {"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True}, {"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True}, ]) ``` ### Produce a blob Declare blob inputs and outputs explicitly. `extract_frame` reads one frame out of a video at a timestamp and returns it as a JPEG, without loading the whole clip first -- see [Read a blob incrementally](#incremental) below for how the `video: BlobReader` parameter does that: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta from lancedb import BlobReader, col from lancedb.functions import function @function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], input_schema=pa.schema([ lancedb.blob("video"), pa.field("ts", pa.float64(), nullable=False), ]), output_schema=lancedb.blob("jpeg", nullable=False), ) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # decode the frame at ts, encode as JPEG, return its bytes extract_frame_version = db.create_function_async(extract_frame).wait( timeout=timedelta(minutes=15) ) ``` An empty byte string is a filled result. A scalar output cannot be nullable, because a physical NULL marks an unfilled computed row. To return a nullable blob as a value, use a named-struct output schema with a nullable blob field; the struct itself records whether the result has been filled. Read a nested blob with `table.fetch_blobs("payload.image", hits)`. A list or large-list output may also contain Blob v2 elements; inputs and fixed-size lists do not support this layout. List-nested values are queryable as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their payloads. > [!WARNING] > > `output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2 > rather than plain Arrow `binary`. Returning `bytes` from a function whose > output type is inferred from a bare annotation, with no explicit > `lancedb.blob(...)` output schema, persists as ordinary `binary`: the column > still holds the right bytes, but it skips the Managed storage path, descriptor > reads, and `fetch_blobs`. Declare it explicitly on every function whose output > should be a blob, not just the first one in a chain. ### Chain a Function on its output A second Function can bind a blob another Function produced. Register `caption` the same way, consuming a blob instead of producing one: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(gpu=True, pip=["transformers==4.47.0"]) def caption(jpeg: bytes) -> str: ... # run a vision-language model over the JPEG, return one sentence caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15)) ``` Compose both in one SQL statement over a join, instead of applying each as its own column. The join supplies `video` and `ts` from two different tables, and `caption` reads `extract_frame`'s result as it is computed, before anything is written: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true ``` [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain) on a query like this shows `RemoteTake`: the blob is read once, where the worker runs, and never pulled into the query node first. ### Persist it as a column, or a materialized view Apply the same registered version with `add_columns` to persist its output as an ordinary table column, on a table that already has both of its inputs -- here, a single-clip table with its own `video` and `ts`, rather than the two tables the join above reads from: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} clips = db.create_table("clips", schema=pa.schema([ pa.field("frame_id", pa.int64(), nullable=False), lancedb.blob("video", nullable=False), pa.field("ts", pa.float64(), nullable=False), ])) clips.add_columns({"jpeg": extract_frame_version(video=col("video"), ts=col("ts"))}) result = clips.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15)) assert result.rows_failed == 0 hits = clips.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow() values = clips.fetch_blobs("jpeg", hits).to_pylist() ``` Or wrap the join and both Functions in a [materialized view](/oss/v0-41-0/sql/ddl/materialized-view) instead, so the extracted frame and its caption stay current as new videos and frames arrive. See [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for keeping either one fresh without calling refresh yourself. On deployments that support computed-column inputs, another Function can bind to `col("jpeg")` directly, the same as the SQL join above does through its own expression. Refresh the producer first, then the consumer. Once outputs are current, a later refresh fills appended rows. A filtered refresh preserves payload references for unselected Managed outputs. An unfiltered refresh can recompute a whole fragment when it cannot establish that the fragment's outputs are current. Function output blobs follow the same compaction and cleanup lifecycle as ingested Managed blobs. Retained versions continue to own their payloads; cleanup reclaims an object only after its retained references are gone. ### Read a blob incrementally Annotate a row Function parameter with `BlobReader` to read a Blob v2 input incrementally, the way `extract_frame` above does, instead of materializing the whole payload first. The signature selects the access mode without another registration option. A minimal example, reading only the first MP4 box type without loading the rest of the video: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import BlobReader, function @function def first_box_type(video: BlobReader) -> bytes: video.seek(4) return video.read(4) ``` The worker passes a seekable reader backed by the stored blob -- `video.seekable()` is `True`. `read(size)` reads from the current cursor; `read_range(offset, length)` reads a byte range without moving it, the same bytes a `seek(offset)` followed by `read(length)` would read. `size()` returns the payload size without reading it. Each row call receives its own reader, which closes when the call returns or raises. Do not retain it for another invocation. Use `video: bytes` when the Function needs the complete payload. Bytes inputs materialize before invocation and remain subject to eager input limits. Reader inputs keep the unread payload out of the input batch, but calling `video.read()` without a size loads all remaining bytes in Python. Reader inputs are supported in row mode. Return values remain ordinary values such as `bytes`; this feature does not add streamed outputs. ## What to read next > [card] [Function](/oss/v0-41-0/management/function) > > List, describe and drop registered Function versions. > [card] [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret) > > Bind a credential by reference instead of putting it in the function's source. > [card] [Chunk records into multiple rows](/oss/v0-41-0/curation/chunking) > > A Function whose output is a list, exploded into one row per element. > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > Filling the column a Function is bound to, and re-filling it as inputs change. # Deduplicate near-duplicate records Source: https://docs.lancedb.com/oss/v0-41-0/curation/dedupe Collapse records that are only approximately alike, judged by embedding distance, without a pairwise scan. **Applies to:** Embedded ❌, Enterprise ✅ [Ranking](/oss/v0-41-0/curation/windowing#dedup) removes records by an explicit rule, such as keeping the latest version of a known key. This page covers the other kind of duplicate: records with no shared key that are still nearly identical, judged by distance between their embeddings -- a stopped camera holding one pose for a few seconds, or two scraped pages with the same paragraph reworded. `dedupe` and `duplicate_pairs` find these directly over a vector index, without a pairwise scan. ## Example data Connect with an [Enterprise connection](/oss/v0-41-0/basics/catalog#enterprise). A small fixture keeps the distances easy to check by hand. > [accordion] Create the example table > > `curation_embeddings` has eight records. Rows 10 and 20 are near-identical; > rows 30, 40 and 50 form one looser cluster; the rest are distinct. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import pyarrow as pa > from lancedb.index import IvfFlat > > schema = pa.schema([ > pa.field("id", pa.int64(), nullable=False), > pa.field("caption", pa.utf8()), > pa.field("embedding", pa.list_(pa.float32(), 2)), > ]) > table = db.create_table("curation_embeddings", [ > {"id": 10, "caption": "a cat on a chair", "embedding": [0.0, 0.0]}, > {"id": 20, "caption": "a cat on the chair", "embedding": [0.0, 0.03]}, > {"id": 30, "caption": "a dog in a field", "embedding": [5.0, 5.0]}, > {"id": 40, "caption": "a dog in the field", "embedding": [5.0, 5.05]}, > {"id": 50, "caption": "a dog out in a field", "embedding": [5.0, 5.10]}, > {"id": 60, "caption": "a bird in a tree", "embedding": [10.0, 10.0]}, > {"id": 70, "caption": "a boat on the water", "embedding": [20.0, 20.0]}, > {"id": 80, "caption": "a car on the road", "embedding": [30.0, 30.0]}, > ], schema=schema) > > table.create_index("embedding", config=IvfFlat(num_partitions=1, distance_type="l2")) > table.wait_for_index(["embedding_idx"]) > ``` > > `dedupe` and `duplicate_pairs` read the vector index, so the column needs one > before either function runs; a query against unindexed fragments is rejected > rather than silently returning stale or wrong results. > > For an `l2` index, `distance_threshold` and the `distance` column below are > both **squared** L2, not the plain L2 a plain SQL `distance()` call returns. ## Collapse near-duplicates `dedupe` returns one representative row per cluster of records within `distance_threshold` of each other -- rows 10/20 collapse to one, 30/40/50 collapse to one, and the four distinct rows pass through unchanged, leaving ids 10, 30, 60, 70 and 80: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, caption FROM dedupe( 'curation_embeddings', 'embedding', distance_threshold => 0.003 ) ORDER BY id ``` Every other column survives unchanged, since `dedupe` returns full rows, not just which ones matched. Clustering is transitive: 30 and 40 are within `distance_threshold` of each other, and so are 40 and 50, so all three collapse into one representative even though 30 and 50 alone sit outside the threshold. Pass `resolution => 'direct_representative'` for a simpler, non-transitive selection instead, if a chained cluster like that should not merge into one representative. Which row survives as the representative is not guaranteed to stay the same across appends: a later row that bridges two previously separate clusters can change which id represents the merged cluster. Do not treat a representative's id as a stable identifier for its cluster. ## Inspect the pairs instead `duplicate_pairs` returns the matching edges themselves, without collapsing anything -- useful for review, or for a threshold that is still being tuned: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id_a, id_b, distance FROM duplicate_pairs( 'curation_embeddings', 'embedding', distance_threshold => 0.003, id_column => 'id' ) ORDER BY id_a ``` This returns the pairs `(10, 20)`, `(30, 40)` and `(40, 50)` -- note 30 and 50 are not a direct pair here (their squared L2 distance is `0.01`, outside the threshold), even though `dedupe` merges all three transitively above. ## Keep it current with a materialized view Wrap either call in a [materialized view](/oss/v0-41-0/management/materialized-view) so the deduplicated set stays current as new records arrive, instead of recomputing it from scratch on every curation pass: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW curation_embeddings_deduped AS SELECT * FROM dedupe( 'curation_embeddings', 'embedding', distance_threshold => 0.003 ) ``` See [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) for manual and automatic refresh options to keep it current as new records land. ## At production scale [LeRobotDataset](/oss/v0-41-0/integrations/lerobotdataset) runs the same `dedupe` call over 27.6 million real embedding rows to remove near-static frames from a robotics training set in under 30 seconds -- the mechanism does not change with scale, only the table it runs against. ## Continue with the curated data [Profile the result](/oss/v0-41-0/curation/aggregate) to check how much a threshold removes before committing to it, or go back to [choosing a curation task](/oss/v0-41-0/curation#questions). # Distributed Shuffle Source: https://docs.lancedb.com/oss/v0-41-0/curation/distributed-shuffle How a SQL query's intermediate results move between plan executors for a join, aggregate or sort. **Applies to:** Embedded ❌, Enterprise ✅ A distributed SQL query plans as a sequence of **stages**, each with its own set of partitions, connected by an **exchange**: a streaming gRPC service that carries one stage's output to the next stage's plan executors. [Distributed Search](/oss/v0-41-0/enterprise/distributed-search) covers how a query gets placed on the fleet in the first place; this page covers what happens between placement and the final result, for a query whose plan needs data repartitioned across machines -- a hash join or a grouped aggregate, for example, where rows with the same key must land on the same worker regardless of which plan executor originally read them. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph Stage1["Stage: scan"] direction TB PE1["Plan executor<br/>reads its partition"] PE2["Plan executor<br/>reads its partition"] end EX["Exchange<br/>streaming gRPC,<br/>repartitions by join/group key,<br/>backpressure via a byte budget"] subgraph Stage2["Stage: join / aggregate"] direction TB PE3["Plan executor<br/>probes its share of keys"] PE4["Plan executor<br/>probes its share of keys"] end PE1 --> EX PE2 --> EX EX --> PE3 EX --> PE4 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class EX accent ``` ## Pipelined, not batched The exchange moves data as a gRPC stream of row batches, not a file a later stage waits for: a consuming plan executor pulls batches as they become available, and a slow consumer throttles its producer through a byte budget on unread messages rather than letting memory grow without bound. A partition that stops being read -- for example the probe side of a hash join whose build side turned out empty -- is drained rather than left to stall the budget for every other partition sharing the same connection. ## What to read next > [card] [Distributed Search](/oss/v0-41-0/enterprise/distributed-search) > > How a query gets placed on the query-serving fleet in the first place. > [card] [Query plans](/oss/v0-41-0/basics/sql#query-plans) > > Inspect a specific query's plan and its actual execution metrics. # Data curation Source: https://docs.lancedb.com/oss/v0-41-0/curation/index Prepare datasets for search, evaluation and training by profiling, selecting and combining records. Data curation turns a collection of records into a dataset suited to a task. You might select labeled examples for training, prepare a fixed evaluation set, or remove duplicate documents from a search corpus. Start with the result you need. Then inspect the source data, choose which records belong, and save the selected data or the rules used to produce it. ## Choose a curation task | Task | What it helps you decide | | - | - | | [Create a Function](/oss/v0-41-0/curation/create-function) | How to run your own Python -- on CPU, on GPU, or against a remote service -- as part of SQL. | | [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret) | How a bound Secret's value actually reaches a running Function. | | [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) | How to query a table, a HuggingFace dataset, or an object-storage dataset the same way, and import without a separate download step. | | [Chunk records](/oss/v0-41-0/curation/chunking) | How to split one record into several -- passages, clips, or tiles. | | [Scope to what changed](/oss/v0-41-0/curation/changes) | How to process only the rows added since your last run. | | [Profile a dataset](/oss/v0-41-0/curation/aggregate) | Whether coverage, missing values and class balance suit the task. | | [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. | | [Selective Sampling](/oss/v0-41-0/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. | | [Join datasets](/oss/v0-41-0/curation/join) | How to attach labels, metadata or scores stored elsewhere. | | [Rank and deduplicate](/oss/v0-41-0/curation/windowing) | Which records to keep when several share an explicit key. | | [Cluster by index partition](/oss/v0-41-0/curation/clustering) | How to group records by vector proximity without training a new clustering model. | | [Deduplicate near-duplicates](/oss/v0-41-0/curation/dedupe) | Which records to collapse when they only look alike, with no shared key. | The analytical examples in this section use **Enterprise SQL**. Connect with the [SQL guide](/oss/v0-41-0/basics/sql). For a random subset through the Python SDK in LanceDB Embedded or LanceDB Enterprise, see [Permutation](/oss/v0-41-0/training/permutation). ## Prepare a labeled document dataset Suppose you need one labeled record per document for a training experiment. Inspect the source records, choose the latest version of each document, then join its label. Finally, check the class balance of the selected records. ### Example data Connect with an [Enterprise SQL client](/oss/v0-41-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. The following query chooses the latest record for each document, then keeps only documents with a label: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS rn FROM curation_documents ) SELECT d.row_id, d.doc_id, d.caption, l.label FROM ranked AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.rn = 1 ORDER BY d.doc_id; ``` The result contains documents **10, 20 and 30**, with labels **cat, dog and cat**. Document 40 is excluded because this particular task requires a label. The `row_id` tie-breaker makes the choice for document 30 deterministic; choose a tie-breaker that fits your own data. The example assumes one label per document. Duplicate keys in the label table would multiply the result rows. The [joining guide](/oss/v0-41-0/curation/join#labels) shows how to check that assumption. ## Check the selected dataset Compare the result with the task's requirements: are the expected documents present, are required fields populated, and is the class distribution suitable? This example has two cats and one dog. That distribution may be appropriate for exploration, but it does not establish a representative evaluation set. [Profiling](/oss/v0-41-0/curation/aggregate) provides the counts to inspect. [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) and [ranking](/oss/v0-41-0/curation/windowing) help you adjust the selection without changing the original records. ## Save and reuse the result Choose the output according to how you will use it: * **A fixed dataset:** save the query result in a new table with [`CREATE TABLE AS SELECT`](/oss/v0-41-0/sql/ddl/table#create). Keep that output unchanged when comparing experiments. * **A reusable selection:** save the query as a [view](/oss/v0-41-0/management/view). A view stores the query definition, so it is not a frozen evaluation set. * **Stored results that you refresh:** use a [materialized view](/oss/v0-41-0/management/materialized-view) when its supported query and refresh behavior fit the workflow. Record the source versions and selection rules alongside the output. Continue with [data loading](/oss/v0-41-0/training/data-loading) to use the curated data in a training pipeline. # Inspect Datasets Source: https://docs.lancedb.com/oss/v0-41-0/curation/inspect-datasets Query a table, a HuggingFace dataset, or a dataset in object storage the same way, with plain SELECT, WHERE, projection and LIMIT. **Applies to:** Embedded ❌, Enterprise ✅ The same `SELECT` statement inspects three kinds of source: a table already in your database, a HuggingFace dataset, or a dataset in object storage -- once a [storage integration](/oss/v0-41-0/management/storage-integration) covers the latter two. Nothing is downloaded or imported until you choose to import it. ## The basics: project, filter, limit A table name, a HuggingFace URI, and an object-storage URI all work the same way after `FROM`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM documents WHERE text IS NOT NULL LIMIT 100 ``` * **Project** -- name the columns you need (`id, text`) instead of `SELECT *`, especially for a source with large or many columns. * **Filter** -- `WHERE` narrows rows before they come back; combine predicates with `AND`/`OR` the same as any other table. * **Limit** -- `LIMIT n` caps how many rows return. It bounds the result, not the read: a remote source is still fetched at file or row-group granularity, so a small `LIMIT` on a source with large files or row groups can still touch more data than the row count suggests. The rest of this page swaps `documents` for a HuggingFace or object-storage source -- the `SELECT`/`WHERE`/`LIMIT` syntax above doesn't change. ## Inspect a HuggingFace dataset A single-quoted HuggingFace dataset URI works directly in a SQL `FROM` clause, the same as a table name -- no separate download, no intermediate file on disk: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM 'hf://datasets/owner/repo/data/train-*.parquet' WHERE text IS NOT NULL LIMIT 100 ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query(""" SELECT id, text FROM 'hf://datasets/owner/repo/data/train-*.parquet' WHERE text IS NOT NULL LIMIT 100 """) sample = reader.read_all().to_pylist() ``` The URI is `hf://datasets/<owner>/<repo>[@<revision>]/<path>`. `<path>` can be one Parquet file, a directory, or a glob: `*` matches within one directory, `**` matches across directories, and a repository root selects every Parquet file beneath it. Select a dataset configuration or split by including it in the path. The default revision is `main`; each statement resolves the revision to a commit once, so every worker reads the same snapshot. This source reads Parquet files -- it does not run a dataset's own generation scripts, and it does not compute embeddings or build indexes, so [chunk](/oss/v0-41-0/curation/chunking), embed, or index the result as a separate step, the same as data from any other source. > [!NOTE] > > Files matched by one statement must have compatible schemas, and an > unmatched path is an error rather than a silent fallback to a different > split. Nested Parquet values come through as-is; a floating-point list is > not automatically converted into a fixed-size vector column. ## Inspect a dataset in object storage An `s3://`, `gs://` or `az://` prefix covered by a storage integration reads an existing **Lance** dataset at that prefix, the same way as a managed table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text FROM 's3://customer-data/raw/documents.lance' WHERE text IS NOT NULL LIMIT 100 ``` This reads a dataset another process already wrote in Lance format, not an arbitrary file format -- there is no Parquet-style reader for cloud storage the way there is for `hf://`. See [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration#read-import) for every provider's setup. ## Access a private repository or bucket A private HuggingFace repository, one subject to HuggingFace's authenticated rate limits, or any non-public bucket needs a [storage integration](/oss/v0-41-0/management/storage-integration) covering it. For HuggingFace that integration is bound to a token [Secret](/oss/v0-41-0/management/secret); for a non-public S3 bucket it can instead be an IAM role integration, which needs no Secret at all -- see [AWS S3](/oss/v0-41-0/ingestion/define-storage-integration#aws). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_secret("hf_token", "<your-hugging-face-token>") # create_storage_integration is not in a released SDK yet; use the SQL # form below until it ships. db.execute_query(""" CREATE STORAGE INTEGRATION private_hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token """).read_all() reader = db.execute_query( "SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10" ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET hf_token TYPE = GENERIC_STRING SECRET_STRING = '<your-hugging-face-token>' CREATE STORAGE INTEGRATION private_hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10 ``` A query never names the integration: the planner matches the most specific `STORAGE_PREFIX` that covers the URI being read, across every integration the caller has `USAGE` on. A HuggingFace integration always needs `HUGGINGFACE_TOKEN_SECRET`; creating one without it is rejected. For public access, register no integration for that prefix at all -- an `hf://` read that matches no integration is anonymous, with no environment-variable fallback. See [Storage Integration](/oss/v0-41-0/management/storage-integration) for every provider and the full credential model. ## Import into a table Once you've inspected a source and it looks right, `CREATE TABLE ... AS SELECT` imports it: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' """).read_all() table = db.open_table("imported") ``` This `CREATE TABLE AS SELECT` runs as a distributed import when the deployment has an available plan-executor fleet: the planner assigns disjoint file and row-group ranges to workers, each worker writes uncommitted Lance files directly to the destination, and a coordinator commits the completed table from their transaction metadata once every worker finishes. A query with a global limit, aggregation or join keeps its usual coordination; a small import can run as one local task without a fleet. The table becomes queryable only after that final commit -- nothing partial is ever visible, and a failed or cancelled import can resume the same durable job from its retained attempt rather than restarting from nothing. To start over after a failed one-off import instead, drop the partial table and rerun the statement. > [!NOTE] > > Importing requires a native database with `database_manifest_enabled`. > Combining a HuggingFace source with a WAL-backed destination table in one > CTAS is rejected, since the import cannot publish a base-only read that > omits the destination's unflushed data. ## What to read next > [card] [Storage Integration](/oss/v0-41-0/management/storage-integration) > > The credential object behind private repository access. > [card] [Create a Function](/oss/v0-41-0/curation/create-function) > > Add embeddings or derived columns to the imported data. > [card] [Chunk records into multiple rows](/oss/v0-41-0/curation/chunking) > > Split long text or media fields after importing. > [card] [Table](/oss/v0-41-0/sql/ddl/table#create) > > `CREATE TABLE AS SELECT` syntax and options in full. # Joining datasets Source: https://docs.lancedb.com/oss/v0-41-0/curation/join Combine records with labels or metadata, and check for missing or duplicate matches. **Applies to:** Embedded ❌, Enterprise ✅ A SQL join combines records from two tables using a shared key. Use joins to attach labels, metadata or model scores to your documents. Choose an inner join to keep matching records, or a left join to retain records without a match. ## Example data Connect with an [Enterprise SQL client](/oss/v0-41-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Basic join An inner join keeps matching records: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.row_id, d.doc_id, l.label FROM curation_documents AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id ORDER BY d.row_id; ``` This returns **5 rows**: both records for document 10, one for document 20, and both records for document 30. To produce one row per document, [deduplicate the source records](/oss/v0-41-0/curation/windowing#dedup). ### Find records without a match A left join keeps every record from the left table and fills missing right-side values with `NULL`. Add `WHERE l.doc_id IS NULL` to return only unlabeled documents: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT DISTINCT d.doc_id FROM curation_documents AS d LEFT JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE l.doc_id IS NULL ORDER BY d.doc_id; ``` The result is **document 40**. You might send it for annotation, retain it for an unlabeled-data workflow, or exclude it from a task that requires labels. ## Handle duplicate keys This example joins `curation_documents.doc_id` to `curation_labels.doc_id`. First check whether the label table contains more than one row per document: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT doc_id, count(*) AS labels FROM curation_labels GROUP BY doc_id HAVING count(*) > 1; ``` The example returns no rows. If your data returns duplicates, decide whether they represent valid multiple labels or records that need consolidation. A join does not enforce one-to-one matching. ## Call a Function across the join A [Function](/oss/v0-41-0/curation/create-function) can read columns from either side of a join, the same as any other expression -- it runs once the join has matched rows, not before. Register `caption_quality` first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.row_id, l.label, caption_quality(d.caption) AS quality FROM curation_documents AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.caption IS NOT NULL ORDER BY d.row_id; ``` Scoring after the join, rather than before, means `caption_quality` only runs on rows that actually matched a label -- a document with no label never pays for the Function call. ## Join tables across namespaces Use a table's qualified path to address it in another [namespace](/oss/v0-41-0/management/namespace). For example, a table named `images` in `prod.media` is addressed as `prod.media.images`. The same matching-key and join-type rules apply; your identity needs access to the source objects. ## Combine search results with metadata A [SQL full-text search](/oss/v0-41-0/sql/dql/fts) returns rows that can be joined to other tables. Join using an identifier retained in the search result, then check whether the metadata has one or several matches per result. For an SDK search, retain the matching IDs and combine them with metadata in your application or save the selected records to a table for further SQL work. See [SQL search interfaces](/oss/v0-41-0/basics/sql#no-vector-sql) for supported query forms. ## Join performance Check the row count, unmatched keys and duplicate matches before using a joined dataset. Select only the columns needed for the next step, especially when source records include large media or embedding columns. Use [Query plans](/oss/v0-41-0/basics/sql#query-plans) to see how the query reads and combines data. Check the plan to see whether the query uses indexes and how it performs the join. An index on a key does not guarantee that the join will use it. ### Defer wide columns until after the join When one side of a join carries a BlobV2 column, an embedding, or both, join on a narrow key first and project the wide columns only in the final select list, so the planner can defer reading them until after the join has already narrowed down which rows survive. See [Blob Late Materialization](/oss/v0-41-0/curation/blob-late-materialization) for the mechanism, eligibility, and how to confirm it happened. ## Save the result or continue curating Keep the query for reuse or [save the selected data](/oss/v0-41-0/curation#next). See [Joins](/oss/v0-41-0/sql/dql/join) for join types and exact SQL behavior. # Selective Sampling Source: https://docs.lancedb.com/oss/v0-41-0/curation/selective-sampling Fetch specific rows by row ID, row address or offset instead of drawing a random fraction. **Applies to:** Embedded ✅, Enterprise ✅ Selective sampling fetches specific, already-known rows -- by row ID, row address or offset -- rather than drawing a random fraction of the table. Use it to re-fetch rows a previous query identified, resume from a saved position, or pull a batch by index for a data loader. For a random subset instead, see [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling). LanceDB exposes three ways to address a row: | Identifier | Stability | Typical source | | - | - | - | | Row ID (`_rowid`) | Stable across compaction, with [stable row IDs](/oss/v0-41-0/basics/guarantees) enabled | A previous query's result, or `function_errors()` | | Row address (`_rowaddr`) | Changes on compaction; encodes `(fragment_id << 32) \| row_offset` | A previous query's result, when you need the physical location | | Offset | Table-wide position; **not** stable -- a row's offset shifts when an earlier row is deleted | `range(len(table))`, since every valid offset is known in advance | ## From Python The SDK takes a list of row IDs or offsets directly, without going through SQL: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # By row ID -- from a previous search or scan that selected "_rowid" rows = tbl.take_row_ids([1001, 1002, 1005]).to_arrow() # By offset -- the full range is always [0, len(tbl)) rows = tbl.take_offsets([0, 1, 2]).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // By row ID -- from a previous search or scan that selected "_rowid" const rowsById = await tbl.takeRowIds([1001n, 1002n, 1005n]).toArray(); // By offset -- the full range is always [0, tbl.countRows()) const rowsByOffset = await tbl.takeOffsets([0, 1, 2]).toArray(); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::query::ExecutableQuery; // By row ID -- from a previous search or scan that selected "_rowid" let rows_by_id = tbl.take_row_ids(vec![1001, 1002, 1005]).execute().await?; // By offset -- the full range is always [0, tbl.count_rows().await?) let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?; ``` Both methods return a query builder; call `.to_arrow()`, `.to_list()` or similar to execute it. > [!NOTE] > > The guarantees for row IDs below apply to SDK releases containing > [the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826). > Earlier releases may collapse repeated IDs and return rows in a different > order. `take_row_ids` returns matching rows in the order of the input IDs and preserves repeated IDs in both LanceDB Embedded and LanceDB Enterprise. For example, `take_row_ids([1005, 1001, 1005])` returns row 1005, row 1001, then row 1005 again if both IDs exist. Missing or deleted IDs are omitted. This supports sampling with replacement. In Rust, an explicit nonempty `QueryBase::order_by` list overrides the requested order; limits and offsets apply after restoring repeated rows. `take_offsets` also preserves repeated offsets, but does not guarantee input order. It tracks `_rowoffset` internally to restore repeated rows and drops that column from the output unless you explicitly `select` it. Add `_rowoffset` to your selection when you need to align a `take_offsets` result with the input offsets. > [!NOTE] > > Ordered takes by row ID collect all matching batches, combine them into one > batch and reorder the rows before returning output batches. Even > `to_batches(max_batch_length=1)` only limits the returned batch size; it > does not bound working memory. For large requests or rows with large > column values, split the input IDs into smaller requests and use > `.select(...)` to fetch only the columns you need. Offsets are mostly useful for sampling: the valid range is always `[0, len(table))`, so you can draw a random sample of offsets without reading the table first. Row IDs require you to already have them, from an earlier query's `_rowid` column -- but unlike offsets, a row ID keeps addressing the same logical row even after compaction, as long as the table has stable row IDs enabled. ## From SQL The same three identifiers are available as [pseudo-columns](/oss/v0-41-0/sql/data-types#pseudo-columns) -- select or filter on them like any other column: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} -- By row ID SELECT * FROM documents WHERE _rowid IN (1001, 1002, 1005); -- By row address SELECT * FROM documents WHERE _rowaddr IN (4294967296, 4294967297); -- Including the identifier in the result, to save for a later take SELECT _rowid, * FROM documents WHERE score > 0.9; ``` There is no dedicated Python method for taking by row address -- use `.where("_rowaddr IN (...)")` on the SDK query builder, or the SQL form above, since the expression language is the same either way. ## Related guides [Query plans](/oss/v0-41-0/basics/sql#query-plans) show whether a row-ID or offset filter reads the whole table or seeks directly to the requested rows. See [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) for a random fraction instead of specific rows, and [Permutation](/oss/v0-41-0/training/permutation) for shuffled, batched reads through the Python SDK. # Statistical Sampling Source: https://docs.lancedb.com/oss/v0-41-0/curation/statistical-sampling Draw a random subset of a table with SQL TABLESAMPLE, by rows or by fragments. **Applies to:** Embedded ❌, Enterprise ✅ Statistical sampling draws a random subset of a table's rows using SQL's `TABLESAMPLE` clause, attached directly to a table in `FROM`. Use it to explore unfamiliar data, run a smaller experiment, or estimate aggregate statistics without reading every row. For a random subset through the Python SDK instead -- in Embedded or Enterprise -- see [Permutation](/oss/v0-41-0/training/permutation). To select specific, known rows rather than a random fraction, see [Selective Sampling](/oss/v0-41-0/curation/selective-sampling). ## Example data Connect with an [Enterprise SQL client](/oss/v0-41-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Basic sampling A percentage selects a fraction of the source; `ROWS` requests a row count: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (3 ROWS); ``` A percentage sample does not guarantee an exact number of rows. Use a count when the desired sample size is the main constraint, and inspect the result rather than assuming it contains every category you need. `TABLESAMPLE` requires a table that is not WAL-backed. See the [sampling reference](/oss/v0-41-0/sql/dql/sampling#refused) for this restriction; do not change a production table's write configuration just to try an example. ## Sampling methods Choose a method according to how records should be selected: | Method | Selection | When to use it | | - | - | - | | `BERNOULLI` (default) | Select individual rows | When records should be sampled independently of their storage fragments | | `SYSTEM` | Select whole Lance fragments | When reducing reads matters and grouping by fragment is acceptable | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE BERNOULLI (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE SYSTEM (50); ``` If write order groups records by label, date or source, a fragment sample can reflect that grouping. On a tiny table stored in one fragment, it may include all records or none. Row sampling also needs an adequate sample size to represent rare groups; check that the resulting sample covers the groups you need. ## Repeatable samples A seed requests a repeatable draw: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` Keep the source data and sampling configuration fixed when comparing draws. For a lasting evaluation set, save the selected records rather than relying on a seed to preserve membership as the source changes: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE curation_eval AS SELECT * FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` Create this output once with a fresh name and keep it unchanged. Record the source version and selection policy. Sampling records independently can place revisions of the same document into different splits; decide the [grouping policy](/oss/v0-41-0/curation/windowing#splits) before using the result for training or evaluation. ## Sampling with joins Sampling both input tables independently changes which pairs can match. For a one-to-one match, independent 10% row samples retain a given pair with about 1% probability, not 10%. To sample documents while retaining their available labels, sample only the document table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT curation_documents.row_id, curation_documents.doc_id, l.label FROM curation_documents TABLESAMPLE (50) JOIN curation_labels AS l ON l.doc_id = curation_documents.doc_id; ``` This samples source records, not distinct documents. If you need to sample the result of a join or deduplication, first save that result as a table suitable for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result. ## Apply a Function to a sample Sample first, then call a [Function](/oss/v0-41-0/curation/create-function) only on the rows you drew -- useful for trying an expensive Function on a subset before running it over the whole table. Register `caption_quality` first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import udf @udf def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model db.create_function_async(caption_quality).wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id, caption, caption_quality(caption) AS quality FROM curation_documents TABLESAMPLE (50) WHERE caption IS NOT NULL; ``` The Function runs only on the sampled rows, not the whole table -- a quick way to check a Function's output, cost or latency before committing to a full [column refresh](/oss/v0-41-0/feature-engineering/refresh-column). ## Related guides Count the sampled rows and [inspect their distribution](/oss/v0-41-0/curation/aggregate) before using them. Preserve the selected data when the exact membership matters. See [SQL sampling](/oss/v0-41-0/sql/dql/sampling) for the complete syntax and restrictions, and [Permutation](/oss/v0-41-0/training/permutation) for a random subset through the Python SDK. # Vend a Secret to a Function Source: https://docs.lancedb.com/oss/v0-41-0/curation/vend-secret Bind a Secret to a Function by reference, and how its value reaches running code during SQL evaluation and refresh. **Applies to:** Embedded ❌, Enterprise ✅ Early access A Function that calls an external service needs a credential without putting it in the function's source -- see [Create a Function](/oss/v0-41-0/curation/create-function#remote) for how to register one. A [Secret](/oss/v0-41-0/management/secret) is a database-scoped named credential: you create it once, then bind it *by reference* -- by name, not by value -- when you register the Function that needs it. ## Specify the Secret when you register the Function Store the credential, then bind it to an environment variable the function's code already reads: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb import EnvVarSecret, udf db.create_secret("embedding-api-key", os.environ["EMBEDDING_API_KEY"]) @udf class embed_remote: def __init__(self, model: str = "text-embedding-3-small"): import os from openai import OpenAI self.client = OpenAI(api_key=os.environ["EMBEDDING_API_KEY"]) self.model = model def __call__(self, text: str) -> list[float]: response = self.client.embeddings.create(input=text, model=self.model) return response.data[0].embedding version = db.create_function_async( embed_remote, secrets=[ EnvVarSecret(secret_name="embedding-api-key", env_variable="EMBEDDING_API_KEY") ], ).wait() ``` The function's own code never names the Secret -- it reads `EMBEDDING_API_KEY` the same way it would outside LanceDB. The binding, in `secrets=[...]`, is what connects that variable to the stored credential. It is checked for shape at registration (valid variable name, not reserved, not repeated) but not resolved yet: the Secret does not have to exist until a column actually uses this Function version, so you can create the Function and its Secret in either order. ## Hugging Face models For a model loaded from the Hugging Face Hub, store the token as a Secret and bind it to the variable the Hub client reads. Use a class Function so the model is loaded once per remote instance rather than once per row: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb import EnvVarSecret, col, udf db.create_secret("hf-token", os.environ["HF_TOKEN"]) @udf( name="embed_text", pip=["sentence-transformers==3.3.1"], ) class EmbedText: def __init__(self, revision: str): from sentence_transformers import SentenceTransformer self.model = SentenceTransformer( "sentence-transformers/all-MiniLM-L6-v2", revision=revision, ) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() embed_fn = db.create_function( EmbedText, secrets=[EnvVarSecret(secret_name="hf-token", env_variable="HF_TOKEN")], ) table = db.open_table("documents") table.add_columns( { "embedding": embed_fn( text=col("text"), revision="<full-40-character-commit-sha>", ) } ) table.refresh_column("embedding") ``` A decorated class calls `__init__` once per remote instance and `__call__` for each row or batch. The class's `__init__` parameters are binding initialization values, so `revision` is fixed for this binding and the model is reused for all rows handled by that instance. Instances are not shared across workers. Use a full 40-character commit SHA for `revision`. A branch or tag can move; a commit pins the model version. See the official Hugging Face documentation for [`HF_TOKEN`](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hftoken) and [downloading a specific revision](https://huggingface.co/docs/huggingface_hub/guides/download#revision). `HF_TOKEN` authenticates Hub requests, but a cached model and a pinned revision are not a guarantee of offline execution. The Hub client may still request metadata or missing files, and authentication does not guarantee that requests will avoid rate limits. ## How the value reaches a running evaluation The Secret's value is resolved fresh for each job, never read once and cached in the Function's definition: | Step | What happens | | - | - | | `add_columns` with this Function version | Every bound Secret must now exist. The column pins this exact version, not a value. | | A refresh starts -- `refresh_column`, or a materialized view's refresh | Every bound Secret must still exist, checked before any row is computed. | | The job captures each bound Secret's current value | LanceDB looks up the value once, when the job starts, and sets it as that environment variable for every row the job evaluates, including its retries. No other environment variable carries over. | This is why rotating a Secret needs no new Function version and no column change: `alter_secret` changes the value a *future* lookup returns. The agent captures that value once, when a job starts, and reuses its own captured copy for that job's full run and any of its retries -- a refresh already running keeps the value it started with for every row, and only a job that starts *after* the rotation sees the new one. ### Rotate and revoke `alter_secret` and `drop_secret` never interrupt work in progress, so a routine rotation cannot fail a backfill halfway through: | Action | Running jobs | Next job | New Function version? | | - | - | - | - | | `alter_secret` | A running job and its retries keep the value captured at start; only a new job gets the latest value | Uses the latest value | No | | `drop_secret` | Run to completion on the last value | Refused, naming the Secret | No | | Revoke the key at its provider | Fails on their next call to the provider | Fails until a new value is set | No | | Re-create a dropped name | Keeps the dropped Secret's last value | Picks up the new Secret | No | Because a rotation creates no new Function version, it also reaches columns pinned to a version registered before it. Binding a Function to a *different* Secret or variable does register a new version, and existing columns keep the binding they were declared with. > [!WARNING] > > To stop a credential from being used **now**, revoke it at its provider, > for example by deleting the key in the OpenAI console. A value already > handed to a running job cannot be recalled. `drop_secret` cannot be undone, and it does not check for Functions still bound to the Secret. > [!NOTE] > > Reading a column this Function already filled needs only `SELECT` on the > table. No Function runs on the read path, so a reader needs no grant on the > Function or its Secrets -- only someone triggering a refresh does. ## Vending during SQL evaluation specifically A computed column's expression and a `CREATE MATERIALIZED VIEW` query both plan and execute as SQL, so a Function called from either one is vended its Secrets the same way: at the evaluation that fills the column or refreshes the view, not at declaration time. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT f.frame_id, caption(f.jpeg) AS caption FROM frames f ``` `caption` here is a Function bound to a Secret through the Python SDK when it was registered -- SQL has no syntax for the binding itself, only for calling the already-registered Function. The `CREATE MATERIALIZED VIEW` statement's initial population, and every `REFRESH MATERIALIZED VIEW` after it, each look up the bound Secret's current value independently. ## Troubleshooting **403 when adding or refreshing a Function column**: you need `USAGE` on the Function *and* on every Secret it binds, in addition to the table privilege. The error names the object you are missing. **The Function runs but its provider rejects the key**: a misspelled *environment variable* cannot be caught at registration, because nothing knows which variables a Function reads. Check that `env_variable` matches what the Function's code reads, such as `EMBEDDING_API_KEY` above. ## Related guides > [card] [Create a Function](/oss/v0-41-0/curation/create-function#remote) > > Write the function that reads the credential. > [card] [Secret](/oss/v0-41-0/management/secret) > > Create, rotate, list and drop the credential itself. > [card] [Privileges](/oss/v0-41-0/governance/privileges#sql) > > Grant and revoke privileges on a Secret. > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > Running the evaluation that vends the Secret. # Ranking Source: https://docs.lancedb.com/oss/v0-41-0/curation/windowing Choose records with explicit ranking rules and deterministic tie handling. **Applies to:** Embedded ❌, Enterprise ✅ Window functions calculate values across related rows while keeping each row in the result. Use them to rank documents, keep one record per item, or compare a record with the one before it. ## Example data Connect with an [Enterprise SQL client](/oss/v0-41-0/basics/sql). The examples use a small document table and a separate label table. Expand the setup below to create them. > [accordion] Create the example tables > > `curation_documents` has six records describing four documents. > `curation_labels` has one label for each of three documents. `row_id` identifies > a record; `doc_id` identifies the document it describes. > > Run each statement separately in a scratch database or namespace. Create these > tables once for the whole section, using fresh names if they already exist. > > ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > CREATE TABLE curation_documents ( > row_id BIGINT, doc_id BIGINT, version BIGINT, > source VARCHAR, caption VARCHAR, score DOUBLE > ); > INSERT INTO curation_documents VALUES > (1, 10, 1, 'web', NULL, 0.80), > (2, 10, 2, 'web', 'A cat on a chair', 0.95), > (3, 20, 1, 'books', 'A dog in a field', 0.90), > (4, 30, 1, 'web', NULL, 0.70), > (5, 30, 1, 'web', 'A cat by a window', 0.85), > (6, 40, 1, 'books', 'A bird in a tree', 0.60); > > CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); > INSERT INTO curation_labels VALUES > (10, 'cat'), (20, 'dog'), (30, 'cat'); > ``` > > `score` is a sample quality score, not a search result score. Document 10 has > two versions. Document 30 has two records at the same version. Document 40 > has no label. These cases let you check the effect of each operation. ## Keep one record per document `row_number()` numbers rows within each group. `PARTITION BY` defines the group, and `ORDER BY` determines which record comes first. This query selects the latest version of each document, using `row_id` to break ties: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS rn FROM curation_documents ) SELECT row_id, doc_id, version, caption FROM ranked WHERE rn = 1 ORDER BY doc_id; ``` This returns row IDs **2, 3, 5 and 6**. For document 30, rows 4 and 5 have the same version; the example deliberately chooses the larger `row_id`. Without a complete ordering, the selected row among ties is not determined by the query. Use `rank()` instead of `row_number()` when tied records should all survive, and order only by the fields that define a tie. Adding a unique tie-breaker would make every rank distinct. The outer query filters the calculated rank because window functions are evaluated after the inner query's `WHERE` clause. ## Select the highest-scoring records per class Deduplicate first, then rank the labeled documents within each class: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH latest AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC ) AS version_rank FROM curation_documents ), ranked AS ( SELECT d.doc_id, l.label, d.score, row_number() OVER ( PARTITION BY l.label ORDER BY d.score DESC, d.doc_id ) AS class_rank FROM latest AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.version_rank = 1 ) SELECT doc_id, label, score FROM ranked WHERE class_rank <= 1 ORDER BY label; ``` The result is **document 10 for cat and document 20 for dog**. Change the cap from `1` to the maximum number you want per class. A class with fewer records cannot supply the full cap. This selects by score, not at random. For a random subset, use [sampling](/oss/v0-41-0/curation/statistical-sampling) instead of ordering by score or ID. ## Training and evaluation splits Ranking can divide ordered records into groups, but ordering by ID does not make those groups random or representative. `ntile()` produces approximately equal-sized buckets within a partition; small classes may not populate every bucket. Choose the split policy for the task. Keep related records, such as revisions of one document or frames from one video, in the same split to avoid leakage. A time-based evaluation may instead require a cutoff date. Save the final assignments or resulting datasets so later updates do not silently change the evaluation population. ## Compare neighboring records `lag()` and `lead()` read neighboring rows in the specified order. For example, inspect how scores change across a document's records: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT doc_id, row_id, score, lag(score) OVER ( PARTITION BY doc_id ORDER BY version, row_id ) AS previous_score FROM curation_documents ORDER BY doc_id, version, row_id; ``` The first record in each document has no previous score. In this dataset, row 2 follows a score of 0.80 and row 5 follows a score of 0.70. ## Window query performance Window operations can require sorting. Filter out records you do not need before ranking, and inspect the [query plan](/oss/v0-41-0/basics/sql#query-plans) when cost matters. For cumulative counts, sums and other running summaries, use an aggregate with an explicit window order and frame. The [window reference](/oss/v0-41-0/sql/dql/window#window) covers those expressions. ## Continue with the curated data [Profile the selected records](/oss/v0-41-0/curation/aggregate) and [save the result](/oss/v0-41-0/curation#next) for downstream use. See [Window functions](/oss/v0-41-0/sql/dql/window) for the full syntax and function list. # Support Source: https://docs.lancedb.com/oss/v0-41-0/deployment/support Where to get help: community Discord and email for LanceDB Embedded, dedicated support for LanceDB Enterprise. ## LanceDB Embedded For a quick question, the [Discord community](https://discord.gg/AUEWnJ7Txb) has channels for Python, TypeScript and Rust where you can ask the community for help. Use GitHub for discussions and issues that others can search and follow: | | | | - | - | | [GitHub Discussions](https://github.com/lancedb/lancedb/discussions) | Open-ended questions, design questions, "what's the right way to do X" | | [GitHub Issues](https://github.com/lancedb/lancedb/issues) | A specific bug, or a feature request | For anything the community can't resolve, email [support@lancedb.com](mailto:support@lancedb.com). ### What to include A faster answer usually depends on the same handful of details, whether you post in Discord or email: | | | | - | - | | SDK and version | `lancedb.__version__` (Python), `package.json` (TypeScript), the crate version (Rust) | | Connection type | embedded path, or a `db://` deployment | | The exact error | full traceback or error message, not a paraphrase | | A minimal repro | the smallest table schema and call that reproduces it | ## LanceDB Enterprise Talk to your account executive, file a support ticket, or reach the LanceDB support and engineering team directly for dedicated assistance. # Cache Prewarm Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/cache-prewarm Populate the tiered index cache ahead of a request, instead of filling it lazily on first read. **Applies to:** Embedded ❌, Enterprise ✅ Cache Prewarm loads the [tiered index cache](/oss/v0-41-0/enterprise/tiered-index-cache) a plan executor keeps as part of Enterprise's serving layer, instead of leaving it to fill lazily on first read. You configure which tables to prewarm; on startup, each plan executor loads those tables' indexes into cache before it joins the fleet. The executor does not accept queries until prewarming finishes, so it never serves a request against a cold cache. LanceDB Embedded has no such cache, so there is nothing for it to warm there. Embedded does have its own, separate `prewarm_index()` on a table -- an idempotent hint that loads a built index into memory ahead of a query. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR List[("Configured list<br/>of tables to prewarm")] Start["Plan executor starts<br/>(not ready — no queries served)"] --> Warm["Loads the configured<br/>tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,<br/>starts serving queries"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Warm,List accent ``` ## Why it matters Without prewarming, a fresh or restarted executor would fill its indexes lazily, so the first queries it serves pay the cost of loading and deserializing them from object storage. Holding the executor out of the fleet until its configured tables are warm means every query it ever serves gets a warm cache, so performance stays consistent through restarts and rollouts instead of dipping right after each one. [Contact us](https://www.lancedb.com/contact) to learn more about how prewarming is configured for your deployment. ## What to read next > [card] [Data Page Cache](/oss/v0-41-0/enterprise/data-page-cache) > > The raw-data-page cache -- a separate cache from the one prewarm fills. > [card] [Tiered Index Cache](/oss/v0-41-0/enterprise/tiered-index-cache) > > The deserialized-index cache prewarm fills. > [card] [Architecture](/oss/v0-41-0/index#architecture) > > Where plan executors and query nodes sit in the serving fleet. # Console Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/console A web UI for running SQL, browsing tables, and monitoring jobs on LanceDB Enterprise. **Applies to:** Embedded ❌, Enterprise ✅ The **Console** is a web UI for LanceDB Enterprise -- an alternative to the SDK for people who want to explore and operate a deployment from a browser instead of writing code. It ships with every Managed and BYOC deployment, reachable at the URL your deployment provisions. ## What you can do in the Console * **Run SQL.** A workspace for writing and running [SQL](/oss/v0-41-0/sql) against your tables, with results rendered as a browsable grid -- the same engine the SDK and `lancedb` CLI use, reachable without either one. Multimodal columns render inline, so an image column shows as a thumbnail in the grid instead of raw bytes. * **Browse tables.** Inspect a table's schema, row count, and recent versions, and preview rows, without writing a query first. * **Monitor jobs.** Follow the running, queued, completed, and failed jobs behind [refreshes](/oss/v0-41-0/feature-engineering/refresh-column), [materialized views](/oss/v0-41-0/feature-engineering/materialized-views), and maintenance, including per-job progress and errors. * **Manage access.** Sign in with your organization's identity provider, and manage who else on your team can reach the deployment. [Reach out to us](https://www.lancedb.com/contact) if you'd like to see the Console as part of a LanceDB Enterprise deployment. ## Related guides > [card] [LanceDB Enterprise](/oss/v0-41-0/enterprise/index) > > What Enterprise is, and why teams use it. > [card] [SQL reference](/oss/v0-41-0/sql) > > The SQL the Console's workspace runs. > [card] [Job management](/oss/v0-41-0/sql/ddl/job) > > The job states and history the Console's job view surfaces. > [card] [Deployment and governance](/oss/v0-41-0/enterprise/index#deployment-and-governance) > > Managed and BYOC deployment models the Console ships with. # Data Page Cache Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/data-page-cache How LanceDB Enterprise caches table data pages to avoid re-reading object storage. **Applies to:** Embedded ❌, Enterprise ✅ The data page cache holds fixed-size pages of raw table data read from object storage, keyed by their location, so a later read of the same range is served from memory or local disk instead of round-tripping to the backing store. Plan executors and query nodes each keep their own cache for the pages they serve. A background prewarm job can populate a cache ahead of a request that needs it, rather than filling it lazily on first read. See [Architecture](/oss/v0-41-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Read request<br/>for a data page"] --> M{"In memory?"} M -->|hit| Return["Served from memory"] M -->|miss| D{"In local disk cache?"} D -->|hit| Promote["Loaded into memory,<br/>served"] D -->|miss| O[("Object storage")] O --> Fill["Fills memory and disk,<br/>served"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` A table's local disk cache shares one configurable budget with the [tiered index cache](/oss/v0-41-0/enterprise/tiered-index-cache#disk-budget)'s disk tier where both are enabled on the same executor. ## Why it matters Object storage is durable and cheap, but every round trip to it adds latency and egress cost. For workloads that read the same ranges repeatedly -- a hot subset of embeddings, a frequently-filtered column -- the data page cache turns most of those reads into local memory or disk hits instead, so performance stays predictable as traffic grows and you pay object storage once per page, not once per read. [Contact us](https://www.lancedb.com/contact) to learn more about how caching is sized and tuned for your workload. ## Cache interfaces * [Tiered Index Cache](/oss/v0-41-0/enterprise/tiered-index-cache) for the related cache that holds deserialized index structures instead of raw data pages. * [Query plans](/oss/v0-41-0/basics/sql#query-plans) for inspecting what a query actually read. # Distributed RTE Read Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-real-time-read How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine. **Applies to:** Embedded ❌, Enterprise ✅ [RTE Read](/oss/v0-41-0/search/realtime-read) covers what a query against an RTE-enabled table returns: base-table rows merged with the fresh tier, fresh rows superseding base rows with the same primary key. On a single Embedded process that merge is one function call against one Lance dataset. In LanceDB Enterprise, the base table and the fresh tier are usually served by different machines -- plan executors for the base table, an [RTE node](/oss/v0-41-0/tables/realtime-engine#wal-nodes) for the table's shards -- so a query has to combine their results across the network instead. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>plans the query"] subgraph PE["Plan executors"] direction TB B1["Base-table arm<br/>index-covered scan or ANN search"] end subgraph WN["RTE node (owns this table's shards)"] direction TB W1["SSTable arm<br/>index-covered"] W2["Active memtable arm<br/>vector: in-memory HNSW*<br/>FTS/scalar: indexed"] end U["Union exec<br/>PK-keyed last-write-wins dedup,<br/>top-K cut on distance"] Q --> B1 Q --> W1 Q --> W2 B1 --> U W1 --> U W2 --> U U --> R["Merged result"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class U accent ``` ## An extra exec node, not a parallel system The distributed plan for an RTE-enabled table is an ordinary plan executor query plan with one additional node spliced in: a union exec that queries the owning RTE node's shard and merges its rows into the base arm's stream by primary key, keeping the newest generation on a collision and cutting back to the requested top-K once both sides have contributed. An optimizer pass inserts this node only when the query actually touches an RTE-enabled table; a query that touches none produces a plan identical to one with no RTE tables involved at all, so RTE adds no overhead to queries that never use it. Because the base arm already read through the plan-executor fleet's ordinary caches and index structures, the only new network hop this adds is the one to the RTE node that owns the table's shards -- the same RTE node [Real Time writes](/oss/v0-41-0/ingestion/realtime-write) land on, found by the query node through the same consistent hash of database and table name. ## Search stays index-covered Every tier the union exec reads from -- the base table, the RTE node's SSTables, and its currently-active memtable -- is covered by a maintained index, for vector, full-text, and scalar search alike: | Layer | Vector search | Full-text / scalar search | | - | - | - | | Base table | ANN index | Maintained index | | SSTables | ANN index | Maintained index | | Active memtable | In-memory HNSW graph\* | Maintained index | ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR B["Base table"] --> I1["Vector, full-text, and<br/>scalar index coverage"] S["SSTables"] --> I1 M["Active memtable"] --> I2["Full-text and scalar index<br/>coverage; vector via<br/>in-memory HNSW*"] I1 --> R["No unindexed data<br/>left to scan in full"] I2 --> R classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class R accent ``` For full-text and scalar search, a maintained index covers every tier the union exec reads from -- the base table, the RTE node's SSTables, and its currently-active memtable -- so a row written a moment ago is just as index-searchable as one written yesterday. If a resident memtable predates an index being added to the maintained set, the query is rejected outright rather than silently missing that memtable's rows; there is no code path that quietly returns an incomplete result. Vector (ANN) search follows the same rule for the base table and SSTables. The active memtable's rows are ANN-searchable too: it builds its own in-memory HNSW graph as rows land, so writes stay vector-searchable within milliseconds without waiting for a freeze into an SSTable. \* That graph search steps aside for a full scan of the memtable only when it can't honor the query correctly through a graph: a prefilter predicate (graph traversal can't apply an arbitrary filter first), a primary-key override that could let a stale near vector occupy a top-K slot a newer row should have, a distance lower bound (only a full scan can exclude the nearest rows before the top-K cut), or before the memtable has any index yet on a cold start. Outside those cases, every committed row -- base table, SSTables, and the active memtable alike -- is covered by a real index, with no sliver of unindexed data left to scan in full. Both guarantees depend on the table's RTE write spec actually maintaining the index in question -- by default every index is maintained, but a deployment that pins a smaller set with `with_maintained_indexes` loses the guarantee for whatever it leaves out, and a query against an unmaintained index is rejected the same way, rather than silently searching the base table alone. ## What to read next > [card] [RTE Read](/oss/v0-41-0/search/realtime-read) > > What a query returns, and how Embedded does this same merge in-process. > [card] [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write) > > How writes reach the RTE node this page's queries read from. > [card] [Distributed Search](/oss/v0-41-0/enterprise/distributed-search) > > The ordinary plan-executor path this layers on top of. # Distributed RTE Write Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-real-time-write How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it. **Applies to:** Embedded ❌, Enterprise ✅ [RTE writes](/oss/v0-41-0/ingestion/realtime-write) describes `table.enable_rte(spec)` as one call that works the same way on either connection. On Enterprise, that call does not run locally -- it posts to the server, which installs the write path on a dedicated, horizontally scalable serving tier instead of running it in your process. This page covers that tier: how it shards a table's writes, the one real limit sharding does not remove, and the throughput you can expect. ## How writes are routed Enabling RTE on a remote table sends the spec to the server, which installs the write path on the dataset instead of running it in your process. From then on, the query node routes every request for that table -- reads and writes alike -- to a single owning **RTE node**, a stateful component separate from the query nodes and plan executors that serve ordinary queries. A query node routes different tables to different RTE nodes, and a single RTE node can host shards from many different tables at once. RTE nodes share nothing but the underlying object storage; no node talks to another one directly. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>routes each table's shards to an RTE node"] subgraph W0["RTE node A"] direction TB S0["Shard 0 — table 'frames'"] S1["Shard 0 — table 'events'"] end subgraph W1["RTE node B"] direction TB S2["Shard 0 — table 'metrics'"] S3["Shard 1 — table 'metrics'"] end Q -- "'frames'" --> W0 Q -- "'events'" --> W0 Q -- "'metrics'" --> W1 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` ## Shards scale one table, replicas scale the cluster `RTEWriteSpec::bucket(column, num_buckets)` splits a table into `num_buckets` **table shards**, each a separate, independently-appending stream, giving the table that many parallel write paths instead of one. A shard's identity is derived from the table itself, not assigned by an operator, so a shard survives the table being claimed by a different RTE node later. This is where the horizontal scaling actually happens: splitting `frames` into 8 shards gives it 8 independent append streams instead of 1, raising that table's own write ceiling. Adding RTE node replicas spreads shard ownership across more nodes, so the cluster can host more tables -- and more shards -- without any one node becoming a bottleneck for everything it serves. `RTEWriteSpec::identity(column)` and `RTEWriteSpec::unsharded()` both resolve to a single table shard -- `bucket` is the sharding mode that actually parallelizes write throughput; the other two are about routing semantics, not scaling. ## Throughput A table shard is the unit of capacity: measured runs show it sustaining roughly 85-90 MB/s of durable append before acknowledgement, and throughput scaling nearly linearly with shard count up to at least 8 shards on one node -- the bottleneck is the durable write itself, not CPU or memory. This is observed capacity, not an enforced quota; nothing in the deployment caps a shard's or a table's throughput below it. [Contact support](https://www.lancedb.com/contact) if your workload needs more write throughput than this provides. ## What to read next > [card] [RTE Write (Upsert)](/oss/v0-41-0/ingestion/realtime-write) > > Enable RTE and write to a table; the same call on Embedded or Enterprise. > [card] [How the real time engine works](/oss/v0-41-0/tables/realtime-engine) > > MemWAL, shards, memtables and SSTables -- the shared architecture. > [card] [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read) > > How reads combine the WAL tier's fresh rows with the base table across the fleet. # Distributed Search Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-search How LanceDB Enterprise distributes index execution, data reads, and caching across query nodes and executors. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB Enterprise separates query planning from index execution and data reads so that search can use the memory, CPU, and caches of multiple machines. A query node plans and coordinates a query. Executors search indexes, read table data, and return partial results for the query node to combine. For the service components and overall request paths, see [Architecture](/oss/v0-41-0/index#architecture). ## Search architecture LanceDB Enterprise prioritizes horizontal scalability. Index execution on a single node can be limited by the memory available to cache the index for fast search and by the CPU available to execute queries. Dividing one logical index into multiple **index segments** lets each segment be distributed to an executor, cached independently, and searched in parallel with other segments. The two serving components have different responsibilities: | Component | Responsibility | | - | - | | Query node (query planning + routing fleet) | Accept requests, plan queries, distribute work, and combine results. | | Executor (executor + cache fleet) | Cache index structures and table data, execute subplans from the query node, and return partial results. | Eligible scalar index operations can also execute on executors. See [scalar indexes](/oss/v0-41-0/indexing/scalar-index) and [filtering](/oss/v0-41-0/search/filtering) for index types and query syntax. For example, consider a vector index with six segments served by three executors. Each executor searches its two segments and returns its best 10 candidates. The query node compares the candidates returned by all three executors and selects the final 10. This example assumes enough matching rows and the default search path without additional reranking. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB Client["Application: vector search, limit 10"] QueryNode["Query node<br/>Plan, distribute, combine"] Index["One logical vector index<br/>Six index segments"] PlanExecutor1["Executor 1<br/>Cache and search segments A and B"] PlanExecutor2["Executor 2<br/>Cache and search segments C and D"] PlanExecutor3["Executor 3<br/>Cache and search segments E and F"] Merge["Query node<br/>Select final top 10 from up to 30 candidates"] Client --> QueryNode Index -.-> PlanExecutor1 Index -.-> PlanExecutor2 Index -.-> PlanExecutor3 QueryNode -->|Search subplan| PlanExecutor1 QueryNode -->|Search subplan| PlanExecutor2 QueryNode -->|Search subplan| PlanExecutor3 PlanExecutor1 -->|Up to 10 candidates| Merge PlanExecutor2 -->|Up to 10 candidates| Merge PlanExecutor3 -->|Up to 10 candidates| Merge Merge --> Result["Application receives up to 10 results"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Merge accent ``` ### Tiered index cache Executors cache index structures in memory, and extend that cache onto local disk when the disk tier is enabled. See [Tiered Index Cache](/oss/v0-41-0/enterprise/tiered-index-cache) for how the two tiers work together and how the disk tier's budget is shared and sized; ask your deployment operator about enabling it on your cluster. ### Create and query an IVF-RQ index Use the regular table API. These examples assume `table` is an open Enterprise table with a `vector` column and the query vector is compatible with that column. For connection setup, see [connect to LanceDB](/oss/v0-41-0/basics/catalog). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import IvfRq table.create_index("vector", config=IvfRq(num_bits=5, distance_type="cosine")) # Run after the background index build is complete. results = table.search(query_vector).distance_type("cosine").limit(10).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { Index } from "@lancedb/lancedb"; await table.createIndex("vector", { config: Index.ivfRq({ numBits: 5, distanceType: "cosine" }), }); // Run after the background index build is complete. const results = await table .vectorSearch(queryVector) .distanceType("cosine") .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; use lancedb::index::{vector::IvfRqIndexBuilder, Index}; use lancedb::query::{ExecutableQuery, QueryBase}; use lancedb::DistanceType; table .create_index( &["vector"], Index::IvfRq( IvfRqIndexBuilder::default() .num_bits(5) .distance_type(DistanceType::Cosine), ), ) .execute() .await?; // Run after the background index build is complete. let results: Vec<arrow_array::RecordBatch> = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10) .execute() .await? .try_collect() .await?; ``` Enterprise builds indexes in the background. Submitting index creation does not mean the index is ready; check index status before evaluating indexed search. These examples explicitly select 5 bits per dimension. See the shared docs for [RaBitQ and `num_bits`](/oss/v0-41-0/indexing/vector-index#using-rabitq), [index creation parameters](/oss/v0-41-0/indexing/vector-index#build-time-parameters), and [vector search](/oss/v0-41-0/search/vector-search#vector-search-with-ann-index). For the `fast`, `normal`, and `accurate` latency/recall modes, see [tuning `approx_mode`](/oss/v0-41-0/search/vector-search#tuning-approx-mode). The Rust SDK currently exposes that query setting; the examples above use the default mode. ## Distributed full-text search FTS work is organized by inverted index. Compatible operations targeting the same table and text column can execute together on executors over that index's segments. Operations targeting different indexed columns can execute separately, with their results combined on the query node according to the query. For example, suppose an `articles` table has separate FTS indexes on `title` and `body`. A query asks for rows whose title matches the exact term `vector` **or** whose body contains the phrase `nearest neighbor`: 1. The query node plans the title and body index searches separately. 2. Executors search the relevant segments of each index. 3. The query node combines the scored rows according to the cross-column query's semantics and returns the requested results. ### Local and global scoring Distributed FTS defaults to **local scoring**. For indexed searches, each executor uses statistics from its assigned segments to calculate BM25 scores. This avoids a separate statistics round, but document frequencies and average document lengths can differ between executors. Merging their scores can therefore produce a different ranking from scoring with statistics across the entire index. **Global scoring for indexed searches** adds a statistics round before search. The query node collects and aggregates document counts, token counts, and query-term document frequencies across the target FTS index. Executors then score with the shared statistics before the query node combines their results. The statistics are global to that index, not blended across all text columns in the table. Both modes combine results. The difference is the statistics used during scoring on executors; global mode does not rescore the returned rows on the query node. It trades an additional statistics round for consistent BM25 statistics across executors. When term frequencies and document lengths are similarly distributed across index segments, local scoring can produce rankings comparable to global scoring. If segments contain substantially different document populations, prefer global scoring for consistent statistics across the index, at the cost of an additional statistics round and higher query latency. Eligible flat searches over entirely unindexed text also use this setting. In **local mode**, the scoring corpus is split by ownership of table data. Each executor computes BM25 statistics over its assigned documents before candidate selection, then returns matching rows. This takes one FTS execution round without a global statistics barrier; the query node applies the final top-k. Changing executor ownership can change scores and ranking even when the table data is unchanged. In **global mode**, an eligible unindexed flat search sends its complete scoring corpus to a single executor, which computes statistics and scores together. This preserves global BM25 for that corpus without a separate statistics round. The query node still performs the final sorting and top-k. Inputs for flat search that cannot be safely partitioned retain their complete scoring domain. If executor capabilities or routing are unavailable, execution can remain on the query node. Global scoring is a query node setting, configured at the deployment level. See [full-text search](/oss/v0-41-0/search/full-text-search) for query syntax and [FTS indexes](/oss/v0-41-0/indexing/fts-index) for index configuration. ## Distributed data search A table can be larger than any single node's local storage. Enterprise keeps the durable table in object storage and distributes data reads and caches across executors. An executor needs capacity for its cached working set rather than a complete local copy of the table. With fragment-based data routing, reads for a data fragment go to a serving executor. Different fragments can be served and cached on different executors. The following example shows six fragments served by three executors: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB QueryNode["Query node<br/>Plan data reads and assemble results"] PlanExecutor1["Executor 1<br/>Read fragments 1 and 2<br/>Local NVMe disk cache"] PlanExecutor2["Executor 2<br/>Read fragments 3 and 4<br/>Local NVMe disk cache"] PlanExecutor3["Executor 3<br/>Read fragments 5 and 6<br/>Local NVMe disk cache"] Store[("Object storage<br/>Durable table fragments")] QueryNode -->|Read subplan| PlanExecutor1 QueryNode -->|Read subplan| PlanExecutor2 QueryNode -->|Read subplan| PlanExecutor3 PlanExecutor1 -->|Cache miss| Store PlanExecutor2 -->|Cache miss| Store PlanExecutor3 -->|Cache miss| Store classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Store accent ``` ### NVMe data caching The data page cache stores pages read from table fragments on **local disk, including NVMe SSDs**. On a cache hit, the executor reads the page from local disk; on a miss, it fetches the page from object storage and fills the cache for subsequent reads. The cache holds accessed pages, not necessarily every byte of each fragment assigned to an executor. See [Data Page Cache](/oss/v0-41-0/enterprise/data-page-cache) for how it's structured and sized. ## Inspect execution Use `analyze_plan()` (`analyzePlan()` in TypeScript) to understand how a query executes and troubleshoot slow searches. It runs the query and returns the execution plan with runtime metrics. Using the same table and query vector as above: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = table.search(query_vector).distance_type("cosine").limit(10) print(query.analyze_plan()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const query = table.vectorSearch(queryVector).distanceType("cosine").limit(10); console.log(await query.analyzePlan()); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::query::{ExecutableQuery, QueryBase}; use lancedb::DistanceType; let query = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10); println!("{}", query.analyze_plan().await?); ``` Inspect the plan to check which indexes are used, which operations run on query nodes or executors, and where execution time is spent. Compare index search with data retrieval to identify expensive work. Repeating the query can also help distinguish cold-cache reads from warm-cache performance. # Distributed Write Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-write How LanceDB Enterprise distributes a CTAS import's writes across plan executors. **Applies to:** Embedded ❌, Enterprise ✅ Distributed write applies specifically to importing data with `CREATE TABLE ... AS SELECT`: the query node that planned the statement partitions the source -- Parquet files from a HuggingFace dataset, or row-group ranges of an existing Lance dataset in object storage -- across plan executors, each of which writes its own uncommitted Lance data files and reports back. The query node collects those results and commits them together as the new table's first version; no separate coordinator service is involved. See [Architecture](/oss/v0-41-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Source<br/>HuggingFace Parquet, or an<br/>existing Lance dataset in<br/>S3 / GCS / Azure"] Q["Query node<br/>plans the CTAS,<br/>commits the result"] PE1["Plan executor<br/>writes uncommitted files"] PE2["Plan executor<br/>writes uncommitted files"] PE3["Plan executor<br/>writes uncommitted files"] S --> Q Q --> PE1 Q --> PE2 Q --> PE3 PE1 --> Q PE2 --> Q PE3 --> Q classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Q accent ``` An ordinary `INSERT` or `merge_insert`, from SQL or the SDK, does not distribute this way -- it runs as a single write, on whichever node or process executes it. Only a CTAS import fans the write itself out across machines. ## Write interfaces * [Import Datasets](/oss/v0-41-0/ingestion/import) for the CTAS syntax this distributes. * [Insert data](/oss/v0-41-0/ingestion/insert) and [Merge](/oss/v0-41-0/ingestion/merge-insert) for the ordinary, non-distributed write paths. * [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) for configuring the source a CTAS import reads from. # LanceDB Enterprise Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/index Features and benefits of LanceDB Enterprise. **LanceDB Enterprise** is the production deployment option for teams that want to run LanceDB as a private cloud or bring-your-own-cloud (BYOC) **multimodal lakehouse**. If you are new to multimodal lakehouses, the short version is this: LanceDB keeps vectors, metadata, and source data together in open table storage, while Enterprise adds the distributed infrastructure needed to serve real production workloads on top of that data. It is designed for teams that need more scale, more operational visibility, and more control than a single embedded process can provide. LanceDB Enterprise distributes query execution, indexing, maintenance and refresh work across the service, outside your application. If you need private deployments, high performance at extreme scale, or if you have strict security requirements, [reach out to our team](https://www.lancedb.com/contact) to set up a LanceDB Enterprise cluster in your environment. ![LanceDB Enterprise architecture](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/overview/lancedb-distributed.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=02f7f5f535f076989f0124b0b427d311) LanceDB Enterprise: the LanceDB SDK connects to the Enterprise service, where a query fleet, executor and cache fleets, the realtime engine, and a jobs fleet run on top of the Lance format and object storage. ## Why use LanceDB Enterprise? If you are evaluating LanceDB for a production AI system, Enterprise is built around three practical needs: handling very large vector workloads, running feature engineering close to the data, and operating the platform with production visibility. ### 1. Scale shared workloads LanceDB Enterprise is built for demanding workloads that exceed the capabilities of a single machine, whether from extremely large data volumes or a high number of concurrent queries. Instead of asking your application to own caching, query scaling, and maintenance, Enterprise turns those into **platform** capabilities. This matters when your AI application moves past a prototype and starts serving real users, larger datasets, and more concurrent requests. * **Low-latency tiered cache**: Enterprise keeps frequently read data closer to compute, so common queries do not need to fetch the same data from object storage over and over again. That helps reduce wait times and makes performance more predictable as traffic increases. * **Horizontal query throughput**: Instead of relying on one application process to answer every query, Enterprise can spread search traffic across multiple nodes. This lets teams add capacity as usage grows, rather than re-architecting the application each time demand spikes. * **Background maintenance**: Enterprise builds indexes and compacts tables on background workers, reducing the maintenance work your application needs to schedule. ### 2. Feature engineering For many teams, retrieval is only part of the problem. They also need a reliable way to derive new columns, run backfills, and keep feature pipelines close to the data they already store in LanceDB. This is what [feature engineering](/oss/v0-41-0/feature-engineering) enables. * **Derived features**: Create new columns from existing data and user-defined logic without standing up a separate feature platform first. * **Large-table backfills**: Update or recompute features across large datasets without wiring your own distributed batch system around LanceDB Embedded tables. * **Shared workflows**: Manage feature engineering work -- clusters, jobs, and their configuration -- in one place. ### 3. Enterprise-grade monitoring Production retrieval systems need more than search or training performance. Teams also need to observe the system, choose how it is deployed, and satisfy security and compliance requirements. * **Metrics and traces**: Integrates with existing observability systems for monitoring and distributed tracing using OpenTelemetry. * **Deployment choice**: Run LanceDB as a managed deployment or install it inside your own cloud account with [BYOC](#deployment-and-governance). * **Private networking and compliance**: Designed for production environments that need encryption at rest, private connectivity options, and compliance coverage such as SOC 2 Type II and HIPAA. ## Deployment and governance LanceDB Embedded is included as part of your binary, Docker, or serverless function. The footprint is small, and no extra services run beside it. LanceDB Enterprise comes in three deployment models, all supporting AWS, GCP, and Azure: **Managed** is a private deployment of LanceDB Enterprise: applications run in cloud accounts managed by LanceDB, in the same location as your client applications. This hands-off approach suits teams that do not want to manage the infrastructure themselves. LanceDB can provision either a public or private load balancer for access. **Bring-your-own-cloud (BYOC)** installs LanceDB Enterprise into your own cloud account, so data never leaves it. Reach for this when data-residency requirements preclude data from leaving your account, or when other applications need to access the object storage directly. An identity is provisioned in your account with permissions to manage the infrastructure. **Custom deployments** cover requirements beyond the two models above -- [reach out to our support team](https://www.lancedb.com/contact). Both Managed and BYOC are designed for private networking, compliance, and operational oversight. ## See how Enterprise compares to Embedded > [card] [Embedded vs Enterprise](/oss/v0-41-0/basics/embedded-vs-enterprise) > > A feature-by-feature comparison: architecture, latency, throughput, caching, maintenance, and day-to-day usage > differences. [Reach out to us](https://www.lancedb.com/contact) to set up LanceDB Enterprise in your organization, or to arrange a proof of concept for your workload. # Tiered Index Cache Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/tiered-index-cache How LanceDB Enterprise caches deserialized index structures across memory and local disk. **Applies to:** Embedded ❌, Enterprise ✅ The tiered index cache holds deserialized vector, full-text and scalar index structures in memory, backed by a local-disk tier beneath it. When memory fills, the cache serializes evicted entries and spills them to disk instead of dropping them; a later hit on a spilled entry promotes it back into memory. This lets a plan executor serve an index larger than its available memory without re-reading and re-deserializing it from object storage on every eviction. See [Architecture](/oss/v0-41-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Index lookup"] --> M{"In memory?"} M -->|hit| Return["Served from memory"] M -->|miss| D{"Spilled to disk?"} D -->|hit| Promote["Deserialized,<br/>promoted into memory,<br/>served"] D -->|miss| O[("Object storage")] O --> Fill["Deserialized,<br/>loads into memory,<br/>served"] Evict["Memory eviction"] -.->|serialize, don't drop| D classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` ## Sharing the disk budget Where enabled, the index disk tier and the [data page cache](/oss/v0-41-0/enterprise/data-page-cache)'s disk tier draw from one combined, configurable disk allocation per executor, split between the two tiers so neither one needs its own dedicated volume. ## Why it matters Vector, full-text, and scalar indexes can easily outgrow available memory on large tables. Without this cache, an eviction means re-reading and re-deserializing that index from object storage on the next request -- slow, and repeated on every eviction. Spilling to local disk instead keeps index lookups fast even when the working set is larger than memory, without giving every executor enough memory to hold every index at once. [Contact us](https://www.lancedb.com/contact) to learn more about how caching is sized and tuned for your workload. ## Index cache interfaces * [Cache Prewarm](/oss/v0-41-0/enterprise/cache-prewarm) for warming this cache ahead of the first request. * [Data Page Cache](/oss/v0-41-0/enterprise/data-page-cache) for the related cache that holds raw table data pages instead of deserialized index structures. * [Vector indexes](/oss/v0-41-0/indexing/vector-index), [full-text indexes](/oss/v0-41-0/indexing/fts-index), and [scalar indexes](/oss/v0-41-0/indexing/scalar-index) for the index types this cache serves. # Create a computed column Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/add-computed-column Declare a column from a SQL expression. Nothing is evaluated until you refresh it. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/oss/v0-41-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Lance can write a new column without rewriting the columns already in the table. That matters most on a table that also holds large images, video or embeddings, where rewriting everything just to add one small derived field would be wasteful. See [Lance format](/oss/v0-41-0/basics/lance) for the storage model this relies on. A computed column is how LanceDB formalizes that capability for feature engineering specifically: instead of writing the derived values immediately, it is declared with an expression and starts with no values. Declaring it is cheap on any table size, because nothing is evaluated until [a refresh](/oss/v0-41-0/feature-engineering/refresh-column) asks for it. > [!NOTE] > > `computed` requires LanceDB Enterprise. Ordinary eager `add_columns` > transforms, without `computed`, remain available in LanceDB Embedded. ## Fill a column with a Function Enterprise When the value cannot be expressed in SQL -- an embedding, a model call, an image decode -- the column is filled by a registered [function](/oss/v0-41-0/management/function) instead of a SQL expression. It needs a deployment with Functions enabled. Connect with an [Enterprise connection](/oss/v0-41-0/basics/catalog#enterprise). Continuing the [`caption` Function](/oss/v0-41-0/curation/create-function#chain) registered in Create a Function, against a `frames` table that already has a `jpeg` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} version = db.create_function_async(caption).wait() table.add_columns({"caption": version(jpeg=col("jpeg"))}) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames ADD COLUMN caption AS caption(jpeg) WITH (version = 'fv_1') ``` A Function application is called with its parameters bound to source columns through `col(...)`, keyed by the output column name. It commits a new, empty table version the same way a SQL expression does, so the usual [versioning](/oss/v0-41-0/management/table#versioning) applies. Both a Function application and a SQL expression accept `auto_refresh_enabled` and `auto_refresh_interval_seconds`, and both refresh and toggle the same way; see [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh). Enterprise 1.12.0 supports the automatic-refresh enable and interval settings above. Aggregate resource budgets for automatic Function refreshes are not supported in this release. For a budget on an explicit refresh, use the [SQL refresh options](/oss/v0-41-0/feature-engineering/refresh-column#resources). ## Fill a column with a SQL expression A value that SQL can compute doesn't need a Function. Declare it with `computed` instead, as an expression evaluated over the row: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) # AddColumnsResult(version=2) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 ``` That commits a new table version with the column present and empty. It is an ordinary table version, so the usual [versioning](/oss/v0-41-0/management/table#versioning) applies, including that you can travel back to before the column existed. The expression can reference any column in the table, including another computed column -- declaration order is dependency order, so it may reference one declared earlier in the same mapping, but not one declared after it: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns(computed={ "power_score": "cast(x as double) / 2.0", "is_strong": "power_score > 0.5", }) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN power_score AS cast(x as double) / 2.0 ALTER TABLE computed_demo ADD COLUMN is_strong AS power_score > 0.5 ``` The functions available are the ones the [SQL dialect](/oss/v0-41-0/sql/dql/functions) documents. A literal in the expression has to fit the column it meets: `x / 2.0` is refused when `x` is an integer column, so write `cast(x as double) / 2.0`. > [!WARNING] > > Keep the expression to top-level columns. A column refresh can fail on an > expression that reads a field inside a struct, such as > `stats.magic + stats.strength`. Try a new expression on a small table first. ## Compute now or on refresh `add_columns` takes either, and the difference matters: * **SQL expressions in `transforms`** are evaluated *now*, for every row, as part of the call. Good for a small table, or a column you want populated immediately. A `FunctionApplication` passed through `transforms` instead declares empty Function-bound columns, which a refresh fills; that needs a deployment with Functions enabled, and the embedded library refuses it. * **`computed`** stores the expression and evaluates nothing. The column is committed empty and filled later by [`refresh_column`](/oss/v0-41-0/feature-engineering/refresh-column). `computed` and `transforms` cannot be combined in one call. Reach for `computed` when the table is large enough that you would rather control when the work happens. Automatic refresh is on by default for each computed column, and takes effect when your Enterprise deployment enables its refresh scheduler. Until then, call [`refresh_column`](/oss/v0-41-0/feature-engineering/refresh-column) yourself. Pass `auto_refresh_enabled=False` to opt a column out, or `auto_refresh_interval_seconds` to set how often it refreshes: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns( computed={"doubled": "x * 2"}, auto_refresh_interval_seconds=300, ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 WITH (auto_refresh_interval_seconds = 300) ``` See [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for the full behavior, including how to change the setting later. An eager `transforms` call looks like this, starting from a small product table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_add_example", data, mode="overwrite") ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a discounted price column (10% discount) table.add_columns({"discounted_price": "cast((price * 0.9) as float)"}) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE schema_evolution_add_example ADD COLUMN discounted_price AS cast((price * 0.9) as float) ``` SQL's `ADD COLUMN ... AS` always declares the column empty and defers the expression to a refresh, the same as `computed` does -- there is no SQL form of eager `transforms`. The Python call above is the only way to get discounted_price filled immediately; declaring it in SQL fills it only once [`REFRESH COLUMN`](/oss/v0-41-0/sql/dml/refresh-column) runs. For feature engineering on large existing tables, group related derived features into one `add_columns` call instead of running many separate writes: this creates one new table version for the schema change and computes every new column from the existing rows in it, rather than growing the table's version history with many small updates. > [!NOTE] > > On local tables, Python `add_columns` also accepts pandas or Polars > DataFrames, PyArrow Tables, RecordBatches, RecordBatchReaders, and iterables > of batches. Pass only the new columns, with exactly one row per current live > table row in storage scan order. DataFrame indexes are ignored, and reader > batch boundaries need not match table fragments. Keep the table unchanged > between computing the values and adding them. Readers are consumed once. > > Data inputs cannot be combined with `computed` columns and are not supported > on remote tables. Python callables and batch UDFs are not accepted; compute > those values first, then pass the result as a DataFrame or reader. ## Change columns used by a computed column > [!WARNING] > > While a computed column's declaration references another column, that column > cannot be renamed, retyped, or dropped. Drop the computed column first > if you need to change one of its inputs. This is worth knowing before deriving a column from something you expect to reshape later. Dropping the computed column releases the constraint. ## Related guides > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > Fill the rows that lack values. > [card] [Functions](/oss/v0-41-0/management/function) > > Fill a column with Python. # Feature engineering Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/index Derive columns and tables from data already in the lakehouse, without moving it somewhere else to compute. Use feature engineering to turn raw data into features for search, analysis and model training. LanceDB stores derived columns and materialized views alongside the source data, so you can reuse the results across those workflows. [Functions](/oss/v0-41-0/management/function) and [materialized views](/oss/v0-41-0/feature-engineering/materialized-views) are ordinary [catalog objects](/oss/v0-41-0/basics/catalog). Create them through the SDK or SQL, then refresh the derived data when its inputs change. > [!NOTE] > > In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/oss/v0-41-0/sql/ddl/table#alter) to declare a column and [REFRESH COLUMN](/oss/v0-41-0/sql/dml/refresh-column) to fill it. ## Computed columns and materialized views Computed columns and materialized views both keep derived data in the lakehouse, but they fill it differently, and the difference decides what a refresh costs: | | Computed column | Materialized view | | - | - | - | | Declaring or creating it | records the expression; no values are written | runs the query and stores its rows, unless created empty | | A refresh | fills rows with no value and recomputes rows whose inputs changed | rebuilds the view completely from its source query | | A refresh when nothing changed | fills nothing | still rebuilds the view and commits a new version | | In LanceDB Enterprise | runs as a [job](/oss/v0-41-0/basics/jobs) | runs as a server-side materialization job | ### Computed columns fill incrementally A [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) separates **declaring** from **filling**: * Declaring is cheap and immediate. It records the expression in the schema and commits a new table version, with no data written. It does not evaluate the expression over existing rows. * Fill the column with a separate refresh call that you can retry. In LanceDB Enterprise, submit the refresh as a [job](/oss/v0-41-0/basics/jobs) and track its progress. **Refresh new and changed rows.** A [refresh](/oss/v0-41-0/feature-engineering/refresh-column) gives values to rows that lack them and recomputes rows whose inputs changed since they were computed. It leaves the rest alone, so calling it twice is not twice the work, and appending rows means the next refresh handles only the new ones. **Computed values update when you refresh.** If a column derives from `price` and a row's `price` is later updated, the derived value keeps its old value until the next refresh recomputes it. Schedule refreshes after changing the source data when consumers need up-to-date features. ### Materialized views store query results A [materialized view](/oss/v0-41-0/feature-engineering/materialized-views) has no separate declaration step: creating one runs its query and stores the result, so the view is ready to read. A refresh rebuilds the stored result completely from the source query; see [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) for the full behavior, including automatic refresh. Enterprise runs materialization on remote compute, as a server-side job. ## Choose a feature engineering workflow | | What it produces | Filled by | Available | | - | - | - | - | | [View](/oss/v0-41-0/feature-engineering/view) | a saved query, no stored rows of its own | nothing -- it runs on every read | Enterprise | | [Computed column](/oss/v0-41-0/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Enterprise | | [Materialized view](/oss/v0-41-0/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Enterprise | | [Function](/oss/v0-41-0/management/function) | a computed column filled by Python | registered code | Enterprise | | [Geneva](/oss/v0-41-0/geneva) | columns filled by Python, for existing pipelines | the `geneva` package | Enterprise | **A view** has no refresh and no staleness window, because it stores the query rather than its result. Reach for one first, before a computed column or a materialized view, when the query is cheap enough to simply re-run on every read. **Computed columns** are the common case: a column declared with a SQL expression, filled by [a refresh](/oss/v0-41-0/feature-engineering/refresh-column). **Materialized views** derive a whole table (a filtered, projected, or aggregated view of a source) and bring it up to date on each refresh. The result is an ordinary table: queryable, indexable, searchable. **Functions** run Python where the data is, for work SQL cannot express: embedding a column, calling a model, decoding an image. Registered once, versioned, then applied as a column. They are the way to do that on a deployment; [Geneva](/oss/v0-41-0/geneva) remains available for existing pipelines. A materialized view can select computed columns. A computed column can be filled by a registered function. ## Where the work runs Enterprise Locally, a refresh runs in your process. With LanceDB Enterprise it runs across the cluster, and the API reflects that: `refresh_column` raises, and `refresh_column_async` returns a [job](/oss/v0-41-0/basics/jobs) handle instead. Computed columns are off by default in LanceDB Enterprise, and its administrator has to enable them before a column can be declared there. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("power_score") result = job.wait() result.rows_assigned ``` A backfill over a large table can therefore be started, left, and checked on from a different process: the connection does not have to stay open. Enterprise manages the compute for the refresh. Declaring a computed column doesn't refresh it on a schedule unless your deployment enables automatic refresh; see [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh). That is also why a function must declare the environment it needs. ## Recovering from a failure A function that raises fails the job. There is no per-row retry or skip policy in the function definition, so a function calling a flaky external service should handle that itself, inside the function body. When a refresh fails, fix the cause and run the refresh again. The new refresh fills what is still empty or stale. How much of the failed run was kept depends on where it ran (see [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column#failures)), and a retry can recompute values that were already written, so do not count on it costing only the rows that did not complete. ## Related guides > [card] [Create a view](/oss/v0-41-0/feature-engineering/view) > > A saved query, with no storage or refresh of its own. > [card] [Create a computed column](/oss/v0-41-0/feature-engineering/add-computed-column) > > Declare a column from a SQL expression. > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > Fill the rows that lack values, locally or as a job. > [card] [Create a materialized view](/oss/v0-41-0/feature-engineering/materialized-views) > > Store a query's result as a table. > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > Bring a derived table up to date with its source. > [card] [Functions](/oss/v0-41-0/management/function) > > Register Python to fill a column with. # Create a view Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/view Define a derived dataset as a saved query, with no storage or refresh of its own. **Applies to:** Embedded ❌, Enterprise ✅ A view is the lightest way to derive a feature-engineered dataset: it stores a **query**, not rows, so there is nothing to refresh and nothing that can fall out of date. Reach for one before [a computed column](/oss/v0-41-0/feature-engineering/add-computed-column) or [a materialized view](/oss/v0-41-0/feature-engineering/materialized-views) when the underlying query is cheap enough to simply re-run on every read. ## Define a view A view over a products table, selecting and deriving a few columns: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE VIEW "discounted_products" AS SELECT id, name, price, price * 0.9 AS sale_price FROM "products" WHERE in_stock = true ``` The statement resolves the view's schema from the query at creation time. Anything the [SQL dialect](/oss/v0-41-0/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions -- the same expressiveness as [a computed column's](/oss/v0-41-0/feature-engineering/add-computed-column#expressions) SQL expression, just over a whole derived table instead of one column. ## Read it like a table ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM "discounted_products" WHERE sale_price < 20 ``` Every read runs the saved query against current data, so `sale_price` reflects whatever `price` is right now -- there is no staleness window to reason about, unlike a materialized view between refreshes. A predicate applied when reading the view composes with the query inside it, rather than filtering the view's output afterward, so a selective filter does not pay for rows the view would have produced and then discarded. ## When to use a view instead | | View | Computed column / materialized view | | - | - | - | | Stores | the query | derived values | | Freshness | always current | as of the last refresh | | Read cost | the full query, every read | a column or table scan | | Write cost | none | a refresh | Reach for a view when the query is cheap, or when reading a stale value would be wrong for the workload. Reach for a computed column or a materialized view when the query is expensive and the data changes less often than it is read. See [View](/oss/v0-41-0/sql/ddl/view#choosing) for the full SQL reference comparison, including the separate privileges each one needs. ## What to read next > [card] [View](/oss/v0-41-0/sql/ddl/view) > > CREATE VIEW, DROP VIEW, and listing views alongside tables. > [card] [Create a materialized view](/oss/v0-41-0/feature-engineering/materialized-views) > > The stored-rows counterpart, and when a refresh is worth paying for. # LanceDB Source: https://docs.lancedb.com/oss/v0-41-0/index Multimodal lakehouse for AI. **LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need one data layer for curation, feature engineering, search and retrieval, and model training. It is built on top of [Lance](/oss/v0-41-0/basics/lance), an open-source lakehouse format designed for multimodal AI data. Move from data exploration to model training on one unified platform without needing to manage a fragmented stack of storage, feature, retrieval, and training systems. ## Train on the right data faster Search, curate, and train at petabyte scale, with all your multimodal data in one table. Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. ## Accelerate the data flywheel for model research Keep your AI data in one table. Find the failure, fix the data, and retrain. **1. Find a curated training subset for every failure case** Start from one failed grasp or evaluation example. [Search](/oss/v0-41-0/search/) multimodal data, metadata, and embeddings together, retrieve similar examples, and [curate](/oss/v0-41-0/curation) them into a targeted training subset. **2. A single dataset for every modality** Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without pipelines to keep them in sync. Table [versions](/oss/v0-41-0/management/table#versioning) let you trace each training run back to the exact data it used. **3. More hillclimbing, less babysitting preprocessing jobs** Define the [computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) and [materialized views](/oss/v0-41-0/feature-engineering/materialized-views) your experiment needs, such as extracted features or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background jobs on the cluster instead of in your code. **4. Higher GPU utilization, faster convergence** Keep GPUs fed. [`StreamingDataset`](/oss/v0-41-0/training/data-loading) streams multimodal training data into PyTorch with globally shuffled, deterministic batches, combining fast random access with high-throughput scans. Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected through the same table model, whether a workflow uses one table or several related ones. ## Architecture: Embedded and Enterprise LanceDB ships as two offerings on the same [Lance](/oss/v0-41-0/basics/lance) format and table model, which stores table data, versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale, managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and retrieval, and training workflows. > [card] [LanceDB Embedded](/oss/v0-41-0/basics/lancedb-embedded) > > An open-source, embedded retrieval library that runs inside your application process, with no separate > database server to deploy. > [card] [LanceDB Enterprise](/oss/v0-41-0/enterprise/index) > > A distributed multimodal lakehouse service for production workloads that need managed infrastructure and > higher-throughput workflows. See [Embedded vs Enterprise](/oss/v0-41-0/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including architecture, latency, throughput, and day-to-day usage differences. ## Projects using LanceDB ### Training * [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a fraction of the disk footprint. * [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on the stable-worldmodel platform and its LanceDB data layer. * [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace LeRobot datasets with faster loading across robotics datasets. ### Agentic applications * [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. * [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent memory across sessions, using LanceDB as one of its vector store backends. * [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, features, and training or memory access patterns in one format instead of scattering them across task-specific stores. ## Start with your workload > [card] [Ingest your data](/oss/v0-41-0/ingestion) > > Create tables, append records, and update or delete rows as your data changes. > [card] [Build search and retrieval](/oss/v0-41-0/search/) > > Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. > [card] [Curate training data](/oss/v0-41-0/curation) > > Profile, sample, chunk, join, and deduplicate records before training on them. > [card] [Engineer features in place](/oss/v0-41-0/feature-engineering) > > Derive computed columns and materialized views without moving data elsewhere. > [card] [Load data into PyTorch](/oss/v0-41-0/training/data-loading) > > Use LanceDB tables and permutations for projected, shuffled, random-access training reads. > [card] [Manage catalog objects](/oss/v0-41-0/management) > > Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. # Creating a table Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/create-table Create a table from records or a schema and choose input formats. **Applies to:** Embedded ✅, Enterprise ✅ Create a table from existing records, or define an empty table before data arrives. Define a schema to specify column types, allow or disallow missing values, and set the size of your vectors. ## Create a table with data The Python, TypeScript and Rust blocks below illustrate the corresponding input formats; each assumes a `db` connection already open, as in [Connect to LanceDB](/oss/v0-41-0/basics/catalog). For a complete connection-to-result program, expand [the write workflow](#complete-example). Table names follow the [naming rules](/oss/v0-41-0/basics/naming). ### From list of objects You can provide a list of objects to create a table. The Python and TypeScript SDKs support lists/arrays of records. The Rust example converts structs to Arrow batches. In Python, pass a list or other batch-like object; a single bare `dict` or single `LanceModel` is rejected. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1}, ] db.create_table("test_table", data, mode="overwrite") tbl = db["test_table"] tbl.head() print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} type Location = { vector: number[]; lat: number; long: number; }; const data: Location[] = [ { vector: [1.1, 1.2], lat: 45.5, long: -122.7 }, { vector: [0.2, 1.8], lat: 40.1, long: -74.1 }, ]; const table = await db.createTable("test_table", data, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} struct Location { vector: [f32; 2], lat: f32, long: f32, } let data = vec![ Location { vector: [1.1, 1.2], lat: 45.5, long: -122.7, }, Location { vector: [0.2, 1.8], lat: 40.1, long: -74.1, }, ]; let schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( data.iter() .map(|row| Some(row.vector.iter().copied().map(Some).collect::<Vec<_>>())), 2, ), ), Arc::new(Float32Array::from_iter_values( data.iter().map(|row| row.lat), )), Arc::new(Float32Array::from_iter_values( data.iter().map(|row| row.long), )), ], ) .unwrap(); let reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema.clone())); let table = db .create_table("test_table", reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### If the table already exists By default, creating a table fails if its name is already in use. Choose whether to open that table or overwrite it. #### Open the existing table Use `exist_ok=True` in Python or `existOk: true` in TypeScript to return the existing table without changing its contents. This is useful for setup code that may run more than once. Any data supplied to the create call is ignored when the table already exists. Inspect the returned table's schema if your code depends on specific columns or types. Opening an existing table does not change its schema to match the data supplied in the create call. #### Overwrite the table Use `mode="overwrite"` in Python or `mode: "overwrite"` in TypeScript to replace the existing table with the supplied data and schema. Choose this only when you intend to replace its previous contents. The following Python program demonstrates both choices: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("conflict_table", data) # Idempotent open: reuse the existing table if it exists. # The provided data is ignored; the schema is validated against the # existing table and a mismatch raises an error. tbl = db.create_table("conflict_table", data, exist_ok=True) # Overwrite: replace the contents with the provided data. tbl = db.create_table("conflict_table", data, mode="overwrite") print("Rows:", tbl.count_rows()) ``` > [!NOTE] > > `exist_ok` / `existOk` does not append the provided data to an existing table. Use > [`table.add()`](/oss/v0-41-0/ingestion/insert) for that. If you need to ensure a table exists *and* > contains specific rows, choose an explicit [merge policy](/oss/v0-41-0/ingestion/merge-insert). Creating an empty table > and repeatedly appending the same batch does not deduplicate it. ### From a custom schema You can define a custom Arrow schema for the table. This is useful when you want to have more control over the column types and metadata. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa custom_schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 4)), pa.field("lat", pa.float32()), pa.field("long", pa.float32()), ] ) data = [ {"vector": [1.1, 1.2, 1.3, 1.4], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8, 0.4, 3.6], "lat": 40.1, "long": -74.1}, ] tbl = db.create_table( "my_table_custom_schema", data, schema=custom_schema, mode="overwrite" ) print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const customSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("lat", new arrow.Float32()), new arrow.Field("long", new arrow.Float32()), ]); const customSchemaData = lancedb.makeArrowTable( [ { vector: [1.1, 1.2, 1.3, 1.4], lat: 45.5, long: -122.7 }, { vector: [0.2, 1.8, 0.4, 3.6], lat: 40.1, long: -74.1 }, ], { schema: customSchema }, ); const customSchemaTable = await db.createTable( "my_table_custom_schema", customSchemaData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let custom_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let custom_batch = RecordBatch::try_new( custom_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(1.1), Some(1.2), Some(1.3), Some(1.4)]), Some(vec![Some(0.2), Some(1.8), Some(0.4), Some(3.6)]), ], 4, ), ), Arc::new(Float32Array::from(vec![45.5, 40.1])), Arc::new(Float32Array::from(vec![-122.7, -74.1])), ], ) .unwrap(); let custom_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(custom_batch)].into_iter(), custom_schema.clone())); let custom_table = db .create_table("my_table_custom_schema", custom_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` An explicit schema also determines which columns accept missing values (`null`). If later writes omit a non-nullable column, or provide actual nulls for it, ingestion fails; nullable columns can be omitted or written with null values. Without an explicit schema, Python infers list-like vector values as fixed-size `float32` vector fields from the observed dimension. For images, audio, video, or other binary columns whose payloads should load on demand, declare a [blob column](/oss/v0-41-0/management/table#multimodal-blob-v2) in the schema. For Python ingestion, malformed vectors fail by default (`on_bad_vectors="error"`). This includes vectors with incorrect sizes, NaNs, or null components, including pandas NaNs converted to Arrow nulls. Use `"drop"` to remove affected rows, or `"null"` to replace affected vectors with nulls. Use `"fill"` to replace NaN or null components with `fill_value` while preserving valid components. This also pads short vectors with `fill_value` and truncates long vectors to the expected dimension. ### From an Arrow Table You can also create LanceDB tables directly from Arrow tables. Rust uses an Arrow `RecordBatchReader` for the same Arrow-native ingest flow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa dim = 16 total = 2 schema = pa.schema( [ pa.field("vector", pa.list_(pa.float16(), dim)), pa.field("text", pa.string()), ] ) data = pa.Table.from_arrays( [ pa.array( [np.random.randn(dim).astype(np.float16) for _ in range(total)], pa.list_(pa.float16(), dim), ), pa.array(["foo", "bar"]), ], ["vector", "text"], ) tbl = db.create_table("f16_tbl", data, schema=schema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const arrowSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 16, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("text", new arrow.Utf8()), ]); const arrowData = lancedb.makeArrowTable( [ { vector: Array(16).fill(0.1), text: "foo" }, { vector: Array(16).fill(0.2), text: "bar" }, ], { schema: arrowSchema }, ); const arrowTable = await db.createTable("f32_tbl", arrowData, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let arrow_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 16), false, ), Field::new("text", DataType::Utf8, false), ])); let arrow_batch = RecordBatch::try_new( arrow_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1); 16]), Some(vec![Some(0.2); 16])], 16, ), ), Arc::new(StringArray::from(vec!["foo", "bar"])), ], ) .unwrap(); let arrow_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(arrow_batch)].into_iter(), arrow_schema.clone())); let arrow_table = db .create_table("arrow_table_example", arrow_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### From a Pandas DataFrame Python Only ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pandas as pd data = pd.DataFrame( { "vector": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]], "lat": [45.5, 40.1], "long": [-122.7, -74.1], } ) db.create_table("my_table_pandas", data, mode="overwrite") db["my_table_pandas"].head() ``` > [!NOTE] > > Data is converted to Arrow before being written to disk. For maximum control over how data is saved, either provide the PyArrow schema to convert to or else provide a PyArrow Table directly. > [!NOTE] > > The **`vector`** column needs to be a [Vector](/oss/v0-41-0/integrations/data/pydantic#vector-field) (defined as [pyarrow.FixedSizeList](https://arrow.apache.org/docs/python/generated/pyarrow.list_.html)) type. ### From a Polars DataFrame Python Only Pass a Polars DataFrame as input. Install `polars` for this example; the conversion preserves the table structure through Arrow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import polars as pl data = pl.DataFrame( { "vector": [[3.1, 4.1], [5.9, 26.5]], "item": ["foo", "bar"], "price": [10.0, 20.0], } ) tbl = db.create_table("my_table_pl", data, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ### From Pydantic Models Python Only When you create an empty table without data, you must specify the table schema. LanceDB supports creating tables by specifying a PyArrow schema or a specialized Pydantic model called `LanceModel`. For example, the following Content model specifies a table with 5 columns: `movie_id`, `vector`, `genres`, `title`, and `imdb_id`. When you create a table, you can pass the class as the value of the `schema` parameter to `create_table`. The `vector` column is a `Vector` type, which is a specialized Pydantic type that can be configured with the vector dimensions. It is also important to note that LanceDB only understands subclasses of `lancedb.pydantic.LanceModel` (which itself derives from `pydantic.BaseModel`). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector class Content(LanceModel): movie_id: int vector: Vector(128) genres: str title: str imdb_id: int @property def imdb_url(self) -> str: return f"https://www.imdb.com/title/tt{self.imdb_id}" tbl = db.create_table("movielens_small", schema=Content, mode="overwrite") print("Rows:", tbl.count_rows()) ``` #### Nested schemas Sometimes your data model may contain nested objects. For example, you may want to store the document string and the document source name as a nested Document object: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pydantic import BaseModel class Document(BaseModel): content: str source: str ``` This can be used as the type of a LanceDB table column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector from pydantic import BaseModel class Document(BaseModel): content: str source: str class NestedSchema(LanceModel): id: str vector: Vector(1536) document: Document tbl = db.create_table("nested_table", schema=NestedSchema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` This creates a struct column called "document" that has two subfields called "content" and "source": ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} In [28]: tbl.schema Out[28]: id: string not null vector: fixed_size_list<item: float>[1536] not null child 0, item: float document: struct<content: string not null, source: string not null> not null child 0, content: string not null child 1, source: string not null ``` #### Validators Because `LanceModel` inherits from Pydantic's `BaseModel`, you can combine them with Pydantic's [field validators](https://docs.pydantic.dev/latest/concepts/validators). The example below shows how to add a validator to ensure that only valid timezone-aware datetime objects are used for a `created_at` field. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import datetime from zoneinfo import ZoneInfo from lancedb.pydantic import LanceModel from pydantic import Field, ValidationError, ValidationInfo, field_validator tzname = "America/New_York" tz = ZoneInfo(tzname) class TestModel(LanceModel): dt_with_tz: datetime = Field(json_schema_extra={"tz": tzname}) @field_validator("dt_with_tz") @classmethod def tz_must_match(cls, dt: datetime) -> datetime: assert dt.tzinfo == tz return dt ok = TestModel(dt_with_tz=datetime.now(tz)) try: TestModel(dt_with_tz=datetime.now(ZoneInfo("Asia/Shanghai"))) assert 0 == 1, "this should raise ValidationError" except ValidationError: print("A ValidationError was raised.") pass ``` The example catches a `ValidationError` for the timestamp with a different timezone. A validator runs when the Pydantic model is constructed; declaring a model as the table schema does not make every later write run that validator. > [!NOTE] > > Datasets too large to pass to `create_table` at once are covered separately; > see [Insert data](/oss/v0-41-0/ingestion/insert#large-datasets) for batches, file-backed > input and write parallelism. ## Create empty table You can create an empty table for scenarios where you want to add data to the table later. An example would be when you want to collect data from a stream/external file and then add it to a table in batches. An empty table can be initialized via an Arrow schema. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 2)), pa.field("item", pa.string()), pa.field("price", pa.float32()), ] ) tbl = db.create_table("test_empty_table", schema=schema, mode="overwrite") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const emptySchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 2, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("item", new arrow.Utf8()), new arrow.Field("price", new arrow.Float32()), ]); const emptyTable = await db.createEmptyTable( "test_empty_table", emptySchema, { mode: "overwrite", }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let empty_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("item", DataType::Utf8, false), Field::new("price", DataType::Float32, false), ])); let empty_table = db .create_empty_table("test_empty_table", empty_schema) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` Alternatively, define the schema with `LanceModel`, a Pydantic model class provided by `lancedb.pydantic`. Its `Vector` type declares a fixed vector dimension. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector class Item(LanceModel): vector: Vector(2) item: str price: float tbl = db.create_table( "test_empty_table_new", schema=Item.to_arrow_schema(), mode="overwrite" ) print("Rows:", tbl.count_rows()) ``` Once the empty table has been created, you can append to it or modify its contents, as explained in [Ingesting data](/oss/v0-41-0/ingestion). ## Open an existing table You can open an existing table by specifying the name of the table to the `open_table` / `openTable` method. If you forget the name of your table, you can always get a listing of all table names. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("test_table", data, mode="overwrite") # List table names print(db.list_tables().tables) # Open existing table tbl = db.open_table("test_table") print("Rows:", tbl.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const openTableData = [{ vector: [1.1, 1.2], lat: 45.5, long: -122.7 }]; await db.createTable("test_table_open", openTableData, { mode: "overwrite", }); console.log(await db.tableNames()); const openedTable = await db.openTable("test_table_open"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let open_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), Field::new("long", DataType::Float32, false), ])); let open_batch = RecordBatch::try_new( open_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(1.1), Some(1.2)])], 2, ), ), Arc::new(Float32Array::from(vec![45.5])), Arc::new(Float32Array::from(vec![-122.7])), ], ) .unwrap(); let open_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(open_batch)].into_iter(), open_schema.clone())); db.create_table("test_table", open_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); println!("{:?}", db.table_names().execute().await.unwrap()); let opened_table = db.open_table("test_table").execute().await.unwrap(); ``` ## Drop a table Use the `drop_table()` method on the database to remove a table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5}] db.create_table("my_table", data, mode="overwrite") # Drop the table db.drop_table("my_table") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.createTable("my_table", [{ vector: [1.1, 1.2], lat: 45.5 }], { mode: "overwrite", }); await db.dropTable("my_table"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let drop_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), false, ), Field::new("lat", DataType::Float32, false), ])); let drop_batch = RecordBatch::try_new( drop_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(1.1), Some(1.2)])], 2, ), ), Arc::new(Float32Array::from(vec![45.5])), ], ) .unwrap(); let drop_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(drop_batch)].into_iter(), drop_schema.clone())); db.create_table("my_table", drop_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); db.drop_table("my_table", &[]).await.unwrap(); ``` Dropping a table removes the table object. Deleting rows keeps the table and changes its contents; retained versions and cleanup are described in [Garbage Collection](/oss/v0-41-0/maintenance/cleanup). On a local database, dropping a table that does not exist raises an error; in Python, pass `ignore_missing=True` to suppress it. A deployment may report success instead, depending on how it stores its catalog, so do not rely on the error to tell you a table was missing. Python's deployment connection does not take `ignore_missing`. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Define Storage Integration Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/define-storage-integration Set up a reusable credential for AWS, GCP, Azure or HuggingFace before importing data from it. **Applies to:** Embedded ❌, Enterprise ✅ Before you can [import data](/oss/v0-41-0/ingestion/import) from external storage or [attach an existing database](/oss/v0-41-0/ingestion/migrate-from-embedded), define a storage integration once per location. It is a namespace-scoped catalog object that stores the credential -- neither operation names the integration directly, LanceDB matches the URI you read against whichever integration's prefix covers it. ## What each provider needs | Provider | Credential | Notes | | - | - | - | | AWS S3 | An IAM role to assume, or a static access key pair | A role needs one extra step outside LanceDB: [trust policy setup](#trust). | | Google Cloud Storage | A service account's JSON key | No role-based alternative. | | Azure Blob Storage | A service principal's tenant, client ID and client secret | All three required together. | | HuggingFace | An access token | Always required to create an integration. For anonymous access at HuggingFace's default rate limits, register no integration for that prefix instead. | Every credential option takes a [Secret](/oss/v0-41-0/management/secret) reference, never the value directly -- create the Secret first. ## Create one ### AWS S3 Give either an IAM role to assume, or a static access key pair -- mixing the two, or supplying only one half of the key pair, is refused. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ACCESS_KEY_ID_SECRET = aws_key_id STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = aws_key_secret ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "raw", "s3://customer-data/raw/", storage_provider="S3", aws_role_arn="arn:aws:iam::123456789012:role/lancedb-access", ) db.create_storage_integration( "raw", "s3://customer-data/raw/", storage_provider="S3", aws_access_key_id_secret="aws_key_id", aws_secret_access_key_secret="aws_key_secret", ) ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::storage_integration::CreateStorageIntegrationRequest; let info = db.create_storage_integration( "raw", CreateStorageIntegrationRequest::s3( "s3://customer-data/raw/", "arn:aws:iam::123456789012:role/lancedb-access", ), &[], ).await?; ``` ### Google Cloud Storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION gcs STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = 'gs://customer-data/raw/' GCP_CREDENTIALS_JSON_SECRET = gcp_service_account ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "gcs", "gs://customer-data/raw/", storage_provider="GCP", gcp_credentials_json_secret="gcp_service_account", ) ``` The Secret holds the full service-account JSON key. GCP has no role-based alternative. ### Azure Blob Storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION blobs STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = 'az://customer-data/raw/' STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' STORAGE_AZURE_TENANT_ID_SECRET = azure_tenant STORAGE_AZURE_CLIENT_ID_SECRET = azure_client STORAGE_AZURE_CLIENT_SECRET_SECRET = azure_credential ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "blobs", "az://customer-data/raw/", storage_provider="AZURE", azure_storage_account="customeraccount", azure_tenant_id_secret="azure_tenant", azure_client_id_secret="azure_client", azure_client_secret_secret="azure_credential", ) ``` All four options are required together; there is no role-based alternative for Azure. ### HuggingFace ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_storage_integration( "hub", "hf://datasets/owner/private/data/", storage_provider="HUGGINGFACE", huggingface_token_secret="hf_token", ) ``` `HUGGINGFACE_TOKEN_SECRET` is required to create this integration; omitting it is rejected, not treated as anonymous. For anonymous access at HuggingFace's default rate limits, register no integration for that prefix at all. ### Finish the AWS trust policy An IAM role integration needs one step outside LanceDB: describing it returns the `trust_policy` and `permissions_policy` documents your role needs. Attach them in AWS, then describe the integration again and check `access_verified` to confirm LanceDB can assume the role. A static access key pair skips this step entirely. See [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) for every provider's complete option reference, S3's two credential modes in full, and the output schema, or [Storage Integration](/oss/v0-41-0/management/storage-integration) for the Python and SQL CRUD operations at a glance. ## What to read next > [card] [Import Datasets](/oss/v0-41-0/ingestion/import) > > Read or import through the integration once it exists. > [card] [Attach Database](/oss/v0-41-0/ingestion/migrate-from-embedded) > > Attach an existing database at a location the integration covers. > [card] [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) > > The complete SQL reference: every provider's options and output columns. # Delete rows Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/delete Select and delete records, verify the remaining rows, and understand storage retention. **Applies to:** Embedded ✅, Enterprise ✅ Deleting rows removes matching records from the current table contents. It keeps the table and schema so you can continue reading and writing. To remove the table itself, see [Drop a table](/oss/v0-41-0/ingestion/create-table#drop-a-table). ## Inspect the rows you intend to delete Use the same predicate for inspection and deletion. The example below creates Alice, Bob and Charlie, prints Charlie's row, and deletes it by `id = 3`. Inspection and deletion are separate operations; concurrent writes can change which rows match between them. ## Delete matching records Each program creates Alice, Bob and Charlie in a temporary local database, deletes Charlie, and prints the remaining rows: **Alice and Bob**. The temporary database is removed when the program finishes. * **Python:** install `lancedb`, save the code as `delete_rows.py`, and run `python delete_rows.py`. * **TypeScript:** install `@lancedb/lancedb`, save the code as `delete_rows.mts`, and run `node delete_rows.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 delete`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table( "users", [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}, ], ) predicate = "id = 3" print("Selected:", table.search().where(predicate).to_list()) table.delete(predicate) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print("Remaining:", rows) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const lancedb = await import("@lancedb/lancedb"); const { mkdtemp, rm } = await import("node:fs/promises"); const { tmpdir } = await import("node:os"); const { join } = await import("node:path"); const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); try { const db = await lancedb.connect(uri); const table = await db.createTable("users", [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" }, ]); const predicate = "id = 3"; console.log("Selected:", await table.query().where(predicate).toArray()); await table.delete(predicate); const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); console.log("Remaining:", rows); } finally { await rm(uri, { recursive: true, force: true }); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; use lancedb::query::{ExecutableQuery, QueryBase}; fn make_users_reader(rows: &[(i64, &str)]) -> Box<dyn RecordBatchReader + Send> { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), ], ) .unwrap(); Box::new(RecordBatchIterator::new( vec![Ok(batch)].into_iter(), schema, )) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let directory = tempfile::tempdir()?; let db = lancedb::connect(directory.path().to_str().unwrap()) .execute() .await?; let table = db .create_table( "users", make_users_reader(&[(1, "Alice"), (2, "Bob"), (3, "Charlie")]), ) .execute() .await?; let predicate = "id = 3"; let selected: Vec<RecordBatch> = table .query() .only_if(predicate) .execute() .await? .try_collect() .await?; println!("Selected: {selected:?}"); table.delete(predicate).await?; let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; println!("Remaining: {rows:?}"); assert_eq!(table.count_rows(None).await?, 2); assert_eq!( table .count_rows(Some("id = 1 AND name = 'Alice'".into())) .await?, 1 ); assert_eq!( table .count_rows(Some("id = 2 AND name = 'Bob'".into())) .await?, 1 ); assert_eq!(table.count_rows(Some("id = 3".into())).await?, 0); Ok(()) } ``` Enterprise also supports [`DELETE`](/oss/v0-41-0/sql/dml/delete). ## Verify that the rows are absent Query the same predicate after deletion and check the remaining row count. A reader still using an older snapshot may see the earlier contents; see [Consistency](/oss/v0-41-0/tables/consistency). Deleted rows are excluded from current query results, including indexed searches. Deletion does not imply immediate physical erasure of every stored copy of the data. ## Understand storage reclamation Compaction rewrites the live data layout; cleanup removes eligible retained versions and files. Retained history can continue to reference data that no longer appears in the latest table version. In LanceDB Embedded, `optimize()` provides maintenance operations. In Enterprise, managed maintenance and retention follow the service configuration. Choose retention according to the history you need, rather than shortening it as part of a routine delete example. See [Compaction](/oss/v0-41-0/maintenance/compaction) and [Garbage Collection](/oss/v0-41-0/maintenance/cleanup) for the separate maintenance workflow. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Import Datasets Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/import Create a table directly from a HuggingFace dataset or an existing Lance dataset in object storage, with one CREATE TABLE AS SELECT. **Applies to:** Embedded ❌, Enterprise ✅ A `CREATE TABLE ... AS SELECT` (CTAS) reads directly from a HuggingFace dataset or an existing Lance dataset in object storage, once a [storage integration](/oss/v0-41-0/ingestion/define-storage-integration) covers that location -- the integration is never named in the statement, LanceDB matches it by URI prefix. ## Import a HuggingFace dataset ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE imported AS SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' ``` See [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets#import) for the full workflow, including querying a dataset directly without importing it first. ## Import a Lance dataset from object storage ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE events_copy AS SELECT * FROM 's3://customer-data/raw/events.lance' ``` An `s3://`, `gs://` or `az://` prefix reads an existing **Lance** dataset the same way as a managed table -- use this to copy a dataset another process already wrote in Lance format, not an arbitrary file format. See [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration#read-import) for GCS and Azure examples. ## How the import runs See [Distributed Write](/oss/v0-41-0/enterprise/distributed-write) for how an import's writes divide across plan executors, and when a small import instead runs as one local task. > [!NOTE] > > Importing requires a native database with `database_manifest_enabled`. > Combining a HuggingFace source with a WAL-backed destination table in one > CTAS is rejected, since the import cannot publish a base-only read that > omits the destination's unflushed data. ## What to read next > [card] [Define Storage Integration](/oss/v0-41-0/ingestion/define-storage-integration) > > Set up the credential an import reads through. > [card] [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) > > Query and import HuggingFace or object-storage datasets in full. > [card] [Distributed Write](/oss/v0-41-0/enterprise/distributed-write) > > How an import's writes divide across plan executors. > [card] [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) > > The complete SQL reference for every provider. # Ingesting data Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/index Choose how to create a table, append records or change existing data. **Applies to:** Embedded ✅, Enterprise ✅ Ingestion brings data into a LanceDB table. Start by choosing a schema and creating the table, then choose a write operation according to how incoming records relate to data already stored. ## Choose a write operation | Task | Operation | What happens | | - | - | - | | [Create a table](/oss/v0-41-0/ingestion/create-table) | `create_table` / `createTable` | Create a table from data or an explicit schema. | | [Append records](/oss/v0-41-0/ingestion/insert) | `add` | Add rows without matching existing keys. | | [Upsert by key](/oss/v0-41-0/ingestion/merge-insert) | `merge_insert` / `mergeInsert` | Choose whether matching rows are updated and new keys inserted. | | [Update selected rows](/oss/v0-41-0/ingestion/update) | `update` | Change values in rows selected by a predicate. | | [Delete selected rows](/oss/v0-41-0/ingestion/delete) | `delete` | Remove matching rows from the current table contents. | Appending the same input twice can create duplicate records. Use merge insert with a stable key when the incoming data should update existing records. ## Connect and prepare the data Use the [connection guide](/oss/v0-41-0/basics/catalog) to connect to Embedded or Enterprise. The SDK write operations in this section work with both. Enterprise also supports [SQL write statements](/oss/v0-41-0/sql#dml); an SDK filter expression does not require a separate SQL connection. Choose the column types, required fields and vector dimensions before a large load. SDKs support different input representations, including row objects and Arrow batches. The [table creation guide](/oss/v0-41-0/ingestion/create-table) covers those choices. ## Try a complete write workflow This example starts with Alice and Bob, appends Charlie, updates Bob's name and login count, then merges a batch containing Charlie and Dana. Finally, it selects Dana's row for inspection and deletes it. > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. ## Verify the result After a write completes, inspect the affected keys and fields and check the row count. SDK return values differ by operation and language; use the relevant API reference when relying on returned counts or version metadata. Readers with older snapshots may not see another handle's writes immediately. See [Consistency](/oss/v0-41-0/tables/consistency). A table checked out at a historical version must return to the latest version before it can be modified. ## Load larger datasets Use batches or file-backed input when the dataset is too large to hold in memory. The [insert guide](/oss/v0-41-0/ingestion/insert#large-datasets) covers input formats, progress reporting and write parallelism. Keep retry behavior in mind: repeating an append is not the same as retrying a key-based upsert. # Insert data Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/insert Append records, load file-backed data or batches, and verify ingestion. **Applies to:** Embedded ✅, Enterprise ✅ Use `add()` to append records to an existing table. It does not compare incoming keys with stored keys. Choose [merge insert](/oss/v0-41-0/ingestion/merge-insert) when the same record may arrive again and should update an existing row. ## Append a first batch Install the Python SDK with `pip install lancedb`. This complete example starts with Alice, appends Bob and Charlie, and prints all three records. ```python append_rows.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add([{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print(rows) ``` The program uses temporary local storage. For a complete TypeScript or Rust example, see [Complete write workflow](#complete-example). Enterprise SQL offers [`INSERT`](/oss/v0-41-0/sql/dml/insert), including `INSERT ... SELECT`. ## Prepare the input Match the table's schema, including required fields and vector dimensions. Supported input formats differ by SDK; see [Create a table](/oss/v0-41-0/ingestion/create-table). Inspect conversion errors before retrying, and verify the final row count and representative values. ## Choose input for a large load 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. ### Read from files 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. ```python load_parquet.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pyarrow.parquet as pq data_path = "input.parquet" pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path) import pyarrow.dataset as ds dataset = ds.dataset(data_path, format="parquet") table = db.create_table("my_table", schema=dataset.schema, mode="overwrite") table.add(dataset) print("Rows:", table.count_rows()) ``` 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. ### Produce batches during ingestion 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. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), 4)), pa.field("item", pa.utf8()), pa.field("price", pa.float32()), ] ) def make_batches(): for i in range(5): yield pa.RecordBatch.from_arrays( [ pa.array( [[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]], pa.list_(pa.float32(), 4), ), pa.array(["foo", "bar"]), pa.array([10.0, 20.0]), ], ["vector", "item", "price"], ) table = db.create_table("batched_table", schema=schema) table.add(make_batches()) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const batchSchema = new arrow.Schema([ new arrow.Field( "vector", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("item", new arrow.Utf8()), new arrow.Field("price", new arrow.Float32()), ]); const tableForBatches = await db.createEmptyTable( "batched_table", batchSchema, { mode: "overwrite", }, ); const rows = Array.from({ length: 10 }, (_, i) => ({ vector: [i + 0.1, i + 0.2, i + 0.3, i + 0.4], item: `item-${i + 1}`, price: (i + 1) * 10, })); const chunkSize = 2; for (let i = 0; i < rows.length; i += chunkSize) { const batch = lancedb.makeArrowTable(rows.slice(i, i + chunkSize), { schema: batchSchema, }); await tableForBatches.add(batch); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let batch_schema = Arc::new(Schema::new(vec![ Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), Field::new("item", DataType::Utf8, false), Field::new("price", DataType::Float32, false), ])); let batches = (0..5) .map(|i| { RecordBatch::try_new( batch_schema.clone(), vec![ Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(3.1 + i as f32), Some(4.1), Some(5.1), Some(6.1)]), Some(vec![ Some(5.9), Some(26.5 + i as f32), Some(4.7), Some(32.8), ]), ], 4, ), ), Arc::new(StringArray::from(vec![ format!("item{}", i * 2 + 1), format!("item{}", i * 2 + 2), ])), Arc::new(Float32Array::from(vec![ ((i * 2 + 1) * 10) as f32, ((i * 2 + 2) * 10) as f32, ])), ], ) .unwrap() }) .collect::<Vec<_>>(); let batch_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(batches.into_iter().map(Ok), batch_schema.clone())); let batch_table = db .create_table("batched_table", batch_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` 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. ### Control 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. ## Track completion and 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`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add( [{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}], progress=report_progress, ) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) print("After insertion:", rows) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const lancedb = await import("@lancedb/lancedb"); const { mkdtemp, rm } = await import("node:fs/promises"); const { tmpdir } = await import("node:os"); const { join } = await import("node:path"); const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); try { const db = await lancedb.connect(uri); const table = await db.createTable("users", [{ id: 1, name: "Alice" }]); await table.add( [ { id: 2, name: "Bob" }, { id: 3, name: "Charlie" }, ], { progress: (progress) => console.log(`Rows written: ${progress.outputRows}`), }, ); const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); console.log("After insertion:", rows); } finally { await rm(uri, { recursive: true, force: true }); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; use lancedb::query::ExecutableQuery; fn make_users_reader(rows: &[(i64, &str)]) -> Box<dyn RecordBatchReader + Send> { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), ], ) .unwrap(); Box::new(RecordBatchIterator::new( vec![Ok(batch)].into_iter(), schema, )) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let directory = tempfile::tempdir()?; let db = lancedb::connect(directory.path().to_str().unwrap()) .execute() .await?; let table = db .create_table("users", make_users_reader(&[(1, "Alice")])) .execute() .await?; table .add(make_users_reader(&[(2, "Bob"), (3, "Charlie")])) .progress(|progress| println!("Rows written: {}", progress.output_rows())) .execute() .await?; let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; println!("After insertion: {rows:?}"); assert_eq!(table.count_rows(None).await?, 3); assert_eq!( table .count_rows(Some("id = 1 AND name = 'Alice'".into())) .await?, 1 ); assert_eq!( table .count_rows(Some("id = 2 AND name = 'Bob'".into())) .await?, 1 ); assert_eq!(table.count_rows(Some("id = 3".into())).await?, 1); Ok(()) } ``` 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. 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 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. The client's automatic retries can do the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an append after a retryable status such as `504`, even when the server had already committed it, and `add()` still returns success. Reconcile using your record IDs, or choose an upsert policy designed for replay. ## Configure large uploads Enterprise This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lancedb.remote.errors.HttpError: operation timed out ``` 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` | 8 GiB | Maximum size of a single insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable splitting and send one request per partition. | | `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Maximum wall-clock time, in whole seconds, that any one insert part may stay open. Set to `0` to disable the time-based cut. | A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes ``` 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. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Attach Database Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/migrate-from-embedded Point Enterprise at an existing database in object storage with ATTACH DATABASE, without copying data. **Applies to:** Embedded ❌, Enterprise ✅ If your LanceDB Embedded database already lives in object storage -- Embedded reads and writes tables on S3, GCS or Azure as well as local disk -- you can move to Enterprise by attaching that same location, rather than copying any data. A database on local disk has no such path: `ATTACH DATABASE` only accepts an object-storage URI or a path relative to Enterprise's own storage root, never a local filesystem path. Move it to object storage first if it is not there already. ## Prerequisites A [storage integration](/oss/v0-41-0/sql/ddl/storage-integration) covering the database's location must already exist. `ATTACH DATABASE` never names an integration explicitly -- Enterprise automatically binds the most specific integration whose `STORAGE_PREFIX` covers the location you attach. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/embedded-db/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' ``` ## Attach the database ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH DATABASE analytics WITH (location = 's3://customer-data/embedded-db/') ``` See [Database](/oss/v0-41-0/sql/ddl/database#attach) for the full `ATTACH DATABASE` syntax, including GCS and Azure locations (Azure requires an account-qualified URI), `IF NOT EXISTS`, and quoted names. ## What changes, and what doesn't Attaching makes the location a database LanceDB Enterprise manages the same way as one it created itself: Enterprise writes its own tracking metadata into that location to bring it under management, enabling capabilities Embedded never had there -- every table becomes reachable through Enterprise's SQL and SDK surface immediately, with Enterprise's authorization, Secrets, Functions, and [background maintenance](/oss/v0-41-0/basics/jobs) now available to it. Attaching does not rewrite, move, or re-encode any table's own data. [`DROP DATABASE`](/oss/v0-41-0/sql/ddl/database#drop) on an attached database unregisters it and releases the storage-integration reference, without deleting the underlying data -- the location can be reattached at any time. ## What to read next > [card] [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) > > Configure the credential an attach depends on, for S3, GCS, or Azure. > [card] [Database](/oss/v0-41-0/sql/ddl/database) > > Full ATTACH, CREATE, DESCRIBE and DROP DATABASE syntax. # RTE Write (Upsert) Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/realtime-write Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds. **Applies to:** Embedded ✅, Enterprise ✅ The [real time engine](/oss/v0-41-0/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see [RTE reads](/oss/v0-41-0/search/realtime-read). `table.enable_rte(spec)` is the same call on both connections, but what it does underneath differs: * **Embedded** runs Lance's MemWAL `ShardWriter` directly in your process -- the WAL buffer, memtables and SSTables all live wherever your table does, and there is no separate serving layer to scale or configure. * **Enterprise** forwards the call to the server, which runs it on a dedicated, horizontally scalable WAL-node tier instead of your table's query-serving fleet. See [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write) for how that tier shards a table's writes and the throughput limits that come with it. ## Getting started ### 1. Create a table with a primary key RTE deduplicates writes by primary key. Create the table with a non-nullable key column, then declare it with `set_unenforced_primary_key`. The key is a single `int32`, `int64`, string, or binary column, and cannot be changed once set. The table below holds frames captioned and embedded as they stream in from a live camera feed, such as a robot recording episodes into a dataset shaped like [LeRobotDataset](/oss/v0-41-0/integrations/lerobotdataset)'s `frames` table — `frame_id` is the primary key so a re-captioned frame upserts in place: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta import numpy as np import pyarrow as pa from lancedb import RTEWriteSpec from lancedb.index import FTS, BTree, IvfPq # Embedded: db = lancedb.connect("./my_db") db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") dim = 768 schema = pa.schema([ pa.field("frame_id", pa.int64(), nullable=False), pa.field("video_id", pa.utf8(), nullable=False), pa.field("embedding", pa.list_(pa.float32(), dim)), pa.field("caption", pa.utf8()), ]) frames = db.create_table("frames", schema=schema) frames.set_unenforced_primary_key("frame_id") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; const dim = 768; const schema = new arrow.Schema([ new arrow.Field("frame_id", new arrow.Int64(), false), new arrow.Field("video_id", new arrow.Utf8(), false), new arrow.Field( "embedding", new arrow.FixedSizeList(dim, new arrow.Field("item", new arrow.Float32(), true)), true, ), new arrow.Field("caption", new arrow.Utf8(), true), ]); const frames = await db.createEmptyTable("frames", schema); await frames.setUnenforcedPrimaryKey("frame_id"); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_schema::{DataType, Field, Schema}; let dim = 768; let schema = Arc::new(Schema::new(vec![ Field::new("frame_id", DataType::Int64, false), Field::new("video_id", DataType::Utf8, false), Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), dim), true, ), Field::new("caption", DataType::Utf8, true), ])); let frames = db.create_empty_table("frames", schema).execute().await?; frames.set_unenforced_primary_key(["frame_id"]).await?; ``` Or in SQL: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames SET UNENFORCED PRIMARY KEY (frame_id) ``` ### 2. Create indexes By default, RTE maintains every supported index on the table, including indexes created after it is enabled. A scalar index on the primary key is required for partial updates and deletes. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.create_index("embedding", config=IvfPq()) frames.create_index("caption", config=FTS()) frames.create_index("frame_id", config=BTree()) frames.wait_for_index(["embedding_idx", "caption_idx", "frame_id_idx"], timeout=timedelta(minutes=5)) ``` ### 3. Enable RTE ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.enable_rte(RTEWriteSpec.unsharded()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await frames.enableRTE({ specType: "unsharded" }); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::table::RTEWriteSpec; frames.enable_rte(RTEWriteSpec::unsharded()).await?; ``` Or in SQL: ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames SET RTE ``` ### 4. Write > [!WARNING] > > On an RTE table, an upsert through `merge_insert` is the only way to write > rows. Use the form below exactly: `when_matched_update_all()` with no filter, > plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as > conditional updates or deleting rows missing from the source, are rejected. Writes go through `merge_insert` on the primary key, and are visible to queries immediately — see [RTE reads](/oss/v0-41-0/search/realtime-read) for querying them back: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} new_frames = pa.table({ "frame_id": pa.array([2000, 2001], pa.int64()), "video_id": pa.array(["clip-9", "clip-9"]), "embedding": pa.FixedSizeListArray.from_arrays( pa.array(np.random.rand(2 * dim).astype("float32")), dim), "caption": pa.array(["a gripper closing on a cup", "a cup set down on the table"]), }, schema=schema) frames.merge_insert("frame_id") \ .when_matched_update_all() \ .when_not_matched_insert_all() \ .execute(new_frames) ``` **Partial updates.** Send the primary key plus only the columns you want to change; omitted columns keep their current values. This requires a scalar index on the primary key. A re-captioning job, for example, only touches `caption`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} patch = pa.table( {"frame_id": [2000, 2001], "caption": ["a two-finger gripper closing on a cup", "the cup resting upright"]}, schema=pa.schema([schema.field("frame_id"), schema.field("caption")]), ) frames.merge_insert("frame_id").when_matched_update_all().when_not_matched_insert_all().execute(patch) ``` **Deletes.** The predicate must bind the primary key to literal values. Ranges, `OR`, and filters on other columns are rejected. Deletes require a scalar index on the primary key. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.delete("frame_id IN (2000, 2001)") ``` ### Disabling RTE Stop writes and wait for in-flight writes to finish, then flush pending writes into the base table and disable. `checkpoint_rte()` only drains writes that existed when it started, so anything written during the checkpoint can be left behind. `disable_rte()` is rejected while the write-ahead log still holds rows, so run `checkpoint_rte()` first. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames.checkpoint_rte() frames.disable_rte() ``` ## Write throughput RTE acknowledges a write as soon as it is durable in the write-ahead log, so ingest is no longer limited by how fast the table can commit. On Embedded, durability means your local disk or object store, so throughput is bounded by your own machine's resources. An Enterprise table can be split into shards that write independently, with each shard's durable-append throughput bounded by its WAL node's own capacity -- measured, not an enforced cap. See [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write#throughput) for the numbers. ## Next steps * [RTE reads](/oss/v0-41-0/search/realtime-read) — query an RTE table * [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write) — how Enterprise shards and scales this * [How the real time engine works](/oss/v0-41-0/tables/realtime-engine#memwal-format) * [Merge insert](/oss/v0-41-0/ingestion/merge-insert) * [`ALTER TABLE ... SET RTE`](/oss/v0-41-0/sql/ddl/table#properties) # Update rows Source: https://docs.lancedb.com/oss/v0-41-0/ingestion/update Select existing rows, change values or expressions, and verify the changes. **Applies to:** Embedded ✅, Enterprise ✅ Use `update` to change rows selected by a predicate. Use [merge insert](/oss/v0-41-0/ingestion/merge-insert) instead when matching an incoming dataset against existing keys. ## Select the rows to change Check the predicate with a [filtered query](/oss/v0-41-0/search/filtering) before applying the update. These examples target the row with `id = 2`. Review the scope carefully when omitting a predicate, since that can update the entire table. Each example below starts from Alice with 10 logins and Bob with 20. The Python programs create and remove their own temporary database. TypeScript and Rust operation blocks use `db`; a complete program is provided below. ## Assign a new value ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa table = db.create_table( "users_example", data=pa.table( { "id": [1, 2], "name": ["Alice", "Bob"], "login_count": [10, 20], } ), mode="overwrite", ) table.update(where="id = 2", values={"name": "Bobby"}) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable( "users_example", [ { id: 1, name: "Alice", login_count: 10 }, { id: 2, name: "Bob", login_count: 20 }, ], { mode: "overwrite" }, ); await table.update({ where: "id = 2", values: { name: "Bobby" } }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table = db .create_table( "users_example", make_users_reader(vec![1, 2], vec!["Alice", "Bob"], Some(vec![10, 20])), ) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); table .update() .only_if("id = 2") .column("name", "'Bobby'") .execute() .await .unwrap(); ``` The result contains Alice and **Bobby**, with their login counts unchanged. The Python `values` and TypeScript `values` arguments take literal values. Rust's `column` argument is an expression, so the string value includes SQL quotes. ## Calculate a value from the existing row ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa table = db.create_table( "users_example", data=pa.table( { "id": [1, 2], "name": ["Alice", "Bob"], "login_count": [10, 20], } ), mode="overwrite", ) table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) print("Rows:", table.count_rows()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable( "users_example", [ { id: 1, name: "Alice", login_count: 10 }, { id: 2, name: "Bob", login_count: 20 }, ], { mode: "overwrite" }, ); await table.update({ where: "id = 2", valuesSql: { login_count: "login_count + 1" }, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table = db .create_table( "users_example", make_users_reader(vec![1, 2], vec!["Alice", "Bob"], Some(vec![10, 20])), ) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); table .update() .only_if("id = 2") .column("login_count", "login_count + 1") .execute() .await .unwrap(); ``` In this separate example, Bob keeps his name and his login count becomes **21**. Python's `values_sql` and TypeScript's `valuesSql` accept expressions. These SDK expressions work with LanceDB Embedded tables; they do not require an Enterprise SQL endpoint. Enterprise also offers [`UPDATE`](/oss/v0-41-0/sql/dml/update). ## Verify the affected data Read the selected rows again and inspect the changed fields. For another connection or table handle, account for its [read consistency](/oss/v0-41-0/tables/consistency) settings. Python's `update` does not compute embeddings. When changing a configured embedding source column, provide every associated vector column in the same call. This applies to both literal values and SQL expressions, and to synchronous and asynchronous tables. Python 0.41.0 does not check these source/vector pairs before writing: it can change the source while retaining an old vector. Validate the pairs in your application. Python 0.42.0b8 raises `ValueError` for a missing paired vector before writing rows. Use [`merge_insert`](/oss/v0-41-0/ingestion/merge-insert) with the new source values to generate embeddings automatically. Nested-field updates are not supported by these operations. For schema changes, see [schema evolution](/oss/v0-41-0/management/table#schema). Treat derived values separately: changing an input field is not a guarantee that every stored feature has been recomputed. See [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column). Updates can change index coverage and query cost. After a large update, inspect the workload and follow [index maintenance](/oss/v0-41-0/indexing/incremental-indexing) guidance for the backend you use. ## Complete write workflow > [accordion] 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. > > ```python ingestion.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import lancedb > > with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: > db = lancedb.connect(uri) > table = db.create_table( > "users", > [ > {"id": 1, "name": "Alice", "login_count": 10}, > {"id": 2, "name": "Bob", "login_count": 20}, > ], > ) > table.add([{"id": 3, "name": "Charlie", "login_count": 5}]) > table.update(where="id = 2", values={"name": "Bobby"}) > table.update(where="id = 2", values_sql={"login_count": "login_count + 1"}) > ( > table.merge_insert("id") > .when_matched_update_all() > .when_not_matched_insert_all() > .execute( > [ > {"id": 3, "name": "Charlie", "login_count": 6}, > {"id": 4, "name": "Dana", "login_count": 1}, > ] > ) > ) > print("Rows selected for deletion:", table.search().where("id = 4").to_list()) > table.delete("id = 4") > rows = sorted(table.search().to_list(), key=lambda row: row["id"]) > print(rows) > ``` > > ```typescript ingestion.mts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > > const uri = await mkdtemp(join(tmpdir(), "lancedb-ingestion-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("users", [ > { id: 1, name: "Alice", login_count: 10 }, > { id: 2, name: "Bob", login_count: 20 }, > ]); > await table.add([{ id: 3, name: "Charlie", login_count: 5 }]); > await table.update({ where: "id = 2", values: { name: "Bobby" } }); > await table.update({ > where: "id = 2", > valuesSql: { login_count: "login_count + 1" }, > }); > await table > .mergeInsert("id") > .whenMatchedUpdateAll() > .whenNotMatchedInsertAll() > .execute([ > { id: 3, name: "Charlie", login_count: 6 }, > { id: 4, name: "Dana", login_count: 1 }, > ]); > console.log( > "Rows selected for deletion:", > await table.query().where("id = 4").toArray(), > ); > await table.delete("id = 4"); > const rows = (await table.query().toArray()).sort((a, b) => a.id - b.id); > console.log(rows); > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust src/main.rs icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase}; > > fn make_users_reader(rows: &[(i64, &str, i64)]) -> Box<dyn RecordBatchReader + Send> { > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("name", DataType::Utf8, false), > Field::new("login_count", DataType::Int64, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.0))), > Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))), > Arc::new(Int64Array::from_iter_values(rows.iter().map(|r| r.2))), > ], > ) > .unwrap(); > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let table = db > .create_table( > "users", > make_users_reader(&[(1, "Alice", 10), (2, "Bob", 20)]), > ) > .execute() > .await?; > table > .add(make_users_reader(&[(3, "Charlie", 5)])) > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("name", "'Bobby'") > .execute() > .await?; > table > .update() > .only_if("id = 2") > .column("login_count", "login_count + 1") > .execute() > .await?; > let mut merge = table.merge_insert(&["id"]); > merge > .when_matched_update_all(None) > .when_not_matched_insert_all(); > merge > .execute(make_users_reader(&[(3, "Charlie", 6), (4, "Dana", 1)])) > .await?; > let selected: Vec<RecordBatch> = table > .query() > .only_if("id = 4") > .execute() > .await? > .try_collect() > .await?; > println!("Rows selected for deletion: {selected:?}"); > table.delete("id = 4").await?; > let rows: Vec<RecordBatch> = table.query().execute().await?.try_collect().await?; > println!("Remaining rows: {rows:?}"); > assert_eq!(table.count_rows(None).await?, 3); > assert_eq!( > table > .count_rows(Some( > "id = 2 AND name = 'Bobby' AND login_count = 21".into() > )) > .await?, > 1 > ); > assert_eq!( > table > .count_rows(Some("id = 3 AND login_count = 6".into())) > .await?, > 1 > ); > Ok(()) > } > ``` > > 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. # Quickstart Source: https://docs.lancedb.com/oss/v0-41-0/quickstart Install LanceDB, create a table, and run your first vector search. This quickstart uses LanceDB Embedded with a local database and works without an account or API key. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. ## 1. Install LanceDB Choose your language. Python uses Pandas to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. ```bash Python (pip) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lancedb==0.41.0" pandas ``` ```bash Python (uv) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv venv uv pip install "lancedb==0.41.0" pandas ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb@0.41.0 ``` ```bash Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cargo init --name lancedb_quickstart cargo add lancedb@0.41.0 --features polars,remote cargo add tokio --features macros,rt-multi-thread ``` Run the Rust commands in a new, empty directory. The `polars` feature provides DataFrame output; `remote` also lets this example connect to Enterprise. > [accordion] Python pre-release builds and older CPUs > > ### Python pre-release builds > > To pick up the latest features and bug fixes > before the next stable release, install a pre-release from LanceDB's Fury index. > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb > ``` > > ```bash Python (uv) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > uv venv > uv pip install --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb > > # To add to pyproject.toml, use: > uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb > ``` > > Most applications only need `lancedb`. Install the optional `pylance` extra and > include the Lance preview index only when building query engines or connectors, > calling format-level `lance` APIs directly, converting plain-scan lazy blob > handles with `to_pandas()`, or reading legacy v1 blob bytes into pandas with > Python 0.41.0 or 0.42.0b8. Those clients use the native bytes path for supported > v2 blob queries; they still need `pylance` for legacy pandas bytes conversion: > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install --pre \ > --extra-index-url https://pypi.fury.io/lancedb/ \ > --extra-index-url https://pypi.fury.io/lance-format/ \ > "lancedb[pylance]" > ``` > > ```bash Python (uv) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > uv pip install --prerelease allow \ > --index https://pypi.fury.io/lancedb/ \ > --index https://pypi.fury.io/lance-format/ \ > --index-strategy unsafe-best-match \ > "lancedb[pylance]" > ``` > > The LanceDB preview index contains old `pylance` releases; current Lance previews > are published to the `lance-format` index. By default, uv only considers versions > from the first index containing a package, which can select an old `pylance` or > backtrack to an older LanceDB release. `unsafe-best-match` searches all configured > indexes, like pip; use it only with indexes you trust. Install the extra rather > than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. > > > [!NOTE] > > > > Pre-release builds receive the same level of testing as stable releases, but their availability is not guaranteed > > for more than 6 months after release. For real-world workloads, we recommend you use the latest stable release > > as far as possible. > > ### Older x86_64 CPUs > > The default `lancedb` wheel targets `x86-64-haswell` (AVX2 + FMA + F16C). On older x86_64 CPUs without AVX2 > (Intel Sandy Bridge, Ivy Bridge, Westmere; AMD Bulldozer, Piledriver, Steamroller), `import lancedb` crashes > with `Illegal instruction`. > > Install `lancedb-compat` instead. It exposes the same API (`import lancedb` still works), is built at the > `x86-64-v2` baseline, and uses runtime SIMD dispatch to still use AVX2, FMA, or AVX-512 when available: > > ```bash Python (pip) icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > pip install lancedb-compat > ``` > > The two packages share the same `lancedb/` namespace and conflict at install time, so pick one. To switch, > uninstall the other first (`pip uninstall lancedb && pip install lancedb-compat`). ## 2. Connect to a database ### Local directory LanceDB creates an `ex_lancedb` directory to store your tables. No server is needed. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "ex_lancedb" db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("ex_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("ex_lancedb").execute().await?; ``` For Python's async API, see [Connecting to a database](/oss/v0-41-0/basics/catalog). ### Object storage Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Object storage](/oss/v0-41-0/basics/catalog#object-storage) for credentials and provider-specific options. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb uri = "s3://your-bucket/path" # You can also use "gs://your-bucket/path" or "az://your-container/path". db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". const db = await lancedb.connect(uri); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let uri = "s3://your-bucket/path"; // You can also use "gs://your-bucket/path" or "az://your-container/path". let db = connect(uri).execute().await?; ``` ### Enterprise Use the database URI, API key, and endpoint provided by your administrator or the LanceDB team. Replace the placeholders below with those details. Use the deployment's region if provided; otherwise keep `us-east-1`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; let db = connect("db://your-database") .api_key("your-api-key") .region("us-east-1") .host_override("https://your-endpoint") .execute() .await?; ``` > [!NOTE] > > In application code, load credentials from environment variables or a secrets manager. See [connection settings](/oss/v0-41-0/basics/catalog#enterprise) for an example. Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/oss/v0-41-0/index#architecture). ## 3. Create a table and add data Each row describes a frame from a robot video clip and stores an embedding alongside its video, caption, and quality stats. > [!NOTE] > > These embeddings are made up for this example. In your application, use an embedding model to generate them from your data. > [accordion] Frame records > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > data = [ > { > "frame_id": "1", > "video_id": "clip-1", > "caption": "a robot arm reaching toward a cup", > "stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3}, > "embedding": [0.7, 0.1, 0.9, 0.7], > }, > { > "frame_id": "2", > "video_id": "clip-1", > "caption": "a two-finger gripper closing on a cup", > "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, > "embedding": [0.2, 0.9, 0.4, 0.9], > }, > { > "frame_id": "3", > "video_id": "clip-2", > "caption": "a robot arm holding a cup steady", > "stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4}, > "embedding": [0.9, 0.1, 0.5, 0.4], > }, > ] > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const data = [ > { > frame_id: "1", > video_id: "clip-1", > caption: "a robot arm reaching toward a cup", > stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 }, > embedding: [0.7, 0.1, 0.9, 0.7], > }, > { > frame_id: "2", > video_id: "clip-1", > caption: "a two-finger gripper closing on a cup", > stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 }, > embedding: [0.2, 0.9, 0.4, 0.9], > }, > { > frame_id: "3", > video_id: "clip-2", > caption: "a robot arm holding a cup steady", > stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 }, > embedding: [0.9, 0.1, 0.5, 0.4], > }, > ]; > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use std::sync::Arc; > > use lancedb::arrow::arrow_array::types::Float32Type; > use lancedb::arrow::arrow_array::{ > FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator, > RecordBatchReader, StructArray, > }; > use lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; > > // Define structs representing the data schema > #[derive(Debug, Clone)] > struct Stats { > motion: i8, > sharpness: i8, > exposure: i8, > framing: i8, > } > > #[derive(Debug, Clone)] > struct Frame { > frame_id: String, > video_id: String, > caption: String, > stats: Stats, > embedding: [f32; 4], > } > > fn frames_schema() -> Arc<Schema> { > Arc::new(Schema::new(vec![ > Field::new("frame_id", DataType::LargeUtf8, false), > Field::new("video_id", DataType::LargeUtf8, false), > Field::new("caption", DataType::LargeUtf8, false), > Field::new( > "stats", > DataType::Struct(Fields::from(vec![ > Arc::new(Field::new("motion", DataType::Int8, false)), > Arc::new(Field::new("sharpness", DataType::Int8, false)), > Arc::new(Field::new("exposure", DataType::Int8, false)), > Arc::new(Field::new("framing", DataType::Int8, false)), > ])), > false, > ), > Field::new( > "embedding", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), > false, > ), > ])) > } > > fn frames_to_reader(schema: Arc<Schema>, rows: &[Frame]) -> Box<dyn RecordBatchReader + Send> { > let frame_ids = > LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str())); > let video_ids = > LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str())); > let captions = LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str())); > > let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion)); > let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness)); > let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure)); > let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing)); > let stats_fields: Vec<FieldRef> = vec![ > Arc::new(Field::new("motion", DataType::Int8, false)), > Arc::new(Field::new("sharpness", DataType::Int8, false)), > Arc::new(Field::new("exposure", DataType::Int8, false)), > Arc::new(Field::new("framing", DataType::Int8, false)), > ]; > let stats = StructArray::new( > stats_fields.into(), > vec![ > Arc::new(motion), > Arc::new(sharpness), > Arc::new(exposure), > Arc::new(framing), > ], > None, > ); > > let embeddings = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > rows.iter() > .map(|row| Some(row.embedding.iter().copied().map(Some).collect::<Vec<_>>())), > 4, > ); > > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(frame_ids), > Arc::new(video_ids), > Arc::new(captions), > Arc::new(stats), > Arc::new(embeddings), > ], > ) > .unwrap(); > > Box::new(RecordBatchIterator::new( > vec![Ok(batch)].into_iter(), > schema, > )) > } > let data = vec![ > Frame { > frame_id: "1".to_string(), > video_id: "clip-1".to_string(), > caption: "a robot arm reaching toward a cup".to_string(), > stats: Stats { > motion: 3, > sharpness: 4, > exposure: 4, > framing: 3, > }, > embedding: [0.7, 0.1, 0.9, 0.7], > }, > Frame { > frame_id: "2".to_string(), > video_id: "clip-1".to_string(), > caption: "a two-finger gripper closing on a cup".to_string(), > stats: Stats { > motion: 5, > sharpness: 4, > exposure: 5, > framing: 2, > }, > embedding: [0.2, 0.9, 0.4, 0.9], > }, > Frame { > frame_id: "3".to_string(), > video_id: "clip-2".to_string(), > caption: "a robot arm holding a cup steady".to_string(), > stats: Stats { > motion: 2, > sharpness: 3, > exposure: 3, > framing: 4, > }, > embedding: [0.9, 0.1, 0.5, 0.4], > }, > ]; > ``` Create a `frames` table from those records: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("frames", data=data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createTable("frames", data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::database::CreateTableMode; let schema = frames_schema(); let table = db .create_table("frames", frames_to_reader(schema.clone(), &data)) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` This example uses overwrite mode so you can run it again. It replaces any existing `frames` table in the database you connect to. Add one more frame: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add( [ { "frame_id": "4", "video_id": "clip-2", "caption": "a gripper lowering a cup onto the table", "stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2}, "embedding": [0.3, 0.9, 0.6, 0.8], } ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.add([ { frame_id: "4", video_id: "clip-2", caption: "a gripper lowering a cup onto the table", stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 }, embedding: [0.3, 0.9, 0.6, 0.8], }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let more_data = vec![Frame { frame_id: "4".to_string(), video_id: "clip-2".to_string(), caption: "a gripper lowering a cup onto the table".to_string(), stats: Stats { motion: 5, sharpness: 4, exposure: 4, framing: 2, }, embedding: [0.3, 0.9, 0.6, 0.8], }]; table .add(frames_to_reader(schema.clone(), &more_data)) .execute() .await .unwrap(); ``` ## 4. Search the table Find the two embeddings closest to the query embedding. This example uses a fixed embedding; it does not call an embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Search for frames similar to "a gripper closing on an object" query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install pandas` beforehand result = ( table.search(query_vector) .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .to_pandas() ) print(result) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Search for frames similar to "a gripper closing on an object" const queryVector = [0.2, 0.8, 0.4, 0.9]; const result = await table .search(queryVector) .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .toArray(); console.table(result); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::arrow::IntoPolars; use lancedb::query::{ExecutableQuery, QueryBase, Select}; // Search for frames similar to "a gripper closing on an object" let query_vector = [0.2, 0.8, 0.4, 0.9]; let result = table .query() .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ "frame_id".to_string(), "video_id".to_string(), "caption".to_string(), "_distance".to_string(), ])) .limit(2) .execute() .await .unwrap() .into_polars() .await .unwrap(); println!("{result:?}"); ``` Frames 2 and 4 come back first -- the gripper closing on the cup, then lowering it. Python displays a Pandas DataFrame, Rust displays a Polars DataFrame, and TypeScript displays an array of results. The `_distance` column measures how far each result is from your query embedding, with smaller values indicating a closer match. ## 5. Curate data with SQL > [!NOTE] > > Step 5 needs LanceDB Enterprise: SQL is an Enterprise feature. If you're > using LanceDB Embedded, skip ahead to > [Flatten nested fields](#flatten-nested-fields) below. LanceDB Enterprise accepts SQL over the same connection, for sampling, joins, and curation tasks that go beyond a single table scan. Draw a quick sample to look at the data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} sample = db.execute_query( "SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)" ).read_all() print(sample.to_pylist()) ``` See [SQL](/oss/v0-41-0/basics/sql) for the Flight SQL client and CLI alternatives to `execute_query()`. Now add a near-duplicate frame -- frame 5 is one video frame after frame 2, with an almost identical embedding -- and build the vector index that `dedupe` reads: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Frame 5 is a near-duplicate of frame 2: the gripper is still closing, # one video frame later, with an almost identical embedding. table.add( [ { "frame_id": "5", "video_id": "clip-1", "caption": "the two-finger gripper still closing on the cup", "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, "embedding": [0.2, 0.9, 0.4, 0.89], } ] ) from lancedb.index import IvfFlat table.create_index( "embedding", config=IvfFlat(num_partitions=1, distance_type="l2") ) table.wait_for_index(["embedding_idx"]) ``` Collapse near-duplicates into a materialized view that stays current as new frames arrive, then read it back: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'embedding', distance_threshold => 0.03 ) """) ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} deduped = db.execute_query( "SELECT frame_id FROM frames_deduped ORDER BY frame_id" ).read_all() print(deduped.to_pylist()) ``` Frames 2 and 5 collapse into one representative -- five rows become four. Which of the two ids survives is not guaranteed to stay the same across appends, so don't treat it as a stable identifier for the cluster. See [Deduplicate near-duplicate records](/oss/v0-41-0/curation/dedupe) for `duplicate_pairs`, resolution strategies, and tuning `distance_threshold`, and [Statistical Sampling](/oss/v0-41-0/curation/statistical-sampling) for percentage samples, repeatable draws, and sampling across a join. ## 6. Add a derived feature ### Flatten nested fields A UDF binds to top-level columns, so flatten the fields inside `stats` first. This is a plain eager `add_columns` call, so it works the same on LanceDB Embedded and LanceDB Enterprise -- [step 8](#8-train) needs these columns either way: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns( { "motion": "cast(stats.motion as float)", "sharpness": "cast(stats.sharpness as float)", "exposure": "cast(stats.exposure as float)", "framing": "cast(stats.framing as float)", } ) ``` > [!NOTE] > > The rest of this step needs LanceDB Enterprise -- Functions are an > Enterprise feature. If you're using LanceDB Embedded, skip ahead to > [step 7](#7-store-multimodal-data). Register a UDF as a Function, then call it to fill a column computed from those flattened fields. This fills every existing row once, immediately: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col, udf @udf def quality_score( motion: float, sharpness: float, exposure: float, framing: float ) -> float: return (motion + sharpness + exposure + framing) / 4.0 version = db.create_function_async(quality_score).wait() table.add_columns( { "quality_score": version( motion=col("motion"), sharpness=col("sharpness"), exposure=col("exposure"), framing=col("framing"), ) } ) table.refresh_column("quality_score") ``` Read it back like any other column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} features = table.search().select(["frame_id", "video_id", "quality_score"]).limit(10).to_pandas() print(features) ``` `refresh_column` fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. Run the same refresh as a background job instead, so it doesn't block: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("quality_score") job.wait() ``` See [Create a Function](/oss/v0-41-0/curation/create-function) for UDFs that call external models or services, and [Computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) for the SQL-expression form that doesn't need a registered Function. ## 7. Store multimodal data Store images, audio, or other binary data alongside vectors and metadata, in a column of raw bytes. This creates a new table from one image file -- replace the path with one of your own: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pathlib import Path image_bytes = Path("data/sample-frame.jpg").read_bytes() multimodal_table = db.create_table( "frame_images", data=[ { "frame_id": "thumb-1", "caption": "Sample frame thumbnail", "image": image_bytes, "embedding": [0.9, 0.1, 0.5, 0.4], } ], mode="overwrite", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const arrow = await import("apache-arrow"); const { readFile } = await import("node:fs/promises"); const imageBytes = await readFile("data/sample-frame.jpg"); const imageSchema = new arrow.Schema([ new arrow.Field("frame_id", new arrow.Utf8()), new arrow.Field("caption", new arrow.Utf8()), new arrow.Field("image", new arrow.Binary()), new arrow.Field( "embedding", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), ), ), ]); const imageData = lancedb.makeArrowTable( [ { frame_id: "thumb-1", caption: "Sample frame thumbnail", image: imageBytes, embedding: [0.9, 0.1, 0.5, 0.4], }, ], { schema: imageSchema }, ); const multimodalTable = await db.createTable( "frame_images", imageData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::arrow::arrow_array::BinaryArray; let image_bytes = std::fs::read("data/sample-frame.jpg").unwrap(); let image_schema = Arc::new(Schema::new(vec![ Field::new("frame_id", DataType::LargeUtf8, false), Field::new("caption", DataType::LargeUtf8, false), Field::new("image", DataType::Binary, false), Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])); let image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]]; let image_batch = RecordBatch::try_new( image_schema.clone(), vec![ Arc::new(LargeStringArray::from_iter_values(["thumb-1"])), Arc::new(LargeStringArray::from_iter_values([ "Sample frame thumbnail", ])), Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( image_embeddings .iter() .map(|vector| Some(vector.iter().copied().map(Some).collect::<Vec<_>>())), 4, ), ), ], ) .unwrap(); let image_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(image_batch)].into_iter(), image_schema, )); let multimodal_table = db .create_table("frame_images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` See [Multimodal data types](/oss/v0-41-0/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. ## 8. Train on your data Read table data into PyTorch, projecting and shuffling only the columns a training step needs. This step needs PyTorch, which step 1 doesn't install: ```bash Python (pip) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install torch ``` ```bash Python (uv) icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install torch ``` Then wrap the table in a data loader: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset dataset = StreamingDataset(table, columns=["motion", "sharpness"], shuffle_seed=42) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0) ``` `StreamingDataset` wraps a table for PyTorch training reads; `columns` projects before reading, so a training step touches only the columns it selects, not unused ones such as `caption` or `embedding`. It works the same way against LanceDB Embedded and LanceDB Enterprise. See [PyTorch Data Loader](/oss/v0-41-0/training/data-loading) for shuffling, transforms, resuming, and multi-worker loading, and [Permutation](/oss/v0-41-0/training/permutation) for the lower-level row-ordering primitive it's built on. ## Where to go next > [card] [Basic table operations](/oss/v0-41-0/management/table) > > Create, update, and manage your tables. > [card] [Build a RAG app](/oss/v0-41-0/tutorials/agents/contextual-rag) > > Use retrieved context in a language model application. > [card] [Indexing](/oss/v0-41-0/indexing/) > > Speed up queries on larger datasets. > [card] [Embedding models](/oss/v0-41-0/embedding/) > > Generate vectors from your own data. # Reranking Search Results Source: https://docs.lancedb.com/oss/v0-41-0/reranking/index Choose a reranker, apply it to search candidates and evaluate relevance and latency. **Applies to:** Embedded ✅, Enterprise ✅ Reranking changes the order of records returned by an initial search. It can combine several ranked lists or use a model to score each candidate against the query. It cannot recover records that the initial searches did not retrieve. ## Choose a reranker * **Rank fusion:** start with RRF for hybrid search. It combines vector and full-text rankings without a model or a provider API call. * **Model-based reranking:** try a cross encoder or hosted reranking model when you need a different relevance judgment over the retrieved text. Compare the relevance gain with added latency and provider cost. * **Custom ranking:** implement the reranker interface when your application needs its own scoring policy. > [accordion] Run a complete RRF example in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `rerank_search.py`, then run `python rerank_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `rerank_search.mts`, then run `node rerank_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > from lancedb.rerankers import RRFReranker > > table.create_index("text", config=FTS()) > rows = ( > table.search( > query_type="hybrid", vector_column_name="vector", fts_columns="text" > ) > .vector([1.0, 0.0]) > .text("puppy") > .rerank(RRFReranker()) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const reranker = await lancedb.rerankers.RRFReranker.create(); > const rows = await table > .vectorSearch([1.0, 0.0]) > .fullTextSearch("puppy", { columns: ["text"] }) > .rerank(reranker) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .rerank(Arc::new(lancedb::rerankers::rrf::RRFReranker::default())) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The result includes `_relevance_score` in descending order. RRF is already the > hybrid-search default; passing it explicitly shows where to substitute another > reranker. These scores express a ranking, not a probability of correctness. ## Supported rerankers Use rank fusion to combine search results without a model, or a model-based reranker to score each document against the query. Reranking runs in your application after retrieval, including when the table is in Enterprise. | Reranker | Method | SDK | | :- | :- | :- | | `RRFReranker` | Reciprocal rank fusion | Python, TypeScript, Rust | | `MRRReranker` | Weighted reciprocal rank fusion | Python | | `LinearCombinationReranker` (deprecated) | Blend normalized scores | Python | | `CrossEncoderReranker` | Score query-document pairs with a local cross encoder | Python | | `ColbertReranker`, `AnswerdotaiRerankers` | Local model reranking | Python | | Provider rerankers | Call a hosted model, such as Cohere, Jina or Voyage AI | Python | Local model rerankers need their model runtime packages. Hosted rerankers need provider credentials and make API calls. See [reranking integrations](/oss/v0-41-0/integrations/reranking) for provider setup and model selection; specify a model supported by your provider. Rerankers add `_relevance_score` and return rows ordered by descending relevance. Python rerankers accept a `return_score` option; use `"all"` where supported to keep the original vector distance or FTS score columns for debugging. Model-based rerankers read from `column="text"` by default, so either return that column in the search results or pass a different column. `refine_factor` expands the vector index's internal candidate pool and rescores those candidates using full vectors before keeping the requested limit. It can improve the candidates available for reranking, but it does not multiply the final result count. Compare retrieval recall and total query latency. > [!NOTE] > > **SDK coverage differs across languages** > > The provider-specific rerankers in the table above > (`CohereReranker`, `CrossEncoderReranker`, `ColbertReranker`, and others under `lancedb.rerankers`) > are currently **Python-only**. The TypeScript and Rust SDKs currently expose hybrid reranking through > the generic `Reranker` interface (`rerankHybrid` / `rerank_hybrid`) and the built-in `RRFReranker`. > In TypeScript, create the built-in RRF reranker with `await RRFReranker.create(k)`. To use a > model-based reranker from TypeScript or Rust, you must implement the hybrid reranker interface > yourself. ### Multi-vector reranking Use `rerank_multivector()` to combine result sets from several vector queries. The example below assumes `table` has three vector columns with embedding metadata and uses a cross encoder to rerank their candidates. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.rerankers import CrossEncoderReranker reranker = CrossEncoderReranker() query = "hello" # `deduplicate=True` requires `_rowid` on every input result set, # so call `.with_row_id(True)` on each search before passing it in. res1 = table.search(query, vector_column_name="vector").limit(3).with_row_id(True) res2 = table.search(query, vector_column_name="text_vector").limit(3).with_row_id(True) res3 = table.search(query, vector_column_name="meta_vector").limit(3).with_row_id(True) reranked = reranker.rerank_multivector([res1, res2, res3], deduplicate=True) ``` * Passing `deduplicate=True` to `rerank_multivector(...)` raises a `ValueError` if any of the input result sets is missing the `_rowid` column. Therefore, it's recommended to add `.with_row_id(True)` to every `table.search(...)` call before reranking, or omit `deduplicate=True` if you don't need it. * `RRFReranker.rerank_multivector(...)` always requires `_rowid` on its inputs, regardless of the `deduplicate` flag. ## Implement a custom ranking policy Python custom rerankers implement `rerank_hybrid()` and can optionally implement `rerank_vector()` and `rerank_fts()`. TypeScript and Rust expose hybrid reranking interfaces. See [the interface requirements](#custom) before implementing one. ## Algorithm options The following sections describe the Python constructor options and examples. Provider and local-model examples require their additional packages and model or credential setup. They are separate programs, not steps to concatenate. ## Reciprocal rank fusion > [accordion] RRF options and examples > > **Reciprocal Rank Fusion (RRF)** is a model-free way to merge several ranked result lists into a > single ordering. Rather than comparing raw similarity scores (which aren't directly comparable > across, say, a vector search and a full-text search), RRF looks only at each document's *rank > position* in each list. It scores every document with the formula `1 / (rank + K)`, sums those > contributions across the lists, and re-sorts by the total. Documents that rank highly in more than > one search rise to the top. Because there's no model to load or call, it's fast and cheap, which is > why it's the default reranker for LanceDB hybrid search. The implementation follows the > [Cormack et al. paper](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf). > > > **Supported query types:** hybrid search and [multi-vector reranking](/oss/v0-41-0/reranking#multi-vector-reranking). > > Because RRF fuses two or more ranked lists, it can't rerank a single vector or full-text result set > > on its own. Calling `rerank_vector` or `rerank_fts` on an `RRFReranker` raises `NotImplementedError`. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import RRFReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "rrf-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = RRFReranker() > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `K` | `int` | `60` | A constant used in the RRF formula (default is 60). Larger values reduce the difference in contribution between nearby rank positions. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score`. If "all", will return all scores from the vector and FTS search along with the relevance score. | > > `K` must be greater than `0`. In TypeScript, construct the built-in reranker with > `await RRFReranker.create(k)` before passing it to `.rerank(...)`. > > ### Multi-vector reranking > > `RRFReranker` can also fuse the results of several vector searches with `rerank_multivector`, applying > the same rank-fusion algorithm across more than two lists. Every input result set must include the > `_rowid` column, so add `.with_row_id(True)` to each `table.search(...)` call before reranking, > otherwise the call raises a `ValueError`. See [multi-vector reranking](/oss/v0-41-0/reranking#multi-vector-reranking) > for a full example. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` as the score column alongside the selected data columns. | > | `all` | ✅ Supported | Returned rows have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | ## Linear combination > [accordion] Linear combination options (deprecated) > > > **Note:** This reranker is deprecated. Use `RRFReranker` to combine vector and full-text rankings. > > The Linear Combination Reranker combines the results of semantic and full-text search using a linear combination of the scores. The weights for the linear combination can be specified, and defaults to 0.7, i.e, 70% weight for semantic search and 30% weight for full-text search. > > > **Note:** Supported query type: Hybrid search only. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import LinearCombinationReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "linear-combination-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = LinearCombinationReranker() > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `weight` | `float` | `0.7` | The weight to use for the semantic search score. The weight for the full-text search score is `1 - weight`. | > | `fill` | `float` | `1.0` | Score used when a result is missing from one side of the hybrid query. The default strongly penalizes missing vector or FTS matches. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", returns only `_relevance_score`. If "all", returns all scores from the vector and FTS search along with the relevance score. | > > `weight` must be between `0` and `1`. If either the vector or FTS side returns no rows, the reranker > returns the non-empty side with `_relevance_score` attached rather than failing. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns | > | `all` | ✅ Supported | Results have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`) | ## MRR > [accordion] MRR options and examples > > This reranker uses the Mean Reciprocal Rank (MRR) algorithm to combine and rerank search results from vector and full-text search. You can use this reranker by passing `MRRReranker()` to the `rerank()` method. The MRR algorithm calculates the average of reciprocal ranks across different search results, providing a balanced way to merge results from multiple ranking systems. > > > **Note:** Supported query types: Hybrid and Multivector search. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import MRRReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "mrr-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = MRRReranker(weight_vector=0.7, weight_fts=0.3) > > # Run hybrid search with a reranker > tbl.create_fts_index("text", replace=True) > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > > # Run multivector search across multiple vector columns > rs1 = tbl.search("hello").limit(10).with_row_id(True).to_arrow() > rs2 = tbl.search("greeting").limit(10).with_row_id(True).to_arrow() > combined = MRRReranker().rerank_multivector([rs1, rs2]) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `weight_vector` | `float` | `0.5` | Weight for vector search results (0.0 to 1.0). | > | `weight_fts` | `float` | `0.5` | Weight for FTS search results (0.0 to 1.0). | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score`. If "all", will return all scores from the vector and FTS search along with the relevance score. | > > **Note:** `weight_vector` + `weight_fts` must equal 1.0. > > For multivector reranking, input result sets need `_rowid` so LanceDB can identify the same row > across the ranked lists. Add `.with_row_id(True)` to each vector search before passing the results > to the reranker. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | > > #### Multivector Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector distances from all searches along with `_relevance_score`. | ## Cross encoder > [accordion] Cross-encoder options and examples > > This reranker uses Cross Encoder models from sentence-transformers to rerank the search results. You can use this reranker by passing `CrossEncoderReranker()` to the `rerank()` method. > > > **Note:** Supported query types: Hybrid, Vector, and FTS. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > from lancedb.rerankers import CrossEncoderReranker > > embedder = get_registry().get("sentence-transformers").create() > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cross-encoder-rerank")) > > class Schema(LanceModel): > text: str = embedder.SourceField() > vector: Vector(embedder.ndims()) = embedder.VectorField() > > data = [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > tbl = db.create_table("test", schema=Schema) > tbl.add(data) > reranker = CrossEncoderReranker() > > # Run vector search with a reranker > result = tbl.search("hello").rerank(reranker=reranker).to_list() > > # Build the full-text index before either FTS or hybrid search. > tbl.create_fts_index("text", replace=True) > > # Run FTS search with a reranker > result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() > > # Run hybrid search with a reranker > result = ( > tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() > ) > ``` > > ### Python arguments > > | Argument | Type | Default | Description | > | - | - | - | - | > | `model_name` | `str` | `"cross-encoder/ms-marco-TinyBERT-L-6"` | The name of the reranker model to use. | > | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | > | `device` | `str` | `None` | The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu". | > | `trust_remote_code` | `bool` | `True` | Passed to Sentence Transformers model loading. Set this to `False` when you only want to load models that do not require custom repository code. | > | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", returns only `_relevance_score`. If "all" is supported, returns relevance score along with the vector and/or FTS scores depending on query type. | > > The reranker loads the model locally through `sentence-transformers`, so install the local model > runtime dependencies you need, such as PyTorch and any device-specific acceleration packages. > > ### Supported Scores for each query type > > You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: > > #### Hybrid Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Keeps `_distance`, `_score` and `_relevance_score` alongside the data columns. | > > #### Vector Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | > > #### FTS Search > > | `return_score` | Status | Description | > | - | - | - | > | `relevance` | ✅ Supported | Keeps `_relevance_score` alongside the selected data columns. | > | `all` | ✅ Supported | Results have FTS(`_score`) along with Hybrid Search score(`_relevance_score`). | ## Building a custom reranker You can build your own custom reranker in LanceDB by subclassing the base `Reranker` class. At a minimum, you need to implement `rerank_hybrid()`, which is the logic that combines vector and full-text search results. Beyond that, you can optionally implement `rerank_vector()` and `rerank_fts()` if you want your reranker to also handle pure vector or pure full-text searches. Implement the hooks your query paths call. The base class raises `NotImplementedError` for vector-only or FTS-only reranking unless you implement those methods. The Python base class exposes hybrid, vector-only, and FTS-only rerank hooks. TypeScript and Rust currently expose the custom reranker interface for hybrid reranking. In Rust, a custom reranker must also satisfy the trait bounds `Debug + Send + Sync`. ### Interface The `Reranker` base interface comes with a `merge_results()` method that can be used to combine the results of semantic and full-text search. This is a vanilla merging algorithm that simply concatenates the results and removes the duplicates without taking the scores into consideration. It only keeps the first copy of the row encountered. This works well in cases that don't require the scores of semantic and full-text search to combine the results. If you want to use the scores or want to support `return_score="all"`, you'll need to implement your own merging algorithm. The base `return_score` option accepts only `"relevance"` and `"all"`. Whichever methods you override, your reranker has one job on the way out: attach a `_relevance_score` column with the most relevant rows at the top. LanceDB will reject the result if that column is missing, and downstream `.limit(...)` calls trust the order you return, so sort descending before handing the table back. For vector-only reranking in Python, pass a text query to `.rerank(..., query_string="...")`. The vector query itself may be numeric, but `rerank_vector(query, vector_results)` still receives a string query so your reranker can score each candidate against the user's text intent. The method contract is: | Method | Input | Required output | | :- | :- | :- | | `rerank_hybrid` | Query text, vector results and FTS results | A merged Arrow table ordered by descending `_relevance_score` | | `rerank_vector` | Query text and vector results | An Arrow table ordered by descending `_relevance_score` | | `rerank_fts` | Query text and FTS results | An Arrow table ordered by descending `_relevance_score` | Implement only the single-search hooks your application uses. The base class raises `NotImplementedError` for those hooks until they are implemented. ### Extend an existing reranker This class definition extends `CohereReranker` to exclude text patterns after reranking. It requires the Cohere package and credentials when instantiated. It can return fewer results because exclusions happen after retrieval; use a query predicate instead when a metadata filter expresses the same restriction. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import List, Union import pyarrow as pa from lancedb.rerankers import CohereReranker class ModifiedCohereReranker(CohereReranker): def __init__(self, filters: Union[str, List[str]], **kwargs): super().__init__(**kwargs) filters = filters if isinstance(filters, list) else [filters] self.filters = filters def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table)-> pa.Table: combined_result = super().rerank_hybrid(query, vector_results, fts_results) df = combined_result.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) def rerank_vector(self, query: str, vector_results: pa.Table)-> pa.Table: vector_results = super().rerank_vector(query, vector_results) df = vector_results.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) def rerank_fts(self, query: str, fts_results: pa.Table)-> pa.Table: fts_results = super().rerank_fts(query, fts_results) df = fts_results.to_pandas() for filter in self.filters: df = df.query("not text.str.contains(@filter)") return pa.Table.from_pandas(df) ``` The reranker receives and returns PyArrow tables. Use `to_pandas()` for a DataFrame transformation and `pa.Table.from_pandas()` to convert the result back, preserving `_relevance_score` and the desired row order. ## Evaluate relevance, latency and cost Compare rerankers on the same candidate inputs so you can distinguish ranking changes from retrieval changes. For hybrid retrieval, prepare the text index and query vectors before collecting those candidates. ### Reranking strategies Compare these approaches: * **Rank fusion:** RRF and MRR combine rank positions from multiple result lists. * **Score blending:** linear combination mixes normalized vector and text scores. * **Model-based reranking:** a model scores each query-document pair. Hybrid search uses RRF by default. You do not need to call `rerank()` to select it. Pass a reranker when you want a different algorithm or configuration. By default, rerankers return `_relevance_score`. Pass `return_score="all"` when a reranker supports it, and you also need the original vector or FTS scores for debugging. Evaluation code can rely on returned rows being ordered by descending `_relevance_score`. Empty reranked result sets still include the `_relevance_score` column. The synchronous Python hybrid `rerank(...)` method also accepts a `normalize` argument that controls how the raw vector and FTS scores are made comparable before reranking: * `normalize="score"` (the default); normalizes the raw vector and FTS scores directly. * `normalize="rank"`; converts each result list to ranks first, then normalizes. Normalization matters for algorithms that use raw scores, such as linear combination. RRF uses rank positions instead. Compare normalization settings only when the chosen reranker uses those scores. For score-based evaluation, the main built-in knobs are: * `RRFReranker(K=60)`: rank fusion with a positive smoothing constant. * `MRRReranker(weight_vector=0.5, weight_fts=0.5)`: weighted reciprocal rank fusion where the weights must sum to `1.0`. * `LinearCombinationReranker(weight=0.7, fill=1.0)`: blends vector and FTS scores directly; `fill` controls how strongly to penalize a result missing from one side. A result on one dataset does not establish which reranker will work best on another. Include representative queries and measure both retrieval quality and ranking quality. ### Historical evaluation example The tables below preserve an earlier experiment comparing multiple rerankers on \~800 hybrid search queries. This is a modified version of an evaluation script by [LlamaIndex](https://github.com/run-llama/finetune-embedding/blob/main/evaluate.ipynb) that measures hit-rate @ top-k. The recorded results do not establish performance for current models, SDK releases or your dataset; treat them as an example of an evaluation format. #### Using OpenAI `text-embedding-ada-002` Vector Search baseline: **0.64** | Reranker | Top-3 | Top-5 | Top-10 | | - | - | - | - | | Linear Combination | `0.73` | `0.74` | `0.85` | | Cross Encoder | `0.71` | `0.70` | `0.77` | | Cohere | `0.81` | `0.81` | `0.85` | | ColBERT | `0.68` | `0.68` | `0.73` | ![](https://github.com/AyushExel/assets/assets/15766192/d57b1780-ef27-414c-a5c3-73bee7808a45) #### Using OpenAI `text-embedding-3-small` Vector Search baseline: **0.59** | Reranker | Top-3 | Top-5 | Top-10 | | - | - | - | - | | Linear Combination | `0.68` | `0.70` | `0.84` | | Cross Encoder | `0.72` | `0.72` | `0.79` | | Cohere | `0.79` | `0.79` | `0.84` | | ColBERT | `0.70` | `0.70` | `0.76` | ![](https://github.com/AyushExel/assets/assets/15766192/259adfd2-6ec6-4df6-a77d-1456598970dd) ### Compare results on your workload Build a set of representative queries with known relevant records. Compare retrieval alone with each reranker using the same candidate inputs and result limit. Record a relevance metric such as recall or nDCG alongside latency and provider cost. Include queries with no useful matches and queries containing exact names or identifiers. If the relevant records never reach the reranker, adjust retrieval first. Then change one ranking setting at a time and retain the configuration that meets your application's quality and latency requirements. # Metadata Filtering in LanceDB Source: https://docs.lancedb.com/oss/v0-41-0/search/filtering Use predicates to select rows and control when filters apply to search. **Applies to:** Embedded ✅, Enterprise ✅ A filter restricts results to rows that satisfy a condition. Use it on its own to select records, or combine it with vector, full-text or hybrid search. For example, search for similar documents only within a particular category. > [accordion] Run a complete filtering example > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `filtered_search.py`, then run `python filtered_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `filtered_search.mts`, then run `node filtered_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([0.0, 1.0]) > .where("category = 'animals'", prefilter=True) > .select(["id", "text", "category", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([0.0, 1.0]) > .where("category = 'animals'") > .select(["id", "text", "category", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[0.0_f32, 1.0])? > .only_if("category = 'animals'") > .select(Select::columns(&["id", "text", "category", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The query vector is closest to the gardening record, but the filter excludes > that category. The results contain only the two animal records. ## Prefiltering and postfiltering * **Prefiltering**, the default, limits the rows eligible for retrieval before search chooses its candidates. * **Postfiltering** removes nonmatching rows after candidates are selected. It can return fewer than `limit` rows, including zero, even when matching records exist elsewhere in the table. Both modes exclude rows that fail the predicate. They differ in which matching rows the search can find. On hybrid queries, the filter applies to both the vector and full-text searches. SDK filters use SQL expressions without requiring a SQL connection. For Enterprise SQL queries, see [SELECT](/oss/v0-41-0/sql/dql/select#filtering). ## Filtering examples by language The following excerpts use a connected `db` handle. Create this sample table before running the queries beneath it; each query uses the same four records. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"vector": [3.1, 4.1], "item": "foo", "price": 10.0}, {"vector": [5.9, 26.5], "item": "bar", "price": 20.0}, {"vector": [10.2, 100.8], "item": "baz", "price": 30.0}, {"vector": [1.4, 9.5], "item": "fred", "price": 40.0}, ] table = db.create_table("metadata_filter_example", data=data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const data = [ { vector: [3.1, 4.1], item: "foo", price: 10.0 }, { vector: [5.9, 26.5], item: "bar", price: 20.0 }, { vector: [10.2, 100.8], item: "baz", price: 30.0 }, { vector: [1.4, 9.5], item: "fred", price: 40.0 }, ]; const tableName = "metadata_filter_example"; const table = await db.createTable(tableName, data, { mode: "overwrite", }); ``` ## Combine predicates Repeated filter calls combine predicates with logical `AND`. For example, `where("a > 0").where("b < 10")` is equivalent to `where("(a > 0) AND (b < 10)")`. Use a single expression for a fixed filter. Chain calls when your application builds the filter incrementally. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Both filters apply: item is in the list AND price is above 15. result = ( table.search([100, 102]) .where("item IN ('foo', 'bar', 'baz')") .where("price > 15.0") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Both filters apply: item is in the list AND price is above 15. const result = await table .search([100, 102]) .where("item IN ('foo', 'bar', 'baz')") .where("price > 15.0") .limit(3) .toArray(); ``` > [!WARNING] > > In Python SDK versions before `0.34.0` and Rust/TypeScript SDK versions before `0.31.0`, a second `where(...)` or `only_if(...)` call replaced the first filter, so only the last predicate was applied. If your code needs to run on those older versions, write a single predicate with `AND` instead of chaining calls. When upgrading to the latest SDKs, review any existing chained filters and drop earlier calls you no longer want to apply. ### Filtering Without Vector Search You can always filter your data without search. This is useful when you need to query based on metadata: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered_no_search_result = ( table.search() .where("(item IN ('foo', 'bar', 'baz')) AND (price > 15.0)") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const filteredResult = await table .query() .where("(item IN ('foo', 'bar', 'baz')) AND (price > 15.0)") .limit(3) .toArray(); ``` Set `limit()` explicitly to control how many matching records your application receives. ### Pre-Filtering with Vector Search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered_result = ( table.search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .limit(3) .toArray(); ``` ### Post-Filtering with Vector Search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} post_filtered_result = ( table.search([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)", prefilter=False) .limit(3) .to_arrow() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const postFilteredResult = await table.vectorSearch([100, 102]) .where("(item IN ('foo', 'bar')) AND (price > 15.0)") .postfilter() .limit(3) .toArray(); ``` Postfiltering can return fewer than the requested number of records because the predicate removes candidates after search. ## Write SQL predicates Pass a SQL expression as the filter string. These expressions also select rows for SDK update and delete operations; they are not standalone SQL statements. LanceDB supports a growing list of SQL expressions: | SQL Expression | Description | | :- | :- | | `>, >=, <, <=, =` | Comparison operators | | `AND`, `OR`, `NOT` | Logical operators | | `IS NULL`, `IS NOT NULL` | Null checks | | `IS TRUE`, `IS NOT TRUE`, `IS FALSE`, `IS NOT FALSE` | Boolean checks | | `IN` | Value matching from a set | | `LIKE`, `NOT LIKE` | Pattern matching | | `CAST` | Type conversion | | `regexp_match(column, pattern)` | Regular expression matching | | [DataFusion Functions](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) | Additional SQL functions | ### Simple SQL Filters For example, the following filter string is acceptable: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search([100, 102]).where( "(item IN ('foo', 'baz')) AND (price > 20.0)" ).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .search([100, 102]) .where("(item IN ('foo', 'baz')) AND (price > 20.0)") .toArray(); ``` ### Advanced SQL Filters If your column name contains special characters, upper-case characters, or is a [SQL Keyword](https://docs.rs/sqlparser/latest/sqlparser/keywords/index.html), you can use backtick (`` ` ``) to escape it. For nested fields, each segment of the path must be wrapped in backticks. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} `CUBE` = 10 AND `UpperCaseName` = '3' AND `column name with space` IS NOT NULL AND `nested with space`.`inner with space` < 2 ``` > [!NOTE] > > Periods separate nested fields. LanceDB does not allow a literal period in a > top-level column name; backticks do not remove that restriction. ### Dates, Timestamps, Decimals Literals for dates, timestamps, and decimals can be written by writing the string value after the type name. For example: ```sql SQL icon="SQL" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} date_col = date '2021-01-01' and timestamp_col = timestamp '2021-01-01 00:00:00' and decimal_col = decimal(8,3) '1.000' ``` For timestamp columns, the precision can be specified as a number in the type parameter. Microsecond precision (6) is the default. | SQL | Time unit | | :- | :- | | `timestamp(0)` | Seconds | | `timestamp(3)` | Milliseconds | | `timestamp(6)` | Microseconds | | `timestamp(9)` | Nanoseconds | ## Apache Arrow Mapping LanceDB uses Arrow types for schemas and in-memory data. On disk, tables use the [Lance format](/oss/v0-41-0/basics/lance). The mapping from SQL types to Arrow types is: | SQL type | Arrow type | | :- | :- | | `boolean` | `Boolean` | | `tinyint` / `tinyint unsigned` | `Int8` / `UInt8` | | `smallint` / `smallint unsigned` | `Int16` / `UInt16` | | `int` or `integer` / `int unsigned` or `integer unsigned` | `Int32` / `UInt32` | | `bigint` / `bigint unsigned` | `Int64` / `UInt64` | | `float` | `Float32` | | `double` | `Float64` | | `decimal(precision, scale)` | `Decimal128` | | `date` | `Date32` | | `timestamp` | `Timestamp` | | `string` | `Utf8` | | `binary` | `Binary` | ## Speed up frequently used filters Consider a [scalar index](/oss/v0-41-0/indexing/scalar-index) on frequently filtered columns. Use the query plan to check whether a predicate uses that index. Functions or casts applied to a column can change which optimizations are available. For list columns, a label-list index supports membership filters such as `array_has_any` and `array_has_all`. ## Understand missing matches A restrictive predicate can legitimately leave fewer rows than the requested limit. Approximate vector search can also miss qualifying neighbors, and postfiltering can discard candidates without retrieving replacements. For a recall comparison, run the same query and predicate while bypassing the vector index on a suitably sized test table. Then compare the indexed query's results and latency while changing probe or refinement settings. Increasing those settings does not guarantee a full result set. See [vector search](/oss/v0-41-0/search/vector-search) and [query plans](/oss/v0-41-0/basics/sql#query-plans). # Full-Text Search (FTS) Source: https://docs.lancedb.com/oss/v0-41-0/search/full-text-search Find records by words, phrases or partial matches using a full-text index. **Applies to:** Embedded ✅, Enterprise ✅ Full-text search finds documents by matching words and ranks them with BM25. Use it to search for names, product codes, technical terms or phrases in your text columns. Create an FTS index on the column before running a query. You can also combine keyword matches with vector similarity using [hybrid search](/oss/v0-41-0/search/hybrid-search). > [accordion] Run a complete full-text search example > > Each example creates a temporary local table, runs the query and removes the > table when finished. No embedding model is needed for a text query. > > * **Python:** Install with `pip install lancedb`, save as `text_search.py`, then run `python text_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `text_search.mts`, then run `node text_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > }, > ], > ) > table.create_index("text", config=FTS()) > rows = ( > table.search("puppy", query_type="fts", fts_columns="text") > .select(["id", "text", "_score"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { id: 1, text: "A puppy playing in the park", category: "animals" }, > { id: 2, text: "A dog resting at home", category: "animals" }, > { id: 3, text: "A guide to growing tomatoes", category: "gardening" }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const rows = await table > .query() > .fullTextSearch("puppy", { columns: ["text"] }) > .select(["id", "text", "_score"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .query() > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .select(Select::columns(&["id", "text", "_score"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > Each example searches the indexed `text` column and returns the puppy record. > Higher `_score` values rank first; they are relevance scores, not probabilities. ## Basic usage The steps below create a table, index its `text` column and search for a word. For a standalone program with imports and sample data, expand the complete example above. ### Create the sample table First, open or create the table you want to search: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS uri = "data/sample-lancedb" db = lancedb.connect(uri) table = db.create_table( "my_table_fts", data=[ {"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}, {"vector": [5.9, 26.5], "text": "There are several kittens playing"}, ], ) ``` ```ts TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const uri = "data/sample-lancedb" const db = await lancedb.connect(uri); const data = [ { vector: [3.1, 4.1], text: "Frodo was a happy puppy" }, { vector: [5.9, 26.5], text: "There are several kittens playing" }, ]; const tbl = await db.createTable("my_table", data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let uri = "data/sample-lancedb"; let db = connect(uri).execute().await?; let initial_data: Box<dyn RecordBatchReader + Send> = create_some_records()?; let tbl = db .create_table("my_table", initial_data) .execute() .await?; ``` ### Build the text index Create a full-text search index on your text column: For asynchronous Python index creation, use `await table.create_index("text", config=FTS())`. See [FTS index](/oss/v0-41-0/indexing/fts-index). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index("text", config=FTS()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.createIndex("text", { config: lancedb.Index.fts(), }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) .execute() .await?; ``` LanceDB Embedded builds the index before the call returns. Enterprise builds it in the background. Wait for completion with Python’s `table.wait_for_index(["text_idx"])` or TypeScript’s `await tbl.waitForIndex(["text_idx"], 300)` before querying it. Use your actual index name if you chose a different one. ### Run the query Perform full-text search and retrieve results: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("puppy", query_type="fts", fts_columns="text") .limit(10) .select(["text", "_score"]) .to_list() ) # Returns the puppy record with its BM25 score. ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await tbl .search("puppy", "fts") .select(["text"]) .limit(10) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let results = tbl .query() .full_text_search(FullTextSearchQuery::new("puppy".to_owned())) .select(lancedb::query::Select::Columns(vec!["text".to_owned()])) .limit(10) .execute() .await?; ``` Specify the text column with `fts_columns="text"` in synchronous Python, especially when the table contains multiple text indexes. > [!NOTE] > > A string query can also invoke an embedding function when the table has > embedding metadata. Use `query_type="fts"` in Python when you specifically > want full-text search. If a table has more than one FTS index, specify the indexed text column in the query. In Python you can use `fts_columns` or the query builder's `nearest_to_text(..., columns=...)`; in TypeScript, use `query().nearestToText(..., columns)`. The newer Lance-native FTS does not accept legacy Tantivy-only index parameters. BM25 scores depend on the indexed corpus and its term statistics. Compare rankings on the dataset you will search; treat scores as relative relevance values rather than probabilities. ### Keeping the index up to date In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. Search includes those rows by scanning them, but that work can increase query latency. Call `optimize()` to update the index: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add([{"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}]) table.optimize() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.add([{ vector: [3.1, 4.1], text: "Frodo was a happy puppy" }]); await tbl.optimize(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.add(new_data).execute().await?; tbl.optimize(OptimizeAction::All).await?; ``` Choose a LanceDB Embedded maintenance schedule based on write volume and query latency. Inspect index coverage with `table.index_stats(...)` and optimize when the unindexed data adds too much work. `.fast_search()` skips unindexed rows, so use it only when omitting recent records is acceptable. Enterprise manages index updates automatically. You do not call `optimize()` on an Enterprise table. ## Choose the matching behavior | You need | Use | | :- | :- | | Words in any order | A terms query | | Words in a particular sequence | A [phrase query](#phrase-vs-terms-queries) and an index with token positions | | Tolerance for typing errors | [Fuzzy search](#fuzzy-search) | | Parts of words | An [n-gram index](#search-for-substring) | | Required, optional or excluded terms | [Boolean queries](#boolean-queries) | Use a metadata predicate to restrict qualifying records. See [filtering options](#filtering-options) for prefiltering and postfiltering. Enterprise SQL provides [`fts()`](/oss/v0-41-0/sql/dql/fts) for scored text retrieval. ## Configure tokenization and matching ### Tokenize Table Data The default tokenizer splits text at whitespace and punctuation, lowercases tokens and removes tokens longer than 40 characters. Stemming, stop-word removal and accent folding are also enabled by default. Stemming is useful for improving search results by reducing words to their root form, e.g. "running" to "run". LanceDB supports stemming for Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. You should set the `base_tokenizer` parameter rather than `tokenizer_name` because you cannot customize the tokenizer if `tokenizer_name` is specified. Tokenization and language filters are separate settings. `base_tokenizer` controls how text is split into searchable tokens. `language` controls stemming and stop-word removal when `stem=True` or `remove_stop_words=True`; choose the tokenizer for CJK or mixed-language segmentation. For example, to enable stemming for English: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index("text", language="English", replace=True) ``` Configure tokenization when you create the index. Rebuild the index to change how existing text is tokenized. **Default index parameters:** * `base_tokenizer`: `"simple"` * `language`: English * `with_position`: false * `max_token_length`: 40 * `lower_case`: true * `stem`: true * `remove_stop_words`: true * `ascii_folding`: true * `custom_stop_words`: `None`; pass a `list[str]` to drop additional words beyond the language defaults. Requires `remove_stop_words=True`. For multilingual use cases, use `base_tokenizer="icu"` for unicode-aware word segmentation on mixed-language text. ICU stands for [International Components for Unicode](https://icu.unicode.org/). The ICU tokenizer uses bundled ICU4X segmenter data, so it does not require external tokenizer model files. It is a good default when documents mix languages or include scripts where the simple tokenizer would keep an unspaced span as one large token. The Python API also supports tokenizer implementations that load language model files. Use `base_tokenizer="jieba/default"` for Jieba tokenization, which segments Chinese text into searchable word tokens when the text is written without spaces between words. Use Lindera-backed tokenizers for dictionary-based East Asian morphological segmentation, such as `base_tokenizer="lindera/ipadic"` for Japanese or `base_tokenizer="lindera/ko-dic"` for Korean when you have installed and compiled that Lindera model. These are language-specific tokenizers; ICU is the broader mixed-language option. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index( "text", base_tokenizer="jieba/default", stem=False, remove_stop_words=False, ascii_folding=False, replace=True, ) ``` Model-backed tokenizers require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to a different model root: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCE_LANGUAGE_MODEL_HOME=/path/to/lance/language_models ``` For example, `jieba/default` is resolved under `<model-home>/jieba/default/...`, `lindera/ipadic` under `<model-home>/lindera/ipadic/...`, and `lindera/ko-dic` under `<model-home>/lindera/ko-dic/...`. Model files must be installed where indexing and queries run: on your machine for LanceDB Embedded, or on the Enterprise cluster for an Enterprise table. > [!NOTE] > > Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. If you use another stemming language, such as Arabic, Greek, Romanian, Tamil, or Turkish, set `remove_stop_words=False` or pass `custom_stop_words`. Use `ascii_folding=True` to match accented and unaccented forms, such as “é” and “e”: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_fts_index( "text", language="French", stem=True, ascii_folding=True, replace=True, ) ``` ### Filtering Options Use `where(...)` to restrict text results to rows that match a predicate. Prefiltering applies the restriction before retrieval; postfiltering removes nonmatching candidates afterward and can leave fewer results. With pre-filtering: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search("puppy").limit(10).where("text='foo'", prefilter=True).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl .search("puppy") .select(["id", "doc"]) .limit(10) .where("meta='foo'") .prefilter(true) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .query() .full_text_search(FullTextSearchQuery::new("puppy".to_owned())) .select(lancedb::query::Select::Columns(vec!["doc".to_owned()])) .limit(10) .only_if("meta='foo'") .execute() .await?; ``` With post-filtering: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search("puppy").limit(10).where("text='foo'", prefilter=False).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl .search("apple") .select(["id", "doc"]) .limit(10) .where("meta='foo'") .prefilter(false) .toArray(); ``` ```rust Rust icon="Rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .query() .full_text_search(FullTextSearchQuery::new(words[0].to_owned())) .select(lancedb::query::Select::Columns(vec!["doc".to_owned()])) .postfilter() .limit(10) .only_if("meta='foo'") .execute() .await?; ``` ### Phrase vs. Terms Queries > [!WARNING] > > Lance-based FTS doesn't support queries using boolean operators `OR`, `AND` in the search string. For full-text search you can specify either a **phrase** query like `"the old man and the sea"`, or a **terms** search query like `old man sea`. Enable token positions to search for phrases. Set `remove_stop_words=False` if you also need to match common words such as “the” and “and”: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS table.create_index("text", config=FTS(with_position=True, remove_stop_words=False), replace=True) ``` Storing token positions increases the index size and adds indexing work. ### Fuzzy Search Fuzzy search allows you to find matches even when the search terms contain typos or slight variations. LanceDB uses the classic [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) to find similar terms within a specified edit distance. | Parameter | Type | Default | Description | | - | - | - | - | | fuzziness | int | 0 | Maximum edit distance allowed for each term. The default, `0`, requires an exact match; set `1` or `2` to allow typos. | | max_expansions | int | 50 | Maximum number of terms to consider for fuzzy matching. Higher values may improve recall but increase search time | For a complete walkthrough that creates a sample table and demonstrates fuzzy search and relevance boosting, see [the worked example below](#fuzzy-search-and-boosting-example). ### Search for Substring LanceDB supports searching for substrings in the text column, you can set the `base_tokenizer` parameter to `"ngram"` to enable this feature, and use the parameters `ngram_min_length` and `ngram_max_length` to control the length of the substrings: | Parameter | Type | Default | Description | | - | - | - | - | | ngram_min_length | int | 3 | Minimum length of the n-grams to search for | | ngram_max_length | int | 3 | Maximum length of the n-grams to search for | | prefix_only | bool | false | Whether to only search for prefixes of the n-grams | ## Expected performance at scale Enterprise At 1 billion rows, LanceDB Enterprise reaches p50 62 ms and p99 274 ms on fully cached data with no custom tuning -- a representative floor to plan around, not a ceiling. Measured under a mixed workload of phrase, match-any and match-all queries, with an ICU-tokenized FTS v3 index (positions and lowercasing enabled, stemming disabled). The exact numbers depend on your deployment's shape (cluster size, storage class, dataset); for higher performance, talk to the sales team. ## Fuzzy Search and Boosting Example > [accordion] Worked examples: fuzzy, phrase, boosted and Boolean queries > > ### Generate Data > > Run the following steps in order. They use a temporary local database with four records, so the same data is available for each query. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import pandas as pd > from lancedb.index import FTS > from lancedb.query import MatchQuery, PhraseQuery, BoostQuery, MultiMatchQuery > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > table_name = "fts_examples" > text = ["puppy runs merrily", "car drives crazily", "puppy jumps crazily", "car runs slowly"] > text2 = ["rabbit jumps crazily", "girl runs merrily", "monkey jumps slowly", "rabbit runs merrily"] > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import * as lancedb from "@lancedb/lancedb"; > import { Index, MatchQuery, PhraseQuery, BoostQuery, MultiMatchQuery, BooleanQuery, Occur } from "@lancedb/lancedb"; > import { mkdtemp, rm } from "node:fs/promises"; > import { tmpdir } from "node:os"; > import { join } from "node:path"; > > const directory = await mkdtemp(join(tmpdir(), "lancedb-fts-")); > const db = await lancedb.connect(directory); > const tableName = "fts_examples"; > const text = ["puppy runs merrily", "car drives crazily", "puppy jumps crazily", "car runs slowly"]; > const text2 = ["rabbit jumps crazily", "girl runs merrily", "monkey jumps slowly", "rabbit runs merrily"]; > ``` > > ### Create Table > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create table with sample data > table = db.create_table( > table_name, > data=pd.DataFrame({ > "id": range(len(text)), > "text": text, > "text2": text2, > }), > mode="overwrite" > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create table with sample data > const data = text.map((value, i) => ({ id: i, text: value, text2: text2[i] })); > > const table = await db.createTable(tableName, data, { mode: "overwrite" }); > ``` > > ### Construct the index for these examples > > Create a full-text search index on the first text column: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index on first text column > table.create_index("text", config=FTS(with_position=True, remove_stop_words=False)) > table.wait_for_index(["text_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index on first text column > await table.createIndex("text", { config: Index.fts({ withPosition: true, removeStopWords: false }) }); > await table.waitForIndex(["text_idx"], 300); > ``` > > Then, create an index on the second text column: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index on second text column > table.create_index("text2", config=FTS(with_position=True, remove_stop_words=False)) > table.wait_for_index(["text2_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index on second text column > await table.createIndex("text2", { config: Index.fts({ withPosition: true, removeStopWords: false }) }); > await table.waitForIndex(["text2_idx"], 300); > ``` > > ### Basic and Fuzzy Search > > Now we can perform basic, fuzzy, and prefix match searches: > > #### Basic Exact Search > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > # Basic match (exact search) > basic_match_results = ( > table.search(MatchQuery("crazily", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Basic match (exact search) > const basicMatchResults = await table.query() > .fullTextSearch(new MatchQuery("crazily", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Fuzzy Search with Typos > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Fuzzy match (allows typos) > fuzzy_results = ( > table.search(MatchQuery("craziou", "text", fuzziness=2)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Fuzzy match (allows typos) > const fuzzyResults = await table.query() > .fullTextSearch(new MatchQuery("craziou", "text", { > fuzziness: 2, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Require an exact prefix in fuzzy matching > > `prefix_length` keeps the first characters unchanged when matching a misspelled term. It does not turn a short query into a prefix-completion search. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Fuzzy match (allows typos) > prefix_results = ( > table.search(MatchQuery("craziou", "text", fuzziness=2, prefix_length=3)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Fuzzy match (allows typos) > const prefixResults = await table.query() > .fullTextSearch(new MatchQuery("craziou", "text", { > fuzziness: 2, > prefixLength: 3, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Phrase Match > > Phrase matching enables you to search for exact sequences of words. Unlike regular text search > which matches individual terms independently, phrase matching requires words to appear in the > specified order with no intervening terms. > > > [!NOTE] > > > > Phrase queries are supported but only for a single column; providing multiple columns with a quoted phrase raises an error. > > Phrase matching is particularly useful for: > > * Searching for specific multi-word expressions > * Matching exact titles or quotes > * Finding precise word combinations in a specific order > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Exact phrase match > from lancedb.query import PhraseQuery > > phrase_results = ( > table.search(PhraseQuery("puppy runs", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Exact phrase match > const phraseResults = await table.query() > .fullTextSearch(new PhraseQuery("puppy runs", "text")) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > #### Flexible Phrase Match > > To provide more flexible phrase matching, LanceDB supports the `slop` parameter. This allows you to match phrases where the terms appear close to each other, with gaps between them. The `slop` value limits the extra positions allowed in the phrase. > > For example, the phrase query "puppy merrily" would not return any results by default. However, if you set `slop=1`, it will match phrases like "puppy jumps merrily", "puppy runs merrily", and similar variations where one word appears between "puppy" and "merrily". > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Flexible phrase match with slop=1 for 'puppy merrily' > from lancedb.query import PhraseQuery > > slop_results = ( > table.search(PhraseQuery("puppy merrily", "text", slop=1)) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Flexible phrase match with slop=1 for 'puppy merrily' > const slopResults = await table.query() > .fullTextSearch(new PhraseQuery("puppy merrily", "text", { slop: 1 })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Search with Boosting > > Boosting allows you to control the relative importance of different search terms or fields > in your queries. This feature is particularly useful when you need to: > > * Prioritize matches in certain columns > * Promote specific terms while demoting others > * Fine-tune relevance scoring for better search results > > | Parameter | Type | Default | Description | > | - | - | - | - | > | positive | Query | required | The primary query terms to match and promote in results | > | negative | Query | required | Terms to demote in the search results | > | negative_boost | float | 0.5 | Multiplier for negative matches (lower values = stronger demotion) | > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery, BoostQuery, MultiMatchQuery > > # Boost data with 'runs' in text more than 'puppy' in text > boosting_results = ( > table.search( > BoostQuery( > MatchQuery("runs", "text"), > MatchQuery("puppy", "text"), > negative_boost=0.2, > ), > ) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Search across both text and text2 > multi_match_results = ( > table.search(MultiMatchQuery("crazily", ["text", "text2"])) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Search with field boosting > multi_match_boosting_results = ( > table.search( > MultiMatchQuery("crazily", ["text", "text2"], boosts=[1.0, 2.0]), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Boosting Example > const boostingResults = await table.query() > .fullTextSearch(new BoostQuery(new MatchQuery("runs", "text"), new MatchQuery("puppy", "text"), { > negativeBoost: 0.2, > })) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > > // Search across both text fields > const multiMatchResults = await table.query() > .fullTextSearch(new MultiMatchQuery("crazily", ["text", "text2"])) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .toArray(); > > // Search with field boosting > const multiMatchBoostingResults = await table.query() > .fullTextSearch(new MultiMatchQuery("crazily", ["text", "text2"], { > boosts: [1.0, 2.0], > })) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .toArray(); > ``` > > ### Search Columns as One Field > > > [!NOTE] > > > > `CombinedFieldsQuery` is not available in Python 0.41.0. This example uses the > > [0.42.0b8 client](/oss/v0-41-0/basics/sdk#enterprise-client-versions). `MultiMatchQuery` > > is available in 0.41.0, but does not have the same cross-field AND semantics. > > `MultiMatchQuery` scores each column on its own and keeps the best match. > `CombinedFieldsQuery` treats the columns as one field (BM25F), so with the `AND` > operator a row matches when every term appears in at least one of the columns. > The query below finds `car` in `text` and `merrily` in `text2`, returning rows 1 > and 3. The same query with `MultiMatchQuery` returns no rows, because neither > column contains both words on its own. > > Every column must use the same tokenizer configuration. The two indexes in this > example are built with the same `FTS` settings. Boosts work as they do for > `MultiMatchQuery`: one weight per column, each at least 1. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import CombinedFieldsQuery, FullTextOperator > > # Every term must appear in at least one of the two columns > combined_results = ( > table.search( > CombinedFieldsQuery("car merrily", ["text", "text2"], operator=FullTextOperator.AND), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Weight matches in text2 twice as much as matches in text > combined_boosting_results = ( > table.search( > CombinedFieldsQuery("car merrily", ["text", "text2"], boosts=[1.0, 2.0]), > ) > .select(["id", "text", "text2", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > The typed `CombinedFieldsQuery` convenience class and this example are specific > to the Python SDK. Rust applications can construct the core query type exposed > by `lancedb::index::scalar`. TypeScript and Java do not yet provide typed > convenience entry points for this query. > > ### Boolean Queries > > LanceDB supports boolean logic in full-text search, allowing you to combine multiple queries using `and` and `or` operators. This is useful when you want to match documents that satisfy multiple conditions (intersection) or at least one of several conditions (union). > > #### Combining Two Match Queries > > In Python, combine two `MatchQuery` objects with `&` for intersection or `|` for union. Python's `and` and `or` operators return one operand and do not construct a boolean query. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > intersection = MatchQuery("puppy", "text") & MatchQuery("merrily", "text") > union = MatchQuery("puppy", "text") | MatchQuery("merrily", "text") > ``` > > In TypeScript, pass `[Occur, subquery]` pairs to `BooleanQuery`. Use `Must` for required matches, `Should` for alternatives, and `MustNot` to exclude matches. > > > [!NOTE] > > > > **Which queries are allowed?** > > > > A boolean query must include at least one `SHOULD` or `MUST` clause. Queries that contain only a `MUST_NOT` clause are not allowed. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from lancedb.query import MatchQuery > > # Example: Find documents containing both "puppy" and "merrily" > and_query = MatchQuery("puppy", "text") & MatchQuery("merrily", "text") > and_results = ( > table.search(and_query) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > > # Example: Find documents containing either "puppy" or "merrily" > or_query = MatchQuery("puppy", "text") | MatchQuery("merrily", "text") > or_results = ( > table.search(or_query) > .select(["id", "text", "_score"]) > .limit(100) > .to_arrow().to_pandas() > ) > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Flexible boolean queries with MatchQuery > > // Find documents containing both "puppy" and "merrily" > const mustResults = await table > .search( > new BooleanQuery([ > [Occur.Must, new MatchQuery("puppy", "text")], > [Occur.Must, new MatchQuery("merrily", "text")], > ]), > ) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > > // Find documents containing either "puppy" or "merrily" > const shouldResults = await table > .search( > new BooleanQuery([ > [Occur.Should, new MatchQuery("puppy", "text")], > [Occur.Should, new MatchQuery("merrily", "text")], > ]), > ) > .select(["id", "text", "_score"]) > .limit(100) > .toArray(); > ``` > > > [!NOTE] > > > > **How to use booleans?** > > > > * Use `&` (Python), `Occur.Must` (TypeScript) for intersection (documents must match all queries). > > * Use `|` (Python), `Occur.Should` (TypeScript) for union (documents must match at least one query). > > ### Clean up the example > > Remove the temporary database when you have finished running the queries. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.close(); > db.close(); > await rm(directory, { recursive: true, force: true }); > ``` ## Substring Search Example > [accordion] Worked examples: substring search > > LanceDB supports searching for substrings in text columns using n-gram tokenization. This is useful for finding partial matches within text content. > > ### Setting Up the Table > > First, create a table with sample text data and configure n-gram tokenization: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import pyarrow as pa > from tempfile import TemporaryDirectory > from lancedb.index import FTS > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > > data = pa.table({"text": ["hello world", "lance database", "lance is cool"]}) > table = db.create_table("test", data=data) > table.create_index("text", config=FTS(base_tokenizer="ngram")) > ``` > > ### Basic Substring Search > > With the default n-gram settings (minimum length of 3), you can search for substrings of length 3 or more: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("lan", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > > results = ( > table.search("nce", query_type="fts").limit(10).to_list() > ) # spellchecker:disable-line > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > ``` > > ### Handling Short Substrings > > By default, the minimum n-gram length is 3, so shorter substrings like "la" won't match: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("la", query_type="fts").limit(10).to_list() > assert len(results) == 0 > ``` > > ### Customizing N-gram Parameters > > You can customize the n-gram behavior by adjusting the minimum length and using prefix-only matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.create_index( > "text", > config=FTS(base_tokenizer="ngram", ngram_min_length=2, prefix_only=True), > replace=True, > ) > ``` > > ### Testing Custom N-gram Settings > > With the new settings, you can now search for shorter substrings and use prefix-only matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > results = table.search("lan", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > > results = ( > table.search("nce", query_type="fts").limit(10).to_list() > ) # spellchecker:disable-line > assert len(results) == 0 > > results = table.search("la", query_type="fts").limit(10).to_list() > assert len(results) == 2 > assert set(r["text"] for r in results) == {"lance database", "lance is cool"} > ``` > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` ## Full-Text Search on Array Fields > [accordion] Worked examples: searching string arrays > > LanceDB supports full-text search on string array columns, enabling efficient keyword-based search across multiple values within a single field (e.g., tags, keywords). > > ### Setting Up the Connection > > This example uses a temporary local database. Run the steps in order. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from tempfile import TemporaryDirectory > > import pyarrow as pa > from lancedb.index import FTS > from lancedb.query import MatchQuery, PhraseQuery > > directory = TemporaryDirectory() > db = lancedb.connect(directory.name) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import * as lancedb from "@lancedb/lancedb"; > import { Index, MatchQuery, PhraseQuery, makeArrowTable } from "@lancedb/lancedb"; > import { Schema, Field, List, Utf8 } from "apache-arrow"; > import { mkdtemp, rm } from "node:fs/promises"; > import { tmpdir } from "node:os"; > import { join } from "node:path"; > > const directory = await mkdtemp(join(tmpdir(), "lancedb-array-fts-")); > const db = await lancedb.connect(directory); > ``` > > ### Defining the Schema > > Create a schema that includes an array field for tags: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table_name = "fts-array-field-test" > schema = pa.schema([ > pa.field("id", pa.string()), > pa.field("tags", pa.list_(pa.string())), > pa.field("description", pa.string()) > ]) > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const tableName = "fts-array-field-test-ts"; > > // Create schema > const schema = new Schema([ > new Field("id", new Utf8(), false), > new Field("tags", new List(new Field("item", new Utf8()))), > new Field("description", new Utf8(), false) > ]); > ``` > > ### Creating Sample Data > > Generate sample data with array fields containing tags: > > ```python Python icon="python" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Generate sample data > data = { > "id": [f"doc_{i}" for i in range(10)], > "tags": [ > ["python", "machine learning", "data science"], > ["deep learning", "neural networks", "AI"], > ["database", "indexing", "search"], > ["vector search", "embeddings", "AI"], > ["full text search", "indexing", "database"], > ["python", "web development", "flask"], > ["machine learning", "deep learning", "pytorch"], > ["database", "SQL", "postgresql"], > ["search engine", "elasticsearch", "indexing"], > ["AI", "transformers", "NLP"] > ], > "description": [ > "Python for data science projects", > "Deep learning fundamentals", > "Database indexing techniques", > "Vector search implementations", > "Full-text search guide", > "Web development with Python", > "Machine learning with PyTorch", > "Database management systems", > "Search engine optimization", > "AI and NLP applications" > ] > } > ``` > > ```typescript TypeScript icon="square-js" expandable=true theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Generate sample data > const data = makeArrowTable( > Array(10).fill(0).map((_, i) => ({ > id: `doc_${i}`, > tags: [ > ["python", "machine learning", "data science"], > ["deep learning", "neural networks", "AI"], > ["database", "indexing", "search"], > ["vector search", "embeddings", "AI"], > ["full text search", "indexing", "database"], > ["python", "web development", "flask"], > ["machine learning", "deep learning", "pytorch"], > ["database", "SQL", "postgresql"], > ["search engine", "elasticsearch", "indexing"], > ["AI", "transformers", "NLP"] > ][i], > description: [ > "Python for data science projects", > "Deep learning fundamentals", > "Database indexing techniques", > "Vector search implementations", > "Full-text search guide", > "Web development with Python", > "Machine learning with PyTorch", > "Database management systems", > "Search engine optimization", > "AI and NLP applications" > ][i] > })), > { schema } > ); > ``` > > ### Creating the Table and Adding Data > > Create the table and populate it with the sample data: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create table and add data > table = db.create_table(table_name, schema=schema, mode="overwrite") > table_data = pa.Table.from_pydict(data, schema=schema) > table.add(table_data) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create table > const table = await db.createTable(tableName, data, { mode: "overwrite" }); > console.log(`Created table: ${tableName}`); > ``` > > ### Building the Full-Text Search Index > > Store token positions for phrase queries. This example disables stemming so fuzzy matching compares the original word forms: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Create FTS index > table.create_index("tags", config=FTS(with_position=True, stem=False)) > table.wait_for_index(["tags_idx"]) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Create FTS index > console.log("Creating FTS index on 'tags' column..."); > await table.createIndex("tags", { > config: Index.fts({ withPosition: true, stem: false }) > }); > > // Wait for index > const ftsIndexName = "tags_idx"; > await table.waitForIndex([ftsIndexName], 300); > ``` > > ### Performing Fuzzy Search > > Search for terms with typos using fuzzy matching: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > # Search examples > print("\nSearching for 'learning' in tags with a typo:") > result = ( > table.search(MatchQuery("learnin", column="tags", fuzziness=1)) > .select(["id", "tags", "description", "_score"]) > .to_arrow() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > // Search examples > console.log("\nSearching for 'learning' in tags with a typo:"); > const fuzzyResults = await table.query() > .fullTextSearch(new MatchQuery("learnin", "tags", { > fuzziness: 1, > })) > .select(["id", "tags", "description", "_score"]) > .toArray(); > console.log(fuzzyResults); > ``` > > A string-array query can return a row more than once when several elements match. > Deduplicate by your record ID if your application needs one result per row. > > ### Performing Phrase Search > > Search for exact phrases within the array fields: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > print("\nSearching for 'machine learning' in tags:") > result = ( > table.search(PhraseQuery("machine learning", column="tags")) > .select(["id", "tags", "description", "_score"]) > .to_arrow() > ) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > console.log("\nSearching for 'machine learning' in tags:"); > const phraseResults = await table.query() > .fullTextSearch(new PhraseQuery("machine learning", "tags")) > .select(["id", "tags", "description", "_score"]) > .toArray(); > console.log(phraseResults); > ``` > > ### Clean up the array example > > Remove the temporary database when you have finished running the queries. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > directory.cleanup() > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table.close(); > db.close(); > await rm(directory, { recursive: true, force: true }); > ``` # Hybrid Search Source: https://docs.lancedb.com/oss/v0-41-0/search/hybrid-search Combine vector similarity and keyword matches in a single ranked result set. **Applies to:** Embedded ✅, Enterprise ✅ Hybrid search combines vector similarity with keyword matching. It is useful when a query needs both: for example, finding products with a particular model number whose descriptions match what the customer is looking for. LanceDB runs a vector search and a full-text search, then merges their results with a reranker. Reciprocal Rank Fusion (RRF) is the default. It combines the positions of records in the two ranked lists. Before you query, store vectors and create an FTS index on the text column. > [accordion] Run a complete hybrid search example > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `hybrid_search.py`, then run `python hybrid_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `hybrid_search.mts`, then run `node hybrid_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > from lancedb.rerankers import RRFReranker > > table.create_index("text", config=FTS()) > rows = ( > table.search( > query_type="hybrid", vector_column_name="vector", fts_columns="text" > ) > .vector([1.0, 0.0]) > .text("puppy") > .rerank(RRFReranker()) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > await table.createIndex("text", { config: lancedb.Index.fts() }); > const reranker = await lancedb.rerankers.RRFReranker.create(); > const rows = await table > .vectorSearch([1.0, 0.0]) > .fullTextSearch("puppy", { columns: ["text"] }) > .rerank(reranker) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lance_index::scalar::FullTextSearchQuery; > use lancedb::index::{Index, scalar::FtsIndexBuilder}; > use lancedb::query::{ExecutableQuery, QueryBase}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > table > .create_index(&["text"], Index::FTS(FtsIndexBuilder::default())) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .full_text_search(FullTextSearchQuery::new("puppy".into()).with_column("text".into())?) > .rerank(Arc::new(lancedb::rerankers::rrf::RRFReranker::default())) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The puppy record ranks first because both searches place it first. The query > returns `_relevance_score`, with higher values first. This small example shows > the mechanics; evaluate retrieval quality with embeddings and queries from > your own application. ## Generate query embeddings automatically ### 1. Setup The following walkthrough uses Sentence Transformers in Python and OpenAI in TypeScript. Install the corresponding provider packages before starting. Python downloads a local model; TypeScript calls OpenAI. Install `lancedb sentence-transformers pandas` for Python, or `@lancedb/lancedb apache-arrow openai` for TypeScript. Set your OpenAI API key as described in the [OpenAI embedding setup](/oss/v0-41-0/integrations/embedding/openai). Run the steps for your chosen language in order, choosing one connection option. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS from lancedb.rerankers import RRFReranker from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/openai"; import { Utf8 } from "apache-arrow"; ``` ### 2. Connect to LanceDB Choose a LanceDB Embedded connection or use your Enterprise connection details. Embedded ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uri = "data/sample-lancedb" db = lancedb.connect(uri) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const databaseDir = "data/sample-lancedb"; const db = await lancedb.connect(databaseDir); ``` Enterprise Replace the placeholders with your Enterprise database URI, API key, region and endpoint. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` ### 3. Configure Embedding Model Configure the model used for both document and query embeddings. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} embeddings = get_registry().get("sentence-transformers").create() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const embedFunc = lancedb.embedding.getRegistry().get("openai")?.create({ model: "text-embedding-ada-002", }) as lancedb.embedding.EmbeddingFunction; ``` ### 4. Create Table and Schema Define the data structure for your documents, including both the text content and its vector representation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Documents(LanceModel): category: str text: str = embeddings.SourceField() vector: Vector(embeddings.ndims()) = embeddings.VectorField() table_name = "hybrid_search_example" table = db.create_table(table_name, schema=Documents, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const documentSchema = lancedb.embedding.LanceSchema({ category: new Utf8(), text: embedFunc.sourceField(new Utf8()), vector: embedFunc.vectorField(), }); const tableName = "hybrid_search_example"; const table = await db.createEmptyTable(tableName, documentSchema, { mode: "overwrite", }); ``` ### 5. Add Data Insert sample documents into your table, which will be used for both semantic and keyword search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ {"text": "rebel spaceships striking from a hidden base", "category": "film"}, {"text": "have won their first victory against the evil Galactic Empire", "category": "film"}, {"text": "during the battle rebel spies managed to steal secret plans", "category": "film"}, {"text": "to the Empire's ultimate weapon the Death Star", "category": "film"}, ] table.add(data=data) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const data = [ { text: "rebel spaceships striking from a hidden base", category: "film" }, { text: "have won their first victory against the evil Galactic Empire", category: "film" }, { text: "during the battle rebel spies managed to steal secret plans", category: "film" }, { text: "to the Empire's ultimate weapon the Death Star", category: "film" }, ]; await table.add(data); console.log(`Created table: ${tableName} with ${data.length} rows`); ``` ### 6. Build Full Text Index Create a full-text search index on the text column to enable keyword-based search capabilities. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index("text", config=FTS()) table.wait_for_index(["text_idx"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} console.log("Creating full-text search index..."); await table.createIndex("text", { config: lancedb.Index.fts(), }); await table.waitForIndex(["text_idx"], 300); ``` ### 7. Set Reranker \[Optional] RRF is the default. The examples below configure it explicitly. Other rerankers and their language support are described in [Reranking](/oss/v0-41-0/reranking). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reranker = RRFReranker() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const reranker = await lancedb.rerankers.RRFReranker.create(); ``` ### 8. Hybrid Search Perform a hybrid search query that combines semantic similarity with keyword matching, using the specified reranker to merge and rank the results. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search( "rebel spaceships", query_type="hybrid", vector_column_name="vector", fts_columns="text", ) .rerank(reranker) .limit(10) .to_pandas() ) print("Hybrid search results:") print(results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} console.log("Performing hybrid search..."); const queryVector = await embedFunc.computeQueryEmbeddings("rebel spaceships"); const hybridResults = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .rerank(reranker) .select(["text"]) .limit(10) .toArray(); console.log("Hybrid search results:"); console.log(hybridResults); ``` ### 9. Supply a vector and text separately You can supply the vector and text separately. The vector must use the same model and dimensions as the stored embeddings. This example reuses the model configured above; the complete example at the top also demonstrates this pattern in TypeScript and Rust. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} text_query = "rebel spaceships" vector_query = embeddings.compute_query_embeddings(text_query)[0] ( table.search(query_type="hybrid") .vector(vector_query) .text(text_query) .limit(5) .to_pandas() ) ``` ## Control the candidate results Use a result limit, metadata filters and vector distance bounds to control which candidates are available to the reranker. The examples below show each option on the query builder. > [!NOTE] > > Set `limit()` to the number of results your application needs. The default is 10. > A larger candidate set can help a reranker find relevant records, but adds work. ### Returning row IDs Pass `with_row_id(True)` (Python) or `withRowId()` (TypeScript) to include the internal `_rowid` column in the results. This is useful for joining hybrid results back to a primary table, or for deduping across multiple queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("rebel spaceships", query_type="hybrid") .with_row_id(True) .limit(10) .to_pandas() ) # results now contains a `_rowid` column alongside `_relevance_score` ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .withRowId() .limit(10) .toArray(); ``` ### Bounding vector distance `distance_range(lower, upper)` (Python) and `distanceRange(lower, upper)` (TypeScript) constrain the vector half of the hybrid query to the half-open interval `[lower, upper)`. This is helpful when you want to cap how far semantic candidates can drift from the query vector before reranking: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( table.search("rebel spaceships", query_type="hybrid") .distance_range(lower_bound=0.0, upper_bound=0.4) .limit(10) .to_pandas() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results = await table .query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .distanceRange(0.0, 0.4) .limit(10) .toArray(); ``` Either bound can be omitted to leave that side unbounded. ### Prefilter vs. postfilter A hybrid query applies its metadata filter to both the vector and full-text searches. Prefiltering, the default, restricts eligible rows before retrieval. Postfiltering removes candidates after retrieval and can leave fewer results than requested. See [Filtering](/oss/v0-41-0/search/filtering). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Prefilter (default): filter applied before scoring table.search("rebel spaceships", query_type="hybrid") \ .where("category = 'film'", prefilter=True) \ .limit(10) \ .to_pandas() # Postfilter: filter applied after the sub-queries return top-k table.search("rebel spaceships", query_type="hybrid") \ .where("category = 'film'", prefilter=False) \ .limit(10) \ .to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Prefilter (default): just call .where(...) await table.query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .where("category = 'film'") .limit(10) .toArray(); // Postfilter: chain .postfilter() after .where(...) await table.query() .fullTextSearch("rebel spaceships") .nearestTo(queryVector) .where("category = 'film'") .postfilter() .limit(10) .toArray(); ``` In Python, use [`explain_plan`](/oss/v0-41-0/basics/sql#analyzing-non-vector-queries) on a hybrid query to see whether the filter pushed into the scan or ran as a separate `FilterExec` step. ## Choose and evaluate a reranker Start with RRF, then compare alternatives on representative queries. Review which relevant rows reach the candidate set before evaluating how a reranker orders them. Record latency as well as relevance: increasing candidate counts or applying a model-based reranker adds work. Reranking runs in the application for both Embedded and Enterprise connections. See [Reranking](/oss/v0-41-0/reranking) for model-free fusion, model-based rerankers, custom implementations and score interpretation. In synchronous Python, `.rerank(...)` accepts a reranker and a `normalize` option (`"score"` or `"rank"`). Normalization matters for methods that blend raw scores; RRF uses rank positions. These are Python query options, not a shared signature across every SDK. # Search Source: https://docs.lancedb.com/oss/v0-41-0/search/index Choose vector, full-text or hybrid search and return the records your application needs. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB supports vector, full-text and hybrid search. Use vector search to find similar content, full-text search to match words, or hybrid search to combine both. Filters narrow the results to records that match your criteria. ## Choose a search method | You want to find | Use | Prepare | | :- | :- | :- | | Items similar to a query, such as related passages or images | [Vector search](/oss/v0-41-0/search/vector-search) | Stored vectors and a compatible query vector | | Documents represented by several embeddings | [Multivector search](/oss/v0-41-0/search/vector-search#multivector) | A multivector column and compatible query vectors | | Records containing particular words or phrases | [Full-text search](/oss/v0-41-0/search/full-text-search) | An FTS index on the text column | | Relevant meaning alongside keyword matches | [Hybrid search](/oss/v0-41-0/search/hybrid-search) | Vectors and an FTS index | | Rows matching a condition, without similarity ranking | [Filtering](/oss/v0-41-0/search/filtering) | A predicate over table columns | Vector search can run without an index. An approximate nearest-neighbor index reduces the work needed for larger tables, with a tradeoff between recall and latency. Full-text search needs an FTS index before you query it. ## Before you search For vector search, generate stored and query vectors with the same embedding model and compatible settings. Their dimensions must match. Keep the fields you want to return, such as document text or an item ID, in the same table. For full-text search, choose the text column and build its index. Enterprise builds indexes in the background, so wait for the index to be ready before querying it. Phrase queries also need token positions in the index. See [FTS indexes](/oss/v0-41-0/indexing/fts-index). > [accordion] Run a complete search example in Python, TypeScript or Rust > > These examples use three sample records and hand-written vectors, so no > embedding service is needed. Each program creates a temporary local table > and removes it when finished. > > * **Python:** Install with `pip install lancedb`, save as `search.py`, then run `python search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `search.mts`, then run `node search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([1.0, 0.0]) > .distance_type("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([1.0, 0.0]) > .distanceType("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .distance_type(lancedb::DistanceType::L2) > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > This query returns the puppy and dog records, ordered by vector distance. > It searches the three-row table directly, without an ANN index or an embedding > service. For connection options, see [Connect](/oss/v0-41-0/basics/catalog). ## Read the results Use `select()` to choose the columns your application needs and `limit()` to set the maximum number of results. The search also returns a ranking value: | Search method | Ranking column | Order | | :- | :- | :- | | Vector | `_distance` | Smaller distance first | | Full-text | `_score` | Higher text relevance first | | Hybrid | `_relevance_score` | Higher combined relevance first | These values have different meanings. Do not compare a vector distance directly with a full-text score or treat a reranker score as a probability. ## Add filters and reranking [Filters](/oss/v0-41-0/search/filtering) restrict which rows qualify, such as documents from a particular collection. Prefiltering searches within those rows. Postfiltering removes nonmatching rows from the candidates already retrieved, so it can leave fewer results than requested. [Reranking](/oss/v0-41-0/reranking) reorders the candidates returned by retrieval. Start with representative queries and expected results, then compare changes to relevance and latency. A reranker cannot recover a relevant row that retrieval never returned. ## Read large result sets in batches Materializing all rows at once can exhaust application memory. For exports and training reads, use bounded queries or the batch-reading interfaces described in [Data loading](/oss/v0-41-0/training/data-loading). The SDK buffers Enterprise query responses before exposing batches. Set a query limit rather than relying on batch iteration alone to bound memory. Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB Embedded interface. Use the SDK query builders for reads that need to work with both LanceDB Embedded and LanceDB Enterprise. ## Investigate a slow query Use [query plans](/oss/v0-41-0/basics/sql#query-plans) to see the scans, filters and indexes selected for a query. `explain_plan()` inspects the plan; `analyze_plan()` executes the query and reports measurements. Compare one change at a time, such as adding an index, returning fewer columns, or adjusting search parameters. # RTE reads Source: https://docs.lancedb.com/oss/v0-41-0/search/realtime-read Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table. **Applies to:** Embedded ✅, Enterprise ✅ A table with the [real time engine](/oss/v0-41-0/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL changes. This page covers what you get back; for enabling RTE and writing to a table, see [RTE writes](/oss/v0-41-0/ingestion/realtime-write). For how Enterprise combines these results across machines, see [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read). ## Query a real time table Every query runs against the base table and the fresh tier (unflushed memtables and SSTables) in parallel, and the two are merged into one result. Fresh rows supersede base rows with the same primary key, so a row written a moment ago is already reflected: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # continuing the `frames` table connected and written to in RTE writes import numpy as np query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") frames.search(query_vector, vector_column_name="embedding").limit(10).to_list() frames.search("gripper closing on a cup", fts_columns="caption").limit(10).to_list() ``` By default every index on the table is RTE-maintained, re-read as the table changes, so a new index is picked up automatically; pin a smaller set with `RTEWriteSpec.with_maintained_indexes`. For full-text and scalar (BTree, bitmap) indexes, a maintained index covers every tier -- base table, SSTables, and the active memtable -- so a query rejects outright rather than silently skipping un-compacted rows if a resident memtable predates the index. Vector (ANN) search is maintained on the base table and SSTables the same way, and the active memtable builds its own in-memory HNSW graph as rows land, so writes stay vector-searchable within milliseconds too, without waiting on a freeze into an SSTable. That graph search steps aside for a full scan of the memtable only when it can't honor the query through a graph -- a prefilter, a primary-key override, a distance lower bound, or before the memtable has any index yet on a cold start. ## Embedded: one process, one dataset LanceDB Embedded runs this same LSM scanner directly against the local Lance dataset, in-process -- the identical merge-by-primary-key logic, the same maintained-index rules for vector, full-text, and scalar search, just with no network hop to a separate serving tier. There is no WAL node to route to and nothing to combine across machines: a query against an RTE-enabled Embedded table already reads the fresh tier together with the base table in one call. See [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read) for what Enterprise adds on top when that fresh tier is served by a separate machine from the one answering the rest of the query. Not every query shape runs through the LSM scanner -- a query that asks for `with_row_id`, time travel, multiple query vectors, hybrid search, or a handful of other combinations is rejected with a clear error asking you to set `use_rte(False)` and read the base table only, rather than silently returning a result that omits un-compacted rows. ## Limitations > [!NOTE] > > Support for all table operations on RTE tables is coming soon. Time travel, > `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet > available. ## Next steps * [RTE writes](/oss/v0-41-0/ingestion/realtime-write) — enable RTE and write to a table * [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read) — combining results across machines in Enterprise * [How the real time engine works](/oss/v0-41-0/tables/realtime-engine#memwal-format) * [Hybrid search](/oss/v0-41-0/search/hybrid-search) * [Vector search](/oss/v0-41-0/search/vector-search) # Vector Search Source: https://docs.lancedb.com/oss/v0-41-0/search/vector-search Search by vector similarity, choose a distance metric and tune your queries. **Applies to:** Embedded ✅, Enterprise ✅ Vector search finds similar items by comparing their embeddings: numerical representations of text, images, audio or other data. An embedding model maps related items to nearby points in vector space, so you can search by meaning or similarity instead of matching exact words. ![An embedding model maps data into vectors for similarity search.](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/vector-db-basics.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=5866d16765c1738f175ab007173f0afe) To run a search, pass a query vector to LanceDB and specify how many matches to return. Generate the query vector with the same model and settings used for your stored embeddings. LanceDB ranks the results by distance from the query. For small tables, you can search the vectors directly. A [vector index](/oss/v0-41-0/indexing/vector-index) speeds up searches on larger tables by narrowing the candidates to examine. > [accordion] Run a complete example in Python, TypeScript or Rust > > These examples create a three-row table and find the two closest matches to a > query vector. They use hand-written vectors, so you can try the query without > an embedding model. The temporary table is removed when the program finishes. > > * **Python:** Install with `pip install lancedb`, save as `vector_search.py`, then run `python vector_search.py`. > * **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `vector_search.mts`, then run `node vector_search.mts` with Node.js 22.18 or later. > * **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > table = db.create_table( > "documents", > [ > { > "id": 1, > "text": "A puppy playing in the park", > "category": "animals", > "vector": [1.0, 0.0], > }, > { > "id": 2, > "text": "A dog resting at home", > "category": "animals", > "vector": [0.9, 0.1], > }, > { > "id": 3, > "text": "A guide to growing tomatoes", > "category": "gardening", > "vector": [0.0, 1.0], > }, > ], > ) > rows = ( > table.search([1.0, 0.0]) > .distance_type("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .to_list() > ) > print(rows) > ``` > > ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > const lancedb = await import("@lancedb/lancedb"); > const { mkdtemp, rm } = await import("node:fs/promises"); > const { tmpdir } = await import("node:os"); > const { join } = await import("node:path"); > const uri = await mkdtemp(join(tmpdir(), "lancedb-search-")); > try { > const db = await lancedb.connect(uri); > const table = await db.createTable("documents", [ > { > id: 1, > text: "A puppy playing in the park", > category: "animals", > vector: [1.0, 0.0], > }, > { > id: 2, > text: "A dog resting at home", > category: "animals", > vector: [0.9, 0.1], > }, > { > id: 3, > text: "A guide to growing tomatoes", > category: "gardening", > vector: [0.0, 1.0], > }, > ]); > const rows = await table > .vectorSearch([1.0, 0.0]) > .distanceType("l2") > .select(["id", "text", "_distance"]) > .limit(2) > .toArray(); > console.log(rows); > > } finally { > await rm(uri, { recursive: true, force: true }); > } > ``` > > ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > use arrow_array::types::Float32Type; > use arrow_array::{FixedSizeListArray, Int64Array, RecordBatch, RecordBatchIterator, StringArray}; > use arrow_schema::{DataType, Field, Schema}; > use futures::TryStreamExt; > use lancedb::query::{ExecutableQuery, QueryBase, Select}; > use std::sync::Arc; > > #[tokio::main] > async fn main() -> Result<(), Box<dyn std::error::Error>> { > let directory = tempfile::tempdir()?; > let db = lancedb::connect(directory.path().to_str().unwrap()) > .execute() > .await?; > let schema = Arc::new(Schema::new(vec![ > Field::new("id", DataType::Int64, false), > Field::new("text", DataType::Utf8, false), > Field::new("category", DataType::Utf8, false), > Field::new( > "vector", > DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), > true, > ), > ])); > let batch = RecordBatch::try_new( > schema.clone(), > vec![ > Arc::new(Int64Array::from(vec![1, 2, 3])), > Arc::new(StringArray::from(vec![ > "A puppy playing in the park", > "A dog resting at home", > "A guide to growing tomatoes", > ])), > Arc::new(StringArray::from(vec!["animals", "animals", "gardening"])), > Arc::new( > FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( > [[1.0, 0.0], [0.9, 0.1], [0.0, 1.0]] > .into_iter() > .map(|v| Some(v.into_iter().map(Some).collect::<Vec<_>>())), > 2, > ), > ), > ], > )?; > let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); > let table = db > .create_table( > "documents", > Box::new(reader) as Box<dyn arrow_array::RecordBatchReader + Send>, > ) > .execute() > .await?; > let query = table > .vector_search(&[1.0_f32, 0.0])? > .distance_type(lancedb::DistanceType::L2) > .select(Select::columns(&["id", "text", "_distance"])) > .limit(2); > let rows: Vec<RecordBatch> = query.execute().await?.try_collect().await?; > println!("{rows:?}"); > > Ok(()) > } > ``` > > The first result is the puppy record, whose vector exactly matches the query. > The dog record is next. `_distance` is smaller for closer matches. This example > uses an exhaustive scan; the indexing section explains how to search larger tables. ## Supported distance metrics A distance metric determines how LanceDB compares vectors. Choose the metric recommended by your embedding model. Use the same metric when building an index and querying it. LanceDB supports `l2`, `cosine`, `dot` and `hamming`. An unindexed search uses `l2` by default; Hamming distance is for binary vectors. The table below shows the value returned in the `_distance` column. Smaller values rank first. | Distance metric | Mathematical form | Notes | | - | - | - | | `l2` | $\sum_i (x_i-y_i)^2$ | Squared Euclidean distance returned in `_distance`. | | `cosine` | $1-\frac{x\cdot y}{\|x\|_2\|y\|_2}$ | Measures directional difference between vectors. Insensitive to nonzero scaling of vectors. | | `dot` | $1-\sum_i x_i y_i$ | Dot-product distance. For unit-normalized vectors, this equals cosine distance. | | `hamming` | $\underset{i}{\sum} \,\: \mathbf{1}_{\, [x_i\neq y_i]}$ | Counts the number of bitwise-differing bits between binary vectors. | For indexed search, supported distance metrics vary by index type: | Index type | Supported distance metrics | | - | - | | `IVF_FLAT` | `["l2", "cosine", "dot", "hamming"]` | | `IVF_PQ` | `["l2", "cosine", "dot"]` | | `IVF_SQ` | `["l2", "cosine", "dot"]` | | `IVF_RQ` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_FLAT` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_PQ` | `["l2", "cosine", "dot"]` | | `IVF_HNSW_SQ` | `["l2", "cosine", "dot"]` | ### Configure Distance Metric Without a vector index, searches use `l2` by default. You can specify `cosine` or `dot` instead (`hamming` is supported for `IVF_FLAT` indexes only). When a vector index exists, the search metric must match the metric used to build the index. If you explicitly request a different metric, LanceDB cannot use that index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. LanceDB Enterprise doesn't have the limit. If you omit the search metric, current SDKs use the index metric when an index is available. Some older SDK versions sent `l2` when the metric was omitted; with a non-`l2` index, explicitly set the matching metric or upgrade the SDK. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search(np.random.random((1536))).distance_type("cosine").limit(10).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results2 = await ( tbl.search(Array(128).fill(1.2)) as lancedb.VectorQuery ) .distanceType("cosine") .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Use the same distance metric the index was trained with. let mut results = table .vector_search(&query_vector)? .distance_type(DistanceType::Cosine) .limit(10) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` These examples use cosine distance and return up to ten matches. If the table has a vector index, build it with the same metric. Set `.limit(...)` on vector searches you run in applications. You can page through results with `.offset(...)` and include LanceDB's internal row id with `.with_row_id()` / `.withRowId()` when an operation requires internal row IDs. Use your own ID column for application identifiers. ## Selecting the vector column If your table has exactly one vector column, you can omit the column name and LanceDB will pick it for you. This works for both top-level columns (such as `vector`) and vector fields nested inside a struct (such as `image.embedding`). When LanceDB can't infer a single column, it raises a `ValueError` (Python) or rejects the query (Node/Rust). Two cases trigger this: * No vector column: the schema has no `fixed_size_list` or `list` of floats. * Multiple candidates: more than one column matches the query's dimension. The error lists every candidate path so you can pick one explicitly. To disambiguate, pass the field path with dot notation. Wrap any segment that contains characters outside `[A-Za-z0-9_]` in backticks (for example, `` `image-meta`.`embedding.v1` ``). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema([ pa.field("id", pa.int32()), pa.field( "image", pa.struct([pa.field("embedding", pa.list_(pa.float32(), 2))]), ), ]) table = db.create_table( "nested", data=[{"id": 0, "image": {"embedding": [0.0, 1.0]}}], schema=schema, ) # Inferred: the only vector leaf is `image.embedding`. table.search([0.0, 1.0]).limit(1).to_list() # Explicit: required when more than one vector column matches. table.search([0.0, 1.0], vector_column_name="image.embedding").limit(1).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.openTable("nested"); // Inferred: LanceDB finds the single nested vector leaf automatically. await table.query().nearestTo([0.0, 1.0]).limit(1).toArray(); // Explicit: required when more than one vector column matches. await table .query() .nearestTo([0.0, 1.0]) .column("image.embedding") .limit(1) .toArray(); ``` The same field-path syntax works when creating an index on a nested vector column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index(vector_column_name="image.embedding") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.createIndex("image.embedding"); ``` When several columns share a name across structs (for example, `image.embedding` and `text.embedding`), LanceDB still picks the one whose dimension matches your query vector. If two candidates have the same dimension, you must pass the column name explicitly. ## Search with a vector index An approximate nearest-neighbor (ANN) index narrows the set of vectors examined for a query. It can reduce query latency, but may miss neighbors that an exhaustive search would find. Compare recall and latency on queries that represent your application before choosing an index and its search settings. > [!WARNING] > > When a vector index is used, `_distance` is not always the true distance between full vectors. On quantized ANN indexes, LanceDB may compute `_distance` from the compressed representation for speed. Use `refine_factor` when you want reranking on full vectors. ### Exact vs Approximate Distances When doing vector search, the meaning of "distance" depends on whether you are using an index and whether `refine_factor` is specified as part of your query. `nprobes` controls how many partitions are searched to find candidates, `approx_mode` controls the query-time speed/recall trade-off for RQ-quantized and filtered HNSW indexes, and `refine_factor` controls how many candidates are rescored on full vectors for better distance fidelity and reranking quality. The table below summarizes the behavior of `_distance` in search results based on your query configuration: | Query mode | Neighbor quality | `_distance` in results | | :- | :- | :- | | No index or `.bypass_vector_index()` | Exact kNN (100% recall) | True distance on full vectors | | Indexed ANN, no `refine_factor` | Approximate neighbors | Distance on the index representation: exact for flat indexes, approximate for quantized indexes | | Indexed ANN + `refine_factor(1)` | Approximate neighbors (same candidate set) | Distances recomputed on full vectors for reranked candidates | | Indexed ANN + `refine_factor(>1)` | Better recall than no refine (usually) | Distances recomputed on full vectors for reranked candidates | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Indexed ANN search without refinement (fast, approximate `_distance`) fast_results = ( table.search(embedding) .limit(10) .to_pandas() ) # Recompute distances on full vectors for reranked candidates exact_distance_results = ( table.search(embedding) .limit(10) .refine_factor(1) .to_pandas() ) # Rerank a larger candidate set for better recall (higher latency) higher_recall_results = ( table.search(embedding) .limit(10) .refine_factor(20) .to_pandas() ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Indexed ANN search without refinement (fast, approximate `_distance`) const fastResults = await (table.search(embedding) as lancedb.VectorQuery) .limit(10) .toArray(); // Recompute distances on full vectors for reranked candidates const exactDistanceResults = await ( table.search(embedding) as lancedb.VectorQuery ) .limit(10) .refineFactor(1) .toArray(); // Rerank a larger candidate set for better recall (higher latency) const higherRecallResults = await ( table.search(embedding) as lancedb.VectorQuery ) .limit(10) .refineFactor(20) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Approximate ANN search (fast, distances may come from the index representation) let mut fast_results = table.vector_search(&query_vector)?.limit(10).execute().await?; while let Some(batch) = fast_results.try_next().await? { println!("{:?}", batch); } // Rerank a larger candidate set on full vectors for better recall let mut refined_results = table .vector_search(&query_vector)? .limit(10) .refine_factor(20) .execute() .await?; while let Some(batch) = refined_results.try_next().await? { println!("{:?}", batch); } ``` See [vector indexes](/oss/v0-41-0/indexing/vector-index) for index configuration. The following sections cover query-time settings. ### Tuning `approx_mode` > [!NOTE] > > Python 0.41.0 and TypeScript 0.41.0 do not expose this setting. The Python > example baseline is 0.42.0b8; TypeScript exposes `approxMode` starting with > 0.42.0-beta.1. Rust 0.41.0 already exposes `approx_mode`. See the > [client versions](/oss/v0-41-0/basics/sdk#enterprise-client-versions). Use `approx_mode` when you want to adjust the speed/recall trade-off for approximate vector search at query time. It applies to RQ-quantized indexes, such as `IVF_RQ`, and to filtered searches on HNSW indexes. Other index types, and queries that bypass the index, ignore it. The supported values are: | Value | Behavior | | :- | :- | | `fast` | Prefer lower query latency, which can reduce recall. | | `normal` | Use the default balance between query latency and recall. For RQ indexes built with `num_bits=1`, this uses the same one-bit scoring path as `fast`. | | `accurate` | Prefer higher recall, which can increase query latency. | `approx_mode` defaults to `normal` and can change per query without rebuilding the index. The Python and Rust APIs call it `approx_mode`, and the TypeScript API calls it `approxMode`. On HNSW, `fast` enables ACORN traversal only when a filter leaves a non-trivial subset of rows; unfiltered or all-row searches use the regular traversal, and very selective filters may use an exact scan instead. If you also set `refine_factor`, LanceDB first uses `approx_mode` while finding candidates, then reranks the selected candidates on full vectors. ### Tuning `nprobes` For IVF vector indices, start with **Auto** by leaving the probe settings unset. LanceDB chooses how many partitions to search to balance recall and latency. It can search further if a filter leaves too few results, within any limits you set. The examples below assume `table` has an IVF index and `query_vector` uses the same embedding model and dimension as its vectors. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Start with Auto. auto = table.search(query_vector).limit(10).to_arrow() ``` #### Adjust speed and recall Use `search_effort` to tune how much work a search does. It accepts values from `0` to `1`; `0.5` uses Auto. Increase it to search more partitions when recall is too low, or decrease it when you can trade some recall for lower latency. `search_effort(0.95)` does **not** mean 95% recall. SDK builds using Lance 15.0.0-beta.11 or later provide these calibrated tiers: | Effort | Empirical mean partition-routing target | | :- | :- | | `0.1` | 80% | | `0.25` | 90% | | `0.5` (default) | Approximately 95%; existing Auto behavior | The probe budget adapts to the distance metric and requested `k`, so you can keep the same effort when changing the result count. The lower tiers were calibrated for `l2`, `cosine` and `dot` through `k=100000`. This is the tested range, not a limit on `k`; Hamming and larger requests remain uncalibrated. These are average routing objectives, not guarantees for each query or final Recall\@k. Quantization, filtering and explicit probe bounds can lower final recall. Remote queries require a server with the corresponding Lance version; upgrading only the client does not change server-side routing. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Search more partitions to try to improve recall. higher_effort = table.search(query_vector).search_effort(0.75).limit(10).to_arrow() ``` Measure the effect on your queries. Higher effort may add latency without improving recall. With no maximum set, `search_effort(1)` searches all partitions and can be expensive. In TypeScript, the method is named `searchEffort`. #### Set probe limits Use explicit probe counts when you have measured a suitable range for your workload: | Parameter | When to use it | | :- | :- | | `minimum_nprobes` | Set a lower bound on how many partitions to search. Auto may search more from the start. | | `maximum_nprobes` | Cap the number of partitions searched, including additional searches needed to fill the result count. A low cap can reduce recall or return fewer results than requested. | | `nprobes` | Search a fixed number of partitions instead of using Auto. Useful for comparing settings in a benchmark. | Counts apply **per index segment**, not to the entire query. With many segments, more probes can mean substantially more data reads and cache-fill writes. A probe cap is not a limit on total latency or I/O. Use positive counts and keep the minimum no larger than the maximum. Leave the maximum unset to allow further searching as needed. If filtered queries return too few results, raise or remove that cap; see the [bounded-search example](/oss/v0-41-0/indexing/vector-index#probe-limits-example). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Use a fixed probe count. fixed = table.search(query_vector).nprobes(20).limit(10).to_arrow() ``` Prefer choosing either effort or a fixed count. If both are set, explicit `search_effort` overrides `nprobes`. Explicit min/max bounds still apply; setting them equal fixes the count. #### Check result quality Auto was tuned toward roughly **95% average recall** in benchmark tests. That is a starting point, not a guarantee for your data or every query. Returning `k` results also does not mean they are the true nearest `k` neighbors. [Measure recall](/oss/v0-41-0/indexing/vector-index#measuring-vector-recall) on representative queries against an exact search with the same metric and filter. Test the settings you intend to use: an Auto search capped at 50 probes can search fewer partitions than fixed `nprobes(50)`, so the two can have different recall. If more probes stop improving quality, try increasing `refine_factor` or using a higher-precision index. More probes do not remove quantization error, and refinement can only rerank the candidates the search finds. > [!NOTE] > > The Python examples use APIs available in LanceDB 0.41.0. Remote queries need > server support too. Older clients may send fixed probe settings by default; > upgrading the server alone does not switch those requests to Auto. > > Auto's calibration covers `l2`, `cosine` and `dot` searches up to `k=100000`. > For Hamming or larger requests, measure quality and latency on your workload > before relying on the defaults. ### Vector Search with Prefiltering This is the default vector search setting. You can use prefiltering to boost query performance by reducing the search space before vector calculations begin. The system first applies your filter criteria to the dataset, then conducts vector search operations only on the remaining relevant subset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datasets import load_dataset # Load query vector from dataset query_dataset = load_dataset("sunhaozhepy/ag_news_sbert_keywords_embeddings", split="test[5000:5001]") print(f"Query keywords: {query_dataset[0]['keywords']}") query_embed = query_dataset["keywords_embeddings"][0] # Open table and perform search table_name = "lancedb-enterprise-quickstart" table = db.open_table(table_name) # Vector search with filters (pre-filtering is the default) search_results = ( table.search(query_embed) .where("label > 2") .select(["text", "keywords", "label"]) .limit(5) .to_pandas() ) print("Search results (with pre-filtering):") print(search_results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Generate a sample 768-dimension embedding vector (typical for BERT-based models) // In real applications, you would get this from an embedding model const dimensions = 768; const queryEmbed = Array.from( { length: dimensions }, () => Math.random() * 2 - 1, ); // Open table and perform search const tableName = "lancedb-enterprise-quickstart"; const table = await db.openTable(tableName); // Vector search with filters (pre-filtering is the default) const vectorResults = await table .search(queryEmbed) .where("label > 2") .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Search results (with pre-filtering):"); console.log(vectorResults); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Prefiltering is the default: the filter is applied before vector search. let mut results = table .vector_search(&query_vector)? .only_if("id > 100") .select(Select::columns(&["id"])) .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` The filter limits which rows can match. Use `select()` to choose the returned columns and `limit()` to set the maximum number of results. ### Vector Search with Postfiltering Postfiltering selects vector-search candidates before applying the metadata predicate. It can return fewer matches than requested, even when other rows in the table satisfy the predicate. Use prefiltering when you want the nearest records within the matching subset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results_post_filtered = ( table.search(query_embed) .where("label > 1", prefilter=False) .select(["text", "keywords", "label"]) .limit(5) .to_pandas() ) print("Vector search results with post-filter:") print(results_post_filtered) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const vectorResultsWithPostFilter = await ( table.search(queryEmbed) as lancedb.VectorQuery ) .where("label > 2") .postfilter() .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Vector search results with post-filter:"); console.log(vectorResultsWithPostFilter); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Apply the filter after vector search by calling postfilter(). let mut results = table .vector_search(&query_vector)? .only_if("id > 100") .postfilter() .select(Select::columns(&["id"])) .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Only retrieved candidates that satisfy the predicate remain in the result. Increase the candidate limit or use prefiltering if too few records are returned. > [card] > > [Post-filtering](/oss/v0-41-0/search/filtering/#post-filtering-with-vector-search) in LanceDB applies > the filter condition after obtaining the nearest neighbors based on vector similarity. ## Multivector Search Use multivector search when your documents contain multiple embeddings and you need sophisticated matching between query and document vector pairs. The late interaction approach finds the most relevant combinations across all available embeddings and provides nuanced similarity scoring. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_multi = np.random.random(size=(2, 256)) results_multi = tbl.search(query_multi).limit(5).to_pandas() ``` Here you can see how to take 2 query vectors and find the best matching pairs between them and document vectors using late interaction. The `np.random.random(size=(2, 256))` creates a 2×256 array with two random query vectors, `.limit(5)` returns the top 5 best document-query combinations, and `.to_pandas()` provides results in a DataFrame format. For the supported metric, how scoring works and a complete example, see the [multivector search walkthrough](#multivector). ## Advanced Search Scenarios ### Search With Distance Range Use `distance_range` search when you need vectors within particular similarity bounds rather than just the closest neighbors. The system filters results to only include vectors that fall within your specified distance thresholds from the query. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(256) # Search for the vectors within the range of [0.1, 0.5) tbl.search(query).distance_range(0.1, 0.5).to_arrow() # Search for the vectors with the distance less than 0.5 tbl.search(query).distance_range(upper_bound=0.5).to_arrow() # Search for the vectors with the distance greater or equal to 0.1 tbl.search(query).distance_range(lower_bound=0.1).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const results3 = await ( tbl.search(Array(128).fill(1.2)) as lancedb.VectorQuery ) .distanceType("cosine") .distanceRange(0.1, 0.2) .limit(10) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Only return rows whose distance falls within [0.1, 0.5). let mut results = table .vector_search(&query_vector)? .distance_range(Some(0.1), Some(0.5)) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` This shows three ways to search within distance ranges: bounded, upper bound only, and lower bound only. The `distance_range()` method filters results by similarity thresholds - the first example finds vectors with distance between `0.1` and `0.5`, the second finds vectors closer than `0.5`, and the third finds vectors farther than `0.1`. Each approach returns Arrow tables with vectors that fall within your specified distance thresholds. ### Search With Binary Vectors Use binary vector search for scenarios involving binary embeddings, such as those produced by hashing algorithms. The system stores these efficiently as packed uint8 arrays and uses Hamming distance calculations to determine vector similarity. > [!TIP] > > The number of dimensions of the binary vector must be a multiple of 8. A vector of dimensionality 128 will be stored as a `uint8` array of size 16. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa schema = pa.schema( [ pa.field("id", pa.int64()), # for dim=256, lance stores every 8 bits in a byte # so the vector field should be a list of 256 / 8 = 32 bytes pa.field("vector", pa.list_(pa.uint8(), 32)), ] ) tbl = db.create_table("my_binary_vectors", schema=schema) data = [] for i in range(1024): vector = np.random.randint(0, 2, size=256) # pack the binary vector into bytes to save space packed_vector = np.packbits(vector) data.append( { "id": i, "vector": packed_vector, } ) tbl.add(data) query = np.random.randint(0, 2, size=256) packed_query = np.packbits(query) tbl.search(packed_query).distance_type("hamming").to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.createTable("binary_vectors", data, { mode: "overwrite", }); await tbl.createIndex("vector", { config: lancedb.Index.ivfFlat({ numPartitions: 10, distanceType: "hamming", }), }); const query = Array(32) .fill(1) .map(() => Math.floor(Math.random() * 255)); const results = await tbl.query().nearestTo(query).limit(10).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Binary vectors use `hamming` distance over the packed uint8 bytes. let query: Arc<dyn Array> = Arc::new(UInt8Array::from(vec![1u8; NUM_BYTES as usize])); let mut results = tbl .vector_search(query)? .distance_type(DistanceType::Hamming) .limit(10) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Here you can see how to set up a table for binary vectors, pack them efficiently into bytes, and search using Hamming distance. The schema defines a 32-byte vector field (256 bits ÷ 8), `np.random.randint(0, 2, size=256)` creates binary vectors, `np.packbits()` compresses them to bytes, and `.distance_type("hamming")` specifies `hamming` distance for similarity calculation. The search produces an Arrow table with binary vectors ranked by how many bits differ from the query. ## Scaling Vector Search ### Query multiple vectors in a batch Batch search accepts multiple query vectors in one request. The `query_index` column identifies which query produced each result. Measure throughput and latency with your workload when choosing a batch size. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Load a batch of query embeddings query_dataset = load_dataset( "sunhaozhepy/ag_news_sbert_keywords_embeddings", split="test[5000:5005]" ) query_embeds = query_dataset["keywords_embeddings"] batch_results = table.search(query_embeds).limit(5).to_pandas() print(batch_results) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Batch query console.log("Performing batch vector search..."); const batchSize = 5; const queryVectors = Array.from({ length: batchSize }, () => Array.from({ length: dimensions }, () => Math.random() * 2 - 1), ); let batchQuery = table.search(queryVectors[0]) as lancedb.VectorQuery; for (let i = 1; i < batchSize; i++) { batchQuery = batchQuery.addQueryVector(queryVectors[i]); } const batchResults = await batchQuery .select(["text", "keywords", "label"]) .limit(5) .toArray(); console.log("Batch vector search results:"); console.log(batchResults); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Search multiple query vectors in one call. Each result row carries a // `query_index` mapping it back to the query it matched. let mut results = table .vector_search(&query_1)? .add_query_vector(&query_2)? .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Each input vector has its own nearest-neighbor results. Use `query_index` to associate each row with the corresponding input vector. ### Include or skip unindexed rows To optimize for speed over completeness, enable the `fast_search` flag in your query to skip searching unindexed data. By default, search includes both indexed vectors and unindexed rows visible to the query. LanceDB scans the unindexed rows directly. `fast_search` skips that scan, which can reduce query time but omit recent records. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search(embedding, fast_search=True).limit(5).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .query() .nearestTo(embedding) .fastSearch() .limit(5) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Skip unindexed data for lower latency. let mut results = table .vector_search(&query_vector)? .fast_search() .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` Use this option only when results from indexed data are sufficient. ### Expected performance at scale Enterprise At 1 billion rows, LanceDB Enterprise reaches p50 28 ms and p99 58 ms on fully cached data with no custom tuning -- a representative floor to plan around, not a ceiling. Measured with 1,536-dimensional embeddings, an IVF-RQ index, `nprobe=8`, `k=100`, on the best-performing configuration tested at that scale. The exact numbers depend on your deployment's shape (cluster size, storage class, dataset); for higher performance, talk to the sales team. ## Search without a vector index ### Search With No Index The simplest way to perform vector search is to perform a brute force search, without an index, where the distance between the query vector and all the vectors in the database are computed, with the top-k closest vectors returned. This is equivalent to a k-nearest neighbours (kNN) search in vector space. Choose brute force search when you need guaranteed 100% recall, typically with smaller datasets where query speed isn't the primary concern. The system scans every vector in the table and calculates precise distances to find the exact nearest neighbors. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search(np.random.random((1536))).limit(3).to_list() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.openTable("my_vectors"); const results1 = await tbl.search(Array(128).fill(1.2)).limit(3).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // A plain vector search returns the top-k closest rows. let mut results = table.vector_search(&query_vector)?.limit(3).execute().await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` These queries return the three nearest matches. Without a vector index, LanceDB calculates distances directly from the stored vectors. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/knn_search.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=d23913931f8683dcfdeda0c0c5f9a083) Exhaustive search does more work as the table grows. When query latency becomes too high, add an ANN index and compare its results with the exhaustive baseline. ### Bypass the Vector Index Use `bypass_vector_index` to get exact, ground-truth results by performing exhaustive searches across all vectors. Instead of relying on approximate methods, the system directly compares your query against every vector in the table, ensuring 100% recall at the cost of increased query time. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search(embedding).bypass_vector_index().limit(5).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table .query() .nearestTo(embedding) .bypassVectorIndex() .limit(5) .toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Force an exhaustive (flat) scan for exact, ground-truth results. let mut results = table .vector_search(&query_vector)? .bypass_vector_index() .limit(5) .execute() .await?; while let Some(batch) = results.try_next().await? { println!("{:?}", batch); } ``` This skips the approximate index and checks every single vector for exact, ground-truth results. The `.bypass_vector_index()` method forces LanceDB to perform an exhaustive search through all vectors instead of using the approximate nearest neighbor index, ensuring exact results but at the cost of slower performance. The query returns the nearest five rows within its filters and distance bounds. Use an exhaustive scan as a baseline when measuring ANN recall. This approach is particularly useful when: * Evaluating ANN index quality * Calculating recall metrics to tune index parameters * Ensuring exact results for critical applications ## Multivector search walkthrough LanceDB's multivector support enables you to store and search multiple vector embeddings for a single item. This capability is particularly valuable when working with late-interaction models like ColBERT and ColPaLi, which generate multiple embeddings per document. In this tutorial, you'll create a table with multiple vector embeddings per document and learn how to perform multivector search. For more end-to-end examples, see the [VectorDB recipes repository](https://github.com/lancedb/vectordb-recipes/tree/main/examples). ### Multivector Support Each item in your dataset can have a column containing multiple vectors, which LanceDB can efficiently index and search. When performing a search, you can query with either a single vector embedding or multiple vector embeddings. > [!WARNING] > > Currently, only the `cosine` metric is supported for multivector search. The vector value type can be `float16`, `float32`, or `float64`. Each query vector must match the inner vector dimension in the multivector column. This applies to both single-vector queries and multi-vector query matrices. ### Computing Similarity MaxSim (Maximum Similarity) is a key concept in late-interaction models that: * Computes the maximum similarity between each query embedding and all document embeddings * Sums these maximum similarities to get the final relevance score * Effectively captures fine-grained semantic matches between query and document tokens The MaxSim calculation can be expressed as: $$ \text{MaxSim}(Q, D) = \sum_{i=1}^{|Q|} \max_{j=1}^{|D|} \text{sim}(q_i, d_j) $$ Where $sim$ is the similarity function (e.g., cosine similarity). $$ Q = \{q_1, q_2, ..., q_{|Q|}\} $$ $Q$ represents the query embeddings, and $D = \{d_1, d_2, ..., d_{|D|}\}$ represents the document embeddings. ### Using Multivector Search #### 1. Setup Connect to a local LanceDB database and import the required libraries. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa db = lancedb.connect("data/multivector_demo") ``` > [!NOTE] > > To run this walkthrough on LanceDB Enterprise, connect with > `lancedb.connect(uri="db://your-database", api_key="your-api-key", region="your-region")` > instead. The remaining steps are the same. #### 2. Define Schema Define a schema that specifies a multivector field. A multivector field is a nested list structure in which each document contains multiple vectors. In this case, we'll create a schema with: 1. An ID field as an integer (int64) 2. A vector field that is a list of lists of float32 values * The outer list represents multiple vectors per document * Each inner list is a 256-dimensional vector * Using float32 for memory efficiency while maintaining precision ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} schema = pa.schema( [ pa.field("id", pa.int64()), # float16, float32, and float64 are supported pa.field("vector", pa.list_(pa.list_(pa.float32(), 256))), ] ) ``` #### 3. Generate Multivectors Generate sample data where each document contains multiple vector embeddings, which can represent different aspects or views of the same document. In this example, we create **1024 documents** where each document has **2 random vectors** of **dimension 256**, simulating a real-world scenario where you might have multiple embeddings per item. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ { "id": i, "vector": np.random.random(size=(2, 256)).tolist(), # Each document has 2 vectors } for i in range(1024) ] ``` #### 4. Create a Table Create a table with the defined schema and sample data, which will store multiple vectors per document for similarity search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("multivector_example", data=data, schema=schema) ``` #### 5. Build an Index Only cosine similarity is supported for multivector search operations. For faster search, build the standard `IVF_PQ` index over your vectors: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.create_index(metric="cosine", vector_column_name="vector") ``` > [!NOTE] > > **Indexing matters more for multivector tables than for single-vector ones.** > > A brute-force scan over a multivector column has to compare every query vector to every document vector in every row, so the cost grows with both the row count and the number of vectors per row. > In LanceDB Embedded, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. > > On LanceDB Cloud, the brute-force KNN safety check applies a stricter row threshold to multivector columns; roughly 10× lower than for single-vector columns. So an unindexed multivector table can be rejected with a "vector search would use brute-force KNN" error well before a comparable single-vector table would. LanceDB Enterprise doesn't have the limit. Build the index before you start hitting it from production traffic, even if the dataset is small enough that you'd skip indexing for a single-vector workload. #### 6. Query a Single Vector When searching with a single query vector, it will be compared against all vectors in each document, and the similarity scores will be aggregated to find the most relevant documents. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(256) results_single = tbl.search(query).limit(5).to_pandas() ``` #### 7. Query Multiple Vectors With multiple query vectors, LanceDB calculates similarity using late interaction, a late-interaction technique that computes relevance by finding the best-matching pairs between query and document vectors. This approach provides more nuanced matching while maintaining fast retrieval speeds. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_multi = np.random.random(size=(2, 256)) results_multi = tbl.search(query_multi).limit(5).to_pandas() ``` Visit the [HuggingFace embedding integration](/oss/v0-41-0/integrations/embedding/huggingface/) page for information on embedding models. ### Simple Example: ColBERT Embeddings [ColBERT](https://arxiv.org/abs/2004.12832) is the most well-known late-interaction retrieval model that represents each document and query as multiple token embeddings and scores matches by taking the best token-to-token similarities (MaxSim) across them. Install the dependencies before running this example: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install pylate lancedb pandas ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa from pylate import models ## 1) Load a late-interaction model via PyLate ## PyLate docs show ColBERT() + encode(..., is_query=...) model = models.ColBERT(model_name_or_path="lightonai/GTE-ModernColBERT-v1") ## You can discover dim from one embedding (avoid guessing) dim = model.encode(["hello"], is_query=True)[0].shape[1] ## 2) Create a LanceDB table with a multivector column db = lancedb.connect("./pylate_lancedb") schema = pa.schema([ pa.field("doc_id", pa.string()), pa.field("text", pa.string()), # multivector: list<list<float32, dim>> pa.field("mv", pa.list_(pa.list_(pa.float32(), dim))), ]) docs = [ {"doc_id": "1", "text": "The train to Tokyo leaves at 5pm."}, {"doc_id": "2", "text": "That Pho restaurant in Hanoi is highly rated."}, {"doc_id": "3", "text": "This is a noodle bar in Osaka, Japan."}, ] ## 3) Encode documents with PyLate (token vectors per doc) doc_texts = [d["text"] for d in docs] doc_embs = model.encode(doc_texts, is_query=False) # list/array of (T, dim) per doc rows = [] for d, emb in zip(docs, doc_embs): emb = np.asarray(emb, dtype=np.float32) rows.append({**d, "mv": emb.tolist()}) tbl = db.create_table("docs", data=rows, schema=schema, mode="overwrite") ## 4) Build an index + query using a query matrix. ## Multivector brute-force scales with rows × vectors-per-row, so build the index ## at much smaller dataset sizes than you would for single-vector search; and ## always before exposing the table to remote traffic. tbl.create_index(vector_column_name="mv", metric="cosine") query = "Tell me about ramen in Japan" q_emb = np.asarray(model.encode([query], is_query=True)[0], dtype=np.float32) # (Tq, dim) out = tbl.search(q_emb).limit(5).to_pandas() # multivector search accepts a matrix print(out[["doc_id", "text"]]) ``` Late-interaction model implementations evolve rapidly, so it's a good idea to check the latest popular models when trying multivector search. ### Advanced Example: XTR Embeddings [ConteXtualized Token Retriever (XTR)](https://arxiv.org/abs/2304.01982) is a late-interaction retrieval model that represents text as token-level vectors instead of a single embedding. This lets search score token-to-token matches (MaxSim), which can improve fine-grained relevance. The notebook linked below shows how to integrate XTR, which prioritizes critical document tokens during the initial retrieval stage and removes the gathering stage to improve performance significantly. By focusing on the most semantically salient tokens early in the process, XTR reduces computational complexity while improving recall and ensuring rapid identification of candidate documents. > [card] [Multivector search with ColPali + XTR embeddings and LanceDB](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/multivector_xtr/main.ipynb) # Consistency Source: https://docs.lancedb.com/oss/v0-41-0/tables/consistency Understand when readers see changes and choose the freshness your application needs. **Applies to:** Embedded ✅, Enterprise ✅ ## Table snapshots and freshness Each table read uses one committed version of the data. **Freshness** describes whether that version includes recent writes. For example, after another application appends records, an already-open table handle can still read the version from before the append. For example, a dashboard may need the latest updates, while an experiment may need to keep reading a specific table version. Use read freshness settings for the dashboard and an explicit table version for the experiment. ## Visibility of writes In **LanceDB Embedded**, a table handle sees its own committed writes. By default, it does not automatically check for changes made through other handles or processes. Use a read consistency interval or `checkout_latest()` to pick up those changes. In **LanceDB Enterprise**, readers use the service's configured freshness policy. A connection can request fresher data. When a read must include a completed write, use a zero interval or call `checkout_latest()` after the write, with a client and server that support these freshness controls. ## Configure read freshness Set `read_consistency_interval` when connecting. This controls when reads pick up newer table versions; it does not change how writes commit. | Setting | Embedded | Enterprise | | - | - | - | | **Unset** | Keep the open table version until explicitly refreshed or changed by that handle. | Use the service's configured freshness policy. | | **Zero** | Check for the latest committed version on every read. | Request the latest committed version on every read. | | **Non-zero interval** | Check for updates on a read once the interval since the last check has elapsed. | Request data no older than the interval allows; the service may return fresher data. | `checkout_latest()` explicitly refreshes an Embedded table handle. On Enterprise it asks subsequent reads on that handle to reflect data at least as recent as the refresh request. To read a fixed historical version instead, use [table versioning](/oss/v0-41-0/management/table#versioning). > [accordion] Complete Python example: compare two readers > > Install the Python SDK with `pip install lancedb`, then save this as > `consistency.py` and run `python consistency.py`. It creates a temporary local > database and removes it when finished. No Enterprise connection is needed. > > ```python consistency.py icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > from datetime import timedelta > > import lancedb > > writer = lancedb.connect(uri) > table = writer.create_table("documents", [{"id": 1, "text": "first"}]) > > default_reader = lancedb.connect(uri).open_table("documents") > latest_reader = lancedb.connect( > uri, read_consistency_interval=timedelta(0) > ).open_table("documents") > > table.add([{"id": 2, "text": "second"}]) > > default_count = default_reader.count_rows() > latest_count = latest_reader.count_rows() > print(f"Default reader: {default_count} rows") # 1 > print(f"Zero-interval reader: {latest_count} rows") # 2 > > default_reader.checkout_latest() > refreshed_count = default_reader.count_rows() > print(f"After explicit refresh: {refreshed_count} rows") # 2 > ``` > > The default reader sees one row until refreshed. The reader with a zero > interval sees the new row on its next read. ## Choose a freshness interval * **Reads that must include recent writes:** use a zero interval. Checking more frequently can increase read latency and storage requests. * **Dashboards with an acceptable delay:** choose an interval within that delay budget, then measure the effect on latency and cost. * **Reproducible experiments:** read an explicit table version and retain it for as long as the experiment needs it. Choose the interval based on the delay your application can tolerate between a write completing and a reader seeing it. ## Learn more * [Connect](/oss/v0-41-0/basics/catalog): configure your client. * [Table versioning](/oss/v0-41-0/management/table#versioning): read and restore retained versions. * [Guarantees](/oss/v0-41-0/basics/guarantees): understand commit and failure boundaries. For invalid vector handling during ingestion, see [Create a table](/oss/v0-41-0/ingestion/create-table#from-a-custom-schema). # Real Time engine (RTE) Source: https://docs.lancedb.com/oss/v0-41-0/tables/realtime-engine Absorb small, frequent writes cheaply and make them queryable within milliseconds. **Applies to:** Embedded ✅, Enterprise ✅ ## What is the real time engine? Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. The real time engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. ## The Lance MemWAL format RTE is built on **MemWAL**, a log-structured-merge (LSM) format that Lance itself defines -- the structure Enterprise serves is part of the open Lance format, not a layer bolted on beside it. A table with RTE enabled is divided into one or more **shards** (see [RTE writes](/oss/v0-41-0/ingestion/realtime-write#primary-key) for enabling and sizing them), and each shard holds: * A **memtable**: the active, in-memory table for that shard's newest rows, queryable as soon as a write lands in it. * A **WAL buffer**: the same writes, batched and flushed to object storage before a write is acknowledged, so an unflushed memtable is never the only copy of a row. * Its own **in-memory indexes** (vector, full-text, BTree, and other scalar types), kept current as rows land, independently of the base table's indexes. A write commits in two stages, both before it is acknowledged: the WAL buffer append makes it durable, then it lands in the shard's memtable. When a memtable crosses a size or row-count threshold, it freezes and flushes as an immutable **SSTable** -- an ordinary Lance data file -- and a fresh memtable takes over. [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction) later folds SSTables into the base table, catching its indexes up as it goes. ## WAL nodes serve MemWAL shards This section describes LanceDB Enterprise's serving layer. LanceDB Embedded runs the same MemWAL mechanics directly against the local dataset, in one process -- there is no separate node to route to or scale; see [RTE writes](/oss/v0-41-0/ingestion/realtime-write#getting-started) and [RTE reads](/oss/v0-41-0/search/realtime-read#embedded) for what that looks like. RTE's Enterprise serving layer is a dedicated component, separate from the [query nodes and plan executors](/oss/v0-41-0/enterprise/distributed-search) that serve ordinary queries: | Component | Responsibility | | - | - | | WAL node | Own one or more tables' shards; append their WAL, maintain their memtables and in-memory indexes, and serve reads and writes against them. | A query node routes every request for an RTE-enabled table -- reads and writes alike -- to the WAL node that owns that table, by a consistent hash of the database and table name. WAL node pods share nothing but the underlying object storage; no pod talks to another one directly. One WAL node owns every shard of a given table. Splitting a table into more shards parallelizes that table's own writes into more independent append streams on the node that already owns it; adding more WAL node replicas instead spreads ownership of more *tables* across more pods. Shard a large table to raise its own ingest ceiling, and add WAL node replicas to raise the cluster's overall capacity. If a WAL node pod is replaced, its successor must claim ownership of a shard, by a version number that only ever increases, before writing to it -- so two pods are never both appending to the same shard's WAL at once. ## Reading a real time table Every query runs against the base table and the fresh tier -- every shard's memtable and not-yet-compacted SSTables -- in parallel. Fresh rows supersede base rows with the same primary key, and the two are merged into one result. See [RTE reads](/oss/v0-41-0/search/realtime-read) for what this means for query results. ## Next steps * [RTE writes](/oss/v0-41-0/ingestion/realtime-write) — enable RTE and write to a table * [RTE reads](/oss/v0-41-0/search/realtime-read) — query an RTE table * [Distributed RTE Write](/oss/v0-41-0/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes * [Distributed RTE Read](/oss/v0-41-0/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines * [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction) — how Enterprise folds shards into the base table # Multicloud Source: https://docs.lancedb.com/oss/v0-41-0/deployment/multicloud Keep deployment orchestration in your cloud while dispatching compute-heavy work, like GPU UDF execution, to run in a different cloud. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB Enterprise deployment doesn't have to keep all of its compute in one cloud. Orchestration -- query nodes, job coordination, the catalog -- stays with your deployment in its own cloud account and region. Specific, compute-heavy work, such as a GPU-bound Function's execution during a refresh, can instead dispatch to run in a **different** cloud account, region, or provider entirely, and send its results back to complete the job. ## How it fits together Your deployment's job orchestration plans the work and tracks it to completion the same way it would locally. The part that actually needs the remote capacity -- a GPU UDF call, for example -- runs across a network boundary instead of on a worker in your own cloud, and reports its result back the same way a local worker would. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph P["Your cloud"] direction TB QN["Query node"] Job["Job orchestration"] end subgraph R["Remote cloud"] direction TB Exec["Compute execution<br/>(e.g. GPU UDFs)"] end QN --> Job Job -- "dispatches work" --> Exec Exec -- "results" --> Job classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Exec accent ``` ## Why it matters The cloud that's right for your primary deployment -- where your data and other infrastructure already live -- isn't always the cloud with the best GPU availability or pricing. Splitting orchestration from execution means you don't have to choose: keep your deployment where it already makes sense, and reach compute capacity elsewhere only for the work that actually needs it, without migrating the deployment or operating that remote capacity yourself. [Contact us](https://www.lancedb.com/contact) to learn more about setting up cross-cloud execution for your deployment. ## What to read next > [card] [Slurm](/oss/v0-41-0/deployment/slurm) > > A common way the remote cloud's compute gets scheduled: as Slurm jobs. > [card] [Adaptive Execution](/oss/v0-41-0/enterprise/adaptive-execution) > > How a refresh's resource class, part size and worker count adjust themselves. # Monitor LanceDB with OpenTelemetry Source: https://docs.lancedb.com/oss/v0-41-0/deployment/opentelemetry Export LanceDB object store request counts, bytes, latency, errors, and throttles to any OpenTelemetry backend. LanceDB emits internal metrics (currently object store request counts, bytes transferred, request latency, retryable errors, and throttles) and can bridge them into any [OpenTelemetry](https://opentelemetry.io/) backend. Use this to watch how your application interacts with S3, GCS, Azure Blob, or the local filesystem in production: spot latency regressions, catch retry storms, and size your storage tier from real workload data. The bridge is available in the Python and TypeScript SDKs. It is a thin wrapper over LanceDB's `metrics` recorder; your application supplies and configures the OpenTelemetry SDK. > [!NOTE] > > This page covers LanceDB Embedded instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. ## Available metrics Once instrumented, LanceDB registers one observable instrument per metric on your `MeterProvider`. The current catalog covers the object store layer: | Metric | Kind | Description | | - | - | - | | `lance_object_store_requests_total` | Counter | Total object store requests, labelled by `operation` and `base` (store scheme). | | `lance_object_store_request_duration_seconds` | Histogram | Request latency in seconds. | | `lance_object_store_request_bytes_total` | Counter | Bytes read from or written to the store. | | `lance_object_store_errors_total` | Counter | Object store requests that failed. | | `lance_object_store_retryable_responses_total` | Counter | Retryable HTTP responses (5xx, 429 and 408) from a store reached over HTTP. | | `lance_object_store_throttle_total` | Counter | Throttle responses (429 and 503) from a store reached over HTTP. | | `lance_object_store_in_flight_requests` | Gauge | Currently outstanding object store requests. | The recorder is process-global and pull-based: your configured `MetricReader` collects on its own schedule, so there is no hot-path overhead beyond the atomic aggregation that LanceDB does anyway. > [!NOTE] > > **Histograms are exported Prometheus-style.** OpenTelemetry has no asynchronous histogram instrument, so each histogram surfaces as three observable counters: `<name>_bucket` (with an `le` attribute per bucket boundary, including `+Inf`), `<name>_count`, and `<name>_sum`. Only `_sum` carries the histogram's unit; `_bucket` and `_count` are cumulative sample counts. ## Python Install LanceDB with the `otel` extra to pull in the OpenTelemetry API, plus an OpenTelemetry SDK of your choice. The SDK is intentionally not bundled, so you configure it and its readers and exporters however your platform expects. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lancedb[otel]" opentelemetry-sdk opentelemetry-exporter-otlp-proto-grpc ``` Call `instrument_lancedb_metrics()` once at startup, before opening any tables. It returns `True` when the recorder is installed and instruments are registered. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.otel import instrument_lancedb_metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import ( PeriodicExportingMetricReader, ) from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import ( OTLPMetricExporter, ) reader = PeriodicExportingMetricReader(OTLPMetricExporter()) provider = MeterProvider(metric_readers=[reader]) instrument_lancedb_metrics(provider) # Any object store activity from this point on is now recorded. db = lancedb.connect("s3://my-bucket/lancedb") ``` If you omit `meter_provider`, LanceDB uses the global provider returned by `opentelemetry.metrics.get_meter_provider()`. > [!WARNING] > > `instrument_lancedb_metrics()` returns `False` and emits a warning if another `metrics`-crate recorder is already installed in the process. Only one global recorder is permitted, so instrument LanceDB before any other library that installs its own recorder. ## TypeScript Install the OpenTelemetry SDK and exporter in your application: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @opentelemetry/sdk-metrics @opentelemetry/exporter-metrics-otlp-grpc ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { connect, instrumentLanceDbMetrics } from "@lancedb/lancedb"; import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-grpc"; const reader = new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(), }); const provider = new MeterProvider({ readers: [reader] }); instrumentLanceDbMetrics(provider); const db = await connect("s3://my-bucket/lancedb"); ``` `instrumentLanceDbMetrics()` also accepts no arguments, in which case it uses the global provider from `@opentelemetry/api`. Calling it more than once is safe: instruments are created only on the first successful call. ## Build dashboards and alerts A few starting points for dashboards and alerts: * **Request rate by operation:** `rate(lance_object_store_requests_total[1m])` broken down by `operation` shows read vs. write pressure and helps size ingestion and serving traffic separately. * **Tail latency:** histogram quantiles over `lance_object_store_request_duration_seconds_bucket` catch object store slowdowns before they surface as query timeouts. * **Retryable responses:** a rising `lance_object_store_retryable_responses_total` typically means you are being throttled and should back off or shard writes. * **In-flight requests:** a growing `lance_object_store_in_flight_requests` gauge without a matching rise in throughput indicates queueing. ## Enterprise monitoring Enterprise A deployment emits its own metrics from the server side, using Prometheus for collection and OpenTelemetry (OTel) to export them with data enrichment. No client-side instrumentation is needed. | Component | Metrics | | - | - | | Query node | RPS, query latency, error codes, slow-query count, CPU/memory utilization | | Executor | SSD cache hit/miss rate, CPU/memory utilization | [Contact support](/oss/v0-41-0/deployment/support) for the comprehensive metric list and help integrating them with your monitoring dashboard. ## Related guides > [card] [Performance tips](/oss/v0-41-0/search#performance) > > Tune ingestion, indexing, and query patterns once metrics highlight a hot spot. > [card] [Object storage](/oss/v0-41-0/basics/catalog#object-storage) > > Configure the object store backends whose requests these metrics measure. # Slurm Source: https://docs.lancedb.com/oss/v0-41-0/deployment/slurm Run LanceDB Enterprise's own pods as Slurm-scheduled jobs, and reach a Neocloud's GPU capacity through Slurm in the multicloud case. **Applies to:** Embedded ❌, Enterprise ✅ [Slurm](https://slurm.schedmd.com/) is the workload manager most GPU clusters run to schedule and account for jobs -- queueing work across shared nodes, enforcing fair-share and priority policies between teams, and tracking GPU-hour usage per job. That makes it the de facto standard in AI training infrastructure, where expensive GPU nodes are shared across many training and data jobs instead of dedicated to one team. GPU-focused cloud providers ("Neoclouds") such as CoreWeave and Nebius run Slurm-based scheduling across their Kubernetes clusters for exactly this reason. Slurm shows up for LanceDB Enterprise in two related ways. Its own pods -- query nodes, plan executors, and background job workers alike -- can run as Slurm-scheduled jobs rather than plain Kubernetes pods, under the same scheduling and accounting as everything else on the cluster. And in the [multicloud](/oss/v0-41-0/deployment/multicloud) case, when the remote cloud is a Neocloud, Slurm is commonly how the dispatched GPU work actually gets scheduled there. ## How it fits together Scheduling LanceDB's pods through Slurm puts them under the same scheduler as GPU training jobs, so the cluster's capacity is accounted for consistently regardless of which one is using it -- Slurm's fair-share and priority policies apply to LanceDB the same way they apply to a training job, including preemption when training needs the capacity back. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph P["Your cloud"] direction TB Job["Job orchestration"] end subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] direction TB Slurm["Slurm scheduler"] Train["GPU training jobs"] LDB["LanceDB Enterprise pods"] Slurm --> Train Slurm --> LDB Train -.->|"can preempt"| LDB end Job -- "dispatches GPU work" --> Slurm LDB -- "results" --> Job classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Slurm accent ``` ## Why it matters Most GPU infrastructure already runs Slurm for training. Deploying LanceDB Enterprise into that same infrastructure, under the same scheduler, means it can share capacity with training workloads safely -- queued, accounted, and preemptible like everything else -- instead of requiring a separate, dedicated pool of nodes carved out just for LanceDB. Combined with [multicloud](/oss/v0-41-0/deployment/multicloud) dispatch, that makes it practical to keep your primary deployment wherever it already lives and still reach GPU capacity on a Neocloud built around Slurm, only for the work that needs it. [Contact us](https://www.lancedb.com/contact) to learn more about running LanceDB Enterprise on a Slurm-scheduled cluster. ## What to read next > [card] [Multicloud](/oss/v0-41-0/deployment/multicloud) > > The cross-cloud dispatch model this page's Neocloud case builds on. > [card] [Architecture](/oss/v0-41-0/index#architecture) > > The query, executor, cache and jobs fleets this scheduling applies to. # Adaptive Execution Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/adaptive-execution How a Function refresh's part size, resource class, worker count and checkpoint frequency adjust themselves to observed behavior. **Applies to:** Embedded ❌, Enterprise ✅ Early access When a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) or [materialized view](/oss/v0-41-0/feature-engineering/materialized-views) is filled by a registered [Function](/oss/v0-41-0/curation/create-function), LanceDB Enterprise adapts the refresh to the Function's actual behavior along several axes -- how many rows go in one unit of work, how much CPU, memory and GPU one invocation gets, how many worker processes run inside one worker, and how many workers run at all -- rather than running it at one fixed shape regardless of how slow, fast, or resource-hungry that Function turns out to be. See [Architecture](/oss/v0-41-0/index#architecture). ## Part size follows observed throughput A Function refresh starts with a small probe part -- 10 rows -- and grows it based on an exponentially-weighted average of rows processed per millisecond, aiming each next part at roughly 45 seconds of work. A part can grow or shrink by at most 16x from the previous one, so one unusually slow or fast part doesn't swing sizing to an extreme; the ceiling is 1,000,000 rows per part regardless of how fast the Function appears to run. A consistently slow Function converges on small parts that finish reliably; a fast one converges on large parts that keep worker overhead \-- a fresh scanner and registry round trip per part -- small relative to the work done. ## Resource class follows observed consumption Each invocation is measured -- wall time, CPU time and utilization, peak memory, out-of-memory events, and for a GPU Function, compute and memory utilization per GPU -- and that measurement decides whether the *next* invocation runs with more resources, fewer, or the same: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR I["Invocation runs<br/>wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} D -->|"OOM, or memory/CPU/GPU<br/>over target utilization"| P["Promote:<br/>next size up"] D -->|"fast task, low CPU,<br/>known memory"| Dm["Demote:<br/>one size down,<br/>never past a floor"] D -->|neither| S["Stay:<br/>same class"] P --> N["Next invocation"] Dm --> N S --> N N --> I classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` **Promotion** happens on an out-of-memory event, memory utilization above 70% of the class's limit, or CPU pegged at 85%+ for a sample long enough (5 seconds) that one fast spike isn't mistaken for sustained saturation. A GPU Function promotes the same way on GPU compute or GPU memory saturation. **Demotion** is more conservative: only a task that both finished fast (under 30 seconds) and used 25% or less of its CPU budget demotes, one size down at a time rather than jumping straight to the smallest class, and never below a configured floor. Either way, the class actually chosen is the smallest one whose memory and CPU both cover the observed peak with roughly 40% headroom, so sizing tracks what the Function actually consumes rather than a static guess made once at registration. ## Process and worker count follow the resource budget Within one worker, the number of executor processes is chosen to be the largest count that still fits the worker's memory budget, since memory per process shrinks as the count grows. Across workers, the fleet claims as many additional workers as the configured CPU, memory and GPU budget has room for, given what's already running -- the worker count grows to use available budget rather than running at a single fixed count regardless of how much of the budget sits idle. ## Checkpoint granularity follows part size A refresh checkpoints once per part, not on a separately-tuned interval -- so checkpoint frequency is a direct consequence of the same EWMA-driven part sizing described above, not a second knob. A Function that converges on small parts checkpoints often, losing little work if a worker dies mid-refresh; one that converges on large parts checkpoints less often, trading that for lower per-part overhead. See [Checkpointing](/oss/v0-41-0/enterprise/checkpointing) for the mechanism itself. ## Overriding the defaults A refresh can request a GPU class and count, or cap the maximum rows per Function call directly, instead of relying on this adaptive behavior -- see [Configure workers and resources](/oss/v0-41-0/feature-engineering/refresh-column#resources) for the full set of overrides, SQL and SDK alike. Setting `batch_size` caps the rows passed to each Function call for that refresh; the adaptive part sizing described above still decides how many rows each part covers. ## What to read next > [card] [Incremental Refresh](/oss/v0-41-0/enterprise/incremental-refresh) > > How the rows a Function refresh works on are chosen in the first place. > [card] [Checkpointing](/oss/v0-41-0/enterprise/checkpointing) > > How a part's progress survives a failure or restart. # Advanced Conflict Resolution Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/advanced-conflict-resolution How compaction and indexing stay safe to run concurrently, using Lance's fragment reuse index. **Applies to:** Embedded ❌, Enterprise ✅ [Compaction](/oss/v0-41-0/maintenance/compaction) rewrites fragments into fewer, larger files, which changes the physical row address -- file and offset -- of every row it moves. An index built against the old layout stores exactly those addresses, so a naive compaction would leave any index covering the rewritten fragments pointing at rows that have moved or no longer exist there. LanceDB Embedded avoids this by default by never letting the two run independently: `optimize()` compacts and remaps affected indexes in the same call, before returning. Compaction's `defer_index_remap` option opts out of that -- the call returns once compaction itself commits, leaving the remap for later -- which is what lets a custom remapper or a stable-row-ID table skip the synchronous step. LanceDB Enterprise runs compaction and indexing as separate, independently scheduled background jobs -- a table can compact while an index build is still catching up from an earlier compaction -- so it needs a way to keep an index correct without forcing every compaction to wait for a synchronous remap. ## The fragment reuse index The **fragment reuse index** (FRI) is a Lance format-level mechanism, not an Enterprise add-on: a system index that records every fragment rewrite as a **transition** -- the source fragments' digests, the destination fragments' digests, and a row-address mapping between them (`Transition` and `Mapping` in `lance-table`'s `system_index::frag_reuse::ledger`). An index that covers a rewritten fragment does not need to be rebuilt before the rewrite commits; it can instead translate the row addresses it already stores forward through the chain of recorded transitions at read time. Only a compaction run with `defer_index_remap` ever touches the FRI; a synchronous-remap rewrite -- the Embedded default -- never tags a table or appends anything. Every `defer_index_remap` commit is classified before it is admitted; that classifier is Lance's own commit protocol (`lance-table`'s `frag_reuse::gate::classify`), the same one every write funnels through -- not a lock or a sequencing rule Enterprise imposes from outside. A table starts **untagged**: its deferred rewrites are admitted as ordinary business with nothing appended, unless the rewrite has stable row IDs to translate or touches a fragment an index covers -- either one makes that commit record a legacy, untagged ("v0") FRI entry, which does **not** tag the table. Tagging is a separate, one-way transition (a sticky manifest flag that a later trim never clears) that publishes the FRI's first real transition; this page does not cover what triggers it. Once a table is tagged, its commits are classified against which indexes cover the rewritten fragments the way the rest of this page describes, and every entry it records from then on is a tagged transition, never v0 again. A table with stable row IDs is permanently confined to the untagged, v0 form -- Lance refuses to tag it at all -- so its deferred compactions keep recording v0 entries indefinitely, for every rewrite that moves row addresses, not only ones that touch an indexed fragment: the address translation itself depends on that record, independent of indexing. Once a table is tagged, Lance refuses a compaction that does not set `defer_index_remap`, including a plain Embedded `optimize()` call: an Enterprise-tagged table has to keep deferring the remap, or be compacted by a writer that can remap the tagged history eagerly. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Commit["Compaction commit<br/>(defer_index_remap only)"] --> Tagged{"Table already<br/>tagged with an FRI?"} Tagged -->|no| First{"Stable row IDs, or does<br/>any index cover the<br/>rewritten fragments?"} First -->|no| Admit["Admitted as<br/>ordinary business --<br/>nothing appended"] First -->|yes| V0["Records a legacy v0 entry --<br/>table stays untagged"] Tagged -->|yes| Classify{"Does any index<br/>cover the rewritten<br/>fragments?"} Classify -->|no| Admit Classify -->|yes| Append["Must append a tagged<br/>transition before the<br/>commit is admitted"] V0 --> FRI[("Fragment reuse index")] Append --> FRI classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class FRI accent ``` ## Enterprise defers and batches the catch-up Translating addresses through a long chain of transitions at every read adds up, so Enterprise does not let the FRI grow without bound. Its job planner tracks how many transitions have accumulated for a table and schedules a dedicated **remap catch-up** job -- which applies the accumulated transitions to the indexes that need them, physically, in one pass -- once either: * the FRI reaches **5 pending transitions** (`remap_fri_version_threshold`, tunable), or * the oldest pending transition is **1 day old** (`remap_fri_max_age_secs`, tunable), whichever comes first. The version count only climbs while a table keeps compacting, so the age threshold exists to clear a lingering FRI -- and the per-read remap cost that comes with it -- on a table that stops compacting before reaching the count threshold, without scheduling a catch-up job on every table that is still actively compacting. This is what lets compaction and index maintenance run as separate background jobs (see [Index maintenance jobs](/oss/v0-41-0/indexing/incremental-indexing#index)) rather than one blocking on the other: a handful of compactions can land before their indexes are physically remapped, and the catch-up job amortizes that remap across all of them in one job instead of one per compaction. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index<br/>(ledger of transitions)"] C2["Compaction job"] -->|appends transition| FRI C3["Compaction job"] -->|appends transition| FRI FRI -->|5 transitions or<br/>1 day old| R["Remap catch-up job"] R -->|applies accumulated<br/>transitions| IDX["Affected indexes,<br/>physically remapped"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class FRI,R accent ``` ## What to read next > [card] [Compaction and cleanup](/oss/v0-41-0/maintenance/compaction) > > What compaction merges, and how the embedded library runs it in one call. > [card] [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing#index) > > The `index_remap` job type, and keeping an index current as the table changes. > [card] [Distributed Compaction](/oss/v0-41-0/enterprise/distributed-compaction) > > How compaction itself scales across the jobs fleet. > [card] [Distributed Indexing](/oss/v0-41-0/enterprise/distributed-indexing) > > How an index build scales across the jobs fleet. # Authentication Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/authentication Authentication modes for LanceDB Enterprise: API keys and OAuth credentials. **Applies to:** Embedded ❌, Enterprise ✅ A deployment authenticates each request over a `db://` connection before [authorization](/oss/v0-41-0/governance/authorization) decides what it may do. Choose one of these methods: * **API keys**: a long-lived shared secret passed as `api_key` on connect. Works in every SDK. * **OAuth 2.0**: short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. OAuth is the recommended option when you want to rotate credentials centrally, plug into an existing identity provider, or run on Azure with managed identities so no secret material lives on the client. ## API key Pass the API key from your Enterprise tenant on `connect`. This works with both the synchronous and asynchronous Python clients, as well as TypeScript and Rust. Load the key from an environment variable or secret manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os db = lancedb.connect( uri="db://your-database-uri", api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-enterprise-endpoint.com", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const apiKey = process.env.LANCEDB_API_KEY; if (!apiKey) throw new Error("LANCEDB_API_KEY is required"); const db = await lancedb.connect("db://your-database-uri", { apiKey, region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let api_key = std::env::var("LANCEDB_API_KEY")?; let db = lancedb::connect("db://your-database-uri") .api_key(&api_key) .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .execute() .await?; ``` For Rust, enable the `remote` feature on the `lancedb` dependency to use API key or OAuth authentication. See [Database](/oss/v0-41-0/management/database#deployment) for the connection options. ## OAuth The async Python, TypeScript, and Rust clients can obtain bearer tokens from an OIDC issuer and attach them to every request. Token acquisition, caching, and refresh are handled inside the client. Your application code only provides the configuration. A deployment accepts these tokens only when its administrator has configured it with your identity provider. Ask them for the issuer URL, client ID, scopes, and any resource or audience required by the provider. For Authorization Code, register the loopback redirect URI with the provider. For Device Code, enable the provider's device authorization grant for your application. > [!NOTE] > > In Python, OAuth is supported through `lancedb.connect_async`. The synchronous > `connect` entry point continues to use API key authentication for `db://` > URIs. In TypeScript, `lancedb.connect` accepts `oauthConfig` directly. > In Rust, use `.oauth_config(config)` on the connection builder. ### Supported flows `OAuthFlowType` (Python and TypeScript) or `OAuthFlow` (Rust) selects how the client acquires tokens: | Flow | Python value | TypeScript value | Rust value | When to use | | - | - | - | - | - | | Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | `OAuthFlow::ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | | Authorization Code | `OAuthFlowType.AUTHORIZATION_CODE` | `OAuthFlowType.AuthorizationCode` | `OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new())` | Interactive user sign-in through a browser and local callback server. Uses S256 PKCE by default. | | Device Code | `OAuthFlowType.DEVICE_CODE` | `OAuthFlowType.DeviceCode` | `OAuthFlow::DeviceCode(DeviceCodeOptions::new())` | CLI or headless sign-in. The client displays a verification URL and user code for the user to enter on another device. | | Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | `OAuthFlow::AzureManagedIdentity { client_id: None }` | Azure workloads with access to the IMDS endpoint. Tokens are fetched from IMDS, so no client secret is stored on the client. | ### Configure OAuth Build an OAuth config and pass it on connect. Use `oauth_config` in Python and Rust, and `oauthConfig` in TypeScript. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from lancedb.remote import OAuthConfig, OAuthFlowType # Client Credentials (service-to-service) oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", client_secret=os.environ["LANCEDB_OAUTH_CLIENT_SECRET"], scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.CLIENT_CREDENTIALS, ) db = await lancedb.connect_async( uri="db://your-database-uri", region="us-east-1", host_override="https://your-enterprise-endpoint.com", oauth_config=oauth_config, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; const clientSecret = process.env.LANCEDB_OAUTH_CLIENT_SECRET; if (!clientSecret) throw new Error("LANCEDB_OAUTH_CLIENT_SECRET is required"); // Client Credentials (service-to-service) const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", clientSecret, scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.ClientCredentials, }; const db = await lancedb.connect("db://your-database-uri", { region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", oauthConfig, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{OAuthConfig, OAuthFlow}; // Client Credentials (service-to-service) let oauth_config = OAuthConfig { issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), client_id: "your-application-client-id".into(), client_secret: Some(std::env::var("LANCEDB_OAUTH_CLIENT_SECRET")?), scopes: vec!["api://lancedb-api/.default".into()], flow: OAuthFlow::ClientCredentials, client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: None, }; let db = lancedb::connect("db://your-database-uri") .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .oauth_config(oauth_config) .execute() .await?; ``` For Azure workloads with access to IMDS, use a managed identity instead of a client secret: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthConfig, OAuthFlowType oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.AZURE_MANAGED_IDENTITY, # Set only for a user-assigned managed identity: # managed_identity_client_id="your-user-assigned-identity-client-id", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.AzureManagedIdentity, // Set only for a user-assigned managed identity: // managedIdentityClientId: "your-user-assigned-identity-client-id", }; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{OAuthConfig, OAuthFlow}; let oauth_config = OAuthConfig { issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), client_id: "your-application-client-id".into(), client_secret: None, scopes: vec!["api://lancedb-api/.default".into()], flow: OAuthFlow::AzureManagedIdentity { // Set to Some("your-user-assigned-identity-client-id".into()) // only for a user-assigned managed identity. client_id: None, }, client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: None, }; ``` `managed_identity_client_id` / `managedIdentityClientId` selects a user-assigned identity. Omit it for a system-assigned identity. The required `client_id` / `clientId` field does not select the Azure managed identity. In Rust, set the `client_id` inside `OAuthFlow::AzureManagedIdentity` to `Some(...)` for a user-assigned identity, or `None` for a system-assigned identity. The top-level `OAuthConfig::client_id` is the application client ID. For interactive sign-in, configure Authorization Code or Device Code. The authorization URL or device verification instructions are written to standard error. Authorization Code also tries to open a browser and listens for the callback at `http://127.0.0.1:8400/callback` by default. Register that redirect URI with your identity provider. Public clients can omit `client_secret`; request a refresh token from your provider (often by including `offline_access`) if you want to reuse the session. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthConfig, OAuthFlowType, TokenCacheOptions # Use DEVICE_CODE for a CLI without a local browser or callback server. oauth_config = OAuthConfig( issuer_url="https://your-issuer.example.com", client_id="your-public-client-id", scopes=["openid", "offline_access", "lancedb.read"], flow=OAuthFlowType.AUTHORIZATION_CODE, token_cache=TokenCacheOptions(), ) db = await lancedb.connect_async( uri="db://your-database-uri", region="us-east-1", host_override="https://your-enterprise-endpoint.com", oauth_config=oauth_config, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { OAuthFlowType, type OAuthConfig } from "@lancedb/lancedb"; // Use OAuthFlowType.DeviceCode for a CLI without a local browser or callback server. const oauthConfig: OAuthConfig = { issuerUrl: "https://your-issuer.example.com", clientId: "your-public-client-id", scopes: ["openid", "offline_access", "lancedb.read"], flow: OAuthFlowType.AuthorizationCode, tokenCache: {}, }; const db = await lancedb.connect("db://your-database-uri", { region: "us-east-1", hostOverride: "https://your-enterprise-endpoint.com", oauthConfig, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::{AuthorizationCodeOptions, OAuthConfig, OAuthFlow, TokenCacheOptions}; // Use OAuthFlow::DeviceCode(Default::default()) for a CLI without a local browser or callback server. let oauth_config = OAuthConfig { issuer_url: "https://your-issuer.example.com".into(), client_id: "your-public-client-id".into(), client_secret: None, scopes: vec![ "openid".into(), "offline_access".into(), "lancedb.read".into(), ], flow: OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new()), client_auth_method: None, resource: None, audience: None, refresh_buffer_secs: None, token_cache: Some(TokenCacheOptions::new()), }; let db = lancedb::connect("db://your-database-uri") .region("us-east-1") .host_override("https://your-enterprise-endpoint.com") .oauth_config(oauth_config.clone()) .execute() .await?; ``` With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode(DeviceCodeOptions::new())`, the same configuration and connection calls apply; only the `flow` value changes. Device Code sends no PKCE parameters by default. For a provider that requires S256 PKCE on device grants, Rust callers can select `OAuthFlow::DeviceCode(DeviceCodeOptions::new().use_pkce(true))` (import `DeviceCodeOptions` from `lancedb::remote`). This option is currently Rust-only. Enable it only when the provider supports the extension; a failed PKCE request is not retried without PKCE. ### Reuse an interactive session By default, tokens stay in process memory. Set `token_cache` / `tokenCache` for Authorization Code or Device Code to keep refresh tokens across process restarts. Only refresh tokens are persisted; access tokens and client secrets are not written to the cache. Set `cache_dir` / `cacheDir` to choose the directory, or leave it unset to use the platform cache directory. Your identity provider must issue a refresh token for a later process to sign in without prompting again. Use `OAuthSession` with the same config to log in before connecting, inspect whether a refresh token is cached, or remove the local cached credential: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.remote import OAuthSession session = OAuthSession(oauth_config) status = await session.login() print(status.refreshable) status = await session.status() # Does not contact the provider. print(status.refreshable) logout = await session.logout() print(logout.removed) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { OAuthSession } from "@lancedb/lancedb"; const session = new OAuthSession(oauthConfig); const status = await session.login(); console.log(status.refreshable); const current = await session.status(); // Does not contact the provider. console.log(current.refreshable); const logout = await session.logout(); console.log(logout.removed); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::remote::OAuthSession; let session = OAuthSession::new(oauth_config)?; let status = session.login().await?; println!("{}", status.refreshable); let status = session.status().await?; // Does not contact the provider. println!("{}", status.refreshable); let logout = session.logout().await?; println!("{}", logout.removed); ``` `login()` runs the interactive flow even when a session is cached. `logout()` removes the local cache entry; it does not revoke the provider's token or end a browser sign-in. `OAuthSession` requires a persistent cache and supports only Authorization Code and Device Code. A cache is unused for Client Credentials and rejected for Azure Managed Identity. ### Configuration reference The shared configuration below is available in all three SDKs; device-code PKCE is a Rust-only option through `DeviceCodeOptions`. Python and Rust use `snake_case` field names; TypeScript uses `camelCase`. In Rust, set optional `OAuthConfig` fields to `Some(value)` or `None`. Configure `redirect_uri`, `callback_port`, and `use_pkce` through the builder methods on `AuthorizationCodeOptions`, and select a managed identity through `OAuthFlow::AzureManagedIdentity { client_id: ... }`. | Python field / TypeScript field | Required | Description | | - | - | - | | `issuer_url` / `issuerUrl` | Yes | OIDC issuer URL or OAuth authority URL. For Azure, use `https://login.microsoftonline.com/{tenant_id}/v2.0`. | | `client_id` / `clientId` | Yes | Application / client ID registered with your identity provider. | | `scopes` | Yes | List of OAuth scopes to request. For Azure managed identity, provide exactly one scope or resource, for example `["api://your-app-id/.default"]`. | | `flow` | Yes in Rust; otherwise no | Selects the OAuth flow. Defaults to Client Credentials in Python and TypeScript; Rust requires an explicit `OAuthFlow`. | | `client_secret` / `clientSecret` | Conditional | Required for Client Credentials; only required for Authorization Code and Device Code when the provider registers a confidential client. Redacted from the config's `repr` (Python) and `Debug` output (Rust and TypeScript native binding). | | `client_auth_method` / `clientAuthMethod` | No | Token endpoint authentication: `ClientAuthMethod.NONE` / `ClientAuthMethod.None` for a public client, `ClientAuthMethod.CLIENT_SECRET_BASIC` / `ClientAuthMethod.ClientSecretBasic`, or `ClientAuthMethod.CLIENT_SECRET_POST` / `ClientAuthMethod.ClientSecretPost`. Defaults to Basic when a client secret is set and no client authentication otherwise. The secret methods require `client_secret` / `clientSecret`. Omit for Azure Managed Identity. | | `redirect_uri` / `redirectUri` | No | Authorization Code loopback callback URI. Defaults to `http://127.0.0.1:{callback_port}/callback`; register it with the provider. | | `callback_port` / `callbackPort` | No | Authorization Code callback server port (default 8400). If `redirect_uri` / `redirectUri` has an explicit port, the two ports must match. | | `use_pkce` / `usePkce` | No | Enable S256 PKCE for Authorization Code (default `true`). | | `managed_identity_client_id` / `managedIdentityClientId` | No | Client ID of a user-assigned managed identity. Only used with Azure Managed Identity; omit for system-assigned identities. | | `resource` | No | RFC 8707 resource indicator, an absolute URI without a fragment. Sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `audience` | No | Provider-specific audience sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL: setting it greater than or equal to the TTL forces a refresh on every request. | | `token_cache` / `tokenCache` | No | Opt in to a persistent refresh-token cache for Authorization Code or Device Code. Use `TokenCacheOptions()` in Python, `{}` in TypeScript, or `Some(TokenCacheOptions::new())` in Rust. Defaults to an in-memory session. | `TokenCacheOptions` also accepts `cache_dir` / `cacheDir` to select a cache directory and `lock_timeout_secs` / `lockTimeoutSecs` to set the wait for a cross-process refresh lock (default 30 seconds). In Rust, use the `TokenCacheOptions::cache_dir(...)` and `TokenCacheOptions::lock_timeout_secs(...)` builder methods. Token endpoint authentication uses `Some(ClientAuthMethod::None)`, `Some(ClientAuthMethod::ClientSecretBasic)`, or `Some(ClientAuthMethod::ClientSecretPost)`; `None` selects the default. > [!WARNING] > > Treat the client secret like any other production credential. Load it from a > secret manager or environment variable rather than committing it to source > control. All three SDKs deliberately omit the secret from their debug/repr output > so accidental log lines do not expose the value. LanceDB Embedded has nothing to authenticate to: your process opens the files directly, and the object store's own credentials are the only gate. # Auto Refresh Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/auto-refresh Let a computed column or materialized view refresh itself on a schedule, instead of calling refresh explicitly. **Applies to:** Embedded ❌, Enterprise ✅ Both a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) and a [materialized view](/oss/v0-41-0/feature-engineering/materialized-views) can refresh themselves on a schedule instead of waiting for an explicit `refresh_column()`, `view.refresh()`, or `REFRESH` statement. Either way, `auto_refresh_enabled` turns it on and `auto_refresh_interval_seconds` sets a minimum delay before the next automatic refresh is eligible -- omit the interval to let the server decide. What that delay is measured from differs between the two; see [Pacing follows different state for each](#history) below. See [Architecture](/oss/v0-41-0/index#architecture) for the scheduler's place among the jobs fleet. ## Where the two differ A computed column's auto-refresh setting is per output: each column declared in the same `add_columns` call gets its own independent interval, set when you declare it or changed later. Automatic execution additionally needs the deployment's `column_refresh.enabled` switch, which is off in the base configuration. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = true; ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_interval_seconds = 300; ``` A materialized view's setting is whole-view -- there is no per-column granularity the way a computed column has one setting per output. The view's *initial* population always happens regardless of this setting; only the refreshes after that are gated. Unlike a computed column, a view's setting is declared at `CREATE` time, but it can still be changed afterward with `ALTER`: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW my_view WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT * FROM source_table; ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = false; ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = true; ALTER MATERIALIZED VIEW my_view SET auto_refresh_interval_seconds = 300; ``` Each `SET` above changes the scheduling setting immediately and synchronously; it does not itself run a refresh. Whether and when a refresh actually runs next is a separate, asynchronous decision the scheduler makes against the pacing rules below. If values stop appearing after a `SET`, check the column's Job Registry history rather than assuming the setting itself failed to apply. ## Pacing follows different state for each A computed column's pacing is measured from the last successful refresh recorded in the Job Registry's live history, not from a separate timestamp LanceDB keeps elsewhere. If completed jobs are archived before the column's configured interval has elapsed, the scheduler can lose that last-success record and refresh earlier than the interval implies. Leave archival disabled, or retain live history for at least the longest configured interval you rely on. A deployment archives completed jobs by default, after a default seven-day retention threshold; check with your deployment operator if you rely on a different setting. A materialized view's pacing instead reads a timestamp the view itself persists for when it was last checked, not Job Registry history -- so archival doesn't affect it. Once the interval has elapsed, the scheduler also skips the refresh outright if the source table's version is unchanged since the view's last check, rather than re-running a refresh that would produce the same rows. ## Catching up Re-enabling a column's auto-refresh after it was off catches up the entire accumulated backlog in one pass, not just rows written from that point on -- "catch up," not "resume cadence." Disabling never skips or drops writes either: rows written while disabled simply commit with no computed value yet, the same as a row written before the column existed. ## What to read next > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > Manual refresh, partial refreshes, and what happens on failure. > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > Manual refresh and what happens on failure, for a view. # Function Refresh Checkpointing Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/checkpointing How a Function refresh's progress survives a worker failure or restart, part by part. **Applies to:** Embedded ❌, Enterprise ✅ Early access This page is about checkpointing a [Function refresh](/oss/v0-41-0/enterprise/adaptive-execution) specifically -- not [PyTorch training checkpointing](/oss/v0-41-0/training/checkpointing), a different, unrelated mechanism covered elsewhere. A Function refresh fills a column in [parts](/oss/v0-41-0/enterprise/adaptive-execution#part-size), each one a bounded range of rows. Every part's lifecycle is recorded as a durable, append-only event -- started, then completed -- in a log scoped to the data file that part belongs to. A worker failure or restart does not require redoing the refresh from scratch: the next attempt reads that log, finds which parts already completed, and only works on what's left. Retrying is at-least-once at the part level, not exactly-once: a part that started but never recorded completion is redone in full on the next attempt, so a Function with external side effects (a remote API call, for example) can have those side effects repeated for that part's rows. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Part started<br/>event recorded"] --> E["Function executes"] E --> C["Part completed<br/>event recorded"] C --> M{"More parts?"} M -->|yes| S M -->|no| F["Finalized:<br/>digest-verified assembly<br/>into the real data file"] S -. "worker dies here" .-> R["Next attempt reads the log,<br/>sees no completion,<br/>redoes only this part"] C -. "worker dies here" .-> R2["Next attempt reads the log,<br/>sees this part done,<br/>inherits it, moves on"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class R,R2 accent ``` ## What gets recorded, and when Each part contributes two events to its data file's log: one when a worker starts it, one when it completes with the rows it filled, the rows it skipped, and how long it took. A completed part additionally carries enough identity that a *different* job -- one that took over after the part's original job died -- can verify the part is really done and adopt it rather than redo it. Once every part for a data file has completed, one last event finalizes it: the assembled file's checksum is verified against what the parts actually wrote before it's accepted as the real data file, not just assumed correct because every part reported success. Writes to this log are batched, not one durable write per event, so checkpointing a fast-finishing part costs a fraction of a write rather than a full one. ## The Blob v2 optimization A Function whose output includes a [Blob v2](/oss/v0-41-0/management/table#managed-blobs) column needs an identifier for every blob it writes. Allocating those IDs piggybacks on the same durable event that already records a part starting: the event log itself hands out the next unclaimed range, computed from the highest range any earlier part in this log has already claimed. This means: * **No separate allocation round trip.** The ID range arrives for free inside a write the part was already going to make durably. * **A retried part can't collide with itself or with other parts.** Each attempt at a part writes a new part-started event and gets a fresh range past the highest range already claimed in this log, so no two attempts -- of the same part or of different parts -- ever hold overlapping ranges. Re-sending the *same* event, for example after a lost acknowledgement, is idempotent and returns the range it was already given. A range left behind by a failed attempt is not reclaimed. ## What to read next > [card] [Adaptive Execution](/oss/v0-41-0/enterprise/adaptive-execution) > > Part sizing, and why checkpoint frequency follows it. > [card] [Create a Function](/oss/v0-41-0/curation/create-function) > > Shaping a Function, including ones that return Blob v2 output. # Kubernetes deployment guide Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/deployment/kubernetes Learn how LanceDB Enterprise deploys on Kubernetes with private networking, object storage, and workload identity. LanceDB Enterprise deploys on a Kubernetes cluster (AKS, EKS, GKE, or self-managed) with object storage for data persistence and your cloud's private networking for secure connectivity. The architecture below is the same shape on every cloud; the only cloud-specific part is how storage containers are organized, covered at the end of this page for Azure Blob Storage. ## General architecture overview ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TB subgraph "Client VPC" Client[Client Applications] end subgraph "Server VPC" PLS[Private Link Service] subgraph "Kubernetes Cluster" LDB[LanceDB Enterprise<br/>Query Nodes, Executors,<br/>Lance Agent, Indexer Pods] end EH[Message Queue<br/>for LanceDB internal<br/>message passing] BS[Object Storage] WI[Workload Identity] end Client ==>|Private Link| PLS PLS ==> LDB LDB <-->|Read/Write| BS LDB -->|Async Events| EH EH -->|Process| LDB WI -.->|RBAC| BS WI -.->|Assigned| LDB classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class LDB accent ``` ### Key components * **LanceDB architecture** is deployed in a Kubernetes cluster within its own VPC. * **Client applications** connect to the cluster securely using your cloud's private link service. * **The cluster** is granted object storage read/write permissions using cloud-native workload identity (Azure Workload Identity, IRSA on EKS, or Workload Identity Federation on GKE). * **A message queue** -- a managed service such as Azure EventHub, or a self-hosted Kafka cluster in Kubernetes -- carries LanceDB's internal message passing. ## Read path architecture ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph LR subgraph "Client Network" C[Client App] end subgraph "Kubernetes Cluster" PL[Private Link<br/>Service] QN[Query Nodes<br/>Query planning + routing fleet] PE[Executors<br/>Executor + cache fleet] end subgraph "Storage" BS[Object<br/>Storage] end C -->|Private<br/>Connection| PL PL --> QN QN -->|Query<br/>Request| PE PE -->|Cache Miss<br/>Read Data| BS classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class BS accent ``` ### Read path flow 1. **Client application** sends a query request through the private link. 2. **Query nodes** receive and process the request. 3. **Executors** execute the query using the distributed data cache to speed up read queries. 4. **Object storage** stores data and indices in Lance format, while executors maintain a distributed cache for performance. ## Write path architecture ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TD subgraph "Client Network" C[Client App] end subgraph "Kubernetes Cluster" PL[Private Link<br/>Service] QN[Query Nodes<br/>Query planning + routing fleet] LA[Lance Agent] IP[Indexer Pods<br/>On-Demand] end subgraph "Messaging" EH[Message Queue<br/>Write Events] end subgraph "Storage" BS[Object<br/>Storage] end C -->|Private Connection| PL PL --> QN QN -->|Sync Write| BS QN -->|Async Events| EH EH -->|Consume| LA LA -->|Launch| IP IP -->|Index & Optimize| BS classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class BS accent ``` ### Write path flow Query nodes write data and indices synchronously to object storage in Lance format while asynchronously sending data modification events to the message queue (a managed service such as Azure EventHub, or a self-hosted Kafka cluster). These write events are processed by the Lance Agent, which launches indexing pods or data optimization pods to optimize data for better read performance. ## Deployment models LanceDB Enterprise supports three deployment models, available on AWS, GCP, and Azure: ### 1. Fully managed service * **Infrastructure and storage** in LanceDB's cloud account. * **Complete management** by the LanceDB team. * **Simplest setup** for customers. ### 2. BYOC (bring your own cloud) * **Infrastructure and storage** in the customer's cloud account. * **Fully managed by LanceDB.** * **Full control** over data residency. ### 3. Hybrid -- bring your own container * **Infrastructure** in LanceDB's account. * **Storage containers** in the customer's account. > [!NOTE] > > For private deployments, high performance at extreme scale, or if you have strict security requirements, [contact us about LanceDB Enterprise](https://www.lancedb.com/contact). ## Azure-specific: storage containers The one part of this architecture that is genuinely cloud-specific is how object storage is organized. On Azure, data lives in **Blob Storage containers**, grouped under one or more **storage accounts** -- the same multi-tenant or multi-workload layout applies whether you use a single account with several containers, or split workloads across accounts: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% graph TB subgraph "Multi-Account & Multi-Container Support" SA1[Storage Account 1] SA2[Storage Account 2] SA3[Storage Account N] SA1 --> C1A[Container A] SA1 --> C1B[Container B] SA1 --> C1C[Container C] SA2 --> C2A[Container X] SA2 --> C2B[Container Y] SA3 --> C3A[Container 1] SA3 --> C3B[Container 2] end classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` The equivalent on other clouds is an S3 bucket (AWS) or a Cloud Storage bucket (GCP); everything else on this page \-- the Kubernetes cluster layout, the read and write paths, and the deployment models -- applies unchanged. # Distributed Compaction Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-compaction How LanceDB Enterprise distributes compaction across a fleet of job workers. **Applies to:** Embedded ❌, Enterprise ✅ Distributed compaction splits a table's fragments into independent, fragment-disjoint tasks and fans them out across job workers in LanceDB Enterprise. Unlike an index build, a compaction plan needs no bin-packing: Lance's own planner already produces disjoint tasks, so workers claim and execute them directly, with no coordination needed to decide who does what. See [Architecture](/oss/v0-41-0/index#architecture). ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR L["Lance's planner<br/>splits fragments into<br/>disjoint tasks"] L --> W1["Worker<br/>claims fragments 1-2"] L --> W2["Worker<br/>claims fragments 3-4"] L --> W3["Worker<br/>claims fragments 5-6"] W1 --> C["Fleet-wide eligibility gate:<br/>one worker claims the commit"] W2 --> C W3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class C accent ``` No task depends on another's result, so a worker that finishes early simply claims another task rather than waiting on its peers. Committing is where the fleet does coordinate: finished tasks go through a shared eligibility gate, and only the one worker that claims the commit actually writes it, rather than each worker committing its own task independently. Whether a failed task can still let the rest commit depends on the remap mode. Inline remap is all-or-nothing: one failed task fails the whole job, since the commit updates every affected index inline and can't skip a task's share of that. Deferred remap can commit a subset -- a failed task's fragments are abandoned and replanned in a later round, while the rest of the job's tasks commit without waiting on it. See [Advanced Conflict Resolution](/oss/v0-41-0/enterprise/advanced-conflict-resolution) for when compaction defers a remap at all. ## Compaction interfaces * [Compaction](/oss/v0-41-0/maintenance/compaction) for triggering and configuring a compaction. * [Garbage Collection](/oss/v0-41-0/maintenance/cleanup) for removing files compaction and other operations leave behind. * [Job Framework](/oss/v0-41-0/basics/jobs) for the job types a deployment runs on its own schedule. # Distributed Indexing Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/distributed-indexing How LanceDB Enterprise distributes a vector index build across a fleet of workers, stage by stage. **Applies to:** Embedded ❌, Enterprise ✅ A vector index build splits into stages, and the data in scope narrows at each one: training works from a small sample, shuffling touches every row once, and merging works entirely within one partition at a time. Full-text and scalar index builds skip training and shuffling -- they bin-pack directly into independent tasks workers claim and build in parallel, closer to how [distributed compaction](/oss/v0-41-0/enterprise/distributed-compaction) splits work. See [Architecture](/oss/v0-41-0/index#architecture). ## Stages of a vector index build 1. **Train.** A sample of the table's vectors -- not the full dataset -- trains the shared model every worker will use: IVF partition centroids, and for IVF-PQ, a PQ codebook on top of them. 2. **Shuffle.** Every row in the table gets assigned to its nearest trained partition and regrouped so that all of one partition's rows end up together, wherever in the table they originally lived. 3. **Merge.** Each partition is now self-contained, so workers build and merge partitions in parallel with no cross-partition coordination -- one worker's output never depends on another's. 4. **Commit.** The finished index is committed to the table. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Sample"] --> T["Train IVF centroids<br/>+ PQ codebook"] T --> Sh["Shuffle: assign every row<br/>to its nearest partition"] Sh --> M1["Merge<br/>partition A"] Sh --> M2["Merge<br/>partition B"] Sh --> M3["Merge<br/>partition C"] M1 --> C["Commit the<br/>finished index"] M2 --> C M3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Sh accent ``` ## Indexing interfaces The shared indexing guides describe how to build and maintain each index type: * [Vector indexes](/oss/v0-41-0/indexing/vector-index) and [vector search](/oss/v0-41-0/search/vector-search). * [Full-text indexes](/oss/v0-41-0/indexing/fts-index) and [full-text search](/oss/v0-41-0/search/full-text-search). * [Scalar indexes](/oss/v0-41-0/indexing/scalar-index) and [filtering](/oss/v0-41-0/search/filtering). * [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing) for triggering and tracking a build. # Compress Function output columns Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/function-column-compression Choose Lance storage compression before refreshing a Function output column. Use `update_field_metadata` to choose compression for a top-level column populated by a registered Function. Storage settings belong to the table column; keep compression metadata out of the Function's `output_schema`. To apply compression to the first backfill, disable automatic refresh while adding the column, set its compression, then start a refresh. For an existing table with a `blob_id` column and a registered Function `fetch_content` that returns text: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col table.add_columns( {"content": fetch_content(blob_id=col("blob_id"))}, auto_refresh_enabled=False, ) table.update_field_metadata( { "path": "content", "metadata": { "lance-encoding:compression": "zstd", "lance-encoding:compression-level": "22", }, } ) job = table.refresh_column_async("content") job.wait() ``` Higher compression levels trade write speed for smaller storage. The settings apply to subsequent writes; changing metadata does not rewrite existing files. Set a key's value to `None` to remove that setting. Use the default merge behavior of `update_field_metadata` to preserve the server-managed Function declaration. Compression updates are supported on Function outputs that no Function binding reads. If another Function will consume `content`, configure compression before binding that downstream Function: input contracts capture field metadata, so metadata changes on bound inputs remain rejected. Only `lance-encoding:compression` and `lance-encoding:compression-level` receive this exception; other metadata updates and metadata replacement remain rejected on Function-bound columns. # Horizontal Scaling Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/horizontal-scaling How LanceDB Enterprise spreads serving capacity for a table across replica groups, and replicates it within each one. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB Enterprise scales serving capacity by assigning a table to one or more **replica groups** -- numbered subsets of the plan-executor fleet -- and, within each group, by **replication factor** (RF): how many copies of the table's data that group holds. A table is served only from the groups it is explicitly assigned to; adding plan executors to the fleet, or adding a new group, never auto-includes existing tables. A pristine table that was never explicitly placed stays on one default group at the cluster's default RF. See [Architecture](/oss/v0-41-0/index#architecture). Placement is stored in the table's own manifest, not a separate configuration store, and takes effect for a table within its readers' read-consistency refresh interval after a change. An index can carry its own RF override within each of the table's groups instead of inheriting the table's RF. Reassigning a table's groups or RF is an operator action (through the admin API, not SQL); [contact support](https://www.lancedb.com/contact) to change a table's placement. Replica groups are numbered subsets of the fleet, not per-table resources -- different tables can share a group, use entirely different groups, or overlap partially, and each picks its own RF independently within every group it uses: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph G0["Replica group 0"] direction LR G0A["Plan executor"] G0B["Plan executor"] end subgraph G1["Replica group 1"] direction LR G1A["Plan executor"] end subgraph G2["Replica group 2"] direction LR G2A["Plan executor"] G2B["Plan executor"] G2C["Plan executor"] end TA["Table A<br/>groups 0, 1 · RF 2 in group 0, RF 1 in group 1"] -.-> G0 TA -.-> G1 TB["Table B<br/>group 2 only · RF 3"] -.-> G2 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class TA,TB accent ``` Table A is assigned to groups 0 and 1, at RF 2 and RF 1 respectively -- three plan executors total hold a copy of Table A. Table B never touches groups 0 or 1 at all; it is assigned only to group 2, at RF 3. Group 2's plan executors serve no part of Table A, and group 0's plan executors serve no part of Table B. Raising Table B's RF to 3 did not add a single plan executor to Table A's serving path, and vice versa -- each table's placement decision only changes which plan executors hold *that* table's data. ## Why this scales serving More replicas of a hot table's data, across more plan executors, means more of the fleet can serve that table's queries in parallel -- the same reasoning as adding query-serving capacity generally (see [Architecture](/oss/v0-41-0/index#architecture)), applied per table rather than cluster-wide. Replication also gives a table fault tolerance: losing one plan executor does not take its data offline if another replica still holds it. A single query that reads several tables routes every read to the same replica group -- the intersection of the tables' assigned groups, trying a lead group first and falling back through the rest of the order if it has no healthy plan executor. Keeping one query's reads co-located protects the locality of whichever group's cache is already warm for it, rather than letting each table's read drift to a different group. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node<br/>routes to the lead group"] subgraph G0["Replica group 0 (lead)"] direction LR A0["Plan executor<br/>copy 1"] A1["Plan executor<br/>copy 2"] end subgraph G1["Replica group 1 (fallback)"] direction LR B0["Plan executor<br/>copy 1"] B1["Plan executor<br/>copy 2"] end Q --> A0 Q --> A1 Q -. "only if group 0 has no healthy PE" .-> B0 Q -. "only if group 0 has no healthy PE" .-> B1 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Q accent ``` This table is assigned to two replica groups, each at replication factor 2: four plan executors in total, each holding a full copy of the table's data. Adding a third group, or raising RF within a group, adds more plan executors that can serve this table's reads in parallel -- scaling throughput for this one table without touching any other table's placement. ## Scaling interfaces * [Distributed Search](/oss/v0-41-0/enterprise/distributed-search) for how a query divides across query nodes and plan executors generally. * [Architecture](/oss/v0-41-0/index#architecture) for the components a replica group is made of. # Incremental Refresh Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/incremental-refresh Why refreshing a computed column only recomputes fragments that hold a row whose inputs actually changed. **Applies to:** Embedded ❌, Enterprise ✅ Refreshing a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) is incremental: it fills rows that have no value yet and recomputes the fragments that hold a row whose input changed since it was last computed, leaving every other fragment alone. A second refresh with nothing changed does nothing. The planner finds the rows that actually need work by checking which fragments still carry stale or empty values for the column, then groups them into claimable units a fleet of job workers can pick up in parallel \-- see [Architecture](/oss/v0-41-0/index#architecture). > [!NOTE] > > A **materialized view** doesn't track stale rows the way a computed > column does -- there's no smaller unit than the whole view to recompute > from a saved query. In LanceDB Embedded, every refresh rebuilds the view > completely with no incremental step; LanceDB Enterprise's server chooses > the refresh mode instead, unless the caller forces a full rebuild. See > [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view). ## Why this matters Appending rows is cheap: the next refresh only fills what's new, not what it already computed. Updating an input row is also cheap in the same way -- the derived column keeps its old value until the next refresh notices the input changed. Staleness is tracked per fragment, not per row: the refresh recomputes every row in a fragment where at least one input moved, which can re-evaluate rows whose own value didn't actually need it, not strictly only the row that changed. Nothing is recomputed between refreshes, so a derived column can be stale right up until you call for one. ## What to read next > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column#idempotent) > > The exact fill/recompute/leave-alone rules, with examples. > [card] [Adaptive Execution](/oss/v0-41-0/enterprise/adaptive-execution) > > How the units this planner produces get sized and run. # Intelligent Auto-Maintenance Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/intelligent-auto-maintenance How Enterprise continuously tracks table activity in the background and decides what maintenance -- compaction, cleanup, indexing, remap catch-up -- a table needs next. **Applies to:** Embedded ❌, Enterprise ✅ Keeping a table in good condition takes several different kinds of work -- compacting files, catching indexes up, cleaning old versions, folding a RTE write tier into the base table -- each with its own trigger. In LanceDB Enterprise, a fleet of agent processes decides when each of these needs to run, continuously, per table, in the background across your cluster -- nothing to schedule, trigger, or monitor by hand unless you want to. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR E["Table event notifications"] --> P S["Periodic sweep<br/>every table, on a timer"] --> P P["Planner<br/>evaluates one table"] P --> W["Possible next step:<br/>WAL index catch-up"] P --> I["Possible next step:<br/>Index operations"] P --> C["Possible next step:<br/>Compaction"] P --> CL["Possible next step:<br/>Cleanup"] P --> R["Possible next step:<br/>Remap catch-up"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class P accent ``` ## Tracking activity An agent's long-running process watches two independent sources for a table: **table events** (Job Registry notifications, so it learns about a write, a schema change, or a new index almost immediately) and a **periodic sweep** that revisits every table it owns on a timer -- 600 seconds by default -- so a table that stops producing events still gets re-evaluated rather than going stale. A hot table producing a flood of events does not get to monopolize evaluation: notifications and the periodic sweep share a bounded per-tick budget, and reads for a given table run at most once at a time. Each evaluation reopens the table and reads its manifest, indexes and in-flight jobs fresh, rather than deciding from a cached guess. Those are separate reads rather than one atomic snapshot, so a concurrent write between them is possible; the next evaluation -- triggered by that same write's own event notification -- is what catches anything the current one missed. ## Deciding what to run A table is not reduced to one "next best action" -- each evaluation walks a fixed, priority-ordered sequence of independent decisions, launching whichever ones are due: 1. **WAL index catch-up.** Checked first and gated by nothing else, because it is correctness-driven rather than discretionary: while an index lags behind the compacted generation, the RTE write tier cannot trim its log. See [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction). 2. **Index operations.** Reindexing a column, unless a compaction that cannot defer its remap is about to run this same tick -- deferred-remap compaction lets index work proceed alongside it instead of waiting. See [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing). 3. **Compaction.** Whether enough small fragments or deleted rows have accumulated to merge. See [Compaction](/oss/v0-41-0/maintenance/compaction) and [Distributed Compaction](/oss/v0-41-0/enterprise/distributed-compaction). 4. **Cleanup.** Independent of the other four -- it can always run in parallel with them. [See below](#cleanup) for exactly when it's due. 5. **Deferred-remap catch-up.** The batched, amortized follow-up for index entries a deferred compaction didn't remap synchronously. See [Advanced Conflict Resolution](/oss/v0-41-0/enterprise/advanced-conflict-resolution). More than one of these can fire for the same table in the same evaluation -- a compaction and a cleanup are unrelated and can both launch together -- but some gate each other where running them at the same time would be unsafe, like index operations waiting on a compaction that can't defer its remap. ### When cleanup is due [Cleanup](/oss/v0-41-0/maintenance/cleanup) prunes old table versions and the files only they referenced. In LanceDB Embedded, that always happens because you asked for it -- a call to `optimize()`. LanceDB Enterprise does not support a manual `optimize()` call at all; cleanup there is entirely this planner's own decision, off by default unless the deployment sets a minimum version age -- with no minimum age configured, nothing is ever old enough to clean up automatically, and old versions simply accumulate until an operator enables it. A table can also disable it individually even when the deployment allows it, overriding the deployment-wide setting for just that table. Once enabled, a table becomes due for cleanup when any one of these is true: | Trigger | Condition | | - | - | | Enough new versions | The current version has advanced far enough past the version the last successful cleanup started from | | Enough time has passed | The last successful cleanup finished long enough ago -- the default is 24 hours -- so an idle table whose versions simply age past the retention window still gets revisited | | Version went backward | The current version is lower than the version the last successful cleanup recorded, which re-triggers a run immediately | A table that has never had a successful cleanup run is held to its own initial version threshold first, so a brand-new table is not claimed for cleanup before it has accumulated enough versions to be worth the pass. A failed attempt is retried, but not immediately -- a minimum delay (60 seconds by default) must pass after the failure before the table becomes eligible again, even if one of the triggers above would otherwise fire. ## Confirming it's actually running Rather than asking you to trust that evaluation is happening, the agent exposes coverage metrics scoped to *successful* evaluations specifically -- a failed or timed-out attempt does not count: | Metric (`lance_agent_` prefix) | What it tells you | | - | - | | `coverage_never_evaluated` | Tables this agent owns that have never completed an evaluation | | `coverage_oldest_success_age_seconds` | How long it's been since the longest-overdue table was last successfully evaluated | | `coverage_cycle_target` / `coverage_cycle_pending` | How much work the current full sweep has left | | `coverage_cycles_completed_total` | How many full sweeps have finished | A cycle freezes its target set of tables up front; new tables join the *next* cycle rather than resetting progress on the current one, and a table that disappears or changes ownership is dropped from the target rather than counted as covered. ## What to read next > [card] [Cleanup](/oss/v0-41-0/maintenance/cleanup) > > What a cleanup pass actually removes, and the retention window it respects. > [card] [Advanced Conflict Resolution](/oss/v0-41-0/enterprise/advanced-conflict-resolution) > > Why compaction and index maintenance need the deferred-remap decision at all. > [card] [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction) > > The WAL-tier compaction this page's Decision 1 depends on. > [card] [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing) > > What an index operation actually does once scheduled. > [card] [OpenTelemetry](/oss/v0-41-0/deployment/opentelemetry) > > Viewing the `lance_agent_*` coverage metrics above. # Real Time Engine compaction Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/realtime-engine-compaction How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up. **Applies to:** Embedded ❌, Enterprise ✅ [Distributed Compaction](/oss/v0-41-0/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/oss/v0-41-0/maintenance/compaction) describes for LanceDB Embedded. A table with the [real time engine](/oss/v0-41-0/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and `memwal_catchup_<type>`, already distinct from ordinary `compact` in `SHOW JOBS` and `list_jobs`. This page covers how Enterprise decides when to run them, not just what they do. ## What triggers a compaction pass A per-pod loop, ticking every `WAL_COMPACTION_INTERVAL_SECS` (5s by default), walks every table this pod owns and reads each shard's manifest. It dispatches a compaction job for a shard once any threshold crosses: | Trigger | Default | Checks | | - | - | - | | `WAL_COMPACT_TRIGGER_COUNT` | 4 | The shard's SSTable count | | `WAL_COMPACT_TRIGGER_BYTES` | 1 GiB | The shard's total flushed SSTable bytes | | Oldest generation's age | 7 days | How long the head SSTable generation has sat, whatever the file count -- a file that will never gather enough siblings to cross the count trigger still gets compacted eventually | Whichever crosses first wins. A shard under write pressure does not wait for the next tick either: the same thresholds are re-checked on every backpressure relief pass, so a hot shard that already qualifies compacts sooner than `WAL_COMPACTION_INTERVAL_SECS` would otherwise allow. Setting `WAL_COMPACTION_INTERVAL_SECS` to `0` disables the periodic walk; an operator can still force a pass with `POST /v1/compact`, and `Table::checkpoint_rte` drives the same flush-then-compact cycle from the client when you need a table to converge on demand rather than wait for the trigger. `checkpoint_rte` has no liveness bound of its own -- it is idempotent and abandonable at any point, but the caller owns the deadline for how long to wait on it. This trigger decision is internal to the WAL pod -- it is not the general job scheduler deciding to run `memwal_compaction`, the pod decides to enqueue one. Once enqueued, the work is still tracked as an ordinary job (`memwal_compaction`, then `memwal_catchup_<type>` once it lands), so `SHOW JOBS` and `list_jobs` surface it the same way they surface any other background job. ## What one pass does By default (`wal.remoteMaintenance` is on), a tick's passes are offloaded as ordinary Job Registry worker jobs instead of running in the WAL pod itself, up to `WAL_COMPACT_CONCURRENCY` at a time (32 by default). With remote maintenance off, the pod runs them itself, in a per-pod compactor pool shared across every table it owns, bounded to 2 concurrent passes instead. Either way, each pass: 1. Snapshots the shard's current list of SSTables. 2. Takes a bounded prefix of them, oldest first (`WAL_COMPACT_PREFIX_MAX`, 32 by default), further capped at `COMPACT_PASS_TARGET_BYTES` (2 GiB) \-- a budget every in-pod pass shares, but that an offloaded pass gets in full to itself. 3. Opens each as a Lance file and scans its rows. 4. Deduplicates across the prefix by primary key -- a later SSTable's row wins over an earlier one with the same key. 5. Merges the deduplicated rows into the base table with `merge_insert`. 6. Commits a manifest update that drops exactly the SSTables just folded in, identified individually rather than by position, so a retried commit against a newer manifest can't drop the wrong ones. 7. `memwal_catchup_<type>` then extends each of the base table's indexes \-- one job per index type (`memwal_catchup_btree`, `memwal_catchup_fts`, `memwal_catchup_ivfpq`, and so on) -- over the rows step 5 just added, and records how far that index has caught up. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR A["Shard crosses a trigger<br/>(count, bytes, or generation age)"] --> B["Per-pod trigger loop<br/>or backpressure relief pass"] B --> C["Compactor pool<br/>dedup by PK, merge_insert into base"] C --> D["Manifest drops<br/>the folded SSTables"] D --> E["memwal_catchup_<type><br/>extends each base index"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` Only one compaction pass runs against a given shard at a time. A second, concurrent pass against the same shard would corrupt it: a stale pass can overwrite rows a newer generation already replaced, or resurrect a row a newer generation deleted, since the merge step has no way to tell a late-arriving write from a value that was already superseded. A per-shard latch enforces this -- the periodic trigger skips a shard that's already compacting, a manual `POST /v1/compact` is refused outright (never queued) on the same collision, and node drain waits for the shard's current pass instead of skipping it, since a skipped table is exactly what drain exists to flush. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Shard["Shard's per-shard latch"] --> Held{"Already held by<br/>an in-progress pass?"} Held -->|no| Grant["Grant the latch,<br/>run the pass"] Held -->|yes, periodic trigger| Skip["Skip this tick --<br/>retried next tick"] Held -->|yes, manual POST /v1/compact| Refuse["Refused outright,<br/>never queued"] Held -->|yes, node drain| Wait["Wait for the current<br/>pass to finish, don't skip"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Shard accent ``` ## Reading while compaction runs A query against an RTE-enabled table always reads the shard's current memtable and SSTables unioned with the base table, regardless of where a compaction pass is in its cycle -- compaction only ever changes which side of that union a row's latest value lives on, never which value is current. There's no window where a row is visible in neither side: the manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. A table queried *without* the real time engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks whichever trigger fires -- wider either way than the real time engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough siblings or bytes instead waits on the age trigger, up to 7 days by default, before it's compacted at all. `WAL_MAX_DATA_AGE_SECS` bounds two independent stages -- the memtable freeze and this compaction age trigger \-- so a slow table's worst-case staleness without the live path is up to roughly twice that default, not one interval plus one job's runtime. Either way, the bound also assumes a free compaction slot when the shard becomes eligible; an eligible shard can wait in queue behind `WAL_COMPACT_CONCURRENCY` other passes already running, so the actual delay can run longer than the trigger alone suggests. See [RTE reads](/oss/v0-41-0/search/realtime-read) for what a live RTE read sees instead. ## What to read next > [card] [Real Time Engine](/oss/v0-41-0/tables/realtime-engine) > > The MemWAL format, shards, and WAL nodes this page assumes. > [card] [Distributed Compaction](/oss/v0-41-0/enterprise/distributed-compaction) > > The unrelated, ordinary compaction every table -- WAL-enabled or not -- gets. > [card] [Job Framework](/oss/v0-41-0/basics/jobs) > > Job handles, waiting, and inspecting jobs -- memwal_compaction included. # Compliance Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/security Learn about LanceDB Enterprise security features and best practices. LanceDB Enterprise maintains high security standards with SOC 2 Type II, HIPAA, and GDPR compliance. Our security framework is designed to provide enterprise-grade protection for your data and workloads across deployment models. ## Security Certifications * **SOC 2 Type II**: Independent audit confirming our security controls and operational effectiveness * **HIPAA Compliance**: Certified to handle protected health information (PHI) in healthcare applications * **GDPR Compliance**: Supports organizations with data privacy requirements under the General Data Protection Regulation * **Regular Audits**: Ongoing security assessments to maintain compliance standards ### Ongoing Compliance LanceDB maintains SOC 2 Type II, HIPAA, and GDPR compliance through ongoing audits and continuous improvement of our security practices as standards and risks evolve. > [!NOTE] > > Visit the [LanceDB Trust Center](https://trust.lancedb.com/) to learn more about LanceDB's security posture, data privacy practices, and to request access to security documentation. ## LanceDB Enterprise ### Data Security Customer data is strictly protected and remains within the confines of your account. We maintain rigorous data isolation and encryption protocols to ensure confidentiality. LanceDB Enterprise only receives telemetry data for monitoring system health. At LanceDB, customer data security is paramount. ### Encryption LanceDB Enterprise safeguards your data through encryption at rest, preventing unauthorized access. This comprehensive encryption covers all data stored within the object store and cache. # Create a materialized view Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/materialized-views Store the result of a query as a table, ready to query, index and search. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view stores the result of a query as a table. Use it to keep a filtered or transformed dataset that you can query, index and search repeatedly, instead of recomputing the query every time you read it. > [!NOTE] > > In SQL this is [`CREATE MATERIALIZED VIEW`](/oss/v0-41-0/sql/ddl/materialized-view#create). ## Create a view A materialized view is defined by a SQL query, so it is created with one. From Python, run the statement on an [Enterprise connection](/oss/v0-41-0/basics/catalog#enterprise) with [`execute_query`](/oss/v0-41-0/basics/sql#sql-from-python); the SQL is the same either way: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() view = db.open_materialized_view("frames_captioned") ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` `execute_query` returns once the result stream is readable, not once the statement has finished, so `.read_all()` waits out the full creation before the next line opens it. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for captioning. There is no separate, more limited form for defining one -- joins and [Functions](#functions) in the select list work the same way any other `SELECT` does, within the query shapes your deployment's LanceDB Enterprise version and configuration accept; see the [SQL reference](/oss/v0-41-0/sql/ddl/materialized-view#create). Creating the view computes its rows, so it is ready to read immediately. [`db.open_materialized_view`](/oss/v0-41-0/management/materialized-view#manage) gets a handle back for reading, refreshing or inspecting it from Python; the view itself is also an ordinary table, queryable by name like any other. Your administrator manages stable row IDs and other source-table requirements for materialized views on the server; confirm support for your source table's shape before creating a view over it. ## Selecting a Function's output Enterprise A `SELECT` expression is SQL text, so it can call a registered [Function](/oss/v0-41-0/curation/create-function) the same way a computed column's expression can. Continuing the [`caption` Function](/oss/v0-41-0/curation/create-function#chain) registered in Create a Function, against a `frames` table that already has a `jpeg` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, jpeg, caption(jpeg) AS caption FROM frames WHERE selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, jpeg, caption(jpeg) AS caption FROM frames WHERE selected = true ``` A query that joins tables works the same way, with no separate syntax for it. Continuing the join and chained Functions from [Create a Function](/oss/v0-41-0/curation/create-function#chain), producing `jpeg` from a separate `videos` table and captioning it in the same statement: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) AS SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) AS SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, caption(extract_frame(v.video, f.ts)) AS caption FROM videos v JOIN frames f ON v.id = f.video_id WHERE f.selected = true ``` See [Joins](/oss/v0-41-0/curation/join) for the join itself, and [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for what `WITH` sets here. ## Automatic refresh at creation Set `auto_refresh_enabled` and `auto_refresh_interval_seconds` in the `WITH` clause to schedule refreshes instead of calling [`refresh`](/oss/v0-41-0/feature-engineering/refresh-materialized-view) yourself: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` Omit `auto_refresh_enabled` to let the server decide whether to enable it, and omit `auto_refresh_interval_seconds` to let the server decide the pacing. See [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for how scheduling behaves once the view exists. ## Working with the view `view.table` is the underlying table, for querying, indexing, or search. `view.definition` has a single field, `query` -- the recorded query, in the canonical spelling the server stores. Use it to inspect the query without inferring it from the rows. Both are properties; on an async view, the definition is read with `await view.definition()`. Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/oss/v0-41-0/management/materialized-view#manage). ## Related guides > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > Bring the view up to date with its source. > [card] [Versioning](/oss/v0-41-0/management/table#versioning) > > Inspect the table history and read a particular version. # Refresh a computed column Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/refresh-column Populate a computed column and update it when its inputs change. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/oss/v0-41-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Refresh a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) to fill new rows and recompute values whose inputs changed. The example below continues with the `doubled` column from the computed-column guide. > [!NOTE] > > Computed columns require LanceDB Enterprise. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("doubled") job.wait() table.search().to_arrow().sort_by("x").to_pandas() # x doubled # 0 1 2 # 1 2 4 ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table ``` > [!NOTE] > > `table.refresh_column(...)` (sync) is also a local, blocking form, but it > raises on an Enterprise connection -- use `refresh_column_async`, shown > above, or the SQL form instead. See > [Run a refresh on Enterprise](#async) below for what the returned job > supports. The refresh commits ordinary table versions (the values, then a metadata-only record of the inputs they were computed from), so [versioning](/oss/v0-41-0/management/table#versioning) applies to it like any other write. > [!NOTE] > > The SQL form is [`REFRESH COLUMN`](/oss/v0-41-0/sql/dml/refresh-column), with the same resource options. ## What a refresh recomputes Without a `WHERE` predicate, a refresh fills unassigned rows and recomputes values whose inputs changed since they were computed. Every other row is left alone, so a second refresh with nothing changed does nothing. This supports two common workflows. **Appending is cheap.** Rows added since the last refresh are filled by the next one; filled rows whose inputs are unchanged are skipped. Backfilling a column and then ingesting more data does not mean recomputing the backfill. **A filled value catches up with its input at the next refresh.** If `doubled` derives from `x` and a row's `x` is later updated, `doubled` keeps its old value until the next refresh recomputes it. That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived column is stale between an update and the next refresh. ## Automatic refresh A computed column can refresh itself on a schedule instead of waiting for an explicit call here. See [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for enabling it, the SQL and SDK forms for changing the setting, and how catch-up works when it's re-enabled after being off. ## Refreshing part of a table Enterprise A refresh can be scoped to a predicate, with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice first and checking it before committing to the whole table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01'", ) job.wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` A filtered refresh recomputes **every matching live row**, including rows whose outputs are already current. Repeating the same predicate repeats those Function calls and their cost. To select only null outputs within a slice: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01' AND embedding IS NULL", ) job.wait() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even when their inputs changed, and can recompute outputs that were successfully computed as `NULL`. Use an unfiltered refresh to let LanceDB track which outputs need updating. > [!NOTE] > > **Enterprise job type:** `computed_refresh` for a SQL-expression column, > `function_refresh` for one filled by a registered [function](/oss/v0-41-0/management/function). ## Run a refresh on Enterprise Enterprise With an Enterprise cluster that enables computed columns, the refresh runs on the cluster. `refresh_column` raises there; use `refresh_column_async`, which returns a [job](/oss/v0-41-0/basics/jobs) you can wait on or poll instead of holding a connection open: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async("doubled") result = job.wait() result.rows_assigned # 2 job.status() # 'finished' ``` Poll with `status()`, resolve with `wait()`. `status()` is a point snapshot and does not raise, which is what makes it safe in a loop; `wait()` raises `JobFailedError`, `JobCancelledError` or `TimeoutError`. A long backfill can therefore be started, left, and checked on from a different process. ### Configure workers and resources SQL exposes the worker budget directly, which is the lever when a backfill is too slow or too expensive: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` The resource values cap the Function workers together: this example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. For Enterprise 1.12.0, use the SQL form above to set a complete CPU, memory and GPU budget. Include all three fields; use `gpu_count = 0` for a CPU-only Function. The Python 0.42.0b8 client does not accept the nested `resource_budget` keyword. The SDK can change GPU placement with the top-level `gpu_count` and `gpu_class` options shown below. Omitting them preserves the server defaults. Automatic-refresh resource budgets and per-call concurrency controls are not supported by Enterprise 1.12.0. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to `error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for failing rows and record them in the error store, subject to failure limits. See the [SQL refresh options](/oss/v0-41-0/sql/dml/refresh-column#options). For a column filled by a registered Function, the Python and Rust job APIs can override the Function's GPU placement for this refresh: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} classes = db.list_gpu_classes() gpu_class = next(gpu.name for gpu in classes if gpu.gpu_model == "NVIDIA H100") job = table.refresh_column_async( "embedding", gpu_class=gpu_class, gpu_count=4, batch_size=32, ) ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::{Connection, Table, table::RefreshColumnOptions}; async fn refresh( conn: &Connection, table: &Table, ) -> Result<(), Box<dyn std::error::Error>> { let gpu_class = conn .list_gpu_classes() .await? .into_iter() .find(|class| class.gpu_model.as_deref() == Some("NVIDIA H100")) .map(|class| class.name) .ok_or("H100 GPU class is not configured")?; let _job = table .refresh_column_async_with_options( "embedding", RefreshColumnOptions::default() .gpu_class(gpu_class) .gpu_count(4) .batch_size(32), ) .await?; Ok(()) } ``` `gpu_count` is the aggregate GPU budget for the refresh's Function workers, not a request for that many GPUs per worker. It must be positive and preserves the deployment's CPU and memory defaults. `gpu_class` must name a class returned by `list_gpu_classes()`; class names are lowercase DNS labels. Omit either option to use the Function's registered class or the server's configured budget. `list_gpu_classes()` requires System Usage permission, and raises `NotImplementedError` when the server predates GPU class discovery. > [!NOTE] > > The Rust GPU discovery and refresh controls are not in the latest Rust > release. TypeScript does not expose GPU class discovery; pass `gpuClass` > and `gpuCount` in the `refreshColumnAsync` options. Function outputs become visible when their fragment is published. Enterprise 1.12.0 does not support a row-count publication threshold. The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed to new rows (see [what a filter recomputes](#partial)) and told to skip rows whose Function call fails: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = table.refresh_column_async( "embedding", where="created_at > date '2026-01-01'", error_policy="skip", max_failed_fraction=0.01, row_timeout_seconds=30, ) ``` ```typescript theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const job = await table.refreshColumnAsync("embedding", { where: "created_at > date '2026-01-01'", errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, }); ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::{function::FunctionErrorPolicy, table::RefreshColumnOptions}; let _job = table .refresh_column_async_with_options( "embedding", RefreshColumnOptions::default() .where_clause("created_at > date '2026-01-01'") .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) .row_timeout_seconds(30.0), ) .await?; ``` `max_failed_rows`, `init_timeout_seconds`, `num_workers` and `max_executor_processes_per_worker` are accepted the same way; the [SQL refresh options](/oss/v0-41-0/sql/dml/refresh-column#options) describe each one. The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a timeout that is not a positive number and a zero worker or process count before sending the request; the server validates everything else. A LanceDB Embedded refresh rejects every option other than `batch_size`, `gpu_class` and `gpu_count`; in particular, it rejects `resource_budget` rather than silently ignoring it. ## When a refresh fails What a failure keeps depends on where the refresh ran. The local, blocking `refresh_column` writes the column in one commit, so a failure leaves the column as it was. A refresh job in LanceDB Enterprise -- always `refresh_column_async` or `REFRESH COLUMN` there, never the blocking form -- commits finished batches as it goes, so some values can remain after a failure. Either way, recover by fixing the cause and refreshing again. The new refresh fills rows that are still empty or whose inputs changed, and normally skips values that were kept. That is not guaranteed: a refresh can recompute values that were already written (for example when the record of the inputs they were computed from was not saved), so do not count on a retry costing only the rows that did not complete. For a column filled by a [function](/oss/v0-41-0/management/function), the usual cause is the worker environment rather than the data. See [environment mismatches](/oss/v0-41-0/management/function#mismatch-symptoms) for the symptoms, which rarely name their cause. ## Related guides > [card] [Job Framework](/oss/v0-41-0/basics/jobs) > > Waiting on, inspecting, and cancelling server-side work. > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > The same idea, for a whole derived table. > [card] [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) > > Refresh on a schedule instead of calling this yourself. # Refresh a materialized view Source: https://docs.lancedb.com/oss/v0-41-0/feature-engineering/refresh-materialized-view Bring a materialized view up to date after its source data changes. **Applies to:** Embedded ❌, Enterprise ✅ Refresh a [materialized view](/oss/v0-41-0/feature-engineering/materialized-views) to bring its stored rows up to date after the source table changes. > [!NOTE] > > In SQL this is [`REFRESH MATERIALIZED VIEW`](/oss/v0-41-0/sql/dml/refresh-materialized-view). ## Refresh a view ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} view.refresh() ``` In LanceDB Embedded, every refresh rebuilds the view completely from its source query -- there is no incremental refresh there. Calling it again with no source changes still rebuilds and commits a new table version. In LanceDB Enterprise, the server chooses the refresh mode instead; pass `full=True` to force a full rebuild there too. In LanceDB Embedded, the result reports what the refresh did: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = view.refresh() result.rows_written # rows in the rebuilt view result.source_version # the source table version the view now reflects result.version # the view's own new table version ``` LanceDB Enterprise refreshes run through its SQL job adapter, which doesn't expose these metrics: `mode`, `rows_written` and `source_version` are all `None` on an Enterprise result, even though the refresh itself ran. Pass `source_version=N` to refresh against a particular source version instead of the latest. This is a LanceDB Embedded capability only -- LanceDB Enterprise's SQL refresh does not support pinning a source version: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} view.refresh(source_version=12) # LanceDB Embedded only ``` Use `view.table.count_rows()` for the view's row count at any time; on LanceDB Embedded it always matches `rows_written` from the most recent refresh. ## Automatic refresh A materialized view can refresh itself on a schedule instead of waiting for an explicit `refresh()` call. See [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) for enabling it at creation, the SQL and SDK forms for changing the setting afterward, and how it differs from a computed column's per-output granularity. ## When a refresh fails A refresh replaces the view's stored rows in one commit, so a failure leaves the view as it was after its last successful refresh. Fix the cause and refresh again. ## Related guides > [card] [Create a materialized view](/oss/v0-41-0/feature-engineering/materialized-views) > > Define the query a view stores. > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > The same idea, for a single derived column. > [card] [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh) > > Refresh on a schedule instead of calling this yourself. # Dependency Verification Source: https://docs.lancedb.com/oss/v0-41-0/geneva/deployment/dependency-verification Diagnose and resolve package version mismatches between local and distributed worker environments. When running Geneva UDFs on distributed workers, your code is serialized locally and executed on remote workers. If the worker environment differs from your local environment, you may encounter subtle and difficult-to-debug errors. ## Example environment mismatch errors | Symptom | Likely Cause | | - | - | | `TypeError: Enum.__new__() missing 1 required positional argument` | `attrs` version mismatch | | `TypeError: Can't instantiate abstract class` | Package structure differences | | `ArrowInvalid: cannot cast` / serialization errors | NumPy 1.x vs 2.x mismatch | | `ModuleNotFoundError` on workers | Package only installed locally | | Model loading failures | PyTorch version mismatch | | Permission denied errors | Missing API keys in envrionment variables | These issues are notoriously difficult to debug because the error messages often don't indicate the root cause. ## The `compare_ray_environments` Tool Geneva provides a diagnostic tool to compare your local environment against Ray workers. If you are encountering a hang or exception you can use the following diagnosis worklflow to resolve the problem. **Step 1** **Run the diagnostic tool** programatically or via the CLI. **Step 2** **Check PACKAGES and ENV VARS output sections for mismatches**. **Step 3** **Identify critical packages**: numpy, torch, pyarrow, attrs, pydantic. **Step 4** **Identify inconsistent environment variables**: `AWS_*`, `GOOGLE_APPLICATION_CREDENTIALS` **Step 5** **Fix with manifest** for quick testing: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest.builder import PipManifestBuilder manifest = PipManifestBuilder.create("fix").pip(["numpy==1.26.4"]).build() ``` **Step 6** **OPTIONAL: Build custom image** for production (if using KubeRay). ### Programmatic Usage ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray.compare_env import compare_ray_environments # Compare and print (requires Geneva context to be initialize via `with db.context(..)`) result = compare_ray_environments() # Compare environments, filtering environment variables with specified prefix result = compare_ray_environments(env_prefix="PY") ``` ### CLI Usage ```bash CLI icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Connect to existing Ray cluster python -m geneva.runners.ray.compare_env # Start new local Ray cluster python -m geneva.runners.ray.compare_env --address local # Filter env vars by prefix python -m geneva.runners.ray.compare_env --env-prefix RAY # Show full JSON snapshots python -m geneva.runners.ray.compare_env --show-all # Skip sys.path comparison python -m geneva.runners.ray.compare_env --no-sys-path ``` ## Understanding the Output The tool outputs several sections to help you identify mismatches. ### PYTHON / PLATFORM Shows Python version and OS information for both environments: ``` === PYTHON / PLATFORM === Local: Python: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0] Impl : CPython Exec : /home/user/.venv/bin/python OS : Linux 5.15.0-generic (x86_64) Remote: Python: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0] Impl : CPython Exec : /home/ray/anaconda3/bin/python OS : Linux 5.4.0-aws (x86_64) ``` > [!WARNING] > > Watch for different Python versions or different OS types (macOS local vs Linux remote). #### Architecture Mismatch (macOS to Linux) If you see different OS types (e.g., `Darwin` locally vs `Linux` remotely), compiled extensions may fail with `ModuleNotFoundError` or segfaults. **Solution**: Run Geneva from the same OS/architecture as your cluster (typically Linux x86_64). Use a Linux VM, container, or remote development environment. ### Environment Variables Environment variables present in only one environment: ``` === ENV VARS: keys only in LOCAL === + CONDA_PREFIX + VIRTUAL_ENV === ENV VARS: keys only in REMOTE === + RAY_ADDRESS + KUBERNETES_SERVICE_HOST ``` > [!WARNING] > > Missing `AWS_*` or `GOOGLE_APPLICATION_CREDENTIALS` can cause storage authentication failures. #### Passing Environment Variables to Workers If critical environment variables are missing on workers, you can pass them via the manifest or cluster configuration. Set the values in the shell before starting the Python program: ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export AWS_ACCESS_KEY_ID="your-access-key-id" export AWS_SECRET_ACCESS_KEY="your-secret-access-key" export MY_API_KEY="your-api-key" ``` **Option 1: Via Manifest** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest.builder import PipManifestBuilder import os manifest = ( PipManifestBuilder.create("my-manifest") .env_vars({ "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"], "AWS_SECRET_ACCESS_KEY": os.environ["AWS_SECRET_ACCESS_KEY"], "MY_API_KEY": os.environ["MY_API_KEY"], }) .build() ) ``` **Option 2: Via Cluster Configuration** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder import os cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": { "env_vars": { "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"], "AWS_SECRET_ACCESS_KEY": os.environ["AWS_SECRET_ACCESS_KEY"], } } }) .build() ) ``` > [!WARNING] > > Avoid hardcoding secrets. Use `os.environ` to pass values from your local environment, or use a secrets manager in production. ### Packages The tool shows version mismatches and packages only present in one environment: ``` === PACKAGES: version mismatches === * numpy: local=1.26.4 remote=2.2.6 * torch: local=2.0.1 remote=2.8.0+cpu * attrs: local=23.2.0 remote=24.2.0 * pyarrow: local=14.0.1 remote=17.0.0 === PACKAGES: only in LOCAL === + my-custom-package + dev-tools === PACKAGES: only in REMOTE === + kuberay-client ``` > [!WARNING] > > Watch for major version differences (NumPy 1.x vs 2.x) and PyTorch version mismatches. #### Common Package Issues | Issue | Symptoms | Fix | | - | - | - | | **NumPy 1.x vs 2.x** | `ArrowInvalid`, `ValueError: cannot convert`, serialization failures | Pin `numpy==1.26.4` | | **PyTorch mismatch** | Model loading failures, CUDA errors, unexpected inference results | Pin to matching `torch` version | | **attrs mismatch** | `TypeError: Enum.__new__() missing 1 required positional argument` | Pin `attrs` to local version | | **Missing package** | `ModuleNotFoundError: No module named 'xyz'` | Add package to manifest | #### Fixing Package Mismatches **Option 1: Manifest pip Dependencies** Specify packages in a Geneva manifest for a quick fix: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.manifest.builder import PipManifestBuilder manifest = ( PipManifestBuilder.create("my-manifest") .pip([ "numpy==1.26.4", "torch==2.0.1", "attrs==23.2.0", ]) .build() ) conn = geneva.connect("s3://my-bucket/my-db") conn.define_manifest("my-manifest", manifest) with conn.context(cluster="my-cluster", manifest="my-manifest"): conn.open_table("my-table").backfill("my-column") ``` *Pros*: Quick, reusable across sessions, stored with your database. *Cons*: Slower startup (downloads packages), may not work for complex dependencies. **Option 2: Custom Ray Worker Image** For KubeRay deployments, build a custom worker image: ```dockerfile Dockerfile icon="docker" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Dockerfile.ray-worker FROM rayproject/ray:2.30.0-py311 # Install exact versions RUN pip install \ numpy==1.26.4 \ torch==2.0.1 \ attrs==23.2.0 \ geneva==0.8.0 # Copy any custom packages COPY ./my_udfs /app/my_udfs ``` Then reference in RayCluster spec: ```yaml Kubernetes icon="kubernetes" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} spec: workerGroupSpecs: - template: spec: containers: - image: your-registry/ray-worker:latest ``` *Pros*: Fastest startup, reproducible. *Cons*: Requires image build/push workflow. **Option 3: Conda Environment** Use a conda environment on workers via the cluster builder: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": {"conda": "environment.yml"} }) .build() ) ``` Or specify conda channels and dependencies inline: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.cluster.builder import KubeRayClusterBuilder cluster = ( KubeRayClusterBuilder.create("my-cluster") .ray_init_kwargs({ "runtime_env": { "conda": { "channels": ["conda-forge"], "dependencies": [ "python=3.10", "ffmpeg<8", "torchvision=0.22.1", ], }, "config": {"eager_install": True}, } }) .build() ) ``` *Pros*: Best for complex dependencies with native libraries (ffmpeg, CUDA). *Cons*: Slower environment creation, requires conda on workers. ## API Reference For detailed API documentation on the environment comparison functions, see the [Geneva Diagnostics API Reference](https://lancedb.github.io/geneva/api/diagnostics). # Deploy Geneva using Helm Source: https://docs.lancedb.com/oss/v0-41-0/geneva/deployment/helm Learn how to deploy Geneva on Kubernetes using the Geneva Helm Chart > [!TIP] > > **Feature Engineering is deployed automatically in LanceDB Enterprise** > > In self-managed environments, Geneva can be installed into existing Kubernetes clusters using Helm. Please [contact LanceDB](https://lancedb.com/contact/) for access to the Helm Chart and related resources. ## Pre-requisites * An existing Kubernetes cluster * An existing node pool(s) for Geneva workloads. By default, Geneva uses node selector `{"geneva.lancedb.com/ray-head": "true"}` for Ray head nodes, and `{"geneva.lancedb.com/ray-worker-cpu": "true"}` and `{"geneva.lancedb.com/ray-worker-gpu": "true"}` for Ray CPU worker and Ray GPU worker nodes respectively. This can be overridden in the Geneva client. * Geneva Helm chart. Please [contact LanceDB](https://lancedb.com/contact/) for access to the Helm Chart and related resources. For more information on deploying the required cloud resources, see the [manual deployment instructions](/oss/v0-41-0/geneva/deployment/). ## Geneva Helm Chart The Helm chart includes resources required for running [Geneva](https://lancedb.com/docs/geneva/) in Kubernetes. It includes services, service accounts, RBAC roles, etc. that are used by the Geneva client to manage resources. ## Install 1. Authenticate with Kubernetes cluster, i.e. update kubeconfig 2. Configure Helm chart values In values.yaml, configure the service account, node selectors, and cloud resources, if applicable. ``` geneva: # Object storage root URI rootUri: value: "s3://my-data-bucket" serviceAccount: # Service account for Geneva worker pods and services annotations: # Set per-CSP annotations to provide access to CSP resources, i.e. # eks.amazonaws.com/role-arn: arn:aws:iam::0123456789:role/geneva_service_role # iam.gke.io/gcp-service-account: geneva-service-account@my-project.iam.gserviceaccount.com gcp: # GCP service account email for the Geneva client. # It should have access to the GKS cluster and "roles/storage.objectUser" # permissions on the object storage bucket. # e.g., geneva-client-sa@project-id.iam.gserviceaccount.com clientServiceAccount: "" aws: # AWS IAM role ARN to be assumed by the Geneva client. # This role should have an access entry to the cluster with username matching the role ARN. # It should also have r/w access to the object storage bucket. # e.g., arn:aws:iam::123456789012:role/geneva-client-role clientRoleArn: "" azure: # Azure managed identity client ID for the Geneva client. # This identity should have a federated credential for the LanceDB namespace # and Storage Blob Data Contributor role on the storage account. clientPrincipalId: "" ``` 3. Install kuberay operator ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export NAMESPACE=lancedb helm repo add kuberay https://ray-project.github.io/kuberay-helm/ helm repo update helm install kuberay-operator kuberay/kuberay-operator -n $NAMESPACE --create-namespace ``` 4. Install NVIDIA device plugin (if using GPU nodes) For GPU support, the NVIDIA device plugin must be installed in your EKS cluster: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v0.17.0/deployments/static/nvidia-device-plugin.yml > nvidia-device-plugin.yml kubectl apply -f nvidia-device-plugin.yml ``` 5. Install Geneva Helm chart ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} helm install geneva ./geneva -n $NAMESPACE --create-namespace ``` ## Default cluster and manifest In LanceDB Enterprise, backfill and refresh jobs run on a **default cluster** (the compute pool jobs run on) and a **default manifest** (the Python dependency environment — image and packages). Configuring these in the LanceDB Enterprise chart lets jobs run out of the box without per-job configuration. They are set under `geneva.defaults` in the chart's `values.yaml`: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} geneva: defaults: cluster: cluster_type: external_ray name: deployment-default ray_address: "ray://raycluster-kuberay-head-svc.lancedb.svc.cluster.local:10001" manifest: name: deployment-default pip: [geneva, pyarrow, lancedb, pylance] head_image: rayproject/ray:2.54.0-py312 worker_image: rayproject/ray:2.54.0-py312 skip_site_packages: true ``` If no default is configured, jobs must specify a manifest explicitly. Individual transforms can override the default manifest by pinning one with `@udf` / `@chunker` / `@udtf` (see [Advanced Job Configuration](/oss/v0-41-0/geneva/jobs/advanced-job-configuration)); to override the cluster at runtime, use an [Advanced Execution Context](/oss/v0-41-0/geneva/jobs/contexts). ## Providing a Ray cluster The LanceDB Helm chart can be configured to deploy a static KubeRay cluster, provision KubeRay clusters on demand per job, or use an existing Ray cluster. ### Use default LanceDB Enterprise Ray cluster (default) By default, LanceDB Enterprise will use a shared, statically provisioned Ray cluster for job execution. This can be enabled in the Helm chart by setting the following values. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raycluster: enabled: true global: rayclusterUri: "ray://raycluster-kuberay-head-svc.lancedb.svc.cluster.local:10001" ``` Configuration for the Ray cluster can be specified by modifying raycluster.yaml Helm values. ### Provision KubeRay clusters on demand Set `global.rayclusterUri` to an empty value to provision ephemeral KubeRay clusters on-demand for each execution job. The default KubeRay cluster configuration is specified in `geneva.defaults.cluster`, i.e. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} geneva: defaults: cluster: cluster_type: kuberay name: deployment-default kuberay: namespace: lancedb config_method: IN_CLUSTER head_group: service_account: geneva-service-account num_cpus: 2 memory: 8Gi image: rayproject/ray:2.54.0-py312 worker_groups: - name: cpu service_account: geneva-service-account num_cpus: 4 memory: 8Gi replicas: 2 min_replicas: 0 max_replicas: 4 idle_timeout_seconds: 60 node_selector: geneva.lancedb.com/ray-worker-cpu: "true" image: rayproject/ray:2.54.0-py312 ``` ### Use an external Ray cluster Self-managed enterprise customers can bring an existing Ray cluster to run Geneva jobs. Simply set the rayclusterUri property in the Helm chart to a Ray address that can be accessed from the LanceDB Enterprise deployment. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} global: rayclusterUri: "ray://my-ray-cluster.my-ns.svc.cluster.local:10001" ``` # Manual Deployment on Kubernetes Source: https://docs.lancedb.com/oss/v0-41-0/geneva/deployment/index Learn how to deploy Geneva on Kubernetes using KubeRay for distributed feature engineering workflows on GKE and EKS. > [!TIP] > > **Feature Engineering is deployed automatically in LanceDB Enterprise** > > For manual installation in self-managed environments, follow the instructions below. Feature Engineering can be deployed as part of LanceDB Enterprise in managed or self-managed environments. First class support is provided for Azure, AWS, and GCP, including deployment automation via Terraform and Helm. ## Prerequisites * Kubernetes cluster with KubeRay 1.1+ operator installed * Ray 2.43+ See below for manual installation instructions for: * Amazon Web Services (AWS) Elastic Kubernetes Service (EKS) * Google Cloud Platform (GCP) Google Kubernetes Engine (GKE) ## Basic Kubernetes Setup > [!TIP] > > Kubernetes resources can be deployed automatically via [Helm](/oss/v0-41-0/geneva/deployment/helm/) or manually > via the instructions below. In the following sections we'll use these variables: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name ``` ### Kubernetes Service Account (KSA) Inside your Kubernetes cluster, you need a Kubernetes service account which provides the credentials your k8s pods (Ray) run with. Here's how to create your KSA. #### Create a Kubernetes Service Account (KSA) ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl create namespace $NAMESPACE # skip if it already exists kubectl create serviceaccount $KSA_NAME \ --namespace $NAMESPACE ``` You can verify using: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl get serviceaccounts -n $NAMESPACE $KSA_NAME ``` The Kubernetes service account (KSA) needs RBAC permissions inside the k8s cluster to provision Ray clusters via CRDs. #### Create a k8s Role Create a k8s role that can access the Ray CRD operations. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl apply -f - <<EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: ${KSA_NAME}-role rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch"] - apiGroups: ["ray.io"] resources: ["rayclusters"] verbs: ["get", "patch", "delete"] EOF ``` #### Bind the ClusterRole to Your KSA ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl apply -f - <<EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: ${KSA_NAME}-binding subjects: - kind: ServiceAccount name: ${KSA_NAME} namespace: ${NAMESPACE} roleRef: kind: ClusterRole name: ${KSA_NAME}-role apiGroup: rbac.authorization.k8s.io EOF ``` Now confirm your permissions: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl auth can-i get pods --as=system:serviceaccount:${NAMESPACE}:${KSA_NAME} ``` ## Geneva on GKE Google Kubernetes Engine (GKE) is a GCP service that deploys Kubernetes and can manage on-demand provisioning of cluster nodes. Ray can be deployed on GKE clusters using the KubeRay k8s operator. GKE provides the option for an out-of-the-box KubeRay operator deployment. The version of KubeRay is tied to the version of GKE you have deployed. Currently these versions are supported: * GKE 1.30 / KubeRay 1.1 * GKE 1.31 / KubeRay 1.2 Alternatively, you can also deploy your own KubeRay operator to get the latest KubeRay 1.3 version. The following sections describe in more details other required configuration settings required for Geneva to perform distributed execution. ### GKE Node Pools GKE allows you to specify templates for virtual machines in "node pools". These allow you to manage and configure resources such as the number of CPUs, number of GPUs, amount of memory, and if instances are spot or regular virtual machines. You can define your node pools however you want but Geneva uses three specific Kubernetes labels when deploying Ray pods on GKE: `ray-head`, `ray-worker-cpu`, `ray-worker-gpu` * **Head nodes** are where the Ray dashboard and scheduler run. They should be non-spot instances and should not have processing workloads scheduled on them. Geneva looks for nodes with the `geneva.lancedb.com/ray-head` k8s label for this role. * **CPU Worker nodes** are where distributed processing that does not require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-cpu` k8s label when these nodes are requested. * **GPU Worker nodes** are where distributed processing that require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-gpu` k8s label when these nodes are requested. ### GKE + k8s Permissions Geneva needs the ability to deploy a KubeRay cluster and submit jobs to Ray. The workers in the Ray cluster need the ability to read and write to the Google Cloud Storage (GCS) buckets. This requires setting up the proper k8s permissions and GCP IAM grants. There are three main areas to setup and verify: * Kubernetes Service Account (KSA) * Google Service Account (GSA) * GKE settings (GKE workload identity) ![geneva-security-reqs](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/geneva/geneva-security-reqs.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=3cf143ee765a18785bc097bf78f57208) #### Geneva Security Requirements In the following sections we'll use these variables. `STORAGE_URI` is the underlying `gs://` storage path used for bucket permissions and storage access; it is separate from `LANCEDB_URI`, the database's `db://` URI used to connect. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name PROJECT_ID=... # replace with your google cloud project name GSA_EMAIL=${KSA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com STORAGE_URI=gs://bucket/db # the bucket path your database is stored under ``` #### Google Service Account (GSA) To give your k8s workers the ability to read and write from your LanceDB buckets, your KSA needs to be bound to a Google Cloud service account (GSA) with those grants. With this setup, any pod using the KSA will automatically get a token that lets it impersonate the GSA. Let's set this up: **Create a Google Cloud Service Account** ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts create ${KSA_NAME} \ --project=${PROJECT_ID} \ --description="Service account for ray workloads in GKE" \ --display-name="Ray Runner GSA" ``` You can verify this using: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts list --filter="displayName:Ray Runner GSA" ``` > **Warning**: You need `roles/iam.serviceAccountAdmin` or minimally `roles/iam.serviceAccountTokenCreator` rights to run these commands. Next, you'll need to verify that your KSA is bound to your GSA and has `roles/iam.workloadIdentityUser`: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud iam service-accounts get-iam-policy $GSA_EMAIL \ --project=$PROJECT_ID \ --format="json" | jq '.bindings[] | select(.role=="roles/iam.workloadIdentityUser")' ``` Give your GSA rights to access the LanceDB bucket: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} gcloud storage buckets add-iam-policy-binding ${STORAGE_URI} \ --member="serviceAccount:${KSA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/storage.objectAdmin" ``` #### GKE Workload Identity A GKE workload identity is required to enable k8s workloads access Google Cloud services securely and without needing to manually manage service account keys. The workload identity is attached to Google Cloud service accounts (GSA) and mapped to a Kubernetes service account (KSA). This feature needs to be enabled on the GKE cluster. You can confirm that your workers have abilities to read/write to the LanceDB bucket: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl run gcs-test --rm -it --image=google/cloud-sdk:slim \ --serviceaccount=${KSA_NAME} \ -n ${NAMESPACE} \ -- bash echo "hello" > test.txt gsutil cp test.txt ${STORAGE_URI}/demo-check/test-write.txt ``` Confirm the identity inside the pod: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -H "Metadata-Flavor: Google" \ http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email ``` ## Geneva on AWS EKS Geneva can be used to provision Ray clusters running in Amazon Web Services (AWS) Elastic Kubernetes Service (EKS). In the following sections we'll use these variables: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} NAMESPACE=lancedb # replace with your actual namespace if different CLUSTER=geneva # replace with your actual namespace if different KSA_NAME=geneva-ray-runner # replace with an identity name ``` ### EKS Node Groups EKS allows you to specify templates for virtual machines in "node groups". These allow you to manage and configure resources such as the number of CPUs, number of GPUs, amount of memory, and if instances are spot or regular virtual machines. You can define your node groups however you want but Geneva uses three specific Kubernetes labels when deploying Ray pods on EKS: `ray-head`, `ray-worker-cpu`, `ray-worker-gpu` * **Head nodes** are where the Ray dashboard and scheduler run. They should be non-spot instances and should not have processing workloads scheduled on them. Geneva looks for nodes with the `geneva.lancedb.com/ray-head: true` k8s label for this role. * **CPU Worker nodes** are where distributed processing that does not require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-cpu: true` k8s label when these nodes are requested. * **GPU Worker nodes** are where distributed processing that require GPU should be scheduled. Geneva looks for nodes with the `geneva.lancedb.com/ray-worker-gpu: true` k8s label when these nodes are requested. ### Install KubeRay Operator Using Helm Geneva requires the KubeRay operator to be installed in your EKS cluster. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} helm repo add kuberay https://ray-project.github.io/kuberay-helm/ helm repo update helm install kuberay-operator kuberay/kuberay-operator -n $NAMESPACE ``` ### Install NVIDIA Device Plugin For GPU support, the NVIDIA device plugin must be installed in your EKS cluster: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v0.17.0/deployments/static/nvidia-device-plugin.yml > nvidia-device-plugin.yml kubectl apply -f nvidia-device-plugin.yml ``` ### Configure Access Control ![eks-auth](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/geneva/eks-auth.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=6a9114fa23728aa7a0ed3cc06d0e3d89) #### Environment IAM Principal Geneva must be run in an environment with access to [AWS credentials](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) with permissions to `sts:AssumeRole` on the Geneva Client IAM Role. For example, this could be a laptop with credentials provided by environment variables, or an EC2 instance with credentials provided via Instance Profile. #### Create IAM Role for Geneva Client The Geneva Client IAM Role is assumed by the Geneva client to provision the Kuberay cluster and run remote jobs. This role requires IAM permissions to access the storage bucket and Kubernetes API. Create an IAM role with the following policy: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Sid": "ClusterAccess", "Action": [ "eks:DescribeCluster", "eks:AccessKubernetesApi" ], "Effect": "Allow", "Resource": "<your eks cluster arn>" }, { "Sid": "AllowListBucket", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::<your storage bucket>" }, { "Sid": "AllowAllS3ObjectActions", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:HeadObject" ], "Resource": "arn:aws:s3:::<your storage bucket>/*" } ] } ``` This role should also have a trust policy with `sts:AssumeRole` permissions for any principal initiating the Geneva client. When using Geneva, this role can be specified with the `role_name` RayCluster parameter. #### Create EKS Access Entry Create an [EKS access entry](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html) to allow the Geneva Client Role to access the Kubernetes API for the EKS Cluster. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws eks create-access-entry --cluster-name $CLUSTER --principal-arn <your geneva client role ARN> --type STANDARD aws eks associate-access-policy --cluster-name $CLUSTER --principal-arn <your geneva client role ARN> --access-scope type=cluster --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy ``` #### Create EKS OIDC Provider Create an OIDC provider for your EKS cluster. This is required to allow Kubernetes Service Accounts (KSA) to assume IAM roles. See [AWS documentation](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html#_create_oidc_provider_console). #### Create IAM Role for Service Account An IAM role is required for the Kubernetes Service Account (KSA) that will be used by the Ray head and worker pods. This role must have permissions to access the storage bucket and to describe the EKS cluster: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Sid": "ClusterAccess", "Action": [ "eks:DescribeCluster" ], "Effect": "Allow", "Resource": "<your eks cluster arn>" }, { "Sid": "AllowListBucket", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::<your storage bucket>" }, { "Sid": "AllowAllS3ObjectActions", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:HeadObject" ], "Resource": "arn:aws:s3:::<your storage bucket>/*" } ] } ``` In addition, it must have a trust policy allowing the EKS OIDC provider to assume the role from the Kubernetes Service Account: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "<OIDC Provider ARN>" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "<OIDC Provider>:aud": "sts.amazonaws.com", "<OIDC Provider>:sub": "system:serviceaccount:$NAMESPACE:$KSA_NAME" } } } ] } ``` #### Associate the IAM Role with the Kubernetes Service Account Modify the Kubernetes Service Account created in "Basic Kubernetes setup" to associate it with the IAM role created above. The role ARN is specified using `eks.amazonaws.com/role-arn` annotation: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl annotate serviceaccount "$KSA_NAME" \ -n "$NAMESPACE" \ "eks.amazonaws.com/role-arn=$ROLE_ARN" \ --overwrite ``` ### Initialize the Ray Cluster Initialize the Ray cluster using the node selectors and metadata from above: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray._mgr import ray_cluster from geneva.runners.ray.raycluster import (K8sConfigMethod, _HeadGroupSpec, _WorkerGroupSpec) head_spec = _HeadGroupSpec( service_account="geneva-ray-runner", num_cpus=1, memory=2048, node_selector={"geneva.lancedb.com/ray-head": "true"}, ) worker_spec = _WorkerGroupSpec( name="worker", min_replicas=1, service_account="geneva-ray-runner", num_cpus=2, memory=4096, node_selector={"geneva.lancedb.com/ray-worker-cpu": "true"}, ) with ray_cluster( name="my-ray-cluster", namespace="lancedb", cluster_name="geneva", config_method=K8sConfigMethod.EKS_AUTH, region="us-east-1", use_portforwarding=True, head_group=head_spec, worker_groups=[worker_spec], role_name="geneva-client-role", ) as cluster: table.backfill("embedding") ``` # Troubleshooting Geneva Deployments Source: https://docs.lancedb.com/oss/v0-41-0/geneva/deployment/troubleshooting Learn how to diagnose and resolve common issues with Geneva deployments, including version compatibility, permissions, and serialization errors. We'll cover common problems you may encounter when using Geneva and troubleshooting tips to solve them. ## Common Issues to Verify Here are some areas to verify to identify the source of problems with your Geneva deployment: * **Versions compatibility** (Ray, Python, Lance) * **Remote Ray execution** and hardware resource availability * **Sufficient permissions** to access data * **Worker code** only returns serializable values (no open files, no GPU resident buffers) ## Confirming Dependency Versions Geneva uses Ray for distributed execution. Ray requires the version deployed cluster services and clients to be exactly the same. Minor versions of Python must match both on client and cluster services (e.g. 3.10.3 and 3.10.5 are ok, but 3.10.3 and 3.12.1 are not.) Geneva has been tested with Ray 2.44+ and Python 3.10.x and 3.12.x. You can run this code in your notebook to verify your environment matches your expectations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} !python --version !pip show lancedb # need 0.22.0b0+ !echo $VIRTUAL_ENV ``` ## Confirming Remote Ray Execution Geneva allows you to specify the resources of your worker nodes. You can verify that your cluster has the resources (e.g. GPUs) available for your jobs and that remote execution is working properly. You can get some basic information about resources available to your Ray: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(ray.available_resources()) ``` You can verify basic remote execution via Ray: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @ray.remote def check_remote(): return "Hello from a worker" print(ray.get(check_remote.remote())) ``` You can also verify that versions of specific libraries are present in the execution environment: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # does ray have cuda? @ray.remote def check_pyarrow(): import pyarrow return pyarrow.__version__ print(ray.get(check_pyarrow.remote())) ``` > **Note**: You should execute Geneva code from a machine or VM that has the same architecture and OS type as the nodes in your cluster. This will allow for shared libraries to be shipped. For example, if you use a Mac to host a Jupyter notebook, Geneva will push Mac libraries to your Linux cluster and likely result in module not found errors due to OS/architecture differences. For GPU-dependent UDFs and jobs, you can verify that GPU worker nodes have the CUDA library: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # does ray have cuda? @ray.remote(num_gpus=1) def check_cuda(): import torch return torch.version.cuda, torch.cuda.is_available() print(ray.get(check_cuda.remote())) ``` ## Confirming Sufficient Permissions While your notebook or working environment may have credentials to read and write to particular buckets, your jobs need sufficient rights to read and write to them as well. Adding `import geneva` to any remote function can help verify that your workers have sufficient grants. Here we add `import geneva` to help trigger potential permissions problems: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @ray.remote(num_gpus=1) def check_cuda(): import geneva # this is currently required before other imports import torch return torch.version.cuda, torch.cuda.is_available() print(ray.get(check_cuda.remote())) ``` ### GCE Permissions Errors in Job Logs If you are using Geneva managed Ray deployed on GKE, the errors may look like this: ``` PermissionError: [Errno 13] google::cloud::Status(PERMISSION_DENIED: Permanent error, with a last message of Caller does not have storage.objects.get access to the Google Cloud Storage object. Permission 'storage.objects.get' denied on resource (or it may not exist). error_info={reason=forbidden, domain=global, metadata={gcloud-cpp.retry.function=GetObjectMetadata, gcloud-cpp.retry.reason=permanent-error, gcloud-cpp.retry.original-message=Caller does not have storage.objects.get access to the Google Cloud Storage object. Permission 'storage.objects.get' denied on resource (or it may not exist)., http_status_code=403}}). Detail: [errno 13] Permission denied ``` This indicates that your workers and/or head node are not being run with the correct service account or with an account that has sufficient access. Please double check the service account's accesses and make sure to add your service account that has access to the buckets as a parameter to your Head and Worker specs. See `service_account="geneva-integ-test"` below: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raycluster = ray_cluster( name= k8s_name, namespace=k8s_namespace, use_portforwarding=True, head_group=_HeadGroupSpec( num_cpus=8, service_account="geneva-integ-test" ), worker_groups=[ _WorkerGroupSpec( name="cpu", num_cpus=60, memory="120G", service_account="geneva-integ-test", ), _WorkerGroupSpec( name="gpu", num_cpus=8, memory="32G", num_gpus=1, service_account="geneva-integ-test", ), ], ) ``` ## Serialization Errors Serialization is a critical subsystem of Geneva. In order to store UDFs and perform distributed execution, both code and data must be serializable. Errors in this area can be subtle and difficult to find. There are a few basic rules: 1. **Python objects** passed to distributed processes or written to LanceDB must be able to be pickled or unpickled using the Python pickle or cloudpickle library. 2. **Python code** used for distributed execution, including UDFs used to calculate values written to columns must be able to be pickled or unpickled using the Python pickle or cloudpickle library. 3. **Python code or objects** need to have the same encoding and representation on the client-side and the server-side. Below is a list of error categories and examples and how to fix them. ### Serialization Library Mismatches Any Python code and objects must be able to be serialized by the client and deserialized on the server side, and vice versa. This includes objects that are generated on the fly such as those using the `attrs` library. The distributed processing engine Geneva uses, Ray, also depends on the `attrs` library. Different versions may create different object signatures that are not compatible when shipped from client-side to server-side and vice versa. This means you'll need to have compatible versions of this library on both sides. Here's an example error message. It is subtle and does not directly point to the `attrs` library: ``` ... File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/common.py", line 414, in _prepare_client_task self._ensure_ref() File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/common.py", line 384, in _ensure_ref self._ref = ray.worker._put_pickled( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/runner/work/geneva/geneva/.venv/lib/python3.12/site-packages/ray/util/client/worker.py", line 509, in _put_pickled raise cloudpickle.loads(resp.error) TypeError: Enum.__new__() missing 1 required positional argument: 'value' ``` This was solved by updating the `attrs` module on the client side to use the same version found on the server side. ### Objects with Unserializable Elements Python objects may have internal references to unpickleable objects such as open file handles or open network clients with machine specific state. There are two strategies here: 1. **Remove the reference** to unpickleable objects. 2. **Keep objects with unserializable state** only on the client or only on the server. This could be moving clients into the UDF function, or converting objects into serializable versions before transmitting them. For example, creating clients or opening files must be inside the UDF. You may see pickling-related errors like this: ``` ... raise PicklingError( _pickle.PicklingError: Pickling client objects is explicitly not supported. Clients have non-trivial state that is local and unpickleable. ``` Geneva pulls in your UDFs so they can be sent to remote worker nodes. For the method to be sent, the data must be "pickleable". **So instead of this:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from google.cloud import storage storage_client = storage.Client() # this has unpickleable state bucket = storage_client.bucket(BUCKET_NAME) # this has a reference to storage_client ... @udf def udf_function(video_path: str) -> bytes: # The closure captures bucket and its unpickleable client. return bucket.blob(video_path).download_as_bytes() ``` **Do this:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from google.cloud import storage # ... @udf def udf_function(video_path: str) -> bytes: storage_client = storage.Client() bucket = storage_client.bucket(BUCKET_NAME) # Keep the client inside the worker; return only the downloaded bytes. return bucket.blob(video_path).download_as_bytes() ``` ### Disconnect or Serialization Errors with GPU Dependent UDFs When using GPU code, the typical process loads some values and tensors from CPU memory to GPU memory. Even after moving data (`data.cpu().tolist()`), there may be references to GPU memory. While this is not a problem with local execution, when doing a distributed job it may cause problems because the GPU references are not serializable and not needed. You must take steps to eliminate references to structures in GPU memory since they cannot be serialized and sent between workers. This can be achieved by explicitly disconnecting references to the GPU memory (`data.cpu().detach().tolist()`) to get only-CPU resident fully serializable objects. Here are some typical error messages: ``` Exception in thread Thread-27 (_proxy): Traceback (most recent call last): File "/home/jon/.pyenv/versions/3.10.16/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 772, in run_closure _threading_Thread_run(self) File "/home/jon/.pyenv/versions/3.10.16/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/jon/proj/geneva-deepseek-vl2/src/geneva/runners/ray/_portforward.py", line 172, in _proxy {s1: s2, s2: s1}[s].sendall(data) BrokenPipeError: [Errno 32] Broken pipe Log channel is reconnecting. Logs produced while the connection was down can be found on the head node of the cluster in `ray_client_server_[port].out` 2025-04-11 02:25:21 INFO Starting proxy from pod to client 2025-04-11 02:25:21 INFO Proxy started 2025-04-11 02:25:21 INFO Proxying between <kubernetes.stream.ws_client.PortForward._Port._Socket object at 0x70b2bf9033a0> and <socket.socket fd=230, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 59979), raddr=('127.0.0.1', 32956)> 2025-04-11 02:25:21 INFO Waiting for client connection 2025-04-11 02:25:21,828 ERROR dataclient.py:330 -- Unrecoverable error in data channel. --------------------------------------------------------------------------- ... File ~/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py:1006, in _end_unary_response_blocking(state, call, with_call, deadline) 1004 return state.response 1005 else: -> 1006 raise _InactiveRpcError(state) _InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.NOT_FOUND details = "Failed to serialize response!" debug_error_string = "UNKNOWN:Error received from peer {created_time:"2025-04-11T02:25:22.209209484+00:00", grpc_status:5, grpc_message:"Failed to serialize response!"}" > Unexpected exception: Traceback (most recent call last): File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/ray/util/client/logsclient.py", line 67, in _log_main for record in log_stream: File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py", line 543, in __next__ return self._next() File "/home/jon/proj/geneva-deepseek-vl2/.venv/lib/python3.10/site-packages/grpc/_channel.py", line 969, in _next raise self grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.NOT_FOUND details = "Logstream proxy failed to connect. Channel for client bd854100340640fb8b5770d2bf173197 not found." debug_error_string = "UNKNOWN:Error received from peer {grpc_message:"Logstream proxy failed to connect. Channel for client bd854100340640fb8b5770d2bf173197 not found.", grpc_status:5, created_time:"2025-04-11T02:25:32.223710374+00:00"}" > ``` # End-to-End Example Source: https://docs.lancedb.com/oss/v0-41-0/geneva/end-to-end A complete Geneva example on LanceDB Enterprise — create a table, backfill computed columns, and build a materialized view with embeddings. This example walks through a complete Geneva workflow on LanceDB Enterprise: creating a raw table, adding computed columns with a distributed backfill, and materializing a view with embeddings for downstream search. The dataset is a product catalog with titles and descriptions. We'll compute a `word_count` feature column, then create a materialized view that adds text embeddings. ## 0. What you need to run this All you need is an existing **LanceDB Enterprise deployment**. Distributed job execution, clusters, and dependency manifests are managed for you — there is no Kubernetes or cluster setup in this example. Get the database URI, HTTPS endpoint and API key from your LanceDB Enterprise administrator, then replace the placeholders in the example. In application code, load credentials from environment variables or a secrets manager. ## 1. Connect and create a table ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import geneva # Connect to LanceDB Enterprise db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) # Create a raw product table schema = pa.schema([ pa.field("product_id", pa.int64()), pa.field("title", pa.string()), pa.field("description", pa.string()), pa.field("category", pa.string()), pa.field("price", pa.float64()), ]) data = pa.table({ "product_id": [1, 2, 3, 4, 5], "title": ["Chainmail Coif", "Jousting Lance Grip Tape", "Dragon-Repellent Spray", "Sword Squeegee", "Visor Windshield Wipers"], "description": [ "Premium riveted chainmail head covering. Breathable enough for dragon fire, probably.", "Non-slip grip tape for jousting lances. 3000 PSI tensile strength. Void where tilting is prohibited.", "All-natural herbal spray. Dragons hate it. Effectiveness not guaranteed against actual dragons.", "Ergonomic squeegee fits all standard broadswords. Removes blood, mud, and existential dread.", "Hand-cranked windshield wipers for full-face visors. Never ride blind into battle again.", ], "category": ["armor", "tournament", "defense", "maintenance", "armor"], "price": [129.99, 45.00, 59.99, 34.99, 24.99], }) try: db.drop_table("products_raw") except Exception: pass table = db.create_table("products_raw", data=data, schema=schema) ``` ## 2. Define UDFs ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def word_count(description: str) -> int: """Count words in the description.""" return len(description.split()) @udf(data_type=pa.string()) def price_tier(price: float) -> str: """Bucket price into tiers.""" if price < 30: return "budget" elif price < 75: return "mid-range" else: return "premium" ``` ## 3. Register columns and run a backfill Register the UDFs as virtual columns and trigger a backfill. The job runs on your deployment's default distributed execution environment — no cluster or context to configure. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add computed columns table.add_columns({ "word_count": word_count, "price_tier": price_tier, }) # Run the backfills table.backfill("word_count") table.backfill("price_tier") ``` ## 4. Create a materialized view with embeddings The embedding model needs extra Python dependencies (`sentence-transformers`, `torch`). Rather than configuring a deployment-wide environment, we bundle those dependencies **with the UDF** using `@udf(manifest=...)`. The manifest is snapshotted onto the view, so refreshes use it automatically. The materialized view selects a subset of columns from the source table — here we drop `price` and `price_tier`, keeping only what's needed for search — plus a derived `embedding` column. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.manifest import GenevaManifest # Bundle the embedding model's dependencies and attach them to the UDF embed_manifest = ( GenevaManifest.create_pip("embedding-deps") .pip(["sentence-transformers==3.3.1", "torch==2.5.1"]) .build() ) @udf(data_type=pa.list_(pa.float32(), 384), manifest=embed_manifest) class EmbedDescription: def __init__(self): self.model = None def __call__(self, description: str) -> list[float]: if self.model is None: from sentence_transformers import SentenceTransformer self.model = SentenceTransformer("BAAI/bge-small-en-v1.5") return self.model.encode(description, normalize_embeddings=True).tolist() # Build a query that selects search columns plus the derived embedding query = table.search(None).select({ "product_id": "product_id", "title": "title", "description": "description", "category": "category", "word_count": "word_count", "embedding": EmbedDescription(), }) # Create the materialized view and populate it — the embedding UDF runs on refresh db.create_materialized_view("products_enriched", query) enriched = db.open_table("products_enriched") enriched.refresh() ``` ## 5. Query the enriched table ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} enriched = db.open_table("products_enriched") # Vector search results = ( enriched.search([0.1] * 384, vector_column_name="embedding") .limit(3) .to_arrow() ) # Filtered search — armor category only armor_results = ( enriched.search([0.1] * 384, vector_column_name="embedding") .where("category = 'armor'") .limit(3) .to_arrow() ) ``` ## 6. Incremental refresh As new products are added to the source table, backfill the new rows and refresh the view to compute embeddings for them — only the new rows are processed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Append new products new_data = pa.table({ "product_id": [6, 7], "title": ["Moat Floaties", "Knight-Night Sleep Mask"], "description": [ "Inflatable arm floaties in battleship grey. Because even knights can't always swim in full plate.", "Padded silk sleep mask embroidered with your coat of arms. Blocks out 100% of torchlight.", ], "category": ["defense", "armor"], "price": [29.99, 19.99], }) table.add(new_data) # Only null/new values are computed table.backfill("word_count") table.backfill("price_tier") # Incrementally materialize the new rows (including their embeddings) into the view enriched.refresh() ``` > [!TIP] > > To keep source columns in sync automatically, mark their UDFs with `@udf(auto_backfill=True)`. See > [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling/). # Getting Started Source: https://docs.lancedb.com/oss/v0-41-0/geneva/getting-started Connect to LanceDB Enterprise, define a UDF, and run a distributed backfill — from a notebook or a script. Connect to your LanceDB Enterprise deployment, define a UDF, and run a distributed backfill — all from a notebook or a script. No cluster setup required. ## Installation Geneva is published on [PyPI](https://pypi.org/project/geneva/). Install the latest stable release with [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`. Newer pre-release builds with the latest features are also available on LanceDB's Fury indexes — see [Pre-release builds](#pre-release-builds) below. ### Prerequisites * Python 3.10+ * [uv](https://docs.astral.sh/uv/) (recommended) or `pip` ### Install the latest stable release ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --upgrade geneva ``` ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --upgrade geneva ``` ### Verify ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -c "import geneva; print(geneva.__version__)" ``` ### Pre-release builds To pick up the newest features ahead of a stable release, install a pre-release from LanceDB's Fury indexes. Geneva and its dependencies are published across two indexes: | Package | Index | | - | - | | `geneva`, `lancedb` | `https://pypi.fury.io/lancedb/` | | `pylance` | `https://pypi.fury.io/lance-format/` | ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --pre --upgrade \ --extra-index-url https://pypi.fury.io/lancedb/ \ --extra-index-url https://pypi.fury.io/lance-format \ --index-strategy unsafe-best-match \ geneva ``` ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install --pre --upgrade \ --extra-index-url https://pypi.fury.io/lancedb/ \ --extra-index-url https://pypi.fury.io/lance-format \ geneva ``` > [!NOTE] > > The `--index-strategy unsafe-best-match` flag is required with `uv`. By default, `uv` only > considers package versions from the first index that lists a given package (PyPI). Since > `geneva` and `pylance` also appear on PyPI, this flag tells `uv` to pick the best match across > all indexes. ## Quickstart Get the database URI, HTTPS endpoint and API key from your LanceDB Enterprise administrator, then replace the placeholders in the example. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva import pyarrow as pa # Connect to LanceDB Enterprise db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) tbl = db.open_table("my_table") # Define a User Defined Function (UDF) that counts the words in the text column @geneva.udf(data_type=pa.int32()) def word_count(text: str) -> int: return len(text.split()) # Register the UDF as a new virtual column tbl.add_columns({"word_count": word_count}) # Backfill the new column using distributed execution with incremental checkpointing tbl.backfill("word_count") ``` ## Auto-backfill With `auto_backfill=True`, LanceDB Enterprise recomputes the column for you whenever the data or the UDF version changes — no explicit `backfill()` call needed (see [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling/)). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Change the column to use a new UDF version with auto-backfill enabled @geneva.udf(data_type=pa.int32(), auto_backfill=True) def word_count(text: str) -> int: return len(text.split()) tbl.alter_columns({"path": "word_count", "udf": word_count}) # Add new rows. word_count is computed automatically in the background. tbl.add([{"text": "hello world"}]) ``` ## Materialized views and chunkers A [materialized view](/oss/v0-41-0/geneva/jobs/materialized-views/) applies UDFs over a query and refreshes incrementally. A [chunker](/oss/v0-41-0/geneva/udfs/scalar-udtfs) view expands each source row into many rows (1:N) — useful for splitting documents, videos, or images. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Materialized view: a query with UDF-computed columns, refreshed incrementally query = tbl.search(None).select({"text": "text", "word_count": word_count}) view = db.create_materialized_view("my_view", query) view.refresh() # Chunker view: 1:N row expansion — split each row's text into one row per word from typing import Iterator, NamedTuple class Chunk(NamedTuple): chunk_index: int chunk_text: str @geneva.chunker def split_text(text: str) -> Iterator[Chunk]: for i, word in enumerate(text.split()): yield Chunk(chunk_index=i, chunk_text=word) chunks = db.create_udtf_view( "my_chunks", source=tbl.search(None).select(["text"]), udtf=split_text, ) chunks.refresh() ``` ## Connecting to object storage or a local filesystem Geneva can also run directly against cloud object storage or a local path. In this mode, jobs run on a [distributed execution context](/oss/v0-41-0/geneva/jobs/contexts) you provide. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Cloud object storage (S3, GCS, Azure, or any S3-compatible object store) db = geneva.connect("s3://my-bucket/my-database") # Local filesystem db = geneva.connect("/path/to/my-database") ``` # Multimodal Feature Engineering with Geneva Source: https://docs.lancedb.com/oss/v0-41-0/geneva/index Learn how to do multimodal feature engineering in LanceDB Enterprise to transform raw data into meaningful features for AI models. Enterprise-only When working with multimodal data at scale, [LanceDB Enterprise](/oss/v0-41-0/enterprise) makes it easy to define, extract, and transform raw data into useful information and features for your AI applications. LanceDB Enterprise's *Multimodal Feature Engineering* package is designed to improve the productivity of AI engineers operating at immense scale. With an API designed to leverage LanceDB's optimized data storage and retrieval, it streamlines prototyping extraction and transformation tasks, performing experiments, exploring your data, scaling up execution, and moving to production. LanceDB Multimodal Feature Engineering enables researchers to seamlessly transition from experiments in local notebooks to fully-managed distributed job execution on datasets with billions of rows. > [card] > > The `geneva` Python package is currently only available as part of > [LanceDB Enterprise](/oss/v0-41-0/enterprise). Please [contact us](https://www.lancedb.com/contact) if you're interested > in scaling up your feature engineering workloads for your AI and multimodal use cases. Feature engineering itself is not Enterprise-only: LanceDB Embedded has [computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) and [materialized views](/oss/v0-41-0/feature-engineering/materialized-views), which need no extra package. See [Feature engineering](/oss/v0-41-0/feature-engineering) to choose between them and Geneva. The `geneva` package uses Python [User Defined Functions (UDFs)](/oss/v0-41-0/geneva/udfs/udfs) to define features as columns in a Lance dataset. Adding a feature is straightforward: **Step 1** Prototype your Python function in your favorite environment. **Step 2** Wrap the function with a small UDF decorator (see [UDFs](/oss/v0-41-0/geneva/udfs/udfs)). **Step 3** Register the UDF as a virtual column using `Table.add_columns()`. **Step 4** (Optional, advanced) Override where the job runs — see [Advanced Execution Contexts](/oss/v0-41-0/geneva/jobs/contexts). On LanceDB Enterprise, distributed job execution is fully managed, so most users can skip this step. **Step 5** Trigger a `backfill` operation (see [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling/)). > [!TIP] > > You can build your Python feature generator function in an IDE or a notebook using your project's Python versions and dependencies. `geneva` will automate much of the dependency and version management needed to move from prototype to scale and production. Ready to write your first feature? Head to [Getting Started](/oss/v0-41-0/geneva/getting-started). ## Continue learning Visit the following pages to learn more about featuring engineering in LanceDB Enterprise: * **Get started**: [Getting Started](/oss/v0-41-0/geneva/getting-started) · [What is Feature Engineering?](/oss/v0-41-0/geneva/overview/) · [End-to-end example](/oss/v0-41-0/geneva/end-to-end) * **UDFs**: [Using UDFs](/oss/v0-41-0/geneva/udfs/udfs) · [Blob helpers](/oss/v0-41-0/geneva/udfs/blobs/) · [Error handling](/oss/v0-41-0/geneva/udfs/error_handling) · [Advanced configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration) * **Jobs**: [Job execution overview](/oss/v0-41-0/geneva/jobs/) · [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling/) · [Materialized views](/oss/v0-41-0/geneva/jobs/materialized-views/) · [Startup optimizations](/oss/v0-41-0/geneva/jobs/startup/) · [Advanced job configuration](/oss/v0-41-0/geneva/jobs/advanced-job-configuration/) · [Advanced execution contexts](/oss/v0-41-0/geneva/jobs/contexts/) · [Geneva console](/oss/v0-41-0/geneva/jobs/console) · [Performance](/oss/v0-41-0/geneva/jobs/performance/) * **Deployment**: [Deployment overview](/oss/v0-41-0/geneva/deployment/) · [Helm deployment](/oss/v0-41-0/geneva/deployment/helm/) · [Troubleshooting](/oss/v0-41-0/geneva/deployment/troubleshooting/) ## API Reference * [`geneva.connect()`](https://lancedb.github.io/geneva/api/) — connect to a Geneva database * [Connection](https://lancedb.github.io/geneva/api/connection/) — manage tables, views, jobs, clusters, and manifests * [Table](https://lancedb.github.io/geneva/api/table/) — add columns, backfill, search, and manage table data * [UDF](https://lancedb.github.io/geneva/api/udf/) — define user-defined functions for feature computation # Advanced Job Configuration Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/advanced-job-configuration Pin the dependency manifest a transform's distributed job runs with using @udf, @chunker, and @udtf. Enterprise-only On LanceDB Enterprise, backfill and refresh jobs run on a managed, distributed execution environment configured at deployment time: * the **default cluster** — the compute pool jobs run on, and * the **default manifest** — the Python dependency environment (image and packages) the distributed workers run with. These defaults are set in the [LanceDB Helm chart](/oss/v0-41-0/geneva/deployment/helm) and cover most workloads. When a transform needs dependencies that differ from the deployment default, pin a **manifest** on the transform itself, as described below. > [!NOTE] > > To override the **cluster** a job runs on — for example to route an embedding backfill to a > GPU pool — see [Advanced Execution Contexts](/oss/v0-41-0/geneva/jobs/contexts). ## Pinning a dependency manifest A manifest pins the Python image and packages the distributed workers run with. Build one with the manifest builders, then attach it to your transform with the `manifest=` argument on `@udf`, `@chunker`, or `@udtf`. The manifest is snapshotted into the column (or view) metadata when the transform is registered, so every backfill or refresh of that transform uses it automatically — there is no per-call manifest argument to remember. > [!NOTE] > > **Manifests are immutable at the column / view level.** When a transform is registered, its > manifest is snapshotted onto the column (or view) metadata. Changing the deployment-default > manifest — or the `GenevaManifest` object in your code — does **not** affect existing columns > or views: they keep using the snapshot taken at creation time. To move a column or view to a > new manifest, re-point it to a new (or updated) UDF / chunker / UDTF — for example with > `alter_columns()` for a column, or by recreating the view. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from typing import Iterator, NamedTuple from geneva import udf, chunker, udtf from geneva.manifest import GenevaManifest # Build a manifest that pins the dependencies these transforms need embed_manifest = ( GenevaManifest.create_pip("embedding-deps") .pip(["sentence-transformers==3.3.1", "torch==2.5.1"]) .build() ) ``` ### `@udf(manifest=...)` Pin dependencies for a 1:1 computed column: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 384), manifest=embed_manifest) def embed(text: str) -> list[float]: from sentence_transformers import SentenceTransformer model = SentenceTransformer("BAAI/bge-small-en-v1.5") return model.encode(text, normalize_embeddings=True).tolist() tbl.add_columns({"embedding": embed}) tbl.backfill("embedding") # the backfill job runs with embed_manifest ``` ### `@chunker(manifest=...)` Pin dependencies for a 1:N [chunker](/oss/v0-41-0/geneva/udfs/scalar-udtfs) (scalar UDTF): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Chunk(NamedTuple): chunk_index: int chunk_text: str @chunker(manifest=embed_manifest) def split_document(text: str) -> Iterator[Chunk]: for i, part in enumerate(text.split("\n\n")): yield Chunk(chunk_index=i, chunk_text=part) view = db.create_udtf_view("chunks", source=tbl.search(None), udtf=split_document) view.refresh() # the refresh job runs with embed_manifest ``` ### `@udtf(manifest=...)` Pin dependencies for an N:M [batch UDTF](/oss/v0-41-0/geneva/udfs/batch-udtfs): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), ]), manifest=embed_manifest, ) def group_stats(source) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby("label").size().reset_index(name="count") yield pa.RecordBatch.from_pandas(agg) view = db.create_udtf_view("summaries", source=tbl.search(None), udtf=group_stats) view.refresh() # the refresh job runs with embed_manifest ``` ## Capturing your local environment for testing When iterating locally, you often want the workers to run with the *exact* packages from your current environment rather than a curated pip list. `Connection.capture_local_environment()` zips your workspace (and, optionally, your site-packages), uploads the archives through the connection, and returns a ready-to-use `GenevaManifest` you can attach to a transform with `manifest=`. Replace the connection placeholders below with your deployment details. In application code, load credentials from environment variables or a secrets manager. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import geneva from geneva import udf db = geneva.connect( uri="db://your-database", host_override="https://your-endpoint", api_key="your-api-key", ) # Capture the local workspace; rely on the worker image for site-packages manifest = db.capture_local_environment(skip_site_packages=True) @udf(data_type=pa.string(), manifest=manifest) def shout(text: str) -> str: return text.upper() tbl = db.open_table("my_table") tbl.add_columns({"shout": shout}) tbl.backfill("shout") # workers run with your captured environment ``` Pass `skip_site_packages=False` (the default) to also upload your local site-packages. ## Manifest resolution For a given transform, the manifest is resolved in this order (first match wins): 1. The manifest pinned on the transform via `@udf` / `@chunker` / `@udtf` `manifest=`. 2. For a materialized view, the manifest snapshotted on the view when it was created. 3. The deployment-default manifest from the [LanceDB Helm chart](/oss/v0-41-0/geneva/deployment/helm). > [!NOTE] > > The `manifest=` argument applies to managed enterprise (`db://`) jobs. For direct > object-storage or local-filesystem connections, configure the dependency environment > explicitly with an [Advanced Execution Context](/oss/v0-41-0/geneva/jobs/contexts) instead. # Backfilling Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/backfilling Learn how to trigger backfill operations to populate column values in your LanceDB table using Geneva's distributed framework. ## Triggering Backfill Triggering backfill creates a distributed job to run the UDF and populate the column values in your LanceDB table. The Geneva framework simplifies several aspects of distributed execution. **Checkpoints**: Each batch of UDF execution is checkpointed so that partial results are not lost in case of job failures. Jobs can resume and avoid most of the expense of having to recalculate values. ## Auto-backfill Computed columns can be explicitly backfilled or they can be configured to be backfilled automatically as data changes. Set `auto_backfill=True` on the UDF, and the column is automatically recomputed whenever it falls out of sync with its source data. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Mark the column's UDF for automatic backfill @udf(data_type=pa.list_(pa.float32(), 1536), version="1", auto_backfill=True) def embed_udf(text: str) -> list[float]: return embedding_model.encode(text) tbl.add_columns({"embedding": embed_udf}) # No explicit backfill() needed — adding rows triggers recomputation automatically tbl.add(new_rows) ``` The `auto_backfill` flag is recorded in the column metadata when the column is added or altered. LanceDB Enterprise's managed agent watches for columns that need recomputation and dispatches a distributed backfill job for you — there is no manual trigger and no status polling. A column is recomputed when, for example, **new rows are added** (leaving it null for those rows) or the **UDF version changes** (you bump `version=` and `alter_columns()` to the new function). > [!NOTE] > > Auto-backfill is an enterprise feature. On direct object-storage or local-filesystem > connections there is no managed agent, so `auto_backfill=True` has no effect and you must run > `backfill()` explicitly. ## Adaptive checkpoint sizing Geneva can automatically adjust checkpoint sizes during a backfill. It starts with small checkpoints (faster proof-of-life) and grows them as it observes stable throughput, while staying within safe bounds. Planning still uses your configured checkpoint size (`checkpoint_size`), but the actual checkpoint chunks can be smaller when adaptive sizing is enabled. Adaptive sizing is always clamped to bounds: * `max_checkpoint_size`: Upper bound. Defaults to the job's checkpoint size (`checkpoint_size`) and is capped at that value if you set a larger max. * `min_checkpoint_size`: Lower bound. Defaults to 1. When `min_checkpoint_size == max_checkpoint_size`, adaptive sizing is disabled and checkpoints are fixed-size. You can set adaptive bounds in two places: * On the UDF definition via `@udf(..., min_checkpoint_size=..., max_checkpoint_size=...)` * On the backfill call via `table.backfill(..., min_checkpoint_size=..., max_checkpoint_size=...)` Backfill-level values take precedence over UDF defaults. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(min_checkpoint_size=25, max_checkpoint_size=200) def embed_udf(text): ... # Override the UDF defaults for this run tbl.backfill("embedding", min_checkpoint_size=10, max_checkpoint_size=100) ``` ## Managing concurrency One way to speed up the execution of a job to give it more resources and to have it work in parallel. There are a few settings you can use on the backfill command to tune this. * process-level `concurrency` * thread-level `intra_applier_concurrency` Process level concurrency can be set with the `concurrency` parameter. This lets you specify the number of processes calculating values using the UDF. The default is 8 and should be set to the number of GPUs you would like to dedicate to your job. This can also be used based on CPU constraints. So if you have 40 machines with 4 GPUs each, you could set ths value to 160. If you set the value higher than the resources available, Geneva will try to schedule as much of the resources as it can (and potentially auto-scale to get more resources). Thread level concurrency can be set with the `intra_applier_concurrency` parameter. This lets you specify the number of threads in each process is calculating values using the UDF. The default is 1. If you have CPU heavy jobs this may be the best setting to tweak to get more utilization out of your systems. If you set the value higher than the resources available, Geneva will try to schedule as much of the resources as it can get. The two settings can be used in combination. So if your UDF requires 1 CPU and you set `concurrency` to 10 and `intra_applier_concurrency` to 5, you will potentially have 50 instances of the UDFs running in parallel. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # backfill embeddings with 10 * 5 = 50 instances tbl.backfill("embedding", concurrency=10, intra_applier_concurrency=5) ``` ## Managing commit visibility Feature engineering jobs at scale can take days to complete. Two settings can help you present progress to other readers incrementally. * Limit the number of rows processed with `num_frags` * Perform intermediate commits with `commit_granularity` The `num_frags` parameter lets you limit the number of fragments processed before the job is considered complete. If you have a table with 1000 fragments, you could set `num_frags` to 1 to see how your UDF performs and if to validate the values generated. You can then later run with a larger `num_frags` value or without the `num_frags` setting to complete the backfill. Any fragments prevoiusly computed are not computed again. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill 2 fragments so experiement can be done on the sample tbl.backfill("embedding", num_frags=2) ``` The `commit_granularity` parameter lets you specify how many fragments need to be ready to commit before a intermediate commit occurs and makes partial results visible to other readers. So for our example with a table of 1000 fragments, you can set `commit_granularity` to 10 to see progress updates every 10 fragments. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # backfill all fragments and perform an intermediate commit every 10 fragments to expose incremental results. tbl.backfill("embedding", commit_granularity=10) ``` ## Filtered Backfills Geneva allows you to specify SQL-style filters on the backfill operation. This lets you to apply backfills to a specified subset of the table's rows. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' tbl.backfill("content", where="starts_with(filename, 'a')") # only backfill embeddings of only those videos with content tbl.backfill("embedding", where="content is not null") ``` Geneva also allows you to incrementally add more rows or have jobs that just update rows that were previously skipped. If new rows are added, we can run the same command and the new rows that meet the criteria will be updated. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' tbl.backfill("content", where="starts_with(filename, 'a')") # only backfill embeddings of only those videos with content tbl.backfill("embedding", where="content is not null") ``` Or, you can use filters to add in or overwrite content in rows previously backfilled. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # only backfill video content whose filenames start with 'a' or 'b' but only if content not pulled previously tbl.backfill("content", where="(starts_with(filename, 'a') or starts_with(filename, 'b')) and content is null") # only backfill embeddings of only those videos with content and no prevoius embeddings tbl.backfill("embedding", where="content is not null and embeddding is not null") ``` Reference: * [`backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill) * [`backfill_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill_async) * [`plan_backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.plan_backfill) * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator and UDF configuration options including `checkpoint_size` # Bulk Loading & Updating Columns Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/bulk-load-columns Load or update column data from external sources (Parquet, Lance, IPC) into your LanceDB table using a primary-key join. Beta — introduced in Geneva 0.13.0 ## Overview A common scenario is having column data that **already exists** in an external dataset — embeddings from a vendor, features exported from a data warehouse, or columnar data in cloud storage — that you want to load into an existing LanceDB table. `load_columns` joins value columns from an external source into your table by primary key. It works for both use cases: * **Adding new columns:** If the specified columns don't exist in the destination table, they are created automatically. * **Updating existing columns:** If the columns already exist, matched rows are updated with the source values. Unmatched rows are controlled by the `on_missing` parameter. **Destination table (before):** | pk | col_a | col_b | | - | - | - | | 1 | x | 10 | | 2 | y | 20 | | 3 | z | 30 | **External source (Parquet / Lance / IPC):** | pk | embedding | | - | - | | 1 | \[.1, .2] | | 2 | \[.3, .4] | | 3 | \[.5, .6] | **Destination table (after `load_columns` join on `pk`):** | pk | col_a | col_b | embedding | | - | - | - | - | | 1 | x | 10 | \[.1, .2] | | 2 | y | 20 | \[.3, .4] | | 3 | z | 30 | \[.5, .6] | ### When to use * **Loading new columns:** Attach pre-computed embeddings from a vendor, or add features exported from Spark/BigQuery as Parquet. * **Updating existing columns:** Replace outdated embeddings with a newer model's output, or refresh feature values from an updated export. * **Partial updates:** Update a subset of rows (e.g., only rows whose embeddings were recomputed) while preserving all other values via carry semantics. * **Format consolidation:** Merge columnar data spread across Parquet files into an existing Lance table. ## Basic usage Supports Parquet, Lance, and IPC sources. The format is auto-detected from the URI suffix, or can be overridden with `source_format`. You can load one or more columns in a single call. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("my_db") table = db.open_table("my_table") # Add a new embedding column from a Parquet source table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], ) # Later, update the same column with refreshed embeddings table.load_columns( source="s3://bucket/embeddings_v2/", pk="document_id", columns=["embedding"], ) ``` For non-blocking execution, use `load_columns_async` which returns a `JobFuture` — call `.result()` to block until completion. ## Handling missing keys When the source doesn't cover every row in the destination, the `on_missing` parameter controls what happens to unmatched rows: | Mode | Behavior | | - | - | | `"carry"` (default) | Keep existing value. NULL if the column is new. | | `"null"` | Explicitly set to NULL. | | `"error"` | Raise an error on the first unmatched row. | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Default: unmatched rows keep their current value table.load_columns( source="s3://bucket/partial_embeddings/", pk="document_id", columns=["embedding"], on_missing="carry", ) # Strict mode: fail if source doesn't cover all rows table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], on_missing="error", ) ``` The `carry` mode is particularly important for partial and multi-pass loads — it ensures that previously loaded values are never overwritten. ## Performance tuning ### Concurrency The `concurrency` parameter controls the number of worker processes. The default is 8 — set this to match your available cluster resources. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], concurrency=16, ) ``` ### Checkpointing Bulk load jobs checkpoint each batch for fault tolerance, using the same infrastructure as [backfill jobs](/oss/v0-41-0/geneva/jobs/backfilling#adaptive-checkpoint-sizing). Key parameters: * `checkpoint_interval_seconds`: Target seconds per checkpoint batch (default 60s). The adaptive sizer grows or shrinks batch sizes to hit this target. * `min_checkpoint_size` / `max_checkpoint_size`: Bounds for adaptive sizing. > [!TIP] > > If your job is small enough to complete without needing fault tolerance, you can get better performance by effectively disabling checkpoints. Increase `checkpoint_interval_seconds` to a large value and set `min_checkpoint_size` high enough that each worker processes its entire workload in a single batch. ### Commit visibility For long-running jobs, `commit_granularity` controls how many fragments complete before an intermediate commit makes partial results visible to readers. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.load_columns( source="s3://bucket/embeddings/", pk="document_id", columns=["embedding"], commit_granularity=10, ) ``` ### Multi-pass loads for large sources `load_columns` builds an in-memory primary-key index from the source. If the source is too large to fit in memory, split it into chunks and run sequential calls. Carry semantics guarantee correctness across passes. Index memory depends on primary key type: | PK type | \~Memory per row | 100M rows | 1B rows | | - | - | - | - | | int64 | \~8 bytes | \~800 MB | \~8 GB | | string (avg 32 bytes) | \~32 bytes | \~3.2 GB | \~32 GB | Choose N so that `source_size / N` fits in memory: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow.dataset as pads # Discover source files (metadata only, no data I/O) source_files = pads.dataset("s3://bucket/embeddings/", format="parquet").files # Split into N chunks and run sequentially N = 4 total = len(source_files) for i in range(N): chunk = source_files[i * total // N : (i + 1) * total // N] table.load_columns( source=chunk, pk="document_id", columns=["embedding"], ) ``` Each pass reads only its assigned files, so total source I/O stays at 1x. If the source is already partitioned into subdirectories, pass each URI directly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for shard in range(4): table.load_columns( source=f"s3://bucket/embeddings/shard_{shard}/", pk="document_id", columns=["embedding"], ) ``` > [!WARNING] > > Multi-pass loads must run **sequentially**, not concurrently. Two `load_columns` calls running at the same time against the same column produce an interleaved end state. Use a plain `for` loop, not `concurrent.futures`. ## Reference * [`load_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.load_columns) * [`load_columns_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.load_columns_async) # Backfill Conflicts Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/conflicts Learn how Geneva handles conflicts during backfill operations and what to do when they occur. ## Overview Geneva backfills operate on a **point-in-time snapshot** of your table. When other operations modify the table during or between backfills, conflicts can occur. Geneva >=0.9.0 automatically handles most conflict scenarios, reducing unnecessary recomputation and enabling graceful recovery. ## Safe Operations During Backfill These operations can safely run while a backfill is in progress: | Operation | Why It's Safe | | - | - | | `merge_insert` (Insert-only) | Creates new fragments without modifying existing ones | | `add()` / append data | Creates new fragments without modifying existing ones | | Read operations (`search`, `to_arrow`) | Read-only, no fragment modification | | Adding new columns | Schema change only, no fragment rewrite | ## Operations That Cause Conflicts These operations can conflict with running backfills: | Operation | What Happens | | - | - | | `compact_files()` / `optimize()` | Reorganizes fragments, invalidating the backfill's snapshot | | `merge_insert` with updates | Modifies existing rows, causing fragment conflicts | | `delete()` | Modifies existing fragments | > [!WARNING] > > When a conflict occurs, affected fragments fail gracefully. The backfill completes what it can, and you can re-run it to process the remaining rows. ## How Geneva Handles Conflicts ### Concurrent Backfills on Different Columns When multiple backfills run on the same table but different columns, Geneva handles version conflicts automatically: 1. Each backfill writes to different column files (field IDs) 2. If a commit conflict occurs, Geneva retries at the latest version 3. The retry merges the new column data without overwriting other columns This is controlled by the `GENEVA_VERSION_CONFLICT_MAX_RETRIES` environment variable (default: 10). See [Advanced Configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration) for details. ### Compaction Between Backfills When you run compaction between backfills (not during), Geneva handles it efficiently: | Scenario | Behavior | | - | - | | Backfill, compact, re-backfill (same UDF) | Already-computed rows are skipped via `WHERE <col> IS NULL` | | Partial backfill, compact, resume | Incremental processing continues from where it left off | | Backfill, `alter_columns` (new UDF), re-backfill | Full reprocessing with new UDF (intentional) | > [!NOTE] > > Geneva's default behavior is to skip rows that already have values (`WHERE <col> IS NULL`). This means compaction doesn't cause unnecessary recomputation. ## Recovery Steps When a conflict occurs during a backfill: 1. **Wait** for any concurrent operations (compaction, updates) to complete 2. **Re-run** the backfill: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.backfill("column_name") ``` 3. **Only uncomputed rows** will be processed (rows with NULL values in the target column) Checkpoints from the previous run are preserved, so you won't lose progress on successfully computed rows. ## Best Practices ### Sequence Your Operations For the smoothest experience, sequence your operations: ``` 1. Complete all data ingestion 2. Run backfill to compute UDF columns 3. Run compaction/optimization ``` ### Use Insert-Only Operations During Backfill If you need to add data while a backfill is running, use insert-only operations: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Safe: INSERT-only merge_insert tbl.merge_insert("id").when_not_matched_insert_all().execute(new_data) # Unsafe: Updates to existing rows tbl.merge_insert("id").when_matched_update_all().execute(data) # May conflict ``` ### Monitor Backfill Progress Use async backfills to monitor progress and handle errors: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fut = tbl.backfill_async("column_name") while not fut.done(): time.sleep(1) # Check for errors before subsequent operations result = fut.result() ``` ### Disable Auto-Compaction During Large Backfills If using LanceDB Enterprise which has auto-compaction enabled, consider disabling it during large backfill operations to avoid conflicts. ## Related * [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling) - Triggering and configuring backfill operations * [Advanced Configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration) - Environment variables for retry behavior ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `add()`, `merge_insert()`, and other table mutation methods # Geneva Console Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/console The Geneva Console provides a web-based interface for monitoring and managing Geneva jobs, clusters, and manifests. ![geneva-console](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/geneva/console_screenshot.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=a1cb043fd49470055f332ceb933c103c) ## Why a Geneva Console? * Collaboration: The console helps multiple people work together. Individual jobs can be run in a notebook or workflow, but to collaborate on jobs, it helps to be able to see everything that's running on a given database. * History: See what has run in the past and diagnose any problems with your jobs. * Shared resources: The console stores definitions of clusters and manifests, so you can easily tell what resources you want to use to run your job. ## Getting Started The Geneva console is installed with the Geneva Helm chart; [contact LanceDB](https://lancedb.com/contact/) for access to the Helm chart. 1. Install or upgrade the Geneva Helm chart (see [Helm Deployment](/oss/v0-41-0/geneva/deployment/helm/)). 2. In your web browser, connect to the Geneva Console UI using the external ingress/load balancer URI configured in your deployment. 3. **Backup (no external ingress):** if your deployment doesn't expose the console via ingress or a load balancer, forward port 3000 from the `geneva-console-ui` service and open `http://localhost:3000`: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} kubectl port-forward -n lancedb svc/geneva-console-ui 3000:3000 ``` (Use `-n` to specify the namespace you installed the Helm chart into. We advise `lancedb`.) 4. When prompted, enter your bucket and database, like: ``` s3://my-bucket/my-db ``` ## What's in the Console? ### Jobs Overview The heart of the console is an overview of all jobs that are running on a given database. See each job's status, progress, timing, and initiator. ### Job Details Click on a job's ID to get more details, especially events that have happened in a job's life cycle, and metrics such as number of workers, rows, and fragments written. ### Clusters See the Geneva clusters that you have defined to run jobs. Because clusters can be reused by name, this view can help you run a new job with the same resource constraints as a previous job. ### Manifests See the Manifests you've defined and what packages/dependencies they contain. As with clusters, manifests are reusable, so it's easy to start a new job with the same dependencies as an old one by just specifying the manifest name. ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()`, `list_clusters()`, `list_manifests()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `GenevaCluster` and cluster configuration classes * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — `GenevaManifest` and manifest builder classes # Advanced Execution Contexts Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/contexts Configure the distributed execution backend — clusters and dependency manifests — for Geneva jobs on object-storage and local-filesystem connections. > [!NOTE] > > **This page applies to direct object-storage and local-filesystem connections only.** On > LanceDB Enterprise (`db://`) connections, distributed job execution is fully managed: the > cluster and manifest are configured at deployment time (see > [Helm deployment](/oss/v0-41-0/geneva/deployment/helm)) and can be overridden per job with `cluster=` / > `manifest=` (see [Advanced Job Configuration](/oss/v0-41-0/geneva/jobs/advanced-job-configuration)). You > do not define execution contexts there. > > When you connect Geneva directly to object storage (`s3://`, `gs://`, …) or a local path, > there is no managed control plane, so you configure the execution backend yourself using the > contexts below. The APIs on this page require Geneva **v0.10.0** or later. Geneva's distributed execution backend is **Ray**. There are 3 ways to connect to a Ray cluster: 1. Local Ray 2. KubeRay: create a cluster on demand in your Kubernetes cluster. 3. Existing Ray Cluster ## Ray Clusters ### Local Ray To execute jobs without an external Ray cluster, you can use `LocalRayContext`. This will auto-create a Ray cluster on your machine. Because it's on your laptop/desktop, this is only suitable for prototyping on small datasets. But it is the easiest way to get started. Simply define the UDF, add a column, call [`Connection.local_ray_context()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.local_ray_context), and trigger the job: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.db import Connection @udf def filename_len(filename: str) -> int: return len(filename) tbl.add_columns({"filename_len": filename_len}) with Connection.local_ray_context(): tbl.backfill("filename_len") ``` Geneva will package up your local environment and send it to each worker process, so they'll have access to all the same dependencies as if you ran a simple Python script yourself. ### KubeRay If you have a Kubernetes cluster with kuberay-operator, you can use Geneva to automatically provision RayClusters. To do so, define a Geneva cluster, representing the resource needs, Docker images, and other Ray configurations necessary to run your job. Make sure your cluster has adequate compute resources to provision the RayCluster. Here is an example Geneva cluster definition: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.cluster import GenevaCluster, K8sConfigMethod from geneva.cluster.builder import KubeRayClusterBuilder db = geneva.connect("s3://my-bucket/my-db") cluster_name = "my-geneva-cluster" # lowercase, numbers, hyphens only service_account = "my_k8s_service_account" # k8s service account that Geneva runs as k8s_namespace = "lancedb" # k8s namespace cluster = ( GenevaCluster.create_kuberay(cluster_name) .namespace(k8s_namespace) .aws_config(region="us-east-1") # only required if using AWS .config_method(K8sConfigMethod.LOCAL) # Load k8s config from `~/.kube.config` # (other options include EKS_AUTH to load from AWS EKS, or IN_CLUSTER to load the # config when running inside a pod in the cluster) .head_group( service_account=service_account, cpus=2, node_selector={"geneva.lancedb.com/ray-head":""}, # k8s label required for head in your cluster ) .add_worker_group( KubeRayClusterBuilder.cpu_worker() .cpus(4) .memory("8Gi") .service_account(service_account) .build() ) .add_worker_group( KubeRayClusterBuilder.gpu_worker() # defaults to 1 GPU .cpus(2) .memory("8Gi") .service_account(service_account) .build() ) .build() ) db.define_cluster(cluster_name, cluster) # define_cluster stores the cluster metadata in persistent storage. The Cluster can then be referenced by name and provisioned when creating an execution context. table = db.get_table("my_table") with db.context(cluster=cluster_name): table.backfill("my_udf") ``` See the API docs for all the parameters [`GenevaCluster.create_kuberay()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.mgr.GenevaCluster.create_kuberay), [`add_worker_group()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.add_worker_group), [`cpu_worker()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.cpu_worker), and [`gpu_worker()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.gpu_worker) can use. #### Exit Modes When you launch multiple async jobs in a single context, the exit mode controls whether the cluster waits for all of them to finish and how it handles failures. You can customize this behavior with the `on_exit` parameter: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray.raycluster import ExitMode with db.context(cluster=cluster_name, manifest=manifest_name, on_exit=ExitMode.DELETE): fut1 = tbl.backfill_async("embedding_a") fut2 = tbl.backfill_async("embedding_b") # No need to call .result() — the context waits for both jobs # Both jobs completed; cluster deleted ``` | Exit Mode | Behavior | | - | - | | `ExitMode.DELETE` (default) | Wait for all async jobs in the context to complete, then delete the cluster. Ideal for batch scripts that launch multiple `backfill_async()` calls in one context. | | `ExitMode.RETAIN_ON_FAILURE` | Wait for all async jobs in the context to complete. If any job failed, the context body raised an exception, or `wait_timeout` was exceeded, retain the cluster for debugging; otherwise delete. | | `ExitMode.RETAIN` | Never delete the cluster, regardless of job outcomes. Useful for notebooks and interactive sessions where you run multiple jobs over time. | ### External Ray cluster If you already have a Ray cluster, Geneva can execute jobs against it too. You do so by defining a Geneva cluster with [`GenevaCluster.create_external()`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.mgr.GenevaCluster.create_external) which has the address of the cluster. Here's an example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva from geneva.cluster import GenevaCluster db = geneva.connect(my_db_uri) cluster_name = "my-geneva-external-cluster" cluster = ( GenevaCluster.create_external(cluster_name, "ray://my_ip:my_port") .build() ) db.define_cluster(cluster_name, cluster) ``` > [!TIP] > > If you need to send environment variables to your workers, in either a KubeRay or External Ray cluster, you can use [`ray_init_kwargs`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.ray_init_kwargs), like so. Set the value in the shell before starting your Python program: > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export AWS_ACCESS_KEY_ID="your-access-key-id" > ``` > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import os > > cluster = ( > GenevaCluster.create_kuberay(cluster_name) # or create_external(cluster_name) > .ray_init_kwargs({ > "runtime_env": { > "env_vars": { > "MY_VAR": "value", > "AWS_ACCESS_KEY_ID": os.environ["AWS_ACCESS_KEY_ID"] > }, > }, > }) > # Add other cluster settings here if needed. > .build() > ) > ``` ## Dependencies and Manifests Most UDFs require some dependencies: helper libraries like `pillow` for image processing, pre-trained models like `open-clip` to calculate embeddings, or even small config files. We have three ways to get them to workers: 1. Define dependencies explicitly in a manifest 2. Bake dependencies into an image 3. Auto-upload local dependencies ### Define dependencies explicitly in a manifest We recommend defining dependencies explicitly: it's the easiest way to understand exactly what's running, and the least error-prone. To do so, define a Manifest, like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name="dev-manifest" manifest = ( GenevaManifest.create_pip(manifest_name) .pip(["lancedb", "numpy"]) ).build() db.define_manifest(manifest_name, manifest) ``` After workers start up, this will run `pip install lancedb numpy` on them. You can also use [`.requirements_path(path)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.requirements_path) to point to a local `requirements.txt` file instead of listing packages inline. Note that attempting to use both [`.pip()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.pip) and `.requirements_path()` will raise an exception. For conda-based dependencies, use [`GenevaManifest.create_conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_conda) instead: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest manifest = ( GenevaManifest.create_conda("my-conda-manifest") .conda({"dependencies": ["python=3.10", "numpy"]}) ).build() ``` You can also use [`.conda_environment_path(path)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda_environment_path) to point to a local `environment.yml` file. Note that attempting to use both [`.conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda) and `.conda_environment_path()` will raise an exception. ### Bake dependencies into an image Because the `pip` or `conda` methods involve installing packages, they will incur some startup costs. When your jobs are stable in production, therefore, it will be faster to build all your dependencies into the workers' images, then specify them like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name = "prod-manifest" manifest = ( GenevaManifest.create_pip(manifest_name) .worker_image("myregistry.example.com/my-custom-worker-image:latest") ).build() db.define_manifest(manifest_name, manifest) ``` > [!TIP] > > You can also define images in a cluster via the [`head_group`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.KubeRayClusterBuilder.head_group) method and [`cpu_worker`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.CpuWorkerBuilder)/[`gpu_worker`](https://lancedb.github.io/geneva/api/cluster/#geneva.cluster.builder.GpuWorkerBuilder) methods, e.g.: > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > cluster = ( > GenevaCluster.create_kuberay(cluster_name) > .head_group( > image="myregistry.example.com/my-custom-head-image:latest", > ) > .add_worker_group(KubeRayClusterBuilder.cpu_worker() > .image("myregistry.example.com/my-custom-cpu-worker-image:latest") > ) > .add_worker_group(KubeRayClusterBuilder.gpu_worker() > .image("myregistry.example.com/my-custom-gpu-worker-image:latest") > ) > .build() > ) > ``` > > However, if an image is defined in both a Cluster and a Manifest, the definition in the Manifest will take priority. ### Auto-upload local dependencies Geneva can package your local environment and send it to Ray workers. This includes the current workspace root (if you're in a python repo) or the current working directory (if you're not). [`GenevaManifest.create_site()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_site) additionally uploads your Python site-packages (defined by `site.getsitepackages()`) to workers. This is not recommended for production use, as it is prone to issues like architecture mismatches of built dependencies, but it can be a good way to iterate quickly during development. To upload site packages: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.manifest import GenevaManifest db = geneva.connect(my_db_uri) manifest_name = "dev-manifest" manifest = GenevaManifest.create_site(manifest_name).build() db.define_manifest(manifest_name, manifest) ``` ### What's in a manifest? Here's a summary of what's in a manifest and how you can define it across the three manifest builder types. | Contents | How you can define it | Factory method | | - | - | - | | Local working directory (or workspace root, if in a python repo) | Will be uploaded automatically. | All | | Local python packages (site-packages) | Uploaded automatically. | [`create_site()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_site) | | Pip packages to be installed | Use [`.pip(packages: list[str])`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.pip) or [`.requirements_path(path: str)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.PipManifestBuilder.requirements_path). See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | [`create_pip()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_pip) | | Conda packages to be installed | Use [`.conda(deps: dict[str, Any])`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda) or [`.conda_environment_path(path: str)`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.builder.CondaManifestBuilder.conda_environment_path). See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | [`create_conda()`](https://lancedb.github.io/geneva/api/manifest/#geneva.manifest.mgr.GenevaManifest.create_conda) | | Local python packages outside of `site_packages` | Use `.py_modules(modules: list[str])` or `.add_py_module(module: str)`. See [Ray's RuntimeEnv docs](https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_env.RuntimeEnv.html) for details. | All | | Container image for head node | Use `.head_image(head_image: str)` or `default_head_image()` to use the default. Note that, if the image is also defined in the GenevaCluster, the image set here in the Manifest will take priority. | All | | Container image for worker nodes | Use `.worker_image(worker_image: str)` or `default_worker_image()` to use the default for the current platform. As with the head image, this takes priority over any images set in the Cluster. | All | If you want to see exactly what is being uploaded to the cluster, set `.delete_local_zips(False)` and `.local_zip_output_dir(path)` then examine the zip files in `path`. ## Putting it all together: Execution Contexts An execution context represents the concrete execution environment (Cluster and Manifest) used to execute a distributed job. Calling `context` will enter a context manager that will provision an execution cluster and execute the Job using the Cluster and Manifest definitions provided. Because you've already defined the cluster and manifest, you can just reference them by name. Note that providing a manifest is optional. Once completed, the context manager will automatically de-provision the cluster. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = geneva.connect(my_db_uri) tbl = db.get_table("my_table") with db.context(cluster=cluster_name, manifest=manifest_name): tbl.backfill("embedding") ``` In a notebook environment, you can manually enter and exit the context manager in multiple steps like so: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ctx = db.context(cluster=cluster_name, manifest=manifest_name) ctx.__enter__() # ... do stuff ctx.__exit__(None,None,None) ``` ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `context()`, `local_ray_context()`, `list_clusters()`, `list_manifests()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `LocalRayClusterBuilder`, `ExternalRayClusterBuilder`, and worker configuration classes * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — `PipManifestBuilder`, `CondaManifestBuilder`, `SiteManifestBuilder` # Geneva Jobs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/index Learn about Geneva's job execution framework for distributed feature engineering workflows. Geneva provides a comprehensive job execution framework for distributed feature engineering workflows. This section covers the different types of jobs and execution contexts available in Geneva. ## Job Types ### [Backfilling](/oss/v0-41-0/geneva/jobs/backfilling/) Trigger distributed jobs to populate column values in your LanceDB table using UDFs. Learn about filtered backfills and incremental updates. ### [Materialized Views](/oss/v0-41-0/geneva/jobs/materialized-views/) Create declarative materialized views to manage batch updates of expensive operations. Optimize data layouts for training and simplify orchestration. ### [Startup Optimizations](/oss/v0-41-0/geneva/jobs/startup/) Optimize job and session startup times for faster interactive development and production workflows. Learn about caching, pre-warming, and performance tuning. ## Execution Contexts ### [Advanced Execution Contexts](/oss/v0-41-0/geneva/jobs/contexts/) Understand how Geneva automatically packages and deploys your Python execution environment to worker nodes for distributed execution. ### [Geneva Console](/oss/v0-41-0/geneva/jobs/console/) Set up and access the Geneva Console for monitoring and managing Geneva jobs, clusters, and execution contexts. ## Key Features * **Distributed Processing**: Scale feature computation across multiple nodes * **Checkpointing**: Resume jobs from failures without losing progress * **Incremental Updates**: Only process new or modified data * **Distributed Execution**: Run jobs on Kubernetes or standalone compute clusters * **Environment Management**: Automatic dependency packaging and deployment ## Getting Started 1. **Choose your execution context** based on your infrastructure 2. **Define your UDFs** for feature computation 3. **Trigger backfill operations** to populate your data 4. **Monitor performance** and optimize based on usage patterns For detailed information about each job type and execution context, explore the documentation in this section. ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `backfill_async()`, `refresh()`, `plan_backfill()`, `plan_refresh()`, and other job-triggering methods * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()`, `context()`, and `local_ray_context()` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — configure KubeRay and local Ray execution backends * [Manifest](https://lancedb.github.io/geneva/api/manifest/) — package Python environments for remote workers # Job Metrics (Diagnostics) Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/job_metrics Use Geneva Job Metrics to monitor and troubleshoot jobs in real time. ## How to find metrics Job metrics can be found in the [Geneva Console UI](/oss/v0-41-0/geneva/jobs/console), by clicking on a job's ID to get to the "Job details" page. ## Core diagnostic metrics | Metric | What it means | Common signal | | - | - | - | | `rows_checkpointed` | Rows finished by read/UDF/checkpoint stage. | High value means upstream compute is progressing. | | `rows_ready_for_commit` | Rows ready for atomic commit (becoming visible to other DB connections). | If much lower than `rows_checkpointed`, writer path is likely bottlenecked. | | `rows_committed` | Rows already visible to other DB connections. | If lagging far behind `rows_ready_for_commit`, commit stage may be bottlenecked. | | `cnt_geneva_workers_active` | Current parallel UDF executors. | Lower than expected means reduced effective parallelism. | | `cnt_geneva_workers_pending` | Deficit from desired parallelism. | Persistently high value usually means scheduling/resource pressure. | | `read_io_time_ms` | Cumulative read IO time. | Dominant value suggests storage/read bottleneck. | | `udf_processing_time` | Cumulative UDF execution time. | Dominant value suggests compute/UDF bottleneck. | | `batch_checkpointing_time` | Cumulative batch checkpoint overhead. | High value suggests checkpoint overhead is expensive. | | `writer_write_time` | Cumulative writer output time. | High value often points to object storage throughput/throttling issues. | | `writer_queue_wait_time_ms` | Cumulative writer queue wait time. | High value can indicate writer starvation/backpressure. | | `commit_time_ms` | Cumulative commit time. | High value means commit itself is expensive. | | `commit_conflict_retries` | Commit retries due to version conflicts. | Non-trivial counts indicate commit contention. | | `commit_backoff_time_ms` | Time spent backing off during commit retries. | High value indicates contention/retry pressure. | | `commit_concurrent_writer_retries` | Retries from "Too many concurrent writers". | High value indicates writer concurrency contention. | ## Quick diagnosis workflow 1. Check `rows_checkpointed` vs `rows_ready_for_commit`. * If `rows_checkpointed` is high but `rows_ready_for_commit` is low, fragment writer is usually the bottleneck. * This often indicates object storage read/write pressure (for example S3). 2. Compare read, UDF, and checkpoint timing. * High `read_io_time_ms`: storage or scan bottleneck. * High `udf_processing_time`: UDF compute bottleneck. * High `batch_checkpointing_time`: checkpoint overhead bottleneck. * Typical mitigations: increase `checkpoint_size`, increase `max_checkpoint_size`, or compact the table to produce larger fragments. 3. Check writer timing. * High `writer_write_time` is commonly object storage throttling/throughput limit. * Typical mitigations: use higher network-bandwidth node types, and keep object storage and compute nodes in the same region. 4. Check commit pressure. * High `commit_conflict_retries`, `commit_backoff_time_ms`, or `commit_concurrent_writer_retries` indicates commit contention. 5. Check parallelism deficit. * If `cnt_geneva_workers_pending` stays high while `cnt_geneva_workers_active` stays low, the job is running below desired parallelism due to cluster/resource constraints. ## Notes * Timing metrics are cumulative and may overlap; do not sum them as exact wall time. * For completed jobs, row counters should settle to stable final values. # Job Lifecycle Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/lifecycle Understanding how Geneva jobs work, their lifecycle states, and how to monitor and manage them. Geneva uses background jobs to execute long-running operations like backfills and materialized view refreshes. This guide explains how jobs work, their lifecycle states, and how to monitor and manage them. ## Overview Jobs in Geneva are asynchronous operations that process data in the background. There are two primary job types: | Job Type | Purpose | Created By | | - | - | - | | **Backfill** | Compute column values using UDFs | `table.backfill()` | | **Materialized View Refresh** | Update precomputed query results | `view.refresh()` | Both job types share the same lifecycle states and monitoring capabilities. ## Job States Every job progresses through a well-defined state machine: ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} stateDiagram-v2 [*] --> PENDING PENDING --> RUNNING RUNNING --> DONE RUNNING --> FAILED DONE --> [*] FAILED --> [*] ``` | State | Description | | - | - | | **PENDING** | Job has been created and is queued for execution | | **RUNNING** | Job is actively processing data | | **DONE** | Job completed successfully | | **FAILED** | Job encountered an error during execution | ## Monitoring Jobs The [Geneva Console](/oss/v0-41-0/geneva/jobs/console) provides a web-based interface for monitoring job status, progress, and history across your database. This is the recommended way to track jobs in collaborative environments. For programmatic access, you can query job status directly via the API: ### Querying Job Status ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva db = geneva.connect("/path/to/db") # Get job state manager jsm = db._history # Get a specific job job = jsm.get(job_id)[0] print(f"Status: {job.status}") print(f"Started: {job.launched_at}") print(f"Completed: {job.completed_at}") # List jobs for a table pending_jobs = jsm.list_jobs(table_name="my_table", status="PENDING") running_jobs = jsm.list_jobs(table_name="my_table", status="RUNNING") ``` ### Progress Metrics Jobs report progress through metrics: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Access job metrics for metric in job.metrics: print(f"{metric['name']}: {metric['count']}/{metric['total']}") ``` Common metrics include: | Metric | Description | | - | - | | `fragments` | [Fragments](https://lance.org/format/table/?h=fragment#fragments) scheduled for processing | | `writer_fragments` | Fragments written to storage | | `udf_values_computed` | Rows processed by UDFs | | `rows_checkpointed` | Rows saved to checkpoint store | | `rows_committed` | Rows committed to the table | | `workers` | Workers started for parallel execution | ### Job Events Jobs log significant events during execution: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for event in job.events: print(f"{event['timestamp']}: {event['message']}") ``` Example events: * "Job started" * "Checkpointing complete for fragment 42" * "Partial commit: 64 fragments" * "Job completed successfully" ## Fault Tolerance Geneva jobs are designed to be resilient to failures: ### Checkpoint-Based Recovery Jobs save intermediate results to a checkpoint store. If a job fails: 1. **Completed work is preserved** - Checkpointed batches are not lost 2. **Resume from checkpoint** - Restarted jobs skip already-processed data 3. **No duplicate processing** - Each batch is processed exactly once By default, checkpoints are stored in a `_ckp/` subdirectory inside the table's storage location. At scale, you can redirect checkpoints to a separate bucket to avoid IOPS contention. See [Checkpoint Storage configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration#checkpoint-storage) for details. ### Resuming Failed Jobs To resume a failed job, simply re-run the same backfill or refresh command. The job will automatically detect existing checkpoints, skip already-processed fragments, and continue from where it left off. ## API Reference * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `backfill_async()`, `refresh()`, `JobFuture` * [Connection](https://lancedb.github.io/geneva/api/connection/) — `get_job()`, `list_jobs()` # Materialized Views with UDFs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/materialized-views Learn how to use Geneva's materialized view feature to declaratively manage batch updates of expensive operations using UDFs. Geneva provides a materialized view feature that can be used to declaratively manage "batch" updates of expensive operations such as populating UDF columns. These updates are triggered via refresh operation. This can be used to optimize data layouts for training and to simplify some operations that traditionally may require external procedural orchestration (airflow, prefect, dagster). > **Note**: This is similar to how traditional databases offer a materialized view feature to declaratively manage expensive aggregation and join operations. ## Process Overview The process is straightforward: 1. Define a query on table, optionally including UDFs in the select clause. 2. Create the materialized view using `db.create_materialized_view(...)`. 3. Populate the new materialized view table using the `refresh` operation. Just like with backfills, this operation is incremental, checkpointed, and run in a distributed manner. ## Example Let's walk through an example using a raw video table as a base. We want to create a materialized view off the table that adds transcription columns to a subset of the values. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import connect, udf import pyarrow as pa db = connect("/path/to/lancedb") schema = pa.schema([ pa.field("video_id", pa.int64(), nullable=False), pa.field("video_uri", pa.string(), nullable=False), pa.field("upload_ts", pa.timestamp("us"), nullable=False), pa.field("metadata", pa.json(), nullable=True), ]) raw_videos = db.create_table( "raw_videos", schema=schema, primary_key="video_id" ) ``` Define the transforms, then create an empty materialized view. This example uses video paths accessible to the workers. Install `openai-whisper` in the worker environment before running the transcription transform. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf def transcribe(video_uri: str) -> str: from whisper import load_model model = load_model("base") return model.transcribe(video_uri)["text"] @udf(data_type=pa.binary()) def load_video(video_uri: str) -> bytes: from pathlib import Path return Path(video_uri).read_bytes() q = ( raw_videos.search(None) .shuffle(seed=42) .select( { "video_uri": "video_uri", "video": load_video, "transcription": transcribe, } ) ) view_table = db.create_materialized_view("table_view", q) ``` To populate the values, we call `refresh`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # explicitly copy values from the source table, applying UDF on cols. db.refresh("table_view") ``` Note that the UDF is stored on the destination materialized view table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} raw_table.add(...) db.refresh("table_view") # only materialize new or modified rows. ``` The operation is incremental. So the next time refresh on the table is called, only new fragments with new data get materialized into the materialized view table. Materialized views are just tables so you can query them as well as modify them by adding new `add_columns`, `backfill` particular columns and deriving other materialized views or views from them. Reference: * [`create_materialized_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_materialized_view) ## FAQ ### Do we copy the UDFs from the source table? No. The UDF does not but any UDF calculated values in the original table come to the materialized table via refresh. New columns defined by the UDFs in the materialized view creation are attached only to the materialized view. They can be backfilled (since the UDF belongs to the view) or refreshed. ### On MV refresh, do we force materialization of UDFs cols on the source table? No. They are managed at the source table only. If it is null the null values are propagated. Future options may force materialization/backfill "recursively". ## API Reference * [Connection](https://lancedb.github.io/geneva/api/connection/) — `create_materialized_view()`, `create_view()` * [Table](https://lancedb.github.io/geneva/api/table/) — `refresh()`, `plan_refresh()` * [Query](https://lancedb.github.io/geneva/api/query/) — `create_materialized_view()` on query builder # Distributed Job Performance and Cluster Sizing Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/performance Learn how to tune Geneva distributed job performance by scaling compute resources and balancing write bandwidth. When Geneva runs in distributed mode, jobs are deployed against a Kubernetes KubeRay instance that dynamically provisions a Ray cluster. Job execution time depends on sufficient CPU/GPU resources for *computation* and sufficient *write bandwidth* to store the output values. Tuning the performance of a job boils down to configuring the table or cluster resources. ## Geneva defaults Geneva sets the following defaults when creating a KubeRay cluster via GenevaClusterBuilder. These apply as both Kubernetes requests and limits. ### Head Node | Resource | Default | | - | - | | CPU | 4 | | Memory | 8 GiB | | GPU | 0 | | Node Selector | `geneva.lancedb.com/ray-head: true` | | Service Account | `geneva-service-account` | The head node runs the Ray GCS (Global Control Store), the driver task, and the dashboard. It does not run UDF applier actors. ### CPU Workers | Resource | Default | | - | - | | CPU | 4 | | Memory | 8 GiB | | GPU | 0 | | Node Selector | `geneva.lancedb.com/ray-worker-cpu: true` | | Replicas | 1 (min: 0, max: 100) | | Idle Timeout | 60 seconds | ### GPU Workers | Resource | Default | | - | - | | CPU | 8 | | Memory | 16 GiB | | GPU | 1 | | Node Selector | `geneva.lancedb.com/ray-worker-gpu: true` | | Replicas | 1 (min: 0, max: 100) | | Idle Timeout | 60 seconds | ## Scaling computation resources Geneva jobs can split and schedule computational work into smaller batches that are assigned to *tasks* which are distributed across the cluster. As each task completes, it writes its output into a checkpoint file. If a job is interrupted or run again, Geneva will look to see if a checkpoint for the computation is already present and if not will kick off computations. Usually computation capacity is the bottleneck for job execution. To complete all of a job's tasks more quickly, you just need to increase the amount of CPU/GPU resources available. ### Estimating CPU and memory requirements #### CPU Geneva can run up to `concurrency` tasks in parallel. Within each task, it can run up to `intra_applier_concurrency` UDF applications concurrently. If your UDF requests `udf.num_cpus` CPUs, the peak CPU required is approximately: `total_cpus ≈ concurrency * intra_applier_concurrency * udf.num_cpus` `concurrency` and `intra_applier_concurrency` are parameters on `Table.backfill(...)`. In most cases you do not need to change `udf.num_cpus`, unless the UDF itself uses multiple threads. If your UDF is single-threaded but you want to speed it up with more parallelism, prefer increasing `concurrency` first. If you stop seeing meaningful improvements, then try increasing `intra_applier_concurrency`. #### Memory Geneva defaults to checkpoint batches of up to 100 rows (`checkpoint_size=100`). Peak memory usage scales with both the input rows held for processing and the output rows buffered before they are written. A rough upper bound is: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} memory_bytes ≈ input_row_size * min(checkpoint_size * worker_num_cpus, task_size) + output_row_size * min(checkpoint_size * intra_applier_concurrency, task_size) ``` * `worker_num_cpus` is the number of CPUs on the Ray worker. * `task_size` is a tunable parameter (rows per task). It can be set on the UDF (e.g. `@udf(..., task_size=...)`) and on `Table.backfill(..., task_size=...)` (backfill-level values take precedence). If `task_size` is larger than the number of rows in a fragment, it behaves the same as `task_size = fragment_num_rows`. By default, it is: `task_size = num_rows / (concurrency * intra_applier_concurrency * 2)` (where `num_rows` is the number of rows in the table, or the number of rows selected by your filter) * `input_row_size` / `output_row_size` are the average bytes per row after materialization in memory. For primitive numeric columns (ints/floats), these sizes are usually small. For images, videos, embeddings, etc. you may need to explicitly provision more memory (e.g. via `@udf(..., memory=...)`) and/or reduce `checkpoint_size` / `task_size`. Typical per-row sizes: * Images: \~200KB–2MB (depends on dataset and encoding) * Videos: \~10MB–200MB * Embeddings: `dimension * data_type_size` bytes (e.g. float32 embeddings use 4 bytes per value, so a 1536-dim embedding is `1536 * 4 = 6144` bytes) #### Internal Actor Resource Overhead In addition to UDF applier actors, each backfill job creates internal actors that consume resources: | Component | CPU | Memory | Count | | - | - | - | - | | Driver task | 0.1 | — | 1 | | JobTracker | 0.1 | 128 MiB | 1 | | Writer actors | 0.1 | 1 GiB | 1 per applier | | Queue actors | 0 | — | 1 per applier | | Applier actors | UDF `num_cpus * intra_applier_concurrency` | UDF memory | `concurrency` | #### Example For a job with `concurrency=4`, `intra_applier_concurrency=2`, with a UDF that requests 1 CPU and 1GiB memory: | Component | CPU | Memory | Count | | - | - | - | - | | Driver task | 0.1 | — | 1 | | JobTracker | 0.1 | 128 MiB | 1 | | Writer actors | 0.1 | 1 GiB | 4 | | Queue actors | 0 | — | 4 | | Applier actors | 1×2=2 | 1 GiB | 4 | | Total | 0.1 + 0.1 + 4×0.1 + 4×2 = **8.6** | 128 MiB + 4×1GiB + 4×1GiB = **8.125 GiB** | | ### Overall Cluster Sizing Of course, the size of a cluster will vary dramatically for each task. But if you don't know how to estimate your workload, we can recommend the following cluster sizes as a starting point: | Cluster Size | Head Node | Workers | | - | - | - | | **Small** (Dev / CI) | 1 CPU, 8 GB | 4 x 2 CPU, 8 GB | | **Medium** (Staging) | 2 CPU, 8 GB | 4 x 4 CPU, 8 GB | | **Large** (Production) | 4 CPU, 8 GB | 8+ x 8 CPU, 16 GB | ### Validation Thresholds The cluster builder validates memory configuration and warns or errors on suspicious values: | Threshold | Value | Behavior | | - | - | - | | GPU worker minimum memory | `< 4 GiB` | **Error** — build fails if below this | | Large memory warning | `> 100 GB` | **Warning** — may exceed K8s node capacity | | Memory-per-CPU ratio warning | `> 16 GiB per CPU` | **Warning** — unusual ratio, likely misconfigured | ### GKE node pools GKE + KubeRay can autoscale the number of VM nodes on demand. Limitations on the amount of resources provisioned are configured via [node pools](https://cloud.google.com/kubernetes-engine/docs/how-to/node-pools#scale-node-pool). Node pools can be managed to scale vertically (type of machine) or horizontally (# of nodes). Properly applying Kubernetes labels to the node pool machines allows you to control resources for different jobs in your cluster. ### Options on `Table.backfill(..)` The `Table.backfill(..)` method has several optional arguments to tune performance. To saturate the CPUs in the cluster, the main arguments to change are `concurrency` which controls the number of task processes and `intra_applier_concurrency` which controls the number of task threads per task process. `commit_granularity` controls how frequently fragments are committed so that partial results can become visible to table readers. Setting `checkpoint_size` smaller introduces finer-grained checkpoints and can help provide more frequent proof of life as a job is being executed. This is useful if the computation on your data is expensive. Reference: * [`backfill` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill) * [`backfill_async` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.backfill_async) ## Balancing write bandwidth While computation can be broken down into small tasks, new Lance column data for each fragment must be written out in a serialized fashion. Each fragment has a writer that waits for checkpointed results to arrive, sequences them, and then serially writes out the new data file. Writers can be a bottleneck if a Lance dataset has a small number of fragments, especially if the amount of data being written out is comparatively large. Maximizing parallel write throughput can be achieved by having more fragments than nodes in the cluster. ### Symptom: Computation tasks complete but writers seem to hang Certain jobs that take a small dataset and expand it may appear as if the writer has frozen. An example is a table that contains a list of URLs pointing to large media files. This list is relatively small (\< 100MB) and can fit into a single fragment. A UDF that downloads will fetch all the data and then attempt to write all of it out through the single writer. This single writer can then be responsible for serially writing out 500+GB of data to a single file! To mitigate this, you can load your initial table so that there will be multiple fragments. Each fragment with new outputs can be written in parallel with higher write throughput. ## API Reference * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `CpuWorkerBuilder`, `GpuWorkerBuilder` — configure CPU/GPU/memory resources * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `compact_files()`, `optimize()` * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator options: `num_cpus`, `num_gpus`, `memory`, `batch_size` # Job and Session Startup Optimizations Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/startup Learn how to optimize Geneva job and session startup times for faster interactive development and production workflows. During interactive sessions, there are two main actions where you would interact with Geneva. * Compute cluster creation * Job execution Behind the scenes, Geneva packages your python environment and auto-provisions nodes to execute the jobs. This can be time consuming, taking on the order of 5mins to complete before any work is done. The following sections will describe what happens in these steps and how to diagnose and speed up these interactions. ## Compute cluster creation To execute a Geneva job, you'll need to initialize a compute environment. Here's the basic steps Geneva takes to instantiate that cluster: * User requests a cluster * Scan workspace's python path for modules * Generate local workspace directory zip * Generate python site-packages directory zip(s) * Generate other dirs zip (may include your .venv) * Upload zips * Provision head node * Initialize head node The requests to create an environment can take 5-10 mins to initiate. The most time-consuming steps are generating directory zips and uploading them. AI workloads often require many module packages and can be dependent on specific versions to work. Common modules required for GPU use to run model inferrence can easily be 5GB-10GB of compressed content. On GCE for example, this can take \~5mins to zip all this and \~1min to upload all of this data. To speed this up, Geneva employs caching to help optimize the startup time. There are a few things you can do to make subsequent runs faster, often times \<1 minute: ### Hashing and Caching Geneva generates a hash of each path in the python path that takes into account files and their last modified time. After the first time a directory zip is created and uploaded, the cached copy is used and no new zip is generated or uploaded. However, if there are any changes (e.g. new module added or upgraded) a new hash created and the environment's content is zipped and uploaded. ### Isolate dynamic code and modules If you use a Jupyter notebook environment for your driver, the content of the `.ipynb` file is constantly changing. This means the hash for the directory that contains the notebook will change, even if the subdirectories do not. If your notebook is in your home directory, this could pull in large amounts unneeded code and data. To avoid this you can move your notebook into a subdirectory with no children. When your notebook is executed it is updated but only the notebook content is resent. Other path directories are unchanged, have the same hash and can skip zip and ship. ### Package dependecies into a docker image Geneva has an option to skip the zip and ship of the site-packages. Enabling this assumes that the default docker image is overriden with a custom image that has the `site-package` content preloaded. ### Pre-provision nodes and pods: In your kubernetes configuration, you can tag specific nodes with `geneva.lancedb.com/ray-head` k8s label. These nodes should be configured to be on non-spot instances that are always up. This makes initial kuberay cluster creation quick. ## Job execution A backfill or materialized view jobs triggers the provisioning of worker nodes that will perform the computations and writes. A cold start can be slow because several steps must take place before the UDFs can be applied. However, once nodes and pods are warmed up, the time between submission and execution can be quick. Here's the basic steps Geneva takes to kick off a Geneva job: * User submits job (backfill) * plan scans * provision worker nodes (vms) * load vm * Autoscale workers nodes * provision worker nodes (vms) * load vm * schedule ray actors * download docker images * download zips * execute udf * orchestrate fragment write. In practice, planning the initial distributed step scans require loading vm and pod images. With a cold start, this can take \~5 minutes. Here are some steps you can take to pre-warming worker nodes and pods so that exectuion can be more interactive: **Set worker spec's replicas or min_replicas to a value >0:** When the kuberay cluster is instantiated this also pre-provision vm's so they are ready for k8s to place pod. replicas (for initial # of worker nodes), and minWorkers (to keep a pool for nodes always up) **Make a warmup call:** Making an initial request to ray will load the pod and zips content to the worker node so that subsequent startups will be fast. **Prevent nodes from auto-scaling down:** During cluster creation, you can specify `idle_timeout_seconds` option -- this is the amount of time before a node needs to be idle before it is considered for de-provisioning. # Troubleshooting Geneva Jobs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/jobs/troubleshooting Diagnose and fix common issues when running Geneva backfills, materialized views, and other distributed jobs. This page covers common problems you may hit while running Geneva jobs and how to resolve them. For deployment and cluster issues, see [Troubleshooting Geneva Deployments](/oss/v0-41-0/geneva/deployment/troubleshooting). ## Admission control and resource errors Geneva runs **admission control** before starting a job to check that the cluster has enough resources. If the check fails, the job is rejected with `ResourcesUnavailableError` (or a warning if admission is not strict). ### "Job requires GPUs but cluster has no GPU worker groups configured" Your UDF requests GPUs but the cluster has no GPU nodes. **Check your UDF:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @geneva.udf(num_gpus=1) # This requires GPUs def my_udf(x): ... ``` **Fix options:** 1. Remove the GPU requirement if the UDF can run on CPU: `@geneva.udf(num_gpus=0)` (or omit `num_gpus`). 2. Make sure you have a GPU worker group; e.g. in your ClusterBuilder: ``` KubeRayClusterBuilder.create() ... .add_worker_group( KubeRayClusterBuilder.gpu_worker(1) .image(get_ray_image(ray.__version__, _py, gpu=True)) .service_account("geneva-service-account") .node_selector({"geneva.lancedb.com/ray-worker-gpu": "true"}) .build() ) ``` 3. Add GPU worker nodes to your cluster and ensure the cluster definition includes a GPU worker group with the correct node selector (e.g. `"geneva.lancedb.com/ray-worker-gpu": "true"`). ### "UDF requires X CPUs + Y GPUs but no worker group can satisfy all requirements." Of course, if your cluster doesn't have enough GPUs, add them! But if you're surprised how many CPUs/GPUs your UDF is requesting, it may be because of concurrency. Your tasks's actual CPU/GPU requirement is `concurrency × CPUs/GPUs per task`. **Fix:** Lower `concurrency` so that the total CPUs/GPUs needed (concurrency × CPUs/GPUs per task) does not exceed the cluster's CPU/GPU count. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Before: backfill with `num_gpus(1)` needs 8 GPUs table.backfill("col", concurrency=8) # After: cap at 4 GPUs table.backfill("col", concurrency=4) ``` ### "No single node can satisfy all requirements" The UDF asks for a combination of CPU, memory, and GPU that no single node in the cluster has. This often happens on heterogeneous clusters. **Example:** Node A has 8 CPUs and 4 GB memory; Node B has 4 CPUs and 8 GB memory. A UDF that needs 8 CPUs and 8 GB cannot be placed on either node. **Fix options:** 1. **Reduce UDF resource requests** so they fit on your smallest target node (e.g. lower `num_cpus` or memory). 2. **Add larger nodes** that can satisfy CPU, memory, and GPU together. 3. **Use a homogeneous cluster** where nodes have the same shape. ### Job passes admission but hangs at low progress If admission control passes but the job stalls at a low percentage: **1. Ray dashboard – see what’s actually running** * **Local Ray:** After starting a local cluster, Ray usually prints the dashboard URL (e.g. `http://127.0.0.1:8265`). Open that in a browser. If you didn’t capture it, the dashboard is typically on port **8265** on the host where Ray was started. * **KubeRay (Kubernetes):** Port-forward the dashboard from the Ray head pod, then open it locally: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Find the Ray head pod (replace NAMESPACE and cluster name as needed) kubectl get pods -n NAMESPACE -l ray.io/node-type=head # Forward the dashboard port (Ray uses 8265 for the dashboard) kubectl port-forward -n NAMESPACE POD_NAME 8265:8265 ``` Then open **[http://localhost:8265](http://localhost:8265)** in your browser. * **External Ray cluster:** Use the dashboard URL your cluster operator provides (often the head node’s port 8265). **What to look for in the dashboard:** * **Actors** (or **State** → **Actors**): A long list of actors stuck in **PENDING** means Ray cannot place them (e.g. not enough CPUs, GPUs, or memory on any node). That matches “admission passed but nothing runs.” * **Tasks / Jobs:** If your Geneva job shows as a Ray job, open it and check for tasks that stay **PENDING** or **RUNNING** for a long time without finishing. Pending tasks often mean insufficient resources or that workers aren’t joining. * **Cluster / Nodes:** Check that worker nodes are **ALIVE** and that **Available** resources (CPU, memory, GPU) are not zero. Dead or overloaded nodes can cause jobs to hang. * **Unprovisioned GPUs:** Sometimes the CSP doesn't have enough GPUs available, so even though you have correctly requested them, the job may be unable to run. In this case, run on CPU if possible, or try your job again later. **2. Memory pressure** If nodes are full or workers are being OOM-killed, the job can stall or fail. In the Ray dashboard, check node memory usage; in Kubernetes, check pod restarts (`kubectl get pods -n NAMESPACE`) and pod logs for OOM. Also try reducing `concurrency` or the UDF’s memory request, even slightly. **3. Writers / queues** Geneva uses Ray actors for writers and queues. If the job is stuck at a fixed percentage, writers may be blocked (e.g. on storage or version conflicts). Check Ray dashboard **Actors** for writer-like actors that stay **RUNNING** but make no progress, and check cluster or pod logs for errors from Geneva (e.g. commit or connection errors). You can relax or skip admission to narrow down whether the failure is admission vs. scheduling: set `GENEVA_ADMISSION__CHECK=false` or use `_admission_check=False` on the backfill (for testing only). See [Advanced configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration/) for more details. *** ## Ray connection and startup ### "Geneva was unable to connect to the Ray head" The client could not connect to the Ray cluster (e.g. after starting a KubeRay or external cluster). **Common causes:** * **Head not ready** – The Ray head pod may still be starting. Wait a bit and retry, or increase `GENEVA_RAY_INIT_MAX_RETRIES` (default 5). * **Image/architecture mismatch** – The Ray head image may not match the node architecture (e.g. arm64 vs x64). Use an image built for the same architecture as your nodes. (the function [`get_ray_image`](https://lancedb.github.io/geneva/api/utils/) can help find the right image name.) * **Network / firewall** – If using an external Ray cluster, ensure the `ray://` address is reachable and that no firewall is blocking the Ray client port. **Quick check:** From the same network as the client, try connecting with `ray.init("ray://<host>:<port>")` in a small script to see the exact error. ### Ray client "already connected" or init fails on retry If you see errors about the client already being connected (e.g. when re-running a notebook or script), ensure you're not holding an old Ray client connection. Restart the kernel or process so Ray is re-initialized cleanly. Geneva disconnects the client when the context exits; leaving a context open or reusing a stale connection can cause this. ### Head node out of memory If the head node is under-provisioned (e.g. 1 CPU / 2 GB), it can OOM when: * Many workers connect and register with GCS * The Ray dashboard accumulates metrics * Object store spillover occurs **Recommendation**: Use at least 4 CPU / 8 GiB for the head node in any non-trivial deployment. This is the current default. *** ## Serialization library or `attrs` version mismatch Ray and Geneva use cloudpickle and can be sensitive to library versions. If you see `TypeError: Enum.__new__() missing 1 required positional argument: 'value'` or similar pickling errors with no obvious non-serializable object, ensure **client and cluster use the same Python minor version and compatible library versions** (e.g. same `attrs`). Run the job from a machine with the same OS/architecture as the workers when possible so that shipped environments match. *** ## Permissions and storage ### GCS / S3 permission denied in job logs Workers run under a Kubernetes service account (and possibly a cloud IAM role). If you see `PermissionError`, `storage.objects.get` denied, or 403 from object storage: 1. **Service account** – Confirm the Geneva Ray head and worker specs use the intended `service_account`. That account must have read/write to the bucket (e.g. GCS `roles/storage.objectUser` or equivalent S3 permissions). 2. **Workload identity** – On GKE, bind the K8s service account to a Google service account with bucket access. On EKS, use IRSA or node IAM so the pod role can access the bucket. See [Troubleshooting Geneva Deployments](/oss/v0-41-0/geneva/deployment/troubleshooting) for permission examples and service account configuration. *** ## Version conflicts and commit retries ### Version conflicts during commit Concurrent backfills or other writers can cause version conflicts when committing. Geneva retries with merging; if conflicts persist, you may see repeated retries or failures. **Options:** * Reduce concurrency or avoid overlapping backfills to the same table/fragments. * Tune retries (e.g. `GENEVA_VERSION_CONFLICT_MAX_RETRIES`, default 10) if you expect transient contention. See [Advanced configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration/). ### Writer stalls or commit timeouts If writers are slow (e.g. under resource contention), they may be considered stalled and restarted. You can increase the idle tolerance with `GENEVA_WRITER_STALL_IDLE_ROUNDS` (default 6 rounds of 5s). For commit timeouts or transient storage errors, `GENEVA_COMMIT_MAX_RETRIES` (default 12) controls how many times Geneva retries the commit. *** ## Materialized views ### Matview refresh fails with resource errors Refreshing a materialized view runs admission control for each UDF in the view. If any UDF’s resource requirements cannot be satisfied, the refresh fails. Ensure the cluster has enough resources for **all** UDFs used in the view (same as for a single backfill), and that no single UDF asks for more than any one node can provide. *** ## Quick checks before running a job * **Versions** – Same Ray version on client and cluster; same Python minor (e.g. 3.10.x) on both. See [Troubleshooting Geneva Deployments](/oss/v0-41-0/geneva/deployment/troubleshooting#confirming-dependency-versions). * **Remote execution** – Use `ray.available_resources()` and a simple `@ray.remote` task to confirm the cluster is reachable and has the expected CPUs/GPUs/memory. * **Permissions** – Run a minimal remote task that `import geneva` and touches the same bucket/path as your job to surface permission issues early. ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator options: `num_gpus`, `num_cpus`, `memory` * [Cluster](https://lancedb.github.io/geneva/api/cluster/) — `KubeRayClusterBuilder`, `CpuWorkerBuilder`, `GpuWorkerBuilder` * [Table](https://lancedb.github.io/geneva/api/table/) — `backfill()`, `refresh()` * [Error Handling](https://lancedb.github.io/geneva/api/error_handling/) — `FatalWorkerOOMError`, `FatalWorkerCrashError`, and other worker error types # What is Feature Engineering? Source: https://docs.lancedb.com/oss/v0-41-0/geneva/overview/index Learn how to transform raw data into meaningful features for AI models using LanceDB's feature engineering capabilities. Scale your feature engineering workflows with distributed processing and UDFs. This section introduces the concept of feature engineering using an example of a product recommendation system. [YouTube video player](https://www.youtube.com/embed/VAO4407nHTM?si=mwS7m8aArzvFR_8T) For your AI models to work well — whether for search, recommendations, or anything else — you need good data. But raw data is usually messy and incomplete. Before you can train a model or use it for search, you have to turn that raw data into clear, meaningful features. Feature engineering is the process of cleaning up your data and creating new signals that actually help your model learn or make better predictions. This step is just as important for preparing training data as it is for powering your AI in production. It can take some work to get from raw data to useful features. Let's look at a simple example to see why this matters and how it's done. ## The Challenge: Manual Feature Engineering Imagine you are building a product recommendation system for a large e-commerce platform. The goal is to find items that are genuinely "similar" to a product a user is currently viewing. This notion of "similarity" must be sophisticated. It goes far beyond a simple text match on the product description. It needs to incorporate nuanced business concepts like popularity, value, brand equity, and key product attributes. ### Step 1: The Raw Data Table We start with a raw data table in our data lakehouse. We'll call it `products_raw`. This table contains the basic, unprocessed information scraped from our product catalog. An embedding model could be applied directly to the `description` column for semantic search. However, that would only capture a fraction of the story. **Table: `products_raw`** | product_id | title | description | category | price | original_price | review_count | avg_rating | | :- | :- | :- | :- | :- | :- | :- | :- | | 101 | V-Neck Tee | "A soft, 100% cotton v-neck shirt." | T-Shirt | 25.00 | 25.00 | 1200 | 4.8 | | 102 | Designer Tee | "Limited edition organic cotton tee." | T-Shirt | 90.00 | 150.00 | 25 | 4.9 | | 103 | New Tee | "A new v-neck t-shirt." | T-Shirt | 22.00 | 22.00 | 1 | 5.0 | ### Step 2: The Problem with Raw Data Using this raw data to generate embeddings for a recommendation model is destined for failure. Critical business signals that define true product similarity are either misleading, hidden, or entirely absent. * **Misleading Popularity:** The "New Tee" boasts a perfect 5.0 rating, but with only a single review. Is it truly more "popular" or "better" than the "V-Neck Tee" with 1200 reviews and a 4.8 rating? A naive model would think so. This leads to poor recommendations. * **Missing Price Context:** The model sees a price of \$90.00 for the "Designer Tee." It has no intrinsic understanding that this represents a steep 40% discount. This is a powerful purchasing signal. The model also doesn't know how this price compares to the average price of other T-shirts. * **Hidden Attributes:** Key attributes like "organic" or "limited edition" are buried within the free-text `description`. They are invisible to any model that doesn't perform sophisticated text analysis. Yet, they are crucial for matching user preferences. ### Step 3: Manual Feature Engineering To address these challenges, a data scientist or ML engineer typically embarks on a manual, code-intensive journey. The goal is to extract hidden signals and craft new, meaningful features. This process often takes place in a Jupyter notebook. It involves several intricate steps. 1. **Engineer `popularity_score`:**\ To create a more accurate measure of popularity, combine the average rating with the volume of reviews. A common approach is to use logarithmic scaling. This prevents products with massive review counts from overwhelming the score. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} popularity_score = log(review_count + 1) * avg_rating ``` 2. **Engineer `price_tier`:**\ To help the model understand value, bucket raw prices into clear tiers such as 'budget', 'mid-range', or 'premium'. **Logic:**\ Use conditional logic (for example, `CASE WHEN` in SQL or `np.select` in Python) to assign a tier based on price thresholds. 3. **Engineer `discount_pct`:**\ To explicitly signal a "deal" to the model, calculate the discount percentage by combining the original and current prices. **Logic:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} discount_pct = (original_price - price) / original_price ``` 4. **Engineer `price_vs_cat_avg`:**\ To contextualize a product's price, compare it to the average price within its category. This requires an aggregation step to compute the average price per category. Then, calculate the feature for each product. **Logic:**\ For each product: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} price_vs_cat_avg = price / avg_price_for_category ``` 5. **Engineer `is_organic`:**\ To surface key product attributes, process the `description` text to identify important keywords. **Logic:**\ Use a regular expression or string search for the keyword "organic" to create a boolean (`true`/`false`) flag. Each of these steps requires careful data manipulation and domain knowledge. Iterative experimentation is also needed to ensure the resulting features are both accurate and useful for downstream models. ### Step 4: The Enriched Table After executing this complex chain of logic, we produce a new, enriched table. The features in this table are more potent and ready to be fed into an embedding model. This produces high-quality vectors for our recommendation system. **Table: `products_engineered`** | product_id | ... | popularity_score | price_tier | discount_pct | price_vs_cat_avg | is_organic | | :- | :- | :- | :- | :- | :- | :- | | 101 | ... | 33.6 | 'budget' | 0.0 | 0.54 | false | | 102 | ... | 15.9 | 'premium' | 0.4 | 1.95 | true | | 103 | ... | 3.5 | 'budget' | 0.0 | 0.47 | false | ## Why Use Feature Engineering? Manual feature engineering works for small datasets. However, things change dramatically at scale. In real-world production systems, you often need to process tens or hundreds of millions of records. Sometimes this must happen in real time. The logic that was simple in a notebook, such as aggregations, conditional logic, or text processing, becomes much harder to manage and execute efficiently. As data grows, so does complexity. You might need to generate features from new sources. These could include user behavior logs, images, or videos. This can involve running large-scale machine learning models for tasks like image captioning or text embedding. These tasks require significant compute resources and robust infrastructure. Managing this at scale means dealing with distributed systems, scheduling, and monitoring. You must ensure that feature pipelines are reliable and reproducible. Experimenting with new features or updating existing ones can require major engineering work. This slows down iteration and innovation. Infrastructure challenges, such as orchestrating batch and streaming jobs, handling dependencies, and scaling inference, often become the main bottleneck. In short, the biggest challenge in modern feature engineering is not just coming up with good features. It is also about building infrastructure that can handle complex, multimodal operations. The goal is to deliver fresh, high-quality features quickly and reliably at massive scale. ## API Reference * [`geneva.connect()`](https://lancedb.github.io/geneva/api/) — connect to a Geneva database * [Connection](https://lancedb.github.io/geneva/api/connection/) — manage tables, views, jobs, clusters, and manifests * [Table](https://lancedb.github.io/geneva/api/table/) — add columns, backfill, search, and manage table data * [UDF](https://lancedb.github.io/geneva/api/udf/) — define transforms as user-defined functions # Geneva Python SDK Source: https://docs.lancedb.com/oss/v0-41-0/geneva/reference LanceDB Feature Engineering Python SDK Reference > [card] [Geneva Python SDK Reference](https://lancedb.github.io/geneva/) > > Refer to the Geneva Python SDK reference documentation by clicking here. # Advanced Configuration Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/advanced-configuration Learn about environment variables for configuring Geneva behavior. Geneva supports various environment variables that start with `GENEVA_` to configure advanced behavior and fine-tune system settings. > [!TIP] > > All `GENEVA_` environment variables are optional and have sensible defaults. Only set them if you need to override the default behavior. ## Admission Control Admission control validates cluster resources before starting jobs to prevent failures due to insufficient resources. | Variable | Default | Description | | - | - | - | | `GENEVA_ADMISSION__CHECK` | `true` | Enable admission control checks. Set to `false` to skip all checks. | | `GENEVA_ADMISSION__STRICT` | `true` | If `true`, reject the job with `ResourcesUnavailableError` when resources are insufficient. If `false`, log a warning but allow the job to proceed. | | `GENEVA_ADMISSION__TIMEOUT` | `3.0` | Timeout in seconds for Ray API calls during admission control checks. Prevents hanging when the cluster is in a bad state. | ## Commit and Retry Configuration Control retry behavior for commits and version conflicts. | Variable | Default | Description | | - | - | - | | `GENEVA_COMMIT_MAX_RETRIES` | `12` | Maximum number of retries for commit operations. With exponential backoff (1s, 2s, 4s, 8s, 16s, then 16s capped), 12 retries gives \~2.5 minutes total wait time before giving up. | | `GENEVA_VERSION_CONFLICT_MAX_RETRIES` | `10` | Maximum number of retries for version conflicts during commit. Version conflicts occur when concurrent backfills commit to the same fragments. Prevents infinite loops when concurrent commits keep conflicting. | | `GENEVA_WRITER_STALL_IDLE_ROUNDS` | `6` | Number of idle rounds (5s each) before considering a writer stalled during drain. With many concurrent backfills, resource contention can slow writers without them being truly stalled. | ## Lance Retry Configuration This section configures retry logic for Lance I/O operations. Retries occur on `OSError`, `ValueError`, and `RuntimeError("Too many concurrent writers")` exceptions, and are retried with exponential backoff with jitter. | Variable | Default | Description | | - | - | - | | `GENEVA_RETRY_LANCE_ATTEMPTS` | `7` | Maximum number of retry attempts for Lance I/O operations. | | `GENEVA_RETRY_LANCE_INITIAL_SECS` | `0.5` | Initial wait time in seconds for exponential backoff when retrying Lance I/O operations. | | `GENEVA_RETRY_LANCE_MAX_SECS` | `120.0` | Maximum wait time in seconds for exponential backoff when retrying Lance I/O operations. | ## Checkpoint Storage > [!WARNING] > > Checkpoint storage configuration is **experimental**. The environment variable names and behavior may change in a future release. Configure where Geneva stores checkpoint data during job execution. Checkpoints enable fault-tolerant processing by saving intermediate results so that failed jobs can resume without reprocessing completed work. By default, Geneva stores checkpoints in a `_ckp/` subdirectory inside the table's own storage location. This means checkpoints share the same bucket and IOPS budget as the table data. You can override this to store checkpoints in a separate location. | Variable | Default | Description | | - | - | - | | `JOB__CHECKPOINT__OBJECT_STORE__PATH` | *(table dir)*`/_ckp/` | URI where checkpoint data is stored. When set, overrides the default in-table checkpoint location. Accepts any URI supported by Lance (e.g., `gs://bucket/path/checkpoints`, `s3://bucket/checkpoints`). | > [!TIP] > > This variable maps to the config path `job.checkpoint.object_store.path`. It can also be set via config files in `.config/` or `pyproject.toml` under the `[geneva]` section. ### Why use a separate checkpoint path? At scale, checkpoint I/O and data I/O compete for the same object store IOPS budget when they share a bucket prefix. Setting `JOB__CHECKPOINT__OBJECT_STORE__PATH` to a **different bucket or prefix** decouples checkpoint I/O from data I/O, giving each its own IOPS budget and preventing shared-prefix rate limiting. ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Example: separate checkpoint bucket from dataset storage JOB__CHECKPOINT__OBJECT_STORE__PATH=gs://my-checkpoints-bucket/ckpts ``` Equivalent programmatic configuration: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.config import override_config_kv override_config_kv({ "job.checkpoint.object_store.path": "gs://my-checkpoints-bucket/ckpts", }) ``` ## Other Configuration | Variable | Default | Description | | - | - | - | | `GENEVA_RAY_INIT_MAX_RETRIES` | `5` | Maximum number of retry attempts for `ray.init()` connection failures. Useful when connecting to Ray clusters that may be temporarily unavailable. | | `GENEVA_K8S_AUTH_MAX_RETRIES` | `3` | Maximum number of retries for Kubernetes authentication operations. Must be at least 1. | | `GENEVA_CONFIG_DIR` | `./.config` | Directory path where Geneva looks for configuration files (`.yaml`, `.json`, `.toml`). Can be an absolute or relative path. | # Batch User-Defined Table Functions (UDTFs) Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/batch-udtfs Use batch UDTFs for N:M transformations like deduplication, clustering, and aggregation across entire tables or partitions. Beta — introduced in Geneva 0.11.0 Geneva's standard UDFs operate **row-at-a-time** — one input row produces exactly one output value. Batch User-Defined Table Functions (UDTFs) lift this restriction, enabling **N:M transformations** where the output can have a completely different schema and row count than the input. | Workflow | Input | Output | Cardinality | | - | - | - | - | | Deduplication | N rows | M rows (M ≤ N) | N:M | | Clustering | N rows | K cluster rows | N:K | | Aggregation | N rows | 1 summary row | N:1 | | Cross-row join/merge | N rows | M rows | N:M | ## Defining a Batch UDTF Use the `@udtf` decorator on a class or function. The UDTF receives a query builder over the source data and **yields** `pa.RecordBatch` objects with an arbitrary output schema. ### Class-based ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udtf import pyarrow as pa from collections.abc import Iterator @udtf( output_schema=pa.schema([ pa.field("row_id", pa.int64()), pa.field("cluster_id", pa.int64()), pa.field("is_duplicate", pa.bool_()), ]), input_columns=["row_id", "phash"], num_cpus=4, memory=8 * 1024**3, # 8 GiB ) class PHashDedupe: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow().select(["row_id", "phash"]) clusters = self._cluster(data) yield pa.RecordBatch.from_pydict({ "row_id": clusters["row_id"], "cluster_id": clusters["cluster_id"], "is_duplicate": clusters["is_duplicate"], }) ``` ### Function-based ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf(output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), pa.field("mean_score", pa.float64()), ])) def group_stats(source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby("label").agg( count=("label", "size"), mean_score=("score", "mean"), ).reset_index() yield pa.RecordBatch.from_pandas(agg) ``` ### Decorator Parameters | Parameter | Type | Description | | - | - | - | | `output_schema` | `pa.Schema` | **Required.** Arrow schema of the output table. | | `input_columns` | `list[str] \| None` | Restrict which source columns are visible. `None` means all. | | `partition_by` | `str \| None` | Column name for partition-parallel execution. | | `partition_by_indexed_column` | `str \| None` | Column name with an IVF index for index-based partitioning. Mutually exclusive with `partition_by`. | | `num_cpus` | `float` | Ray CPU resource request per worker. | | `num_gpus` | `float` | Ray GPU resource request per worker. | | `memory` | `int \| None` | Ray memory resource request in bytes. | | `on_error` | `list[ExceptionMatcher] \| ErrorHandlingConfig \| None` | Error handling configuration (see [Error Handling](#error-handling)). | ## Creating and Refreshing a UDTF View Batch UDTFs are always attached to a persistent view via `create_udtf_view()`. Call `refresh()` to populate or update the view. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} conn = geneva.connect("/data/mydb") images = conn.open_table("images") # Create the UDTF view deduped = conn.create_udtf_view( "deduped_images", source=images.search(None).select(["row_id", "phash"]), udtf=PHashDedupe(threshold=4), ) # Populate the view deduped.refresh() ``` UDTF views use the same cluster infrastructure as other Geneva jobs: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # KubeRay cluster with conn.context(cluster="my-cluster", manifest="my-manifest"): deduped.refresh() # Local Ray with conn.local_ray_context(): deduped.refresh() ``` ### Version-aware refresh On each refresh, Geneva checks the source table's version against the version stored in the view metadata. If the source has not changed, the refresh is skipped entirely — an O(1) check. ## Execution Modes ### Single-worker (no partitioning) When neither `partition_by` nor `partition_by_indexed_column` is set, the UDTF runs as a **single Ray task** with access to the entire source dataset. Use this for global operations that need cross-row visibility. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf(output_schema=...) class GlobalAggregation: def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: all_data = source.to_arrow() result = expensive_cross_row_computation(all_data) yield result.to_batches()[0] ``` ### Partition-parallel (`partition_by`) The framework groups source data by the partition column and dispatches each partition as an independent Ray task. Use this when the computation is naturally parallelizable by some grouping key. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ ("row_id_a", pa.string()), ("row_id_b", pa.string()), ("hamming_dist", pa.int32()), ]), partition_by="partition_id", num_cpus=2, ) class EdgeDetection: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow() edges = self._pairwise_compare(data, self.threshold) if edges: yield pa.RecordBatch.from_pydict(edges) ``` ### Index-based partitioning (`partition_by_indexed_column`) Instead of partitioning by a materialized column, the framework reads partition assignments directly from an existing **IVF vector index** (IVF_FLAT, IVF_PQ, IVF_HNSW_FLAT, IVF_HNSW_SQ, etc.). This avoids materializing a `partition_id` column and keeps partitions synchronized with the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.partitioning import create_ivf_flat_index # 1. Build an IVF index on the source table create_ivf_flat_index(images, "phash", k=16) # 2. Define the UDTF with index-based partitioning @udtf( output_schema=pa.schema([ ("row_id_a", pa.string()), ("row_id_b", pa.string()), ("hamming_dist", pa.int32()), ]), partition_by_indexed_column="phash", num_cpus=2, ) class IndexPartitionedEdgeDetection: def __init__(self, threshold: int = 4): self.threshold = threshold def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: data = source.to_arrow() edges = self._pairwise_compare(data, self.threshold) if edges: yield pa.RecordBatch.from_pydict(edges) ``` | | `partition_by` | `partition_by_indexed_column` | | - | - | - | | Partition source | Column values (SQL filter) | IVF index partitions (row ID take) | | Requires materialized column | Yes | No — reads from index metadata | | Partition count | Number of distinct values | Number of non-empty index partitions | | Sync with index | Manual | Automatic — always reads latest index | > [!WARNING] > > `partition_by` and `partition_by_indexed_column` are **mutually exclusive**. Setting both raises `ValueError`. ## Yielding Batches The UDTF yields one or more `pa.RecordBatch` or `pa.Table` objects. Each batch must conform to `output_schema`. The framework validates each batch, writes it, and optionally checkpoints it. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Streaming — yield per source batch (memory-efficient) def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: for batch in source.to_batches(batch_size=1024): yield transform(batch) # Bulk — load all, compute, yield once def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: all_data = source.to_arrow() result = expensive_cross_row_computation(all_data) yield result.to_batches()[0] ``` > [!TIP] > > Use the streaming pattern for memory-efficient processing. Use the bulk pattern when the computation inherently requires all data in memory (e.g., clustering, global deduplication). ## Error Handling Error handling operates at **partition granularity** — the unit of work is the entire `__call__()` execution for a partition (or the full table in single-worker mode). | Mode | Behavior | Use case | | - | - | - | | **Fail** (default) | Exception kills the partition, refresh fails | Correctness-critical UDTFs | | **Retry** | Retry the entire partition with configurable backoff | Transient failures (network, OOM) | | **Skip** | Log error, continue with remaining partitions | Best-effort / tolerant workloads | > [!WARNING] > > Unlike standard UDF error handling, there is no row-level skip — UDTFs yield whole batches, so the smallest error unit is the partition. ## Checkpointing Each yielded batch is checkpointed before reporting completion. On resume after a failure, completed batches are skipped and entire partitions with a `__done__` marker are skipped. Checkpoint keys include the source table version, so stale checkpoints from a previous source version are automatically ignored when the source changes. > [!WARNING] > > Checkpointed UDTFs must be **deterministic** — the same input must yield the same batch sequence for resume to work correctly. ## Examples ### K-Means Clustering ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("row_id", pa.int64()), pa.field("cluster_id", pa.int64()), pa.field("distance_to_centroid", pa.float64()), ]), num_cpus=4, memory=16 * 1024**3, ) class KMeansClustering: def __init__(self, k: int = 100): self.k = k def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: import numpy as np embeddings = source.to_arrow().select(["row_id", "embedding"]) row_ids = embeddings.column("row_id").to_pylist() vectors = np.stack(embeddings.column("embedding").to_pylist()) centroids, assignments, distances = self._fit(vectors) chunk_size = 10_000 for start in range(0, len(row_ids), chunk_size): end = min(start + chunk_size, len(row_ids)) yield pa.RecordBatch.from_pydict({ "row_id": row_ids[start:end], "cluster_id": assignments[start:end].tolist(), "distance_to_centroid": distances[start:end].tolist(), }) ``` ### Aggregation ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udtf( output_schema=pa.schema([ pa.field("label", pa.string()), pa.field("count", pa.int64()), pa.field("mean_score", pa.float64()), ]), ) class GroupStats: def __init__(self, group_by: str = "label"): self.group_by = group_by def __call__(self, source: geneva.GenevaQueryBuilder) -> Iterator[pa.RecordBatch]: df = source.to_pandas() agg = df.groupby(self.group_by).agg( count=("label", "size"), mean_score=("score", "mean"), ).reset_index() yield pa.RecordBatch.from_pandas(agg) ``` Reference: * [`create_udtf_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) * [UDTF](https://lancedb.github.io/geneva/api/udtf/) — full `@udtf` / `@batch_udtf` decorator reference including `output_schema`, `partition_by`, `num_gpus`, and `on_error` # Blob Types in Geneva UDFs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/blobs Learn how to work with Lance Blobs in Geneva UDFs for handling large binary objects efficiently with lazy reading capabilities. Geneva supports UDFs that take [Lance Blobs](/oss/v0-41-0/management/table#multimodal) (large binary objects) as input and has the ability to write out columns with binaries encoded as Lance Blobs. Lance blobs are an optimization intended for large objects (1's MBs -> 100MB's) and provide a file-like object that lazily reads large binary objects. ## Reading Blobs Defining functions that read blob columns is straight forward. For scalar UDFs, blob columns are expected to be of type `BlobFile` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lance.blob import BlobFile @udf def work_on_udf(blob: BlobFile) -> int: assert isinstance(blob, BlobFile) data = blob.read() # do something intresting. return len(data) ``` ## Writing Blobs Defining UDFs that write out `Blob`s to a new column is straightforward. Here we add the standard metadata annotation to the UDF so that Geneva knows to write out Blobs. For scalar udfs, your udf will return `bytes`, explicitly set the `data_type` to `pa.large_binary()`, and add the `field_metadata` that specifies blob encoding. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.large_binary(), field_metadata={"lance-encoding:blob": "true"}) def generate_blob(text: str, multiplier: int) -> bytes: """UDF that generates blob data by repeating text.""" return (text * multiplier).encode("utf-8") ``` For `pa.RecordBatch` batched UDFs you the effort is similar: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.large_binary(), field_metadata={"lance-encoding:blob": "true"}) def batch_to_blob(batch: pa.RecordBatch) -> pa.Array: """UDF that converts RecordBatch rows to blob data.""" import json blobs = [] for i in range(batch.num_rows): # do something that returns bytes blob_data = ... blobs.append(blob_data) return pa.array(blobs, type=pa.large_binary()) ``` ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator for defining blob-processing functions * [Table](https://lancedb.github.io/geneva/api/table/) — `add_columns()`, `backfill()` # Error Handling in Geneva UDFs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/error_handling Learn how configure retry, skip, and fail behaviors for UDFs. Geneva provides three ways to handle errors, in increasing complexity: factory functions, exception matchers, and full Tenacity control. ## Quick Start: Factory Functions Use factory functions for common error handling patterns: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, retry_transient import pyarrow as pa @udf(data_type=pa.int32(), on_error=retry_transient()) def my_udf(x: int) -> int: # Will retry on network errors (ConnectionError, TimeoutError, OSError) return call_external_api(x) ``` Geneva provides four built-in factory functions: | Function | Behavior | | - | - | | `retry_transient()` | Retry `ConnectionError`, `TimeoutError`, `OSError` with exponential backoff | | `retry_all()` | Retry any exception with exponential backoff | | `skip_on_error()` | Return `None` for any exception (skip the row) | | `fail_fast()` | Fail immediately on any exception (default behavior) | ### Customizing Retry Behavior Factory functions accept parameters to customize behavior: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, retry_transient, retry_all # Increase max attempts @udf(data_type=pa.int32(), on_error=retry_transient(max_attempts=5)) def more_retries(x: int) -> int: ... # Change backoff strategy @udf(data_type=pa.int32(), on_error=retry_all(max_attempts=3, backoff="fixed")) def fixed_backoff(x: int) -> int: ... ``` **Parameters:** * `max_attempts` (int): Maximum number of attempts (default: 3) * `backoff` (str): Backoff strategy between retries * `"exponential"` (default): 1s, 2s, 4s, 8s... with jitter, capped at 60s * `"fixed"`: Fixed 1s delay between attempts * `"linear"`: 1s, 2s, 3s, 4s... capped at 60s ## Custom Exception Handling: Matchers For fine-grained control, use `Retry`, `Skip`, and `Fail` matchers: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf, Retry, Skip, Fail @udf( data_type=pa.int32(), on_error=[ Retry(ConnectionError, TimeoutError, max_attempts=3), Retry(ValueError, match="rate limit", max_attempts=5), Skip(ValueError), # Other ValueErrors - skip the row Fail(AuthError), # Auth failures - fail immediately ] ) def custom_handling(x: int) -> int: ... ``` **How matching works:** 1. Matchers are evaluated in order (first match wins) 2. More specific matchers should come before general ones 3. Unmatched exceptions fail the job ### Exception Matchers | Matcher | Behavior | Parameters | | - | - | - | | `Retry(...)` | Retry with backoff, then fail | `max_attempts`, `backoff`, `match` | | `Skip(...)` | Return `None` for that row | `match` | | `Fail(...)` | Fail the job immediately | `match` | **Syntax:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Single exception Retry(ConnectionError) # Multiple exceptions Retry(ConnectionError, TimeoutError, OSError) # With parameters Retry(ConnectionError, max_attempts=5, backoff="fixed") # With message matching Retry(ValueError, match="rate limit") ``` ### Message Matching Use the `match` parameter to filter exceptions by their message content. The pattern is a regex: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import Retry, Skip # Simple substring (works because regex matches substrings) Retry(ValueError, match="rate limit") # Matches: ValueError("rate limit exceeded") # Regex pattern Retry(ValueError, match=r"rate.?limit") # Matches: ValueError("rate limit") # Matches: ValueError("ratelimit") # Matches: ValueError("rate_limit") # Case-insensitive matching (use (?i) flag) Retry(ValueError, match=r"(?i)rate limit") # Matches: ValueError("Rate Limit exceeded") # Matches: ValueError("RATE LIMIT hit") # Regex alternation (match multiple patterns) Retry(ValueError, match=r"429|rate.?limit|throttl") # Matches: ValueError("Error 429") # Matches: ValueError("rate limit exceeded") # Matches: ValueError("Request throttled") ``` For example, using matchers to distinguish error types: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf( data_type=pa.string(), on_error=[ # Retry rate limits with more attempts Retry(ValueError, match="rate limit", max_attempts=10), # Skip invalid input Skip(ValueError, match="invalid"), # Fail on other ValueErrors Fail(ValueError), ] ) def api_call(x: str) -> str: ... ``` ### Behavior Summary | Outcome | What Happens | When to Use | | - | - | - | | **Retry** | Retry with backoff, then fail/skip | Transient errors: network issues, rate limits, timeouts | | **Skip** | Return `None` for that row | Bad input data, row-specific failures, optional enrichment | | **Fail** | Kill the job immediately | Fatal errors: auth failures, configuration errors | ## Advanced: Full Tenacity Control For power users who need custom callbacks or complex retry conditions, omit `on_error` and use `error_handling=`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf from geneva.debug.error_store import ErrorHandlingConfig, UDFRetryConfig from tenacity import wait_random_exponential, stop_after_delay @udf( data_type=pa.int32(), error_handling=ErrorHandlingConfig( retry_config=UDFRetryConfig( retry=my_custom_retry_condition, stop=stop_after_delay(300), wait=wait_random_exponential(min=1, max=120), before_sleep=my_logging_callback, ), ), ) def power_user_udf(x: int) -> int: ... ``` Note: `on_error=` and `error_handling=` cannot be used together. ## Restrictions * **Skip behavior** only works with scalar UDFs (functions that process one row at a time) * For batch UDFs that receive `RecordBatch`, use `Retry` or `Fail` only * **All Retry matchers must use the same backoff strategy.** You cannot mix different backoff strategies in the same `on_error` list: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(on_error=[ Retry(ConnectionError, backoff="exponential"), Retry(TimeoutError, backoff="fixed"), # Error: different backoff! ]) def invalid_backoff(value: str) -> str: return value @udf(on_error=[ Retry(ConnectionError, backoff="fixed"), Retry(TimeoutError, backoff="fixed"), # Same backoff - OK ]) def consistent_backoff(value: str) -> str: return value ``` * **Invalid regex patterns are rejected at construction time:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # This will raise ValueError due to the unclosed bracket Retry(ValueError, match=r"[invalid") # But this will work: Retry(ValueError, match=r"rate.?limit") ``` ## API Reference * [Error Handling](https://lancedb.github.io/geneva/api/error_handling/) — `Retry`, `Skip`, `Fail`, `FatalWorkerOOMError`, `FatalWorkerCrashError`, and all exception matcher classes * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator `on_error` parameter # Understanding Transforms Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/index Understand the three types of user-defined functions in Geneva — UDFs, chunkers (scalar UDTFs), and batch UDTFs — and when to use each. Geneva provides three types of user-defined functions for transforming data. Each type has a different input/output cardinality and is suited to different workflows. ## Choosing the Right Type * **Adding a column to each row?** Use a [**UDF**](/oss/v0-41-0/geneva/udfs/udfs). * **Splitting each row into multiple rows?** Use a [**Chunker**](/oss/v0-41-0/geneva/udfs/scalar-udtfs). * **Computing across rows with a different output shape?** Use a [**Batch UDTF**](/oss/v0-41-0/geneva/udfs/batch-udtfs). ## At a Glance | | UDF | Chunker (Scalar UDTF) | Batch UDTF | | - | - | - | - | | **Cardinality** | 1:1 | 1:N | N:M | | **Decorator** | `@udf` | `@chunker` | `@udtf` | | **Refresh** | Incremental | Incremental | Full | | **Parallelism** | Fragment-parallel | Fragment-parallel | Partition-parallel | | **Inherited columns** | N/A — adds to existing rows | Automatic from query | Independent output schema | | **Registration** | [`table.add_columns()`](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) | [`db.create_udtf_view()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) | [`db.create_udtf_view()`](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) | ## UDFs (1:1) Standard UDFs produce exactly **one output value per input row**. Use them to add computed columns to existing tables or materialized views. | id | text | **embedding** | | - | - | - | | 1 | "hello world" | **→ \[0.12, 0.34, ...]** | | 2 | "foo bar" | **→ \[0.56, 0.78, ...]** | | 3 | "baz qux" | **→ \[0.90, 0.11, ...]** | Each input row produces exactly one output value. The new column is added to the same table. **Use cases**: Embeddings, data enrichment, format conversion, scoring. See [UDFs](/oss/v0-41-0/geneva/udfs/udfs) for the full guide. ## Chunkers (Scalar UDTFs, 1:N) Chunkers — also called scalar UDTFs — **expand each source row into multiple output rows**. The output is a materialized view that inherits parent columns and supports incremental refresh. **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is..." | | 2 | "Data Guide" | "Data pipelines are..." | **Derived: `chunks`** (1:N expansion via `@chunker`) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning..." | | 1 | "Intro to AI" | 1 | "Neural networks..." | | 1 | "Intro to AI" | 2 | "Training data..." | | | | | | | 2 | "Data Guide" | 0 | "Data pipelines..." | | 2 | "Data Guide" | 1 | "ETL processes..." | Each source row produces **one or more** output rows. Parent columns (`doc_id`, `title`) are inherited automatically. **Use cases**: Document chunking, video segmentation, image tiling. See [Chunkers](/oss/v0-41-0/geneva/udfs/scalar-udtfs) for the full guide. ## Batch UDTFs (N:M) Batch UDTFs read from a source table (or partition) and **produce output with an arbitrary schema and row count**. They always perform a full refresh. **Source: `sales`** | product | region | amount | | - | - | - | | Widget | East | 100 | | Widget | East | 250 | | Widget | West | 175 | | Gadget | East | 300 | | Gadget | West | 400 | | Gadget | West | 150 | **Derived: `sales_summary`** (N:M aggregation via `@udtf`) | product | total_amount | avg_amount | num_sales | | - | - | - | - | | Widget | 525 | 175.0 | 3 | | Gadget | 850 | 283.3 | 3 | 6 input rows become 2 output rows with a completely different schema. The output shape is determined entirely by the UDTF logic — it could be fewer rows (aggregation), more rows (clustering), or the same count with different columns. **Use cases**: Deduplication, clustering, aggregation, cross-row joins. See [Batch UDTFs](/oss/v0-41-0/geneva/udfs/batch-udtfs) for the full guide. ## API Reference * [UDF](https://lancedb.github.io/geneva/api/udf/) — `@udf` decorator and `UDF` class * [UDTF](https://lancedb.github.io/geneva/api/udtf/) — `@udtf`, `@chunker`, `@batch_udtf` decorators and `UDTF`/`Chunker` classes * [Table](https://lancedb.github.io/geneva/api/table/) — `add_columns()`, `backfill()` * [Connection](https://lancedb.github.io/geneva/api/connection/) — `create_udtf_view()`, `create_materialized_view()` # Profiling Stateful UDF Memory Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/profiling-memory Find memory leaks and runaway peak usage in stateful UDFs with memray, before they cause worker OOMs in production. Stateful UDFs are the most common source of worker memory pressure in Geneva. Unlike scalar UDFs, a stateful UDF instance lives for the **entire lifetime of a Ray actor**, processing many batches in sequence. Anything your `setup()` allocates is held for the duration of the job, and anything `__call__` retains accumulates batch after batch — sometimes silently, until a worker OOMs partway through a large backfill. This page shows you how to profile a stateful UDF locally with [memray](https://github.com/bloomberg/memray), what to look for, and the common patterns that leak. > [!TIP] > > If your worker is being OOM-killed and you don't know why, **profile a single actor locally first**. A 5-minute memray run on your laptop is faster than another 45-minute distributed run that fails the same way. ## Why stateful UDFs leak A stateful UDF in Geneva is a class: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @geneva.udf(data_type=pa.list_(pa.float32(), 512)) class MyEmbedding: def __init__(self): self.model = None def setup(self): self.model = load_model() # allocated once per actor def __call__(self, text: str) -> list[float]: if self.model is None: self.setup() return self.model.embed(text) ``` A few facts make memory behavior easy to get wrong: * **One instance per worker, many batches.** Geneva instantiates the class once per Ray actor. The same `self` processes every batch routed to that worker — potentially thousands. * **`setup()` runs once.** Whatever you allocate there stays in memory until the actor dies. That's intentional for things like ML models, but it's a footgun for "lazy" caches that grow. * **`self.<attr>` survives across calls.** Anything you attach to `self` inside `__call__` is retained for the rest of the actor's life. * **Workers don't restart between batches.** Unlike a serverless function, you don't get a fresh process per invocation. Memory accumulates linearly with batch count until the worker hits its memory cap. The result: a leak that looks tiny in unit tests (1 batch, 4 MiB) can blow up an 8-hour backfill (10 000 batches, 40 GiB). ## When to profile Profile your UDF if **any** of these are true: * The UDF loads a model, builds an index, or otherwise allocates more than \~100 MiB in `setup()`. * The UDF maintains a cache, deduplication table, or running statistic in `self`. * A worker is being OOM-killed during backfill (look for `FatalWorkerOOMError`, see [Job troubleshooting](/oss/v0-41-0/geneva/jobs/troubleshooting)). * Worker RSS grows steadily during a backfill rather than staying flat after `setup()`. You do **not** need to profile pure functional UDFs (no `self` state) or UDFs that only ever read from `self` — those can't leak by construction. ## Profiling a UDF with memray memray ships as a `dev` dependency in Geneva, so it's already in your environment if you installed with `uv sync`. The trick to profiling under Ray is that **workers run in separate processes**. Wrapping `pytest` with `memray run` only sees the driver, not the actors that actually run your UDF. The cleanest pattern is to have **the UDF instrument itself**, controlled by an environment variable that's only set when you want a profile. ### Step 1 — add an opt-in tracker to your UDF ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os, pathlib, uuid from typing import Any import memray import geneva import pyarrow as pa _MEMRAY_OUT_DIR_ENV = "MY_UDF_MEMRAY_OUT_DIR" @geneva.udf(data_type=pa.list_(pa.float32(), 512)) class MyEmbedding: def __init__(self): self.model = None self._tracker: Any = None # memray.Tracker, when profiling is on def setup(self): # Open a memray tracker per worker process, if requested. Each # worker writes its own .bin file so traces don't collide. out_dir = os.environ.get(_MEMRAY_OUT_DIR_ENV) if out_dir: pathlib.Path(out_dir).mkdir(parents=True, exist_ok=True) bin_path = pathlib.Path(out_dir) / ( f"memray-{os.getpid()}-{uuid.uuid4().hex}.bin" ) self._tracker = memray.Tracker( str(bin_path), native_traces=False, follow_fork=False ) self._tracker.__enter__() self.model = load_model() def __call__(self, text: str) -> list[float]: if self.model is None: self.setup() return self.model.embed(text) ``` The tracker is a no-op when `MY_UDF_MEMRAY_OUT_DIR` isn't set, so leaving this code in your UDF is safe for production runs. ### Step 2 — propagate the env var to Ray workers Ray workers don't inherit driver environment variables by default. When you start a local Ray cluster from Geneva, pass `extra_env` so the variable reaches each worker: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.runners.ray._mgr import ray_cluster with ray_cluster( local=True, extra_env={"MY_UDF_MEMRAY_OUT_DIR": "/tmp/my-udf-profile"}, ): table.backfill("embedding", concurrency=1) ``` > [!TIP] > > Set `concurrency=1` while profiling. One actor processing all batches sequentially produces a single clean trace; the default of 8 produces 8 noisier traces that you'd have to merge mentally. ### Step 3 — read the trace When backfill finishes, you'll have one (or more) `memray-<pid>-<uuid>.bin` files under `/tmp/my-udf-profile/`. Render and inspect them: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Quick summary — peak heap, total allocations, what's leaked uv run -m memray summary /tmp/my-udf-profile/memray-*.bin # Interactive flamegraph in your browser uv run -m memray flamegraph /tmp/my-udf-profile/memray-*.bin open /tmp/my-udf-profile/memray-*.html # Top allocators by retained bytes uv run -m memray tree /tmp/my-udf-profile/memray-*.bin ``` ## What the numbers mean memray reports two values you'll care about most: * **Peak heap** (`metadata.peak_memory`) — the high-water mark. This is what triggers OOMs. A peak well above your `setup()` allocations means a batch transiently doubles memory before freeing. * **Leaked allocations** (`get_leaked_allocation_records()`) — what was still allocated when the tracker ended. **This is not necessarily a bug** — your `setup()` model is "leaked" in this sense because it lives the actor's lifetime. The signal is *how much above expected baseline* is leaked. A healthy stateful UDF profile, after processing many batches, looks roughly like: ``` peak heap ≈ setup() allocations + 1 batch of working memory leaked ≈ setup() allocations (i.e. nothing extra retained from __call__) ``` An **unhealthy** profile looks like: ``` peak heap ≈ setup() + N × per-call allocation ← grows with batch count leaked ≈ setup() + N × per-call allocation ← per-call state never freed ``` The flamegraph will show a thick stack frame anchored in `__call__` rising as you scroll through time — that's the leak. ## Going deeper: RSS vs Arrow allocations memray gives you the *Python-side* allocation story. For real diagnosis of "where is the worker's memory actually going?", it pays to watch **process RSS** and **Arrow's own allocator** side-by-side — together they tell you which subsystem owns the bytes, often faster than reading a flamegraph. Drop this into your UDF (or anywhere on the worker) to log a snapshot: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import resource, pyarrow as pa def log_memory(seq: int) -> None: rss_bytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # ru_maxrss is bytes on macOS, KiB on Linux: import sys if sys.platform != "darwin": rss_bytes *= 1024 arrow_live = pa.total_allocated_bytes() print( f"seq={seq} " f"rss_mb={rss_bytes // 1024**2} " f"arrow_live_mb={arrow_live // 1024**2} " f"gap_mb={(rss_bytes - arrow_live) // 1024**2}", flush=True, ) ``` The three numbers answer different questions: * **`rss_mb`** — every byte the OS has handed this Python interpreter. Includes Python heap, Arrow, native libraries, and pages the C allocator (`glibc`/`jemalloc`) is holding even though Python freed them. This is what triggers cgroup OOM-kills. * **`arrow_live_mb`** — bytes currently held by *live PyArrow buffers* (`RecordBatch`, `Array`, `ChunkedArray`, etc.). Goes up when you create Arrow data, down when those references are dropped. * **`gap_mb` = rss − arrow_live** — "everything else." This is the Python heap (your own `self.cache`, model weights, dicts, lists), native libraries (PyTorch, ONNX), and allocator retention. ### Diagnostic patterns Log the breakdown every few batches and the *shape of growth over time* tells you which subsystem to fix: | Pattern | Diagnosis | First thing to try | | - | - | - | | `rss` climbs slowly, `arrow_live` flat near zero, big growing `gap` | Allocator retention — Python freed it but `glibc` is keeping the pages | `ctypes.CDLL("libc.so.6").malloc_trim(0)` periodically (Linux only); or set `MALLOC_TRIM_THRESHOLD_=131072` | | `rss` climbs, `arrow_live` climbs in lockstep | Real Arrow leak — your code is holding `RecordBatch` / `Array` references | Find where you're appending batches to `self`, or where checkpoint / error payloads aren't being released | | `rss` spikes hugely on a few calls then settles, eventually one spike OOMs | Peak is too big, not a leak — a single call allocates more than the worker has | Shrink `batch_size`, `blob_read_buffer_size`, or split the work | | `rss` flat for hours then sudden cliff upward | One pathological row — usually one huge blob (a 4K-resolution image, a 50 MB PDF) | Find the offending row by ID; add a size check at the top of `__call__` | | `rss` rises during `setup()`, then flat for the whole run, `gap` constant | Healthy — that's your model loaded once per actor | Nothing to do | > [!TIP] > > The reference UDFs in Geneva's own integration test (`src/stress_tests/_memray_probe.py`) print exactly this breakdown every 32 calls. The workflow's stdout logs are a working example of the "clean" and "leaky" patterns — the leaky one shows the **lockstep with Python heap** signature (the second row above, but with `gap` climbing instead of `arrow_live` — because the leak is `bytearray`, not Arrow). ## Common leak patterns ### 1. The growing cache ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadEmbedding: def __init__(self): self.cache: dict[str, list[float]] = {} def __call__(self, text: str) -> list[float]: if text not in self.cache: self.cache[text] = self.model.embed(text) return self.cache[text] ``` Looks harmless. Fine on a unit test with 10 inputs. **Catastrophic on a backfill of 10M rows**, where most inputs are unique and the cache grows to fill the worker. **Fix:** Use a bounded cache (`functools.lru_cache` with `maxsize`, or a manual size cap), or skip caching when you don't know the cardinality. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from functools import lru_cache class GoodEmbedding: def __init__(self): self._embed = None def setup(self): model = load_model() self._embed = lru_cache(maxsize=1024)(model.embed) def __call__(self, text: str) -> list[float]: if self._embed is None: self.setup() return self._embed(text) ``` ### 2. Accumulating per-call buffers ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadAggregator: def __init__(self): self.history = [] def __call__(self, batch: pa.RecordBatch) -> pa.Array: self.history.append(batch) # holds every batch ever processed ... ``` **Fix:** Don't hold references to inputs past the return of `__call__`. If you need rolling state, summarize into a small aggregate (counts, sums) instead of holding the raw batches. ### 3. Closures capturing batch arrays ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BadDeferred: def __init__(self): self.work_queue = [] def __call__(self, x: pa.Array) -> pa.Array: # Lambda captures `x` by reference — the whole Array stays alive self.work_queue.append(lambda: expensive(x)) ... ``` **Fix:** Extract only the small values you actually need into the closure, or execute the work eagerly. ### 4. ML model state that grows Some ML libraries retain per-call state internally (KV caches, gradient buffers, autograd graphs). If you're using PyTorch: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def __call__(self, text: str) -> list[float]: with torch.inference_mode(): # <-- prevents autograd graph retention return self.model.encode(text) ``` For Hugging Face pipelines, ensure you're in `eval()` mode and not accumulating gradients. For long-running stateful UDFs on GPUs, also see `torch.cuda.empty_cache()` between large batches. ## A confidence check A useful "does my profiling actually work?" sanity check: temporarily introduce a deliberate leak and confirm memray catches it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def __call__(self, x): scratch = bytearray(8 * 1024 * 1024) # 8 MiB self._scratches.append(scratch) # <-- deliberate leak return ... ``` If `memray summary` doesn't show leaked bytes growing roughly with batch count after this change, your tracker isn't actually attached (most often: the env var isn't reaching workers — re-check `extra_env`). Geneva's own test suite ships a reference implementation of this pattern in `src/stress_tests/_memray_probe.py` and `src/stress_tests/test_memray_stateful_udf.py`, plus a GitHub Actions workflow (`memray-stateful-udf-profile.yml`) that uploads the per-actor `.bin` and rendered flamegraph as a CI artifact. Feel free to copy that scaffolding for your own project's UDFs. ## Related * [UDFs](/oss/v0-41-0/geneva/udfs/udfs) — defining stateful UDFs * [Job troubleshooting](/oss/v0-41-0/geneva/jobs/troubleshooting) — diagnosing OOMs and other worker errors * [Advanced configuration](/oss/v0-41-0/geneva/udfs/advanced-configuration) — admission control and resource limits * [memray documentation](https://bloomberg.github.io/memray/) — flamegraph, summary, and tree report formats # Gemini Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/providers/gemini Embed text and generate completions using Google's Gemini models. See the API reference for [Gemini UDFs](https://lancedb.github.io/geneva/api/gemini/) and [Embedding UDFs](https://lancedb.github.io/geneva/api/embeddings/) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-gemini]' ``` > [!WARNING] > > Gemini UDFs make API calls that incur **per-token costs**. Each row processed results in one > or more API requests billed to your account. Review > [Gemini pricing](https://ai.google.dev/gemini-api/docs/pricing) before running on large tables. > [!NOTE] > > Set the `GEMINI_API_KEY` environment variable before calling any factory function below. > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export GEMINI_API_KEY="your-api-key" > ``` > > The key is read **at UDF creation time** and serialized with the UDF — no cluster-level > `env_vars` configuration is needed. ## Embeddings Embed text with optional task-type hints for retrieval, classification, and clustering scenarios. See the [API reference](https://lancedb.github.io/geneva/api/embeddings/#geneva.udfs.text.embeddings.gemini_embedding_udf) for all parameters. **Multiple embeddings tuned for different retrieval tasks:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import gemini_embedding_udf table.add_columns({ # Full-dimension embedding for document retrieval "embedding_doc": gemini_embedding_udf( column="body", model="gemini-embedding-001", task_type="RETRIEVAL_DOCUMENT", ), # Compact embedding for semantic similarity "embedding_sim_256": gemini_embedding_udf( column="body", model="gemini-embedding-001", task_type="SEMANTIC_SIMILARITY", output_dimensionality=256, ), }) ``` ## Generation Generate text from Gemini models. Supports text, image, audio, video, and document inputs. See the [API reference](https://lancedb.github.io/geneva/api/gemini/#geneva.udfs.text.gemini.gemini_udf) for all parameters. **Enrich a table with sentiment, captions, and transcriptions at once:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import gemini_udf table.add_columns({ # Classify review sentiment with a fast model "sentiment": gemini_udf( column="review", prompt="Classify the sentiment as positive, negative, or neutral. Return only the label.", model="gemini-2.5-flash", ), # Caption product images with a more capable model "caption": gemini_udf( column="image", prompt="Describe the main subject of this image in one sentence", model="gemini-2.5-pro", mime_type="image/jpeg", ), # Transcribe audio clips "transcript": gemini_udf( column="audio", prompt="Transcribe this audio clip", model="gemini-2.5-flash", mime_type="audio/mp3", ), }) ``` ## API Reference * [Gemini](https://lancedb.github.io/geneva/api/gemini/) — `gemini_udf()` parameters: `column`, `prompt`, `model`, `mime_type`, and more * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `gemini_embedding_udf()` parameters: `column`, `model`, `task_type`, `dimensionality`, `normalize` # Built-in LLM and Embedding UDFs Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/providers/index Geneva ships pre-built UDFs for common LLM providers so you don't have to write custom classes for everyday embedding and generation tasks. | Provider | Embeddings | Generation | Runs locally | Install extra | | - | :-: | :-: | :-: | - | | [OpenAI](/oss/v0-41-0/geneva/udfs/providers/openai) | ✓ | ✓ | — | `geneva[udf-text-openai]` | | [Gemini](/oss/v0-41-0/geneva/udfs/providers/gemini) | ✓ | ✓ | — | `geneva[udf-text-gemini]` | | [Sentence Transformers](/oss/v0-41-0/geneva/udfs/providers/sentence-transformers) | ✓ | — | ✓ | `geneva[udf-text-sentence-transformers]` | OpenAI and Gemini UDFs make remote API calls that incur per-token costs. Sentence Transformers run locally on your workers with no API costs — see [GPU acceleration](/oss/v0-41-0/geneva/udfs/providers/sentence-transformers#gpu-acceleration) for performance tips. ## Comparing models and prompts Because `add_columns` accepts a dictionary, you can evaluate multiple models, parameter settings, or prompts in a single pass over your data. Each entry produces its own column, so results sit side by side in the same table for easy comparison. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_udf, gemini_udf, openai_embedding_udf table.add_columns({ # Compare two embedding models "emb_small": openai_embedding_udf(column="body", model="text-embedding-3-small"), "emb_large": openai_embedding_udf(column="body", model="text-embedding-3-large"), # Compare the same task across providers "summary_openai": openai_udf( column="body", prompt="Summarize in one sentence", model="gpt-5-mini", ), "summary_gemini": gemini_udf( column="body", prompt="Summarize in one sentence", model="gemini-2.5-flash", ), }) ``` This works for any combination — different models from the same provider, different providers, different prompts with the same model, or different dimensionality settings. All columns are computed in parallel during the same backfill job. To recompute columns later (e.g., after altering a UDF or adding new rows), use `backfill`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Backfill a single column table.backfill("emb_small") # Backfill only rows missing a value table.backfill("summary_openai", where="summary_openai is null") ``` ## What's included All built-in UDFs share these capabilities: * **API key handling** — Keys are captured from your local environment at UDF creation time and securely serialized with the UDF. No cluster-level environment configuration required. * **Retry with backoff** — Transient API errors (rate limits, timeouts, server errors) are automatically retried with exponential backoff. * **Batch processing** — Embedding UDFs batch multiple rows per API call for better throughput. * **L2 normalization** — Embedding UDFs support optional L2 normalization via the `normalize` parameter (disabled by default since both providers return pre-normalized vectors). ## See also * [Working with UDFs](/oss/v0-41-0/geneva/udfs/index) — Write custom scalar, batched, and stateful UDFs * [Error handling](/oss/v0-41-0/geneva/udfs/error_handling) — Fine-grained retry and skip policies * [Working with blobs](/oss/v0-41-0/geneva/udfs/blobs) — Process binary data (images, audio, video) ## API Reference * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `sentence_transformer_udf()`, `gemini_embedding_udf()`, `openai_embedding_udf()` * [Gemini](https://lancedb.github.io/geneva/api/gemini/) — `gemini_udf()` * [OpenAI](https://lancedb.github.io/geneva/api/openai/) — `openai_udf()`, `openai_embedding_udf()` # OpenAI Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/providers/openai Embed text and generate completions using OpenAI models. See the [API reference](https://lancedb.github.io/geneva/api/openai/) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-openai]' ``` > [!WARNING] > > OpenAI UDFs make API calls that incur **per-token costs**. Each row processed results in one > or more API requests billed to your account. Review > [OpenAI pricing](https://openai.com/api/pricing/) before running on large tables. > [!NOTE] > > Set the `OPENAI_API_KEY` environment variable before calling any factory function below. > > ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > export OPENAI_API_KEY="your-api-key" > ``` > > The key is read **at UDF creation time** and serialized with the UDF — no cluster-level > `env_vars` configuration is needed. ## Embeddings **Compare models by adding multiple embedding columns at once:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_embedding_udf table.add_columns({ # Default model — fast, 1536 dimensions "embedding_small": openai_embedding_udf( column="body", model="text-embedding-3-small", ), # Higher-quality model — 3072 dimensions "embedding_large": openai_embedding_udf( column="body", model="text-embedding-3-large", ), # Same large model, truncated to 256 dimensions for storage efficiency "embedding_large_256": openai_embedding_udf( column="body", model="text-embedding-3-large", output_dimensionality=256, ), }) ``` ## Generation Generate text from OpenAI chat completion models. Supports both text and binary (image) input columns. See the [API reference](https://lancedb.github.io/geneva/api/openai/#geneva.udfs.openai.openai_udf) for all parameters. **Add a summary and an image caption in one call, using different models:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import openai_udf table.add_columns({ # Fast model for bulk text summarization "summary": openai_udf( column="body", prompt="Summarize this document in 3 bullet points", model="gpt-5-mini", ), # More capable model for nuanced image captions "caption": openai_udf( column="image", prompt="Provide a 1 sentence description of the scene", model="gpt-5", mime_type="image/jpeg", ), }) ``` ## API Reference * [OpenAI](https://lancedb.github.io/geneva/api/openai/) — `openai_udf()` and `openai_embedding_udf()` — all parameters including `column`, `prompt`, `model`, `mime_type`, `dimensions`, and `normalize` # Sentence Transformers Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/providers/sentence-transformers Embed text using any HuggingFace Sentence Transformer model locally — no API key needed. See the [API reference](https://lancedb.github.io/geneva/api/embeddings/#geneva.udfs.text.embeddings.sentence_transformer_udf) for all parameters. ```shell theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install 'geneva[udf-text-sentence-transformers]' ``` > [!TIP] > > Sentence Transformer models run **locally** on your workers — there are no API calls and no > per-token costs. This makes them a good fit for large-scale embedding jobs where cost is a > concern. ## Embeddings **Compare a lightweight and a high-quality model side by side:** ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva.udfs import sentence_transformer_udf table.add_columns({ # Lightweight default model — fast, CPU-friendly "embedding_mini": sentence_transformer_udf( column="body", model="sentence-transformers/all-MiniLM-L6-v2", ), # Larger model with GPU acceleration "embedding_bge": sentence_transformer_udf( column="body", model="BAAI/bge-large-en-v1.5", num_gpus=1.0, ), }) ``` ## GPU acceleration Sentence Transformer models can run on CPU or GPU. Smaller models like `all-MiniLM-L6-v2` work well on CPU, but larger models like `bge-large-en-v1.5` benefit significantly from GPU acceleration. Use the `num_gpus` parameter to request GPU resources for a worker: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # CPU-only (default) — suitable for lightweight models sentence_transformer_udf(column="body", model="sentence-transformers/all-MiniLM-L6-v2") # GPU-accelerated — recommended for larger models sentence_transformer_udf(column="body", model="BAAI/bge-large-en-v1.5", num_gpus=1.0) ``` Setting `num_gpus` to a fractional value (e.g., `0.5`) tells the [Ray scheduler](https://docs.ray.io/en/latest/ray-core/scheduling/accelerators.html) to co-locate multiple workers on the same physical GPU. For example, two UDFs with `num_gpus=0.5` will be scheduled on a single GPU. Note that Ray does not enforce GPU memory limits — it is your responsibility to ensure the combined models fit in GPU memory. ## API Reference * [Embeddings](https://lancedb.github.io/geneva/api/embeddings/) — `sentence_transformer_udf()` — all parameters including `column`, `model`, `num_gpus`, `normalize`, and `batch_size` # Chunkers (Scalar UDTFs) Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/scalar-udtfs Use chunkers (scalar UDTFs) for 1:N row expansion — split videos into clips, chunk documents, or tile images with automatic parent column inheritance and incremental refresh. Beta — introduced in Geneva 0.11.0 Standard UDFs produce exactly **one output value per input row**. **Chunkers** — also called scalar UDTFs — enable **1:N row expansion**: each source row can produce multiple output rows. The results are stored as a materialized view with MV-style incremental refresh. | Source Table | Derived Table | Expansion | | - | - | - | | 1 video row | → N clip rows | Video segmentation | | 1 document row | → N chunk rows | Text chunking | | 1 image row | → N tile rows | Image tiling | For example, a chunker that splits documents into passages turns a `documents` table into a `chunks` table, carrying the parent columns into every child row: **Source: `documents`** | doc_id | title | text | | - | - | - | | 1 | "Intro to AI" | "Machine learning is..." | | 2 | "Data Guide" | "Data pipelines are..." | **Derived: `chunks`** (1:N expansion) | doc_id | title | chunk_index | chunk_text | | - | - | - | - | | 1 | "Intro to AI" | 0 | "Machine learning..." | | 1 | "Intro to AI" | 1 | "Neural networks..." | | 1 | "Intro to AI" | 2 | "Training data..." | | 2 | "Data Guide" | 0 | "Data pipelines..." | | 2 | "Data Guide" | 1 | "ETL processes..." | Parent columns (`doc_id`, `title`) are inherited automatically; `chunk_index` and `chunk_text` are generated by the chunker. ## Defining a Chunker Use the `@chunker` decorator on a function that **yields** output rows. Geneva infers the output schema from the return type annotation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import chunker from typing import Iterator, NamedTuple class Clip(NamedTuple): clip_start: float clip_end: float clip_bytes: bytes @chunker def extract_clips(video_path: str, duration: float) -> Iterator[Clip]: """Yields multiple clips per video.""" clip_length = 10.0 for start in range(0, int(duration), int(clip_length)): end = min(start + clip_length, duration) clip_data = extract_video_segment(video_path, start, end) yield Clip(clip_start=start, clip_end=end, clip_bytes=clip_data) ``` Input parameters are bound to source columns **by name** — the parameter `video_path` binds to source column `video_path`, just like standard UDFs. > [!TIP] > > A chunker can yield **zero rows** for a source row. The source row is still marked as processed and will not be retried on the next refresh. ### List return pattern If you prefer to build the full list in memory rather than yielding, you can return a `list` instead of an `Iterator`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @chunker def extract_clips(video_path: str, duration: float) -> list[Clip]: clips = [] for start in range(0, int(duration), 10): end = min(start + 10, duration) clips.append(Clip(clip_start=start, clip_end=end, clip_bytes=b"...")) return clips ``` ### Batched chunker For vectorized processing, use `batch=True`. The function receives Arrow arrays and returns a `RecordBatch` of expanded rows. Because the return type `pa.RecordBatch` cannot be inferred, you must supply `output_schema` explicitly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @chunker(batch=True, output_schema=clip_schema) def extract_clips(batch: pa.RecordBatch) -> pa.RecordBatch: """Process rows in batches. Same 1:N semantic per row.""" ... ``` ## Creating a Chunker View Chunkers use the `create_udtf_view` API (passing the chunker as the `udtf` argument): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva db = geneva.connect("/data/mydb") videos = db.open_table("videos") # Create the 1:N materialized view clips = db.create_udtf_view( "clips", source=videos.search(None).select(["video_path", "metadata"]), udtf=extract_clips, ) # Populate — runs the UDTF on every source row clips.refresh() ``` The `query` parameter controls which source columns are inherited. Columns listed in `.select()` are carried into every child row automatically. ## Inherited Columns Child rows automatically include the parent's columns — no manual join required. The columns available in the child table are determined by the query's `.select()`: ### `videos` table (source) | video_path | duration | metadata | | - | - | - | | /v/a.mp4 | 120.0 | \{fps: 30} | | /v/b.mp4 | 60.0 | \{fps: 24} | ### `clips` table (derived, 1:N) | video_path | metadata | clip_start | clip_end | clip_bytes | | - | - | - | - | - | | /v/a.mp4 | \{fps: 30} | 0.0 | 10.0 | b"\x00\x1a..." | | /v/a.mp4 | \{fps: 30} | 10.0 | 20.0 | b"\x00\x2b..." | | /v/a.mp4 | \{fps: 30} | 20.0 | 30.0 | b"\x00\x3c..." | | | | | | | | /v/b.mp4 | \{fps: 24} | 0.0 | 10.0 | b"\x00\x4d..." | | /v/b.mp4 | \{fps: 24} | 10.0 | 20.0 | b"\x00\x5e..." | The first three rows come from the `/v/a.mp4` source row, the last two from `/v/b.mp4`. Inherited columns (`video_path`, `metadata`) are carried over automatically; `clip_start`, `clip_end`, and `clip_bytes` are generated by the UDTF. ## Adding Computed Columns After Creation Since chunker views are materialized views, you can add UDF-computed columns to the child table and backfill them: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 512)) def clip_embedding(clip_bytes: bytes) -> list[float]: return embed_model.encode(clip_bytes) # Add an embedding column to the clips table clips.add_columns({"embedding": clip_embedding}) # Backfill computes embeddings for all existing clips clips.backfill("embedding") ``` This is a powerful pattern: expand source rows with a chunker, then enrich the expanded rows with standard UDFs. ## Incremental Refresh Chunkers support **incremental refresh**, just like standard materialized views: * **New source rows**: The UDTF runs on new rows, inserting child rows. * **Deleted source rows**: Child rows linked to the deleted parent are cascade-deleted. * **Updated source rows**: Old children are deleted, UDTF re-runs, new children inserted. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add new videos to the source table videos.add(new_video_data) # Incremental refresh — only processes the new videos clips.refresh() ``` Only the new source rows are processed. Existing clips from previous refreshes are untouched. ## Chaining Chunker Views Chunker views are standard materialized views, so they can serve as the source for further views: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # videos → clips (1:N) clips = db.create_udtf_view( "clips", source=videos.search(None), udtf=extract_clips ) # clips → frames (1:N) frames = db.create_udtf_view( "frames", source=clips.search(None), udtf=extract_frames ) ``` ## Full Example: Document Chunking ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import connect, chunker, udf from typing import Iterator, NamedTuple import pyarrow as pa class Chunk(NamedTuple): chunk_index: int chunk_text: str @chunker def chunk_document(text: str) -> Iterator[Chunk]: """Split a document into overlapping chunks.""" words = text.split() chunk_size = 500 overlap = 50 for i, start in enumerate(range(0, len(words), chunk_size - overlap)): chunk_words = words[start:start + chunk_size] yield Chunk(chunk_index=i, chunk_text=" ".join(chunk_words)) db = connect("/data/mydb") docs = db.open_table("documents") # Create chunked view — inherits doc_id, title, etc. from source chunks = db.create_udtf_view( "doc_chunks", source=docs.search(None).select(["doc_id", "title", "text"]), udtf=chunk_document, ) chunks.refresh() # Add embeddings to chunks for semantic search @udf(data_type=pa.list_(pa.float32(), 1536)) def embed_text(chunk_text: str) -> list[float]: return embedding_model.encode(chunk_text) chunks.add_columns({"embedding": embed_text}) chunks.backfill("embedding") # Backfills embeddings on all existing chunks # Query — parent columns available alongside chunk columns chunks.search(None).select(["doc_id", "title", "chunk_text", "embedding"]).to_pandas() ``` For a comparison of all three function types (UDFs, Chunkers, Batch UDTFs), see [Understanding Transforms](/oss/v0-41-0/geneva/udfs). Reference: * [`chunker` API](https://lancedb.github.io/geneva/api/udtf/#geneva.chunker) * [`create_udtf_view` API](https://lancedb.github.io/geneva/api/connection/#geneva.db.Connection.create_udtf_view) # User-Defined Functions (UDFs) Source: https://docs.lancedb.com/oss/v0-41-0/geneva/udfs/udfs Define 1:1 transforms that add computed columns to your tables — embeddings, enrichment, scoring, and more. UDFs are the core building block for feature engineering in Geneva. A UDF wraps a Python function and applies it to every row in a table, producing exactly **one output value per input row** (1:1). Use UDFs to compute embeddings, enrich data with external APIs, transform formats, or derive new features from existing columns. ## Defining a UDF Converting your Python code to a Geneva UDF is simple. There are three kinds of UDFs that you can provide — scalar UDFs, batched UDFs and stateful UDFs. In all cases, Geneva uses Python type hints from your functions to infer the input and output [arrow data types](https://arrow.apache.org/docs/python/api/datatypes.html) that LanceDB uses. ### Scalar UDFs The **simplest** form is a scalar UDF, which processes one row at a time: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from geneva import udf @udf def area_udf(x: int, y: int) -> int: return x * y ``` This UDF will take the value of `x` and value of `y` from each row and return the product. The `@udf` wrapper is all that is needed. ### Batched UDFs For **better performance**, you can also define batch UDFs that process multiple rows at once. You can use `pyarrow.Array`s: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def batch_filename_len(filename: pa.Array) -> pa.Array: lengths = [len(str(f)) for f in filename] return pa.array(lengths, type=pa.int32()) ``` Or take entire rows using `pyarrow.RecordBatch`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva import udf @udf(data_type=pa.int32()) def recordbatch_filename_len(batch: pa.RecordBatch) -> pa.Array: filenames = batch["filename"] lengths = [len(str(f)) for f in filenames] return pa.array(lengths, type=pa.int32()) ``` > **Note**: Batch UDFS require you to specify `data_type` in the `@udf` decorator for batched UDFs which defines `pyarrow.DataType` of the returned `pyarrow.Array`. ### Struct outputs A UDF can return multiple related values as a single `struct` column by setting `data_type` to a `pa.struct(...)` and returning a tuple (matched by field order) or a `dict` keyed by field name. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io import pyarrow as pa from geneva import udf @udf( data_type=pa.struct( [pa.field("width", pa.int32()), pa.field("height", pa.int32())] ), ) def dimensions(image: bytes) -> tuple[int, int]: """Extract image dimensions (width, height).""" from PIL import Image img = Image.open(io.BytesIO(image)) return img.size ``` Downstream UDFs can then read individual fields via dot notation in `input_columns` (see below). ### Struct fields and list inputs You can pass nested `struct` fields directly into a UDF by specifying `input_columns` with dot notation. For list-typed inputs, Geneva can pass a NumPy array when the argument is annotated as `np.ndarray` (use `np.ndarray | None` for nullable lists). ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np import pyarrow as pa from geneva import udf struct_type = pa.struct([("vals", pa.list_(pa.int32()))]) schema = pa.schema([pa.field("info", struct_type)]) @udf(data_type=pa.int32(), input_columns=["info.vals"]) def sum_vals(vals: np.ndarray | None) -> int | None: if vals is None: return None assert isinstance(vals, np.ndarray) return int(np.sum(vals)) ``` ### Stateful UDFs You can also define a **stateful** UDF that retains its state across calls. This can be used to share code and **parameterize your UDFs**. In the example below, the model being used is a parameter that can be specified at UDF registration time. It can also be used to parameterize input column names of `pa.RecordBatch` batch UDFS. This also can be used to **optimize expensive initialization** that may require heavy resources on the distributed workers. For example, this can be used to load a model to the GPU once for all records sent to a worker instead of once per record or per batch of records. A stateful UDF is a `Callable` class, with `__call__()` method. The call method can be a scalar function or a batched function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import Callable from openai import OpenAI @udf(data_type=pa.list_(pa.float32(), 1536)) class OpenAIEmbedding(Callable): def __init__(self, model: str = "text-embedding-3-small"): self.model = model # Per-worker openai client self.client: OpenAI | None = None def __call__(self, text: str) -> pa.Array: if self.client is None: self.client = OpenAI() resp = self.client.embeddings.create(model=self.model, input=text) return pa.array(resp.data[0].embeddings) ``` > [!TIP] > > For common providers like OpenAI and Gemini, Geneva ships [built-in UDFs](/oss/v0-41-0/geneva/udfs/providers) that handle API keys, retries, and batching for you — no custom class needed. > **Note**: The state is will be independently managed on each distributed Worker. ## UDF options The `udf` can have extra annotations that specify resource requirements and operational characteristics. These are just add parameters to the `udf(...)`. ### Resource requirements for UDFs Some workers may require specific resources such as gpus, cpus and certain amounts of RAM. You can provide these requirements by adding `num_cpus`, `num_gpus`, and `memory` parameters to the UDF. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(num_cpus=1, num_gpus=0.5, memory=4 * 1024**3) def transform(value: str) -> str: # Replace this body with your transformation. return value ``` ### Operational parameters for UDFs #### checkpoint_size `checkpoint_size` controls how many rows are processed before checkpointing, and therefore reporting and saving progress. UDFs can be quite varied: some can be simple operations where thousands of calls can be completed per second, while others may be slow and require 30s per row. So a simple default like "every 1000 rows" might write once a second or once every 8 hours! Geneva will handle this internally, using an experimental feature that will adapt checkpoint sizing as a UDF progresses. However, if you want to see writes more or less frequently, you can set this manually. There are three parameters: * `checkpoint_size`: the seed for the initial checkpoint size * `min_checkpoint_size`: the minimum value that Geneva will use while adapting checkpoint size * `max_checkpoint_size`: the maximum value that Geneva will use while adapting checkpoint size Therefore, to force a checkpoint size (and effectively disable adaptive batch sizing), set all three of these parameters to the same value. ### Error handling Depending on the UDF, you may want Geneva to ignore rows that hit failures, retry, or fail the entire job. For simple cases, Geneva provides a simple parameter, `on_error`, with the following options: | Function | Behavior | | - | - | | `retry_transient()` | Retry `ConnectionError`, `TimeoutError`, `OSError` with exponential backoff | | `retry_all()` | Retry any exception with exponential backoff | | `skip_on_error()` | Return `None` for any exception (skip the row) | | `fail_fast()` | Fail immediately on any exception (default behavior) | If those are not specific enough, Geneva also provides [many more error handling options](/oss/v0-41-0/geneva/udfs/error_handling). ## Registering Features with UDFs Registering a feature is done by providing the `Table.add_columns()` function a new column name and the Geneva UDF. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva import numpy as np import pyarrow as pa lancedb_uri="gs://bucket/db" db = geneva.connect(lancedb_uri) # Define schema for the video table schema = pa.schema([ ("filename", pa.string()), ("duration_sec", pa.float32()), ("x", pa.int32()), ("y", pa.int32()), ]) tbl = db.create_table("videos", schema=schema, mode="overwrite") # Generate fake data N = 10 data = { "filename": [f"video_{i}.mp4" for i in range(N)], "duration_sec": np.random.uniform(10, 300, size=N).astype(np.float32), "x": np.random.choice([640, 1280, 1920], size=N), "y": np.random.choice([360, 720, 1080], size=N), "caption": [f"this is video {i}" for i in range(N)] } # Convert to Arrow Table and add to LanceDB batch = pa.table(data, schema=schema) tbl.add(batch) ``` Here's how to register a simple UDF: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf def area_udf(x: int, y: int) -> int: return x * y @udf def download_udf(filename: str) -> bytes: ... # {'new column name': <udf>, ...} # simple_udf's arguments are `x` and `y` so the input columns are # inferred to be columns `x` amd `y` tbl.add_columns({"area": area_udf, "content": download_udf }) ``` ### Registering Multi-Output UDFs Use a multi-output UDF when one expensive read or decode can produce several features. For example, if a table stores image bytes, a single UDF can open the image once and return `height`, `width`, and an embedding column together. This avoids separate UDFs that would each read or decode the same image. Define the output shape with `typing.NamedTuple` and annotate the UDF return type as `geneva.Columns[YourNamedTuple]`. Passing that UDF directly to [`Table.add_columns()`](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) expands the result into multiple sibling columns using the `NamedTuple` field names. If those names need a namespace or would conflict with existing columns, wrap the UDF with `geneva.UnpackedUDF(udf, prefix="...")` before calling `add_columns()`. The prefix is added to each materialized column name while keeping the outputs in one logical feature group. Manage multi-output sibling columns as a group. Backfill, drop, or alter the full group together instead of changing only one sibling column. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from typing import NamedTuple import geneva from PIL import Image db = geneva.connect("/data/mydb") tbl = db.open_table("images") class ImageFeatures(NamedTuple): height: int width: int embedding: list[float] @geneva.udf def image_features(image: bytes) -> geneva.Columns[ImageFeatures]: img = Image.open(io.BytesIO(image)) # Read and decode the image once. embedding = embedding_model.encode(img) return ImageFeatures( height=img.height, width=img.width, embedding=embedding, ) # Adds sibling columns named "height", "width", and "embedding". tbl.add_columns(image_features) # Or add the same outputs with a prefix to avoid name conflicts. tbl.add_columns(geneva.UnpackedUDF(image_features, prefix="image_")) ``` Batched UDFs require return type in their `udf` annotations ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32()) def batch_filename_len(filename: pa.Array) -> pa.Array: ... # {'new column name': <udf>} # batch_filename_len's input, `filename` input column is # specified by the UDF's argument name. tbl.add_columns({"filename_len": batch_filename_len}) ``` or ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32()) def recordbatch_filename_len(batch: pa.RecordBatch) -> pa.Array: ... # {'new column name': <udf>} # batch_filename_len's input. pa.RecordBatch typed UDF # argument pulls in all the column values for each row. tbl.add_columns({"filename_len": recordbatch_filename_len}) ``` Similarly, a stateful UDF is registered by providing an instance of the Callable object. The call method may be a per-record function or a batch function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 1536)) class OpenAIEmbedding(Callable): ... def __call__(self, text: str) -> pa.Array: ... # OpenAIEmbedding's call method input is inferred to be 'text' of # type string from the __call__'s arguments, and its output type is # a fixed size list of float32. tbl.add_columns({"embedding": OpenAIEmbedding()}) ``` ## Changing data in computed columns Let's say you backfilled data with your UDF then you noticed that your data has some issues. Here are a few scenarios: 1. All the values are incorrect due to a bug in the UDF. 2. Most values are correct but some values are incorrect due to a failure in UDF execution. 3. Values calculated correctly and you want to perform a second pass to fixup some of the values. In scenario 1, you'll most likely want to replace the UDF with a new version and recalculate all the values. You should perform a `alter_table` and then `backfill`. In scenario 2, you'll most likely want to re-execute `backfill` to fill in the values. If the error is in your code (certain cases not handled), you can modify the UDF, and perform an `alter_table`, and then `backfill` with some filters. In scenario 3, you have a few options. A) You could `alter` your UDF and include the fixup operations in the UDF. You'd `alter_table` and then `backfill` recalculating all the values. B) You could have a chain of computed columns -- create a new column, calculate the "fixed" up values and have your application use the new column or a combination of the original column. This is similar to A but does not recalculate A and can incur more storage. C) You could `update` the values in the column with the fixed up values. This may be expedient but also sacrifices reproducibility. The next section shows you how to change your column definition by `alter`ing the UDF. ## Altering UDFs You now want to revise the code. To make the change, you'd update the UDF used to compute the column using the `alter_columns` API and the updated function. The example below replaces the definition of column `area` to use the `area_udf_v2` function. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.alter_columns({"path": "area", "udf": area_udf_v2} ) ``` After making this change, the existing data already in the table does not change. However, when you perform your next basic `backfill` operation, all values would be recalculated and updated. If you only wanted some rows updated, you could perform a filtered backfill, targeting the specific rows that need the new upates. For example, this filter would only update the rows where area was currently null. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.backfill("area", where="area is null") ``` ## Auto-backfill For columns whose values should always stay in sync with their source data, set `auto_backfill=True` on the UDF. On LanceDB Enterprise (`db://` connections), the column is then recomputed for you automatically — you don't need to call `backfill()` yourself. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.int32(), version="2", auto_backfill=True) def area_udf(x: int, y: int) -> int: return x * y # Register a new auto-backfill column... tbl.add_columns({"area": area_udf}) # ...or re-point an existing column to an auto-backfill UDF tbl.alter_columns({"path": "area", "udf": area_udf}) ``` ### How it works The `auto_backfill` flag is recorded in the column's metadata when the column is added or altered. LanceDB Enterprise's managed agent watches for columns that need recomputation and dispatches a [distributed backfill job](/oss/v0-41-0/geneva/jobs/backfilling/) automatically — there is no manual trigger and no status polling. A column is recomputed when, for example: * **New rows are added** to the table (`tbl.add(...)`), leaving the column null for those rows. * **The UDF version changes** — you bump `version=` and `alter_columns()` to the new function. > [!NOTE] > > Auto-backfill is an enterprise feature. On direct object-storage or local-filesystem > connections there is no managed agent, so `auto_backfill=True` has no effect and you must run > `backfill()` explicitly. Reference: * [`alter_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.alter_columns) * [`add_columns` API](https://lancedb.github.io/geneva/api/table/#geneva.table.Table.add_columns) * [UDF](https://lancedb.github.io/geneva/api/udf/) — full `@udf` decorator reference including `data_type`, `num_gpus`, `auto_backfill`, `batch_size`, and other options # Audit Log Source: https://docs.lancedb.com/oss/v0-41-0/governance/audit-log The durable record of access attempts in the cluster: its schema, how to query it, and how to grant access. **Applies to:** Embedded ❌, Enterprise ✅ Every authorization check in LanceDB Enterprise -- the principal, the privilege that was checked, and the object it was checked against -- can be recorded as a durable audit log entry. On a failed check, the first failure is logged; on success, the final successful check is logged. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Request arrives"] --> C["Authorization check"] C -->|denied| L1["Log the first failed check"] C -->|granted| L2["Log the final successful check"] L1 --> T[("__audit_log table<br/>system database")] L2 --> T T --> Q["SELECT ... FROM system.public.__audit_log"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class T accent ``` A deployment chooses how audit records are kept: discarded, written alongside ordinary application logs, or stored durably as rows in a Lance table. Only the durable Lance-backed sink produces something you can query with SQL -- the other two modes exist, but leave nothing in the table this page describes. ## Schema | Column | Type | Nullable | What it holds | | - | - | - | - | | `AccessId` | string | no | The record's own unique ID, a UUIDv4 in hyphenated text form | | `AccessTime` | timestamp (microsecond, UTC) | no | When the check happened | | `PrincipalId` | string | no | The checked principal's ID | | `PrincipalName` | string | yes | The principal's display name, where known | | `Object` | string | yes | The object checked against, when the operation maps to a single object | | `AccessType` | string | no | The privilege that was checked | | `Description` | string | no | A human-readable description of the check | | `RequestId` | string | yes | The query node's own request ID, for correlating with request logs | | `Granted` | boolean | no | Whether the check succeeded | `RequestId` ties an authorization decision back to the request that produced it -- both the REST and Flight SQL transports accept only UUID request IDs, generating one when a request arrives without a valid one, so this column is always a canonical UUID string when present. ## Accessing it The audit log is an ordinary table, not a special API -- it lives in the `system` database's `public` namespace under the name `__audit_log` by default (a deployment can configure a different suffix, producing `__audit_<suffix>` instead, but the `__audit_` prefix is fixed to keep every audit table in its own part of the system database's namespace). Query it the same way you would any other table, with its full three-part name: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT PrincipalName, AccessType, Object, Granted, AccessTime FROM system.public.__audit_log WHERE Granted = false ORDER BY AccessTime DESC LIMIT 100 ``` ## Durability The Lance-backed sink batches records in the background instead of writing on the request path: a batch flushes once it reaches a configured size or once its oldest record has waited a configured linger period, whichever comes first. Its queue holds a bounded number of pending records; once full, requests producing new records wait for the writer to drain it rather than having a record dropped, and a failed write is retried with growing backoff rather than abandoned -- so a sink that cannot keep up applies back pressure and, if sustained, eventually blocks request handling instead of silently losing entries. The audit table is opened at service startup rather than on first use, so a misconfigured or unreachable sink fails startup instead of surfacing the first time something needs to be logged. This page does not cover retention -- how long written records are kept, or whether anything prunes them -- which a deployment operator should confirm for your version and configuration. ## Granting access `system` is not a grantable database -- SQL refuses `GRANT ... ON DATABASE system`. Reaching into it instead requires `USAGE` on the `SYSTEM` authorization object, plus `SELECT` on the table itself. Only a superuser can run these grants. See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full `GRANT`/`REVOKE` syntax: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SYSTEM TO ROLE security_team GRANT SELECT ON TABLE system.public.__audit_log TO ROLE security_team ``` System `USAGE` is broad: beyond reaching the audit log, it also lets the grantee list every job and its events, look up identities, and run untargeted `SHOW GRANTS` / `SHOW ROLE BINDINGS`. Grant it deliberately, not as an incidental step toward audit-log access. The audit log itself still records who was granted access and who reads it -- granting and querying it are both authorization checks like any other, so they appear as rows in the table they govern. ## What to read next > [card] [Compliance](/oss/v0-41-0/enterprise/security) > > Certifications, data handling, and the controls a deployment provides. > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > The full privilege model, and how creation privileges resolve upward. # Authorization Source: https://docs.lancedb.com/oss/v0-41-0/governance/authorization Who may do what: an overview of LanceDB Enterprise's access control model. **Applies to:** Embedded ❌, Enterprise ✅ [Authentication](/oss/v0-41-0/enterprise/authentication) establishes who is calling. Authorization decides what they may do. An access control entry grants **one privilege** on **one object** to **one subject**. Everything on the Principals and Privileges pages is a consequence of that shape. ## Granting a privilege `GRANT` and `REVOKE` cover every object in the catalog -- system, database, schema/namespace, table, view, materialized view, secret, function, and storage integration. A Secret, the one a day-to-day user shares most often, looks like this: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research REVOKE USAGE ON SECRET platform.`model-api-key` FROM ROLE research ``` The caller must already hold `OWNERSHIP` on the object being granted (`GRANT` additionally requires the object to already exist; `REVOKE` does not, so an entry left on a dropped object can still be removed). A role need not exist beforehand, but a `USER` or `GROUP` name must resolve to exactly one identity in your identity provider, or the statement fails. See [Privileges](/oss/v0-41-0/governance/privileges) for the full statement syntax and every privilege each operation needs. See [Principals](/oss/v0-41-0/governance/principals) for who a grant can name. ## What to read next > [card] [Principals](/oss/v0-41-0/governance/principals) > > Users, groups, and roles -- where each comes from, and how a grant names one. > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > Every object's privileges, and the GRANT/REVOKE syntax that covers them. # Principals Source: https://docs.lancedb.com/oss/v0-41-0/governance/principals Users, groups, and roles: where each comes from, and how a GRANT or REVOKE statement names one. **Applies to:** Embedded ❌, Enterprise ✅ A grant names one of three kinds of subject: | Subject | Where it comes from | | - | - | | User (principal) | Your identity provider -- OIDC, Microsoft Entra, Okta, or Keycloak. LanceDB never creates one. | | Group | Also your identity provider. LanceDB never creates one. | | Role | LanceDB itself. There is no statement that creates a role -- naming one in a grant is what brings it into existence. | ## Naming a subject in SQL `GRANT` and `REVOKE` accept a role, user, or group name directly, with an optional keyword to disambiguate: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice GRANT USAGE ON SECRET platform.`model-api-key` TO GROUP `data-science` ``` A `USER` or `GROUP` name is resolved against your identity provider, but only after the caller's `OWNERSHIP` on the object is checked. A name that isn't found, or that matches more than one identity, is an error -- not a silent no-op. `ROLE` needs no such lookup, since a role is simply whatever name a grant has used. Name several subjects of the same kind in one statement by omitting the keyword after the first: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service ``` ## Role membership in SQL SQL manages which users or groups a role applies to -- its membership -- directly: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT ROLE analysts TO USER alice GRANT ROLE analysts TO GROUP `data-science` REVOKE ROLE analysts FROM USER alice SHOW ROLE BINDINGS ``` Changing membership (`GRANT`/`REVOKE ROLE`) needs system `OPERATE`; `SHOW ROLE BINDINGS` needs only system `USAGE`. A role binding accepts a `USER` or `GROUP` on the receiving side, never another `ROLE` -- granting a privilege to a role before anyone is a member of it is still valid; the role simply has no effect until it has members. ## What to read next > [card] [Authorization](/oss/v0-41-0/governance/authorization) > > The access-control model a grant is built from. > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > Every object's privileges, and the GRANT/REVOKE syntax that covers them. # Privileges Source: https://docs.lancedb.com/oss/v0-41-0/governance/privileges Every privilege, which object it's granted on, and the GRANT/REVOKE syntax that covers each one. **Applies to:** Embedded ❌, Enterprise ✅ | Privilege | Granted on | Allows | | - | - | - | | `OWNERSHIP` | any object | full authority over it, including granting any other privilege | | `USAGE` | system | listing, describing and reading the events of jobs, and looking up other identities | | `USAGE` | database | accessing the namespaces inside | | `USAGE` | namespace | accessing the tables inside | | `USAGE` | secret | binding it to a Function, and resolving its value at evaluation time | | `USAGE` | function | binding it to a column, and refreshing a column it computes | | `USAGE` | storage integration | reading through it or importing with it | | `SELECT` | table, view | reading rows | | `INSERT` | table | appending rows | | `UPDATE` | table | modifying existing rows | | `UPDATE` | secret | rotating it, without the right to bind or read it | | `DELETE` | table | deleting rows | | `CREATE_DATABASE` | system | creating a database | | `CREATE_NAMESPACE` | database, namespace | creating immediate child namespaces | | `CREATE_TABLE` | namespace | creating a table in it | | `CREATE_MATERIALIZED_VIEW` | namespace | creating a materialized view in it | | `CREATE_VIEW` | namespace | creating a non-materialized view in it | | `CREATE_SECRET` | namespace | creating a Secret in it | | `CREATE_FUNCTION` | namespace | registering a Function in it | | `CREATE_STORAGE_INTEGRATION` | namespace | registering a storage integration in it | | `OPERATE` | system | controlling jobs (cancel, pause, resume), managing caches, reading server configuration, and managing role membership | `OWNERSHIP` is never revoked -- granting it again transfers it to a new owner instead, and a single `GRANT OWNERSHIP` statement names exactly one subject. The caller must already hold `OWNERSHIP` on an object to change any grant on it. > [!NOTE] > > `CREATE_MATERIALIZED_VIEW` and `CREATE_VIEW` are separate privileges because > [the two objects differ](/oss/v0-41-0/basics/catalog): one stores rows and is refreshed, > the other stores only a query. Granting the ability to create one does not > grant the other. ## Creating an object you don't own yet Creating a database or namespace checks its *parent*, not itself: one with no owner -- because it doesn't exist yet -- falls back to `CREATE_DATABASE` on the system, or `CREATE_NAMESPACE` on its parent namespace, and the creator becomes its owner. This is what makes creation possible at all, so holding `CREATE_DATABASE` is enough to create a table in a database that has not been created yet. ## Granting privileges from SQL `GRANT` and `REVOKE` reach every object in the table above -- `SYSTEM`, `DATABASE`, `SCHEMA`, `NAMESPACE <name> [IN <schema>]`, `TABLE`, `VIEW`, `MATERIALIZED VIEW`, `SECRET`, `STORAGE INTEGRATION`, and `FUNCTION` -- with the same statement shape. `SCHEMA` and `NAMESPACE` both target a namespace, but aren't interchangeable spellings: `SCHEMA` takes a namespace's complete path, while `NAMESPACE` takes one unqualified component, resolved under an explicit parent (`IN <schema>`) or the session's current namespace when `IN` is omitted: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT SELECT ON VIEW dashboard TO ROLE analysts GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins GRANT USAGE ON FUNCTION platform.embed TO ROLE etl GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` A materialized view is a table for authorization purposes: the same `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` privileges apply, and granting one does not reach the non-materialized `VIEW` beside it. | Target in the statement | Privileges it accepts | | - | - | | `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | | `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | | `SCHEMA` / `NAMESPACE` | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | | `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | | `VIEW` | `OWNERSHIP`, `SELECT` | | `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | | `FUNCTION` | `OWNERSHIP`, `USAGE` (bind it to a column) | | `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | See [GRANT and REVOKE](/oss/v0-41-0/sql/ddl/grant) for the full statement syntax, including every grantee form (`ROLE`, `USER`, `GROUP`, the `ID '<id>'` form) and every status a statement can return, shared by every target above. The REST ACL API covers the same objects and reaches further back: it works against deployments whose SQL surface does not yet expose a given target, and is the only option for a client that does not speak SQL. ### What each Secret operation requires | Operation | Requires | | - | - | | Create a Secret | `CREATE_SECRET` on the namespace. The creator owns the new Secret. | | Rotate (`alter`) | `UPDATE` on the Secret | | Describe | `USAGE` on the Secret | | List | `USAGE` on the database and the namespace | | Drop | `OWNERSHIP` on the Secret. Dropping also deletes its grants. | | Bind it to a Function | `USAGE` on the Secret | `UPDATE` is deliberately separate from `USAGE`, so a rotation service can replace a value without being able to bind the Secret to a Function of its own. ### Example: sharing one key * A **platform operator** owns the `platform` namespace. They create `platform$model-api-key`, then grant the `research` group `USAGE` on that one Secret. * A **researcher** in `research` registers a Function bound to `platform$model-api-key`. Binding any other Secret in `platform` is refused. * A **table owner** in `research` adds a column computed by that Function. They hold `USAGE` on the Secret through the group, but are refused until they also hold `USAGE` on the Function. * **Analysts** read the resulting column with table access alone -- no Function runs on the read path, so they need no grant on the Function or its Secret. ## What to read next > [card] [Authorization](/oss/v0-41-0/governance/authorization) > > The access-control model a grant is built from. > [card] [Principals](/oss/v0-41-0/governance/principals) > > Users, groups, and roles -- where each comes from, and how a grant names one. # Full-Text Search (FTS) Indexing Source: https://docs.lancedb.com/oss/v0-41-0/indexing/fts-index Create and tune BM25-based full-text search indexes in LanceDB. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB provides performant full-text search based on BM25, allowing you to incorporate keyword-based search in your retrieval solutions. This page shows examples on how to create and configure FTS indexes in LanceDB Embedded and LanceDB Enterprise, using the synchronous and asynchronous APIs. > [!NOTE] > > In LanceDB Enterprise, `create_fts_index` API returns immediately, but index building happens asynchronously. ## Creating FTS Indexes ### Synchronous API Use `create_fts_index` with synchronous LanceDB connections: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "fts-index-create" table = db.open_table(table_name) table.create_fts_index("text") ``` Check FTS index status using the API: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "fts-index-wait" table = db.open_table(table_name) table.create_fts_index("text") index_name = "text_idx" table.wait_for_index([index_name]) ``` `wait_for_index(...)` waits until the named FTS index exists and `index_stats(...)` reports `num_unindexed_rows == 0`. It can time out if writes keep adding rows faster than the index catches up. If a table has multiple FTS indexes, specify the target text column when querying instead of relying on implicit selection. ### Asynchronous API When using async connections (`connect_async`), use `create_index` with the `FTS` configuration: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import asyncio import lancedb import polars as pl from lancedb.index import FTS data = pl.DataFrame( { "id": [1, 2], "text": [ "His first language is spanish", "Her first language is english", ], } ) async def main(data: pl.DataFrame): uri = "ex_lancedb" db = await lancedb.connect_async(uri) tbl = await db.create_table("my_text", data=data, mode="overwrite") await tbl.create_index("text", config=FTS(language="English")) response = await tbl.search("spanish", query_type="fts") result = await response.limit(1).to_polars() print(result) return result if __name__ == "__main__": asyncio.run(main(data)) ``` > [!NOTE] > > The `create_fts_index` method is not available on `AsyncTable`. Use `create_index` with `FTS` config instead. The current FTS implementation is Lance-native. Legacy Tantivy-only options, including `use_tantivy`, are no longer accepted by the index creation APIs. ## Nested field paths FTS indexes can target text leaves inside struct columns by passing a dotted path (for example, `payload.text`). The same path works for [`MatchQuery`](/oss/v0-41-0/search/full-text-search) and [`PhraseQuery`](/oss/v0-41-0/search/full-text-search), and for the `columns` argument on async `nearest_to_text` queries. You can point an index at any string leaf nested in a struct, regardless of depth. The struct container itself isn't indexable: you have to name a specific text field. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MatchQuery, PhraseQuery table = db.open_table("fts-index-nested") # Index a text leaf inside a struct column using a dotted path. table.create_fts_index("payload.text", with_position=True) # The same dotted path works in MatchQuery and PhraseQuery. matches = ( table.search(MatchQuery("puppy", "payload.text")).limit(5).to_list() ) phrases = ( table.search(PhraseQuery("puppy runs", "payload.text")) .limit(5) .to_list() ) ``` LanceDB rejects paths that don't resolve to a text leaf: * A struct container (for example, `payload`): raises `ValueError: FTS index cannot be created ...`. * A non-text leaf such as an integer or float (for example, `payload.count`): raises the same error. * A path that doesn't exist in the schema (for example, `payload.missing`): raises `ValueError: Field path ... not found`. The async API accepts the same dotted paths through `create_index`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS await async_table.create_index("payload.text", config=FTS(with_position=True)) ``` ## Configuration Options ### FTS Parameters | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `with_position` | bool | `False` | Store token positions (required for phrase queries) | | `base_tokenizer` | str | `"simple"` | Text splitting method (`simple`, `whitespace`, `raw`, `ngram`, `icu`, `jieba/*`, or `lindera/*`) | | `language` | str | `"English"` | Language for stemming and stop-word filters. Choose CJK and mixed-language segmentation with `base_tokenizer`. | | `max_token_length` | int | `40` | Maximum token size; longer tokens are omitted | | `lower_case` | bool | `True` | Lowercase tokens | | `stem` | bool | `True` | Apply stemming (`running` → `run`) | | `remove_stop_words` | bool | `True` | Drop common stop words | | `ascii_folding` | bool | `True` | Normalize accented characters | | `custom_stop_words` | list\[str] | `None` | Explicit stop-word list that replaces the built-in list. Requires `remove_stop_words=True`. | | `ngram_min_length` | int | `3` | Minimum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `ngram_max_length` | int | `3` | Maximum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `prefix_only` | bool | `False` | Index only prefix n-grams rather than all substrings. Applies only when `base_tokenizer="ngram"`. | | `block_size` | int | `128` | Number of documents per compressed posting block. Supported values are `128` and `256`. Setting this to `256` opts in to the experimental FTS V3 layout. | > [!NOTE] > > * `max_token_length` can filter out base64 blobs or long URLs. > * Disabling `with_position` reduces index size but disables phrase queries. > * `ascii_folding` helps with international text (e.g., “café” → “cafe”). ### Tokenizer choices `base_tokenizer` controls segmentation before token filters run: * `simple`, `whitespace`, and `raw` cover common tokenization strategies for space-delimited text. * `ngram` indexes overlapping character spans for substring-style matching. * `icu` uses bundled ICU4X word segmentation for mixed-language text and scripts where whitespace splitting is not enough. ICU stands for [International Components for Unicode](https://icu.unicode.org/), and this tokenizer does not need external model files. * `jieba/*` is for Chinese word segmentation with Jieba. * `lindera/*` loads a compiled Lindera dictionary, such as `lindera/ipadic` for Japanese or `lindera/ko-dic` for Korean. Model-backed tokenizers such as `jieba/default`, `lindera/ipadic`, and `lindera/ko-dic` require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to another model root. For example, `jieba/default` is resolved under `<model-home>/jieba/default/...`. For a table in LanceDB Enterprise, the files must be present where the deployment builds and queries the index, so ask its administrator whether they are installed. `language` is used by token filters, not by the base tokenizer. Stemming and language-specific stop-word removal support Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. The ICU tokenizer uses a combined multilingual stop-word list. An explicit `custom_stop_words` list replaces the built-in list for either tokenizer. > [!WARNING] > > Lance `15.0.0-beta.1` revises the built-in stop-word lists, including the multilingual list used by ICU. Existing index metadata records tokenizer settings, but does not freeze these built-in lists. Rebuild affected FTS indexes with the same configuration before serving queries with the updated SDK, so stored terms and query tokens use the same lists. Indexes with stop-word removal disabled or an explicit `custom_stop_words` list are unaffected by this change. ### Posting block size `block_size` controls the number of documents packed into each compressed posting block on disk. The default of `128` matches the current FTS layout and is the right choice for most workloads. Setting it to `256` opts in to the experimental FTS V3 format, which changes how postings are encoded and may introduce breaking changes in future releases. Any other value is rejected at index creation time. You can set the option through either the synchronous or asynchronous API. In the async Python API, pass it on the `FTS` config, and in the TypeScript API use the camelCase `blockSize` field on `FtsOptions`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import FTS await async_table.create_index("text", config=FTS(block_size=256)) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.createIndex("text", { config: lancedb.Index.fts({ blockSize: 256 }), }); ``` ### Phrase Query Configuration Enable phrase queries by setting: | Parameter | Required Value | Purpose | | :- | :- | :- | | `with_position` | `True` | Track token positions for phrase matching | | `remove_stop_words` | `False` | Preserve stop words for exact phrase matching | ## Indexing nested string fields You can build an FTS index on a string field inside a struct by passing its full dotted path, like `nested.text`. The same path is used when you query the index through `fts_columns`, and the indexed column is reported back as the full path from `list_indices()`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema: pa.struct([pa.field("text", pa.string())]) stored under the `nested` column. table.create_fts_index("nested.text") results = ( table.search("puppy", query_type="fts", fts_columns="nested.text") .limit(5) .to_list() ) ``` > [!NOTE] > > Use the canonical Lance path: dot-separate each struct field from root to leaf (for example, `metadata.author.name`). The same convention applies to scalar and vector indexes. # GPU Indexing Source: https://docs.lancedb.com/oss/v0-41-0/indexing/gpu-indexing Build a vector index faster with GPU acceleration, manually in LanceDB Embedded or automatically in LanceDB Enterprise. **Applies to:** Embedded ✅, Enterprise ✅ GPU acceleration can reduce the time needed to build vector indexes on large datasets. Actual build time depends on the index configuration, vector dimensions, storage throughput and available GPU resources. > [!NOTE] > > **Automatic GPU indexing** > > Automatic GPU Indexing is currently only available in [LanceDB Enterprise](/oss/v0-41-0/index#architecture). > Please [contact us](https://www.lancedb.com/contact) to enable this feature for your deployment. > > The vector index is created when you call `create_index`. The backend uses GPU resources > to build `IVF_PQ` indexes, with the number of GPUs set by the deployment's configuration. > > This process is also asynchronous by default, but you can use `wait_for_index` to convert it > into a synchronous process by waiting until the index is built. `wait_for_index(...)` waits for the index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. It can time out if the table is receiving continuous writes while the build is trying to catch up. GPU acceleration changes how the vector index is built, not the lifecycle after the build. In the embedded library, rows appended later still need `optimize()` before they are part of the index; a deployment adds them in the background -- see [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing). `fast_search()` only searches indexed rows. ## Manual GPU indexing in LanceDB Embedded You can use the Python SDK to manually create the `IVF_PQ` index on a GPU. You'll need [PyTorch>2.0](https://pytorch.org/). Note that GPU-based indexing is currently only supported by the synchronous SDK in LanceDB Embedded. Specify the values `cuda` or `mps` (on Apple Silicon) for the `accelerator` parameter to enable GPU training on your device. ### GPU indexing on Linux ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( num_partitions=256, num_sub_vectors=96, accelerator="cuda", ) ``` ### GPU indexing on macOS (Apple Silicon) ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( num_partitions=256, num_sub_vectors=96, accelerator="mps", ) ``` ## Performance considerations * GPU memory usage scales with `num_partitions` and vector dimensions * Size GPU memory for the training batches and index configuration * Monitor memory use while choosing training batch sizes * Measure build time and recall before changing training settings ## Troubleshooting If you encounter the error `AssertionError: Torch not compiled with CUDA enabled`, you need to [install PyTorch with CUDA support](https://pytorch.org/get-started/locally/). ## What to read next > [card] [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing) > > Keeping an index up-to-date as new data arrives. > [card] [Slurm](/oss/v0-41-0/deployment/slurm) > > Running these GPU workers alongside training on shared Slurm-scheduled infrastructure. # Incremental Indexing Source: https://docs.lancedb.com/oss/v0-41-0/indexing/incremental-indexing Keep an index up-to-date as new data arrives, without a full rebuild. **Applies to:** Embedded ✅, Enterprise ✅ As you add new data to your LanceDB tables, your indexes may become outdated. Reindexing is the process of updating the index to account for new data. This applies to either a full-text search (FTS) index or a vector index. Reindexing is an important operation to run periodically as your data grows, as it has performance implications. As data is being added and a reindex operation is running, LanceDB will combine results from the existing index with exhaustive/flat search on the new data. This is done to ensure that you're still retrieving results over all your data, but it does come at a performance cost. The more data that you add without reindexing, the impact on latency (due to exhaustive search) can be noticeable. Rather than dropping an existing index entirely and reindexing from scratch, LanceDB supports **incremental indexing**. > [!NOTE] > > **Enterprise job types:** an index build runs as `reindex_` followed by the > algorithm, such as `reindex_ivf_pq`, `reindex_btree` or `reindex_fts`, and so > does folding new rows into an existing index. A create-only build, one that must > not replace an existing index, runs as `create_` followed by the algorithm > instead; Python's `create_scalar_index` and `create_fts_index` ask for that by > default. The name says which algorithm is building, not a separate feature. ## Triggering an incremental update In the embedded library, you trigger an incremental indexing operation on updated data with the `optimize()` method on a table. A deployment does this for you and does not support `optimize()`, as described below. Table optimization performs three maintenance operations: 1. **Compaction**: merges small fragments into larger ones to improve read performance 2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/oss/v0-41-0/maintenance/cleanup) for how retention works 3. **Index update**: adds newly-ingested data to existing vector, scalar, and FTS indexes ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("reindexing_incremental") table.add([{"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"}]) table.optimize() ``` Enterprise LanceDB Enterprise supports incremental reindexing through an automated background process. Once enough new rows have been added to a table, the system automatically adds them to its indexes. As the dataset grows, indexes are asynchronously updated in the background. * While indexes are being rebuilt, queries use brute force methods on unindexed rows, which may temporarily increase latency. If you can omit unindexed rows, set `fast_search=True` to search only indexed data. This can return incomplete results while indexing catches up. * Use `index_stats()` to view the number of unindexed rows. This will be zero when indexes are fully up-to-date. If you call `wait_for_index(...)`, it polls the same status and can time out while continuous writes keep adding unindexed rows. * Rows below the deployment's threshold stay unindexed until more arrive, so the count can stay above zero without further writes. `FM` indexes are not updated in the background. The benefit of using LanceDB Enterprise is that it automates the reindexing process and operates continuously in the background, minimizing the impact on latency under high loads. In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. Opening a table in LanceDB Embedded logs a warning at most once per table per process when any index has at least 1,000,000 unindexed rows. Set `LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default. ## Index maintenance jobs Two further Enterprise job types keep an index correct as the rows underneath it move, rather than adding new rows to it: | Job type | What it does | | - | - | | `index_remap` | Reassigns index entries after row ids shift underneath an index (the kind of remap a delta compaction can require). | | `spfresh_merge` | Merges SPFresh-managed segments for indexes that use it. | See [Advanced Conflict Resolution](/oss/v0-41-0/enterprise/advanced-conflict-resolution) for why `index_remap` exists as a separate, deferred job rather than happening synchronously inside every compaction. ## What to read next > [card] [Distributed Indexing](/oss/v0-41-0/enterprise/distributed-indexing) > > How an index build itself scales across the jobs fleet. > [card] [GPU Indexing](/oss/v0-41-0/indexing/gpu-indexing) > > Building a vector index faster with GPU acceleration. # Indexing Data Source: https://docs.lancedb.com/oss/v0-41-0/indexing/index Optimize search performance with LanceDB using vector indexes, full-text search, scalar indexes, and more. **Applies to:** Embedded ✅, Enterprise ✅ Indexes speed up searches and filters by organizing data for specific query patterns. LanceDB supports three main index families: * **Vector Index**: Efficiently searches for similar vectors across high-dimensional data (e.g. images, audio, or text embeddings) * **Full-Text Search Index**: Enables fast keyword-based searches by indexing words and phrases * **Scalar Index**: Accelerates filtering of structured numeric or categorical data ## Supported Indexes | Index | Use Case | Description | | :- | :- | :- | | `IVF` (Vector) | Large-scale vector search with configurable accuracy/speed trade-offs. | Inverted File Index: a partition-based approximate nearest neighbor algorithm that groups similar vectors into partitions for efficient search. **Quantizations**: `None/Flat` `PQ` `SQ` `RQ` | | `IVF_HNSW` (Vector) | Large-scale vector search requiring both high recall and efficient partitioning. Combines the scalability of IVF with the search quality of HNSW. | Hybrid index combining IVF partitioning with HNSW graphs in each partition. Provides improved search quality over pure IVF while maintaining scalability. **Quantizations**: `None/Flat` `SQ` `PQ` | | `FTS` (Full-text search) | String columns (e.g., title, description, content) requiring keyword-based search with BM25 ranking. | Full-text search index using BM25 ranking algorithm. Tokenizes text with configurable tokenization, stemming, stop word removal, and language-specific processing. | | `BTree` (Scalar) | Numeric, temporal, and string columns with mostly distinct values. Best for selective equality, inequality, and range predicates. | Sorted index storing sorted copies of scalar columns with block headers in a btree cache. Header entries map to blocks of rows (4096 rows per block) for efficient disk reads. | | `Bitmap` (Scalar) | Low-cardinality columns with few thousand or fewer distinct values. Accelerates equality and range filters. | Stores a bitmap for each distinct value in the column, with one bit per row indicating presence. Memory-efficient for low-cardinality data. | | `LabelList` (Scalar) | List columns (e.g., tags, categories, keywords) requiring `array_has_all` or `array_has_any` filters. | Scalar index for `List<T>` and `LargeList<T>` columns of primitive values, using an underlying bitmap index structure to enable fast array membership lookups. | | `FM` (Scalar) | String or binary columns that need raw substring search. | FM-Index over `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary` data for filters such as `contains(path, 'needle')`. Use FTS instead for tokenized word search and BM25 ranking. | | `NGram` (Scalar) | String columns that need substring search using character trigrams. | Trigram index over `Utf8` and `LargeUtf8` columns that narrows `contains(col, 'needle')` and some `LIKE` and regular expression predicates to rows sharing the query's trigrams, then rechecks the predicate. A query shorter than the trigram length cannot use it; use `FM` for arbitrary length substrings or `FTS` for tokenized word search. | The Python `NGram` configuration requires a newer client than 0.41.0; see [its SDK requirements](/oss/v0-41-0/indexing/scalar-index#ngram-index-for-substring-search). A deployment builds the vector indexes `IVF_FLAT`, `IVF_PQ`, `IVF_RQ` and `IVF_HNSW_SQ`. `IVF_SQ`, `IVF_HNSW_FLAT` and `IVF_HNSW_PQ` are built only by the embedded library. ## Quantization LanceDB also supports several [quantization](/oss/v0-41-0/indexing/vector-index) methods, used by vector indexes to compress vectors and reduce storage requirements: | Quantization | Use Case | Description | | :- | :- | :- | | `PQ` (Product Quantization) | Default choice for most vector search scenarios. Use when you need to balance index size and recall. | Divides vectors into subvectors and quantizes each subvector independently. Provides a good balance between compression ratio and search accuracy. | | `RQ` (RabitQ Quantization) | Use when you need maximum compression or have specific per-dimension requirements. | Per-dimension quantization using a RabitQ codebook. Provides fine-grained control over compression per dimension. For `IVF_RQ`, vector dimensions must be divisible by `8`. | | `SQ` (Scalar Quantization) | Use when you need faster indexing or when vector dimensions have consistent value ranges. | Quantizes each dimension independently. Simpler than PQ but typically provides less compression. | | `None/Flat` | Use for binary vectors (with `hamming` distance) or when you need maximum recall and have sufficient storage. | No quantization; stores raw vectors. Provides the highest accuracy but requires more storage and memory. | ## Performance #### Vector indexes If vector search latency climbs with table size (i.e., queries that ran in milliseconds on a small table take seconds as it grows to millions of rows), check whether the query is scanning every vector without an index. The point at which an index helps depends on vector dimensions, hardware and your latency target. Measure your workload before choosing an index. Pick the type by your data shape: | Index | When to use | | - | - | | `IVF_PQ` | General-purpose default, and what a deployment builds when it is set to index a column automatically. Higher accuracy than RQ at small dimensions (≤ 256). | | `IVF_RQ` | Maximum compression on high-dim vectors, faster builds than PQ. | | `IVF_HNSW_SQ` | Best recall/latency for unfiltered search; higher latency variance under selective filters. | | `IVF_FLAT` | Required for binary vectors with `hamming`. | The distance metric is fixed once the index is built. Pick the distance metric based on how the embedding model was trained: `cosine` (unnormalized), `dot` (already-normalized, best performance), `l2` (general-purpose, default), `hamming` (binary). If a query explicitly requests a different metric, the index cannot be used and the query falls back to a brute-force scan; a deployment can be configured to reject that scan on a large table. For parameter tuning, see [Vector Indexing](/oss/v0-41-0/indexing/vector-index). #### Scalar indexes Scalar indexes can reduce the rows scanned for selective filters and speed up `merge_insert` key lookups. Start with columns used frequently in those operations, then use [query plans](/oss/v0-41-0/basics/sql#query-plans) to check whether the index helps. Choose the index type based on the column's values: | Index | Best for | | - | - | | `BTREE` (default) | Numeric, string, temporal columns with mostly distinct values | | `BITMAP` | Boolean and low-cardinality columns (\< \~1,000 distinct values) | | `LABEL_LIST` | `List<T>` columns queried with `array_has_any` / `array_has_all` | See [Scalar Indexing](/oss/v0-41-0/indexing/scalar-index). #### Full-text search Token positions and retained stop words increase the information stored in a full-text index. Keep the defaults for basic keyword search; enable `with_position=True` and retain the needed stop words for phrase queries. See [FTS Indexing](/oss/v0-41-0/indexing/fts-index) configuration options for the full set of options. # Scalar Indexing Source: https://docs.lancedb.com/oss/v0-41-0/indexing/scalar-index Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization. **Applies to:** Embedded ✅, Enterprise ✅ Scalar indexes accelerate filters on values such as numbers, categories and strings. Use them for selective table queries or metadata filters combined with vector and full-text search. LanceDB supports five types of scalar indexes: * `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values. * `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags). * `LABEL_LIST`: Special index for `List<T>` and `LargeList<T>` columns of primitive values supporting `array_has_all` and `array_has_any` queries. * `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`. * `NGRAM`: Trigram index over UTF-8 string columns that accelerates substring search via `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters. > [!TIP] > > Use scalar indexes with: > > * Vector search (prefilter results using metadata) > * Full-text search (combining keyword matching with structured filters) > * SQL scans (optimizing WHERE clauses on scalar columns) > * Key-value lookups (enabling rapid primary key-based retrievals) ## Choosing the Right Index Type | Data Type | Filter | Index Type | | :- | :- | :- | | Numeric, String, Temporal | `<`, `=`, `>`, `in`, `between`, `is null` | `BTREE` | | Boolean, numbers or strings with fewer than 1,000 unique values | `<`, `=`, `>`, `in`, `between`, `is null` | `BITMAP` | | List of low cardinality of numbers or strings | `array_has_any`, `array_has_all` | `LABEL_LIST` | | String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')` | `FM` | | String (`Utf8`, `LargeUtf8`) | `contains(col, 'needle')`, `LIKE`, regex | `NGRAM` | ## Scalar Index Operations ### 1. Build the Index You can create multiple scalar indexes within a table. By default, the index will be `BTREE`, but you can always configure another type like `BITMAP` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.open_table("scalar_index_build") tbl.create_scalar_index("book_id") tbl.create_scalar_index("publisher", index_type="BITMAP") ``` > [!NOTE] > > If you are using LanceDB Enterprise, the `create_scalar_index` API returns immediately, but the building of the scalar index is asynchronous. To wait until all data is fully indexed, you can specify the `wait_timeout` parameter on `create_scalar_index()` or call `wait_for_index()` on the table. ### 2. Check Index Status ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "label_idx" table.wait_for_index([index_name]) ``` `wait_for_index(...)` waits until the named scalar indexes exist and `index_stats(...)` reports `num_unindexed_rows == 0`. If a table is receiving steady writes, that fully indexed state may not stabilize before the timeout. In LanceDB Enterprise, rows added after the index was built are indexed only once enough have accumulated, so a small remainder can also keep the wait from finishing. ### 3. Update the Index Updating the table data (adding, deleting, or modifying records) requires that you also update the scalar index. In the embedded library, call `optimize`, which will trigger an update to the existing scalar index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add([{"vector": [7, 8], "book_id": 4}]) table.optimize() ``` > [!NOTE] > > New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically. ### 4. Run Indexed Searches The following scan will be faster if the column `book_id` has a scalar index: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("books") result = table.search().where("book_id = 2").limit(10).to_pandas() ``` Scalar indexes can also speed up scans containing a vector search or full text search, and a prefilter: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.open_table("book_with_embeddings") table.search([1.2] * 2).where("book_id != 3").limit(10).to_pandas() ``` ## FM-Index for substring search The `FM` index is a scalar index built over string or binary columns that accelerates substring lookups expressed as `contains(col, 'needle')`. Unlike the tokenized [FTS index](/oss/v0-41-0/indexing/fts-index), which matches whole words after tokenization, the FM-Index matches arbitrary substrings of the raw bytes. It works well for URLs, file paths, identifiers, log lines, or any column where you search for a fragment rather than a word. Use the FM-Index when: * Filters use `contains(col, 'needle')` (substring), not equality or word search. * The column is `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary`. * You want substring matches without paying for tokenization, language analysis, or BM25 scoring. Pick `FTS` instead when you need word-level relevance ranking, phrase queries, or language-aware tokenization. ### Create an FM-Index Build an FM-Index with the async `create_index` API by passing the `Fm` config in Python or `Index.fm()` in TypeScript. In Rust, use `Index::Fm(FmIndexBuilder::default())`. A deployment builds FM-Indexes too, but does not add new rows to them in the background as it does for the other scalar indexes. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import Fm await tbl.create_index("text", config=Fm()) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import { Index } from "@lancedb/lancedb"; await tbl.createIndex("text", { config: Index.fm() }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::index::Index; use lancedb::index::scalar::FmIndexBuilder; tbl.create_index(&["text"], Index::Fm(FmIndexBuilder::default())) .execute() .await?; ``` After the index is built, substring filters use it automatically: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search().where("contains(text, 'needle')").limit(10).to_pandas() ``` `list_indices()` reports the index type as `"Fm"`. ## NGram index for substring search > [!NOTE] > > The Python `NGram` configuration is not available in Python 0.41.0. Its > example below uses the [0.42.0b8 client](/oss/v0-41-0/basics/sdk#enterprise-client-versions). > Use the FM index above with Python 0.41.0. Rust's 0.41.0 API already supports > `Index::NGram`; the Python binding has a separate version requirement. The `NGram` index is a scalar index over UTF-8 string columns. It tokenizes values into overlapping character n-grams (using Lance's default trigram parameters) and uses them to accelerate `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters. Unlike the `FM` index, which matches arbitrary substrings of the raw bytes, the `NGram` index is trigram based, so a query shorter than the n-gram length cannot be served by it. ### Create an NGram index Build an NGram index with the async `create_index` API by passing the `NGram` config in Python. In Rust, use `Index::NGram(NGramIndexBuilder::default())`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import NGram await tbl.create_index("text", config=NGram()) ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::index::Index; use lancedb::index::scalar::NGramIndexBuilder; tbl.create_index(&["text"], Index::NGram(NGramIndexBuilder::default())) .execute() .await?; ``` After the index is built, substring filters use it automatically: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.search().where("contains(text, 'needle')").limit(10).to_pandas() ``` `list_indices()` reports the index type as `"NGram"`. ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. > [!NOTE] > > **To use `FixedSizeBinary`, ensure you have:** > > * Python SDK version `0.22.0` or later > * TypeScript SDK version `0.19.0` or later ### 1. Define UUID Type ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa ``` ### 2. Generate UUID Data ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def generate_random_names(): base_names = ["Alice", "Bob", "Carla", "David", "Eve", "Frank", "Grace"] letter = random.choice(string.ascii_uppercase) return f"{random.choice(base_names)} {letter}." def generate_uuids(num_items): return [uuid.uuid4().bytes for _ in range(num_items)] # Generate some UUIDs and random names n = 7 uuids = generate_uuids(n) names = [generate_random_names() for _ in range(n)] ``` ### 3. Create Table with UUID Column ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "index-on-uuid" uuid_array = pa.array(uuids, pa.uuid()) name_array = pa.array(names, pa.string()) schema = pa.schema( [ pa.field("id", pa.uuid()), pa.field("name", pa.string()), ] ) data_table = pa.Table.from_arrays([uuid_array, name_array], schema=schema) table = db.create_table(table_name, data=data_table, mode="overwrite") ``` ### 4. Create and Wait for the Index ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "id_idx" table.create_scalar_index("id") table.wait_for_index([index_name]) ``` ### 5. Perform Operations with the UUID Index ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} new_users = [ {"id": uuid.uuid4().bytes, "name": "Hannah D."}, {"id": uuid.uuid4().bytes, "name": "Ian B."}, ] # Insert or update using the UUID index table.merge_insert( "id" ).when_matched_update_all().when_not_matched_insert_all().execute(new_users) ``` ## Index nested fields You can build a scalar index on a field inside a struct column by passing the canonical dot-separated path to `create_index`. This is useful when filters target attributes nested under a `metadata`-style column, for example `metadata.user_id` or `metadata.event.type`. If a literal segment of the path itself contains a dot (for example a column named `user.id` nested inside `metadata`), wrap that segment in backticks so LanceDB can tell the dot apart from the path separator: `` metadata.`user.id` ``. `list_indices()` echoes the same canonical path back, so the column you pass in round-trips through index metadata regardless of nesting depth or escaping. Use the same path in filter predicates, for example `metadata.user_id = 42`. FTS and vector indexes follow the same path convention. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from lancedb.index import BTree metadata_type = pa.struct( [ pa.field("user_id", pa.int32()), pa.field("user.id", pa.int32()), ] ) data = pa.Table.from_arrays( [ pa.array([1, 2, 3], type=pa.int32()), pa.array( [ {"user_id": 10, "user.id": 100}, {"user_id": 20, "user.id": 200}, {"user_id": 30, "user.id": 300}, ], type=metadata_type, ), ], names=["user_id", "metadata"], ) table = await db.create_table("nested_scalar_index", data) # Index a nested struct field. await table.create_index( "metadata.user_id", config=BTree(), name="nested_user_id_idx" ) # Escape literal dots inside a segment with backticks. await table.create_index( "metadata.`user.id`", config=BTree(), name="escaped_user_id_idx" ) # `columns` is returned as the canonical path you passed in. for index in await table.list_indices(): print(index.name, index.columns) # nested_user_id_idx ['metadata.user_id'] # escaped_user_id_idx ['metadata.`user.id`'] ``` > [!NOTE] > > Composite indexes that cover multiple columns aren't supported yet. Each > `create_index` call must target a single (possibly nested) field path. # Vector Indexing Source: https://docs.lancedb.com/oss/v0-41-0/indexing/vector-index Build and manage LanceDB vector indexes. **Applies to:** Embedded ✅, Enterprise ✅ Vector indexes are robust tools in facilitating fast searches across large numeric datasets. LanceDB implements **ANN (Approximate Nearest-Neighbor)** queries with several techniques that provide benefits across a variety of use cases. ## Do you need one? Not always. LanceDB's disk-based brute-force kNN search is fast even without an index: computing 100K pairs of 1000-dimension vectors takes under 20ms in benchmarks. For datasets around 100K rows or fewer, or applications that can accept \~100ms latency, a vector index is usually unnecessary overhead. Build one once a table passes roughly a million rows, dimensionality is high, or query latency matters more than that. See [`bypass_vector_index`](#search-time-parameters) to run an exact search side-by-side and measure whether an index is worth it for your data. ## Choosing the Right Index LanceDB vector indexes are combined with several [quantization](/oss/v0-41-0/indexing/vector-index) techniques to admit efficient storage. The following table lists provided quantized vector indexes and their common use cases. You can specify index type manually in Lance with `index_type`. | If your priority is... | Use this index | Why | Approx. compression ratio | Python config class | | :- | :- | :- | :- | :- | | Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size with `num_bits=1` | `IvfRq` | | Higher accuracy at small dimensions (`dimension <= 256`) | `IVF_PQ` | IVF indexing with product quantization | Usually `1/64` to `1/16` of raw size (depends on `num_sub_vectors`) | `IvfPq` | | Best recall/latency trade-off | `IVF_HNSW_SQ` | IVF-HNSW indexing with scalar quantization | Typically a little larger than `1/4` of raw size | `IvfHnswSq` | | Highest recall / no quantization | `IVF_HNSW_FLAT` | IVF-HNSW indexing with no quantization; embedded library only | Around raw vector size plus HNSW graph overhead | `IvfHnswFlat` | > [!WARNING] > > If your vector search frequently includes metadata filters (`where(...)`), use `IVF_RQ` or `IVF_PQ`. In filtered workloads, HNSW-backed IVF indexes such as `IVF_HNSW_FLAT` and `IVF_HNSW_SQ` can show higher latency variance. ## Understanding Vector Indexes LanceDB offers two vector indexes, which can be created on any numeric Lance dataset: **Inverted File (IVF)** and **Hierarchical Navigable Small World (HNSW)**. ### IVF The **Inverted File Index (IVF)** accelerates ANN searches by drastically reducing the search space. The index consists of a small set of *centroids* corresponding to an approximate solution to the [$k$-means clustering](https://en.wikipedia.org/wiki/K-means_clustering) problem. Each vector remembers its nearest centroid, and each centroid remembers its associated set of vectors, called its *partition*. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/indexing/ivfpq_ivf_desc.webp?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=a6a6878e18ce2d3792381cf1b4342cc5) Example partition of a geometric space, with colored marks denoting centroids. At query time, we can compare the queried vector to the smaller set of *centroids* (as opposed to the entire dataset) for a closest match, then run a brute-force comparison against its resulting partition. This technique quickly prunes a large search space, giving an approximate ANN result. However, observe that a queried vector may lie near the boundary of $2$ or more partitions; thus, the true nearest neighbors are scattered across several different partitions. To address this, LanceDB exposes the `nprobes` parameter, which specifies the number of partitions searched. A higher probe budget searches more partitions, which can improve recall at higher CPU and I/O cost. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/indexing/ivfpq_query_vector.webp?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=46474764c825372954c34ab21aca23db) Edge case for single-partition brute force. ### HNSW **Hierarchical Navigable Small World (HNSW)** constructs a layered graph hierarchy on the vector set, with edges representing distances. We can visualize an HNSW index as a vertical stack of graphs, with the top layer having very few edges and each other layer having a multiplicative factor more edges than the layer above it. High layers of a HNSW hierarchy represent sparse, higher-distance networks, and lower layers represent finer, lower-distance networks. To query a vector $q$, the index proceeds iteratively through layers, first finding $q$'s nearest neighbor in the graph, then proceeding recursively through the induced subhierarchy until the lowest layer is reached. ![HNSW layered graph hierarchy](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/indexing/hnsw_layered_graph.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=ea4e34f4ea8f2de098e536459ac7698f) HNSW hierarchy: sparse network at the top layer, fine network at the bottom. To visualize this process, imagine that you must drive your car from San Francisco to a specific house in Boston. Initially, you must first drive thousands of miles on the interstate freeway I-90 E. Eventually, you merge onto the Massachusetts Turnpike, the center of the greater Boston highway system. From there, you use a series of increasingly smaller, narrower roads within the city (Charles River Bridge, St. Paul St, Thatcher St) before finally reaching the house. A key observation is that you must initially travel far distances through long-distance road networks (the interstate freeway system), before proceeding to finer and finer road networks (greater Boston highway system, central Brookline neighborhood connectors) before finally reaching your destination. This iterative series of road networks mimics the layered graph traversals performed by a HNSW query. > [!NOTE] > > **IVF + HNSW** > > In LanceDB, HNSW is not exposed as a top-level vector index. Instead, it's available as a substructure which > further indexes the selected vectors inside each IVF partition. > This combines the scalability of IVF with the high recall of HNSW. > LanceDB supports IVF-HNSW-based quantized indexes `IVF_HNSW_FLAT`, `IVF_HNSW_PQ`, and `IVF_HNSW_SQ`; a deployment builds only `IVF_HNSW_SQ`. ## Using Vector Indexes Learn how to configure, build, and search LanceDB vector indexes, including build and search time parameters, asynchronous objects, and several examples. ### Configuration #### Build-time Parameters | Parameter | Description | | :- | :- | | `distance_type` | Default is `l2`, others available are `cosine` and `dot`. | | `num_partitions` | The number of IVF partitions constructed (corresponds to the $k$ in $k$-means clustering). This takes precedence over `target_partition_size` if both are set. | | `target_partition_size` | An alternative IVF sizing knob that derives the partition count by setting the number of rows per partition. `num_partitions` takes precedence over `target_partition_size` if both are set. If neither is set the number of partitions is automatically calculated based on the number of rows and the index type. | | `num_sub_vectors` | Applies to `IVF_PQ`; defaults to `dimension // 16` (or `dimension // 8` if not a multiple of 16). Larger values produce better recall and slower search. | | `max_iterations` | Maximum number of k-means training iterations, for every IVF/HNSW index type. Default `50`. Increase for larger datasets or to improve training quality. | | `sample_rate` | Number of k-means training samples per partition, for every IVF/HNSW index type. Default `256`. Higher values increase both accuracy and training time. | #### Search-time Parameters | Parameter | Description | | :- | :- | | `limit` | Number of results to return (the `k` in `k-ANN`). | | `nprobes` | Search a fixed number of partitions per index segment. Leave unset to use Auto. | | `search_effort` | A value from `0` to `1` for tuning recall and latency. `0.5` uses Auto; higher values search more partitions. This is not a recall percentage. | | `minimum_nprobes` | Minimum number of partitions to search per segment. Auto may search more from the start. | | `maximum_nprobes` | Maximum number of partitions to search per segment. Leave unset to allow further searching when needed. A low cap can reduce recall or return fewer results than requested. | | `ef` | HNSW search-time exploration factor. Start around `1.5 * k` and increase up to `10 * k` for higher recall. | | `refine_factor` | Rerank candidates using full vectors to improve accuracy. A factor of `25` requests up to `25 * k` candidates. Higher values read more data; measure the recall gain and latency cost. | | `distance_range(lower_bound, upper_bound)` | Return only rows whose distance falls within `[lower_bound, upper_bound)`. Either bound is optional. Useful for near-duplicate detection or "close-enough" matching. | | `bypass_vector_index()` | Ignore the ANN index entirely and perform an exact (flat) scan. Can be used to measure ANN `recall@k`, or to query with a metric the index was not built for (e.g., a non-cosine query on a multivector column). | > [!NOTE] > > The `distance_type` can be specified at search time in addition to build time. If > you do this, set it to the same value used to build the vector index. If the search > metric does not match the index metric, LanceDB cannot use the index and falls > back to a costly flat search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit > can reject that search on a large table instead of executing it. An Enterprise > deployment applies the same limit only when it is configured to. > > When the search metric is omitted, current SDKs use the index metric if an index > is available. Some older SDK versions sent `l2` when it was omitted, so explicitly > set the matching metric or upgrade the SDK when querying a non-`l2` index with an > older client. **Recommended `nprobes` behavior by index type:** | Index type | Guidance | | :- | :- | | `IVF_HNSW_FLAT`, `IVF_HNSW_SQ` | Leave the probe settings unset, then tune `ef` first. Expect higher latency variance under filtered search. | | `IVF_RQ`, `IVF_PQ` | Leave the probe settings unset and configure them only when recall is insufficient. If using a selective filter you may need to increase `maximum_nprobes` if you do not receive enough results. | > [!NOTE] > > Start with Auto, then measure recall and latency before changing probe settings. > If you set both `search_effort` and `nprobes`, effort takes precedence. Explicit > min/max bounds still apply; equal bounds fix the count. See > [tuning vector search](/oss/v0-41-0/search/vector-search#tuning-nprobes) for examples and > guidance on choosing these controls. For a filtered search, you can let Auto choose within a range. The maximum also limits further searching if too few matches are found: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Let Auto choose between 10 and 50 partitions per segment, if available. filtered = ( table.search(query_vector) .minimum_nprobes(10) .maximum_nprobes(50) .where("id > 100") .limit(5) .to_arrow() ) ``` LanceDB also supports advanced search-time controls for thresholded retrieval, recall measurement, and working around index-level metric constraints. **Thresholding with `distance_range`:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Only return results whose distance falls within [0.0, 0.5). # Useful for near-duplicate detection or thresholded similarity search. ( table.search(np.random.random(128)) .distance_range(lower_bound=0.0, upper_bound=0.5) .limit(10) .to_pandas() ) ``` **Using `bypass_vector_index`:** Use `bypass_vector_index` to compute an exact **kNN** result. Note that exact queries may be prohibitively slow on production scales. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = np.random.random(128) k = 10 # Ground truth: flat (exhaustive) scan, ignoring the ANN index. truth = set(table.search(query).bypass_vector_index().limit(k).to_pandas()["id"]) # ANN results with the current nprobes setting. ann = set(table.search(query).nprobes(20).limit(k).to_pandas()["id"]) recall_at_k = len(truth & ann) / k ``` > [!NOTE] > > Multivector indexing currently requires `distance_type="cosine"`. Use `bypass_vector_index()` for non-`cosine` queries on a multivector column. See [Multivector Search](/oss/v0-41-0/search/vector-search) for the full rules. #### Async API and Config Objects Create vector indexes asynchronously with `await table.create_index("vector", config=...)`. The `config` object admits the same build-time parameters described above. Pass an instance of a Python config class from the table in [Choosing the Right Index](#choosing-the-right-index): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import numpy as np from lancedb.index import IvfPq async def main(): data = [ {"id": i, "vector": np.random.random(8).astype(np.float32).tolist()} for i in range(512) ] db = await lancedb.connect_async("ex_lancedb") table = await db.create_table( "vector_index_async", data=data, mode="overwrite" ) await table.create_index( "vector", config=IvfPq( distance_type="cosine", num_partitions=16, num_sub_vectors=4, ), ) return await table.list_indices() ``` ### IVF Indexes This example creates and queries an `IVF_PQ` index for a table of vectors with respect to `cosine` similarity. Specify `vector_column_name` if you have multiple vector columns or non-default names. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "vector-index-build-ivf" table = db.open_table(table_name) table.create_index( metric="cosine", vector_column_name="keywords_embeddings", ) tbl = table tbl.search(np.random.random((1536))).limit(2).nprobes(20).refine_factor( 10 ).to_pandas() ``` > [!NOTE] > > TypeScript currently doesn't support `IvfSq` (IVF with Scalar Quantization). For a vector field nested inside a struct, pass its full dotted path as `vector_column_name` (e.g. `image.embedding`). The same path is used at query time and is what `list_indices()` reports under `columns`. See [Selecting the vector column](/oss/v0-41-0/search/vector-search#selecting-the-vector-column) for the full path syntax. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # The vector column `embedding` is nested inside the `image` struct. # Pass its full dotted path as `vector_column_name`; the same path is used # at query time and is what `list_indices()` reports under `columns`. table.create_index( vector_column_name="image.embedding", num_partitions=1, num_sub_vectors=1, name="image_embedding_idx", ) results = ( table.search([0.0, 1.0], vector_column_name="image.embedding") .limit(1) .to_list() ) ``` ### IVF-HNSW Indexes Beyond the general build-time parameters above, two additional parameters are specific to IVF-HNSW indexes: | Parameter | Description | | :- | :- | | `m` | The number of neighbors to select for each vector in the HNSW graph. | | `ef_construction` | The number of candidates to evaluate during the construction of the HNSW graph. Start at `150`; increase for better recall, decrease for faster indexing. | Partition sizing follows the general `num_partitions`/`target_partition_size` guidance above. The snippet below builds and queries an `IVF_HNSW_SQ` index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index(index_type="IVF_HNSW_SQ") tbl = table tbl.search(np.random.random((16))).limit(2).to_pandas() ``` ### Managing Vector Indexes Enterprise-only In LanceDB Enterprise, vector indexes are managed **automatically**. The system asynchronously updates and optimizes indexes as a background process: * Automatically manages indexing parameters and storage * Can build an `IVF_PQ` index automatically on a vector column the deployment is configured to index * GPU-based `IVF_PQ` builds are available on request. [Contact support](/oss/v0-41-0/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. Open-Source LanceDB Embedded users can manually create vector indexes by calling `table.create_index()`. See the above sections for guidance on manually tuning index parameters as data changes. > [!NOTE] > > In LanceDB Enterprise, `create_index()` returns immediately and the vector index builds asynchronously. > To wait until all data is indexed, specify the `wait_timeout` parameter, or call `wait_for_index(...)` afterward. > It waits for the named index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. > In the embedded library the index is built before `create_index()` returns. > [!NOTE] > > Rows appended after an initial index build remain outside the index until refreshed manually (Embedded) or automatically (Enterprise). Normal > search still checks those unindexed rows with a slower fallback path; `fast_search()` skips that > fallback and searches only indexed rows. > [!NOTE] > > **Operational checks** > > In the embedded library, use `optimize()` after appends or other writes to fold new rows into existing indexes. > A deployment does this in the background, and `optimize()` is not available there. #### Check Index Status In LanceDB Enterprise, vector index creation runs in the background and may take some time to complete. While it is ongoing, you can check its status through the API or the **LanceDB Enterprise UI**. In the LanceDB Enterprise UI, navigate to your table page - the "Index" column reflects each column's index status: it is blank when no index exists, shows an "in progress" label while the index is being built, and shows the index type once the build completes. To check status programmatically, use `list_indices()` and `index_stats()`. **By default**, the index name is formed by appending `_idx` to the column name (e.g., a `keywords_embeddings` column produces `keywords_embeddings_idx`). Note that `list_indices()` only returns information after the index is fully built. Each entry returned by `list_indices()` also carries detailed per-index metadata, so you can inspect an index without a follow-up `index_stats()` call. Node.js exposes the same fields in camelCase (`num_indexed_rows` → `numIndexedRows`): | Parameter | Description | | :- | :- | | `num_indexed_rows`, `num_unindexed_rows` | Index coverage over the table | | `size_bytes` | Total size of the index files on disk | | `num_segments`, `index_version` | On-disk layout and format version | | `created_at` | Creation time (ms since the Unix epoch in Node.js) | | `index_uuid`, `type_url` | Internal identifiers for the index segment | | `index_details` | Type-specific details (e.g. IVF partition counts or quantization settings) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} index_name = "keywords_embeddings_idx" table.wait_for_index([index_name]) print(table.index_stats(index_name)) ``` > [!NOTE] > > These fields are populated for LanceDB Embedded tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. #### Custom Index Names The `{column}_idx` suffix is the default naming convention. Pass `name=...` to `create_index()` to override it. Once set, the custom name will be reflected in `list_indices()`, `index_stats(name)`, and `wait_for_index([name])`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Override the default `{column}_idx` convention by passing `name=...`. table.create_index( metric="cosine", vector_column_name="keywords_embeddings", name="my_custom_index", ) table.wait_for_index(["my_custom_index"]) print(table.index_stats("my_custom_index")) ``` ## Quantization **Quantization** is used in LanceDB to efficiently compress and store vector indexes. We discuss only the quantization techniques here; discussion of LanceDB vector indexes and quantized vector indexes can be found [here](/oss/v0-41-0/indexing/vector-index). ### Quantization Techniques LanceDB provides $3$ distinct quantization techniques: Product Quantization (PQ), RaBitQ Quantization (RQ), and Scalar Quantization (SQ). Recall that all quantizations perform **lossy** compression, in that they irreversibly lose some degree of precision to compactly store an index. #### Product Quantization (PQ) To visualize PQ, assume a vector dataset has $d$ dimensions, with a **chunk** of a vector denoting a contiguous block of entries. Imagine that each vector has $m$ disjoint chunks of $d/m$ entries each, where the first chunk contains entries $0$ through $d/m-1$, the second contains entries $d/m$ through $2d/m-1$, and so on. Now, for each $i$, let $S_i$ represent the set containing chunk $i$ of each vector (entries $(i-1)d/m$ to $id/m-1$). For each $S_i$ independently, a small set of **centroids** is computed corresponding to an approximate solution to the $k$-means clustering problem. For each original vector in the dataset, every chunk is associated to its nearest centroid; thus, the vector itself is associated with the concatenation of $m$ centroids. We then gather all our centroids (from all chunks) into a single lookup table, and for each vector, we store the concatenation of IDs of its corresponding centroids. At query time, we need only to compare each chunk of the queried vector with our set of centroids. ![IVF vector-space partitioning](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/indexing/ivfpq_pq_desc.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=448f164fd28fb36080b32132b1a918f6) In the above example, the original vector is split into chunks (subvectors), each of which is associated to a centroid. The stored quantization code for this vector is the concatenation $2 || 1 || 4 || 3$. The original vector required $128$ dimensions $\times 32$-bit floats $ =4096$ bits total, which has been compressed to $4$ chunks $\times 8$-bit integers $= 32$ bits of quantized storage. #### RaBitQ Quantization (RQ) RaBitQ is an advanced quantization technique that outperforms PQ in several ways. It needs no codebook to train, estimates distances very quickly at query-time, and can quantize each vector in (with some small overhead) as little as **one bit per dimension!** In practice, RaBitQ compresses a $1024$-dimensional `float32` vector into just a few thousand bits, while maintaining good recall. The inner workings of RaBitQ quantization are rather mathematically dense. It generates a quantization codebook by applying a uniformly random, approximately distance-preserving orthogonal transformation of the vertices of the $d$-dimensional hypercube, where $d$ is the dimensionality of the dataset. We defer the details, and an elegant theoretical error bound, to [the original paper.](https://arxiv.org/pdf/2405.12497) ##### Using RaBitQ Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, import `IvfRq` from `lancedb.index` and call `table.create_index("vector", config=IvfRq())`. Note that when using `IVF_RQ`, the dimension of the dataset must be a multiple of `8`. `num_bits` determines how many bits are used to quantize each dimension. By default, Python, Rust, and Node leave this unset and inherit Lance's default, currently `5` bits. Higher values improve recall at the cost of additional storage and query-time compute. To retain the previous one-bit default and maximum compression, explicitly set `num_bits=1` (for example, `IvfRq(num_bits=1)` in Python). Five-bit quantized vector codes use roughly five times the storage of one-bit codes; total index size also includes other overhead. > [!WARNING] > > RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout and cannot be read by some older LanceDB versions. > The new five-bit default therefore affects reader compatibility as well as index size. > Upgrade readers to versions that support multi-bit IVF_RQ before creating indexes with the default settings, or explicitly set `num_bits=1` when sharing indexes with readers that support only one-bit IVF_RQ. See this [blog post](https://lancedb.com/blog/feature-rabitq-quantization/) for further discussion and benchmarking of LanceDB's RaBitQ implementation. #### Scalar Quantization (SQ) Scalar quantization quantizes each entry of a vector independently, by simply replacing it with the closest of a pre-defined set of values. In practice, it often uses $8$ bits per dimension of a vector, and supports very fast encoding and decoding. For example, suppose we know all vector entries across our dataset lie in the range $[-128 \times 10^5, 127 \times 10^5]$. In this case, we could quantize a given value $v$ as an $8$-bit representation of the integer $j$, where $j \times 10^5$ is the closest value to $v$ among all integral multiples $\{j \times 10^5: -128 \leq j \leq 127 \}$. ### Quantization API Reference | Parameter | Description | | :- | :- | | `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (`IvfRq()` inherits Lance's default, currently `5`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | `max_iterations` and `sample_rate` also affect quantizer training, but since they apply to every IVF/HNSW index type (not just quantized ones), they're documented as general [Build-time Parameters](/oss/v0-41-0/indexing/vector-index#build-time-parameters) instead. All three are passed as keyword arguments to `create_index`, alongside `index_type`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.create_index( index_type="IVF_RQ", num_bits=2, max_iterations=100, sample_rate=512, ) ``` # Garbage Collection Source: https://docs.lancedb.com/oss/v0-41-0/maintenance/cleanup Pruning old versions and the files only they referenced. **Applies to:** Embedded ✅, Enterprise ✅ Every write keeps the version before it, which is what makes [time travel](/oss/v0-41-0/management/table#versioning) possible. Cleanup is what ends that: pruning versions older than a retention window, and the files that only those versions referenced. > [!NOTE] > > **Enterprise job type:** `cleanup`. Distinct from `compact`: compaction > merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call; > Enterprise schedules them as separate jobs, and runs cleanup only when the > deployment's configuration enables it. ## Retention ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta table.optimize(cleanup_older_than=timedelta(days=30)) ``` `cleanup_older_than` defaults to **7 days**. Versions older than that are removed, along with the files only they referenced. In LanceDB Enterprise, the retention period comes from its configuration instead. The latest version is never removed, whatever you pass. `timedelta(0)` makes every older version eligible for removal, but cleanup still keeps tagged versions, as the warning below describes. > [!WARNING] > > Pruning is what makes [time travel](/oss/v0-41-0/management/table#versioning) finite: an > eligible version outside the retention window is gone. Cleanup keeps a version, > whatever its age, when it is: > > * the **latest** version; > * a **tagged** version. > > To keep a version recoverable, tag it, subject to the policy below, or keep > the window wide enough to cover it. > > Under the default policy, a tag can also stop cleanup. When a tagged version is > older than the window and is not the latest, cleanup refuses to run: it raises > an error naming the tag and prunes nothing. To let it proceed, move the tag to a > version inside the window, delete the tag, or widen the window. > > A tag on the latest version does not stop cleanup. But `optimize()` compacts > before it prunes, and compacting commits a new version whenever it merges > files, so a tag on what was the latest version can become an older one by the > time cleanup runs. `optimize()` then raises after compacting, and its index > update does not run. > > Enterprise background cleanup keeps tagged snapshots while pruning unrelated > expired versions. If you rely on reading untagged old versions, set the window > to cover the range you > need before running this, not after. ## Managed blob objects [Managed blobs](/oss/v0-41-0/management/table#managed-blobs) store out-of-line payloads under the table's `_blobs/` directory. Cleanup follows the references from retained snapshots, including protected tags, before selecting objects for deletion. Replacing a blob or deleting a row makes its old payload eligible only after no retained snapshot references it. Cleanup removes whole objects. If a packed object contains several blobs, it remains while any of them is live. Compaction preserves Managed payload objects rather than copying their bytes, so compaction alone does not reclaim the unused portion of a packed object. Use table maintenance to remove Managed objects; deleting `_blobs/` files directly can corrupt current or historical snapshots. Upgrade all clients and maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. Enterprise runs these as background jobs; Python tables connected to Enterprise do not support `optimize()`. See [Intelligent Auto-Maintenance](/oss/v0-41-0/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path. ## Disk usage does not drop immediately Compaction writes new, merged files before the old ones are removed, so disk usage can rise before it falls. Space is reclaimed only when cleanup prunes the versions that referenced the superseded files. If you need to reclaim space aggressively in the embedded library, shorten the retention window rather than waiting for the default: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize(cleanup_older_than=timedelta(days=1)) ``` ## Files from failed transactions A write that fails partway can leave files that look like an operation still in progress. Cleanup will not remove them until they are at least seven days old, because it cannot tell them apart from a live write. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize(delete_unverified=True) ``` This option belongs to `optimize()` in the embedded library. A deployment's cleanup jobs never set it. > [!WARNING] > > `delete_unverified=True` removes them regardless of age. Only set it when you > can guarantee **no other process is writing to the table**. Otherwise it can > delete files belonging to a write that is genuinely in progress, and corrupt > the table. ## What to read next > [card] [Compaction](/oss/v0-41-0/maintenance/compaction) > > Merging small files, the other half of `optimize()`. > [card] [Intelligent Auto-Maintenance](/oss/v0-41-0/enterprise/intelligent-auto-maintenance#cleanup) > > How Enterprise decides to run cleanup without a call from you. # Compaction and cleanup Source: https://docs.lancedb.com/oss/v0-41-0/maintenance/compaction Merge small files, prune old versions, and fold new rows into existing indexes. **Applies to:** Embedded ✅, Enterprise ✅ 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; a deployment handles them in the background and does not support `optimize()`. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. ## Optimize a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.optimize() ``` Three operations, in one call: | | | | - | - | | **Compaction** | merges small files into larger ones | | **Prune** | removes versions older than the retention window (see [Garbage Collection](/oss/v0-41-0/maintenance/cleanup)) | | **Index** | folds newly added rows into existing indexes (see [Incremental Indexing](/oss/v0-41-0/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`](/oss/v0-41-0/maintenance/cleanup). The two are distinct jobs > even though `optimize()` bundles both in one LanceDB Embedded call. ## 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: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.index import IvfFlat table.create_index( "vector", config=IvfFlat(distance_type="l2", num_partitions=4), replace=True, ) ``` 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. > [!NOTE] > > Compaction rewrites files, which conflicts with a concurrent > [computed-column refresh](/oss/v0-41-0/feature-engineering/add-computed-column) or > [view refresh](/oss/v0-41-0/feature-engineering/refresh-materialized-view) planned against the > version it replaces. Sequence them rather than running both at once. See [Garbage Collection](/oss/v0-41-0/maintenance/cleanup) for pruning old versions, and [Incremental Indexing](/oss/v0-41-0/indexing/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: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta table.optimize() # 7-day default retention table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner ``` The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/oss/v0-41-0/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. # Catalog Source: https://docs.lancedb.com/oss/v0-41-0/management/catalog The unnamed root of an Enterprise deployment: initial access, the superuser bootstrap, and where privileges apply. **Applies to:** Embedded ❌, Enterprise ✅ The catalog is the unnamed root of one Enterprise deployment, identified by its endpoint rather than a name -- see [Catalog Hierarchy](/oss/v0-41-0/basics/catalog#hierarchy) for how it relates to the databases, namespaces and tables beneath it, and [Connecting to Catalog](/oss/v0-41-0/basics/catalog#connecting-to-catalog) for `connect_catalog(endpoint)` itself. This page covers what it takes to reach a brand new deployment for the first time. ## Initial access A newly deployed catalog has no databases and no grants: nobody yet holds `CREATE_DATABASE` or any other system-level privilege, so there is nothing for an ordinary principal to do with a catalog connection. Database administration starts from a **superuser**. ## Superuser A superuser is an identity your deployment operator configures outside the normal grant system, not a role anyone can be granted. It bypasses privilege checks entirely, on every object, rather than holding specific privileges -- the same way `OWNERSHIP` on an object grants full authority over that one object, a superuser has it over the whole deployment. This is what makes a brand new deployment usable. Creating a database or namespace can fall back to a system or parent-namespace privilege when the object has no owner yet -- see [Creating an object you don't own yet](/oss/v0-41-0/governance/privileges#creation) -- but a system-level privilege itself has no such fallback, so a superuser signs in first and grants `CREATE_DATABASE`, `OPERATE`, or other system privileges to real principals and roles. Day-to-day administration then runs through those grants, the same as any other object; reach for the superuser identity to recover access or bootstrap a new deployment, not as a standing way to work. ## Privileges The catalog connection itself is gated by privileges on the `system` object: `CREATE_DATABASE` to create one, `OPERATE` to manage jobs, caches, server configuration and role membership, and `USAGE` to list jobs and look up other identities. See [Privileges](/oss/v0-41-0/governance/privileges) for the full table and how a grant is addressed, and [Principals](/oss/v0-41-0/governance/principals) for who a grant can name. ## What to read next > [card] [Catalog Hierarchy](/oss/v0-41-0/basics/catalog#hierarchy) > > How the catalog relates to databases, namespaces and tables. > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > Every privilege, and the grant and revoke syntax that covers each one. > [card] [Database](/oss/v0-41-0/management/database) > > Create and manage a database once you can reach the catalog. # Database Source: https://docs.lancedb.com/oss/v0-41-0/management/database Connect to LanceDB and configure storage, credentials and read consistency. **Applies to:** Embedded ✅, Enterprise ✅ A database connection provides access to tables and namespaces in a [catalog](/oss/v0-41-0/basics/catalog). Use it to create and open tables, list catalog objects, and configure how your application reaches the data. ## Connection URIs | URI | Offering | Where queries run | | - | - | - | | `./.lancedb` | LanceDB Embedded, with local storage | In your application | | `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | LanceDB Embedded, with object storage | In your application | | `db://my-database` | LanceDB Enterprise | On the Enterprise service | [Connect to LanceDB](/oss/v0-41-0/basics/catalog) has examples for each connection type. A connection to object storage still uses the embedded library: your process reads and writes the bucket directly. Enterprise runs operations remotely and manages the supporting compute and maintenance. ## Connect to Enterprise Replace the placeholders with the database URI, key, region and endpoint provided by your administrator. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("db://your-database", { apiKey: "your-api-key", region: "us-east-1", hostOverride: "https://your-endpoint", }); ``` | Python option | TypeScript option | Purpose | | - | - | - | | `api_key` | `apiKey` | Authenticate the connection | | `region` | `region` | Select the database's region | | `host_override` | `hostOverride` | Set the Enterprise endpoint | | `client_config` | `clientConfig` | Configure retries, timeouts and connection pooling. A retry can [repeat an append](/oss/v0-41-0/ingestion/insert#performance). | Use your deployment's region rather than relying on the `us-east-1` default. For application code, load credentials from environment variables or a secrets manager. See [Authentication](/oss/v0-41-0/enterprise/authentication) for OAuth and [SQL](/oss/v0-41-0/basics/sql) for the separate SQL connection settings. ## Storage options For LanceDB Embedded tables in object storage, `storage_options` configures credentials, endpoints and options for new tables. This example enables stable row IDs for tables created through the connection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect( "s3://bucket/path", storage_options={"new_table_enable_stable_row_ids": "true"}, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("s3://bucket/path", { storageOptions: { new_table_enable_stable_row_ids: "true" }, }); ``` Set stable row IDs before creating a table that needs them, such as an ordinary materialized-view source in Python SDK 0.40.0. The option does not change tables that already exist. Enterprise storage settings are managed on the server. See [Object storage](/oss/v0-41-0/basics/catalog#object-storage) for provider credentials and other options. ## Read consistency For LanceDB Embedded connections, `read_consistency_interval` controls how often reads check for table versions committed by other writers. For example, check at most once every five seconds: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from datetime import timedelta db = lancedb.connect( "./.lancedb", read_consistency_interval=timedelta(seconds=5) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("./.lancedb", { readConsistencyInterval: 5 }); ``` By default, an Embedded table handle does not automatically pick up another process's writes. Reopen the table, check out its latest version, or configure a consistency interval when you need those updates. A zero interval checks on every read, with the cost of a metadata check. Enterprise manages read freshness on the server. See [Consistency](/oss/v0-41-0/tables/consistency) for its behavior and the distinction between seeing your own writes and seeing another client's writes. ## Database operations The connection provides methods to create, open, list and drop tables. | Operation | Python | TypeScript | | - | - | - | | Create a table | `create_table` | `createTable` | | Open a table | `open_table` | `openTable` | | List tables | `table_names`, `list_tables` | `tableNames`, `listTables` | | Drop a table | `drop_table` | `dropTable` | Use the namespace and pagination options documented in [Namespaces](/oss/v0-41-0/management/namespace) when working outside the root namespace or listing a large catalog. [Tables](/oss/v0-41-0/management/table) covers table schemas, versions and lifecycle operations. > [!WARNING] > > Dropping a table removes its history as well as its current data. You cannot > recover a dropped table through table versioning. The LanceDB Embedded `drop_database()` > and `drop_all_tables()` operations remove all tables without a confirmation prompt. ## Async connections Python's `connect_async` returns an `AsyncConnection`. Await its operations when working in an asynchronous application: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = await lancedb.connect_async("./.lancedb") table = await db.open_table("documents") ``` TypeScript's connection and table operations already return promises. An async connection and a background job serve different purposes. Async APIs let other tasks run while your application waits for an operation. A [job](/oss/v0-41-0/basics/jobs) represents work that can continue on the server after the submission call returns. ## Privileges A database's `OWNERSHIP`, `USAGE` and `CREATE_NAMESPACE` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers ``` See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Functions Source: https://docs.lancedb.com/oss/v0-41-0/management/function Register a Python function once and apply it as a column, for work SQL cannot express. **Applies to:** Embedded ❌, Enterprise ✅ > [!NOTE] > > SDK examples use the [Enterprise 1.12.0 client versions](/oss/v0-41-0/basics/sdk#enterprise-client-versions). > Python 0.41.0 exports the earlier `udf` API rather than `function`. Early access Some columns cannot be written as a SQL expression: an embedding, a model call, an image decode. A function is a Python callable registered with the database, versioned, and then applied as a column. The code runs where the data is rather than pulling rows to your process. Registering and running a function needs a LanceDB Enterprise deployment with Functions enabled, which they are not by default. On a LanceDB Embedded connection `create_function` raises `NotImplementedError`. With published Embedded packages, compute derived values in your application and write them to the table. SQL computed-column declaration and refresh require an experimental source build. > [!NOTE] > > In SQL, a function is registered with [`CREATE FUNCTION`](/oss/v0-41-0/sql/ddl/function#create) and listed with [`SHOW FUNCTIONS`](/oss/v0-41-0/sql/ddl/function#show). Functions are the way to fill columns with Python in LanceDB Enterprise. If you already use [Geneva](/oss/v0-41-0/geneva), it remains available; see the Geneva docs for how its concepts map onto these. The steps below take a column of numbers to a filled column of their doubles. ## Define a function `@function` packages a scalar Python callable. Input and output types are inferred from annotations, so `double` takes one non-nullable `float64` parameter, `value`, and returns a non-nullable `float64`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import function @function def double(value: float) -> float: return value * 2 ``` The decorated object stays callable. Calling it runs the original function in your process, without the database, so unit tests stay ordinary tests: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(double(1.5)) # 3.0 ``` Where annotations cannot express the Arrow type precisely, pass `input_schema` and `output_schema` together: one without the other is rejected. A scalar output must be non-nullable, because a physical NULL is what marks a computed-column row as unfilled. A named-struct output may declare nullable fields: whether a row has a result at all is the struct's own validity, which Enterprise keeps in a separate internal column when it expands the result into sibling columns, so a null field is a value rather than a missing row. ## Connect and create a table The remaining steps run against your Enterprise deployment. Replace the database URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect( uri="db://your-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", sql_host_override="grpc+tls://your-sql-endpoint:10026", ) ``` For an ordinary stored input column, the Arrow type must match the parameter. A nullable column requires a nullable parameter, such as `Optional[float]`; a non-nullable column can bind to either. This example uses `value: float`, so the table declares `value` non-nullable. Computed-column inputs depend on the Enterprise server version. Where supported, they bind to non-nullable parameters even though the physical column is nullable: refresh skips rows whose computed input is still null. Check your deployment's support before using another computed column as an input. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa schema = pa.schema([pa.field("value", pa.float64(), nullable=False)]) table = db.create_table( "function_demo", [{"value": 1.0}, {"value": 2.0}, {"value": 3.0}], schema=schema, ) ``` ## Register it Registration returns a query-backed job; the immutable version exists once the SQL command finishes and the job succeeds. Its `job_type` is `query`, and its single `id` is the SQL query UUID. Repeated waits reuse the completed result. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} job = db.create_function_async(double) version = job.wait() ``` `create_function` is the blocking equivalent. A registered version is fetched with `db.get_function(name, version="1")`. Python 0.42.0b8 requires a string version. Enterprise 1.12.0 requires an explicit version; select one from `list_functions()` before fetching it. > [!NOTE] > > The SQL command submits an internal `create_function` image-build job and > waits for publication. The SDK returns the SQL query handle. Query handles > have no registry history and cannot be reopened with `open_job()`. ## List and describe `list_functions` pages through every published version in a namespace, ordered by name then version. Python 0.42.0b8's `get_function` takes a string version. Enterprise 1.12.0 does not resolve an omitted version. Both take `namespace_path`, defaulting to the root namespace, the same as `create_function`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for version in db.list_functions(): print(version.name, version.version, version.created_at_millis) version = db.get_function("double", version="1") ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; # async fn list_and_get(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> { let mut versions = connection.list_functions(&[], Default::default()); while let Some(version) = versions.try_next().await? { println!("{} {} {}", version.name(), version.version(), version.created_at_millis()); } let version = connection.get_function("double", "1", &[]).await?; # Ok(()) # } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW FUNCTIONS SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) DESCRIBE FUNCTION double WITH (version = '1') ``` `list_functions` returns a lazy iterator: `page_limit` bounds each request, not the total, and `page_token` resumes from a saved token. Child namespaces are not included; list each namespace separately. A version's `created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are all readable this way without applying or calling the function. ## Try it in SQL A registered function is callable in SQL by its name, the same as any other scalar function. Before applying it as a column, call it directly over the table to check the registration succeeded, without committing a schema change: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query("SELECT value, double(value) AS doubled FROM function_demo") print(reader.read_all().to_pylist()) # [{'value': 1.0, 'doubled': 2.0}, {'value': 2.0, 'doubled': 4.0}, {'value': 3.0, 'doubled': 6.0}] ``` > [!NOTE] > > Equivalent SQL: `SELECT value, double(value) AS doubled FROM function_demo`. > See [Querying with SQL](/oss/v0-41-0/basics/sql) for `execute_query` and other languages. ## Apply it as a column Calling the registered version binds each parameter, by name, to a column with `col(...)`. `add_columns` declares the result as a new column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col table.add_columns({"doubled": version(value=col("value"))}) ``` The column is declared empty; the function has not run yet. A mapping with one function application keeps its scalar or named-struct result in the named column. A bare named-struct application expands its result fields as one atomic binding, with aliases from `rename(columns=...)`. ### Bind more than one input, or fill more than one column Parameters bind by name, so a function that takes several arguments binds several columns in one call. `ratio` divides two existing columns, so give the table a second one first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns({"count": "value + 1"}) @function def ratio(numerator: float, denominator: float) -> float: return numerator / denominator version = db.create_function_async(ratio).wait() table.add_columns({"ratio": version(numerator=col("value"), denominator=col("count"))}) ``` A named-struct output fills more than one column from a single application. Declare the fields with `output_schema`, then alias each field to the column it fills with `rename(columns=...)` and pass the application itself, not a mapping, so both columns come from one atomic binding: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa @function( input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.schema([ pa.field("half", pa.float64(), nullable=False), pa.field("double", pa.float64(), nullable=False), ]), ) def scale(value: float): return {"half": value / 2, "double": value * 2} version = db.create_function_async(scale).wait() application = version(value=col("value")).rename( columns={"half": "value_half", "double": "value_double"} ) table.add_columns(application) ``` > [!NOTE] > > `input_schema` and `output_schema` must be given together on v0.41.0. A > version after it accepts either alone, inferring the other from the > annotations. A single refresh fills `value_half` and `value_double` together: there is no state where one is filled and the other is still empty. ## Fill the column A refresh runs the function on the cluster as a [job](/oss/v0-41-0/basics/jobs). `wait()` blocks until the job finishes and returns its result, including how many rows it filled: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} refresh = table.refresh_column_async("doubled") result = refresh.wait() print(result.rows_assigned) # 3 ``` The filled values are read like any other column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = table.search().select(["value", "doubled"]).to_list() print(sorted((row["value"], row["doubled"]) for row in rows)) # [(1.0, 2.0), (2.0, 4.0), (3.0, 6.0)] ``` Filling then works as it does for a SQL computed column: a later refresh fills rows added since the last one and recomputes rows whose inputs changed, and leaves filled rows with unchanged inputs alone. See [Refresh a column](/oss/v0-41-0/feature-engineering/refresh-column). ## Keep state in a class A function that loads a model or opens a client should not do it for every row. Decorate a class instead: its `__init__` does the expensive setup once, and `__call__` handles each row or batch. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(pip=["sentence-transformers"]) class embed: def __init__(self, model: str = "all-MiniLM-L6-v2"): # Runs on the worker, once per instance: only the worker needs the package. from sentence_transformers import SentenceTransformer self.model = SentenceTransformer(model) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() def close(self): del self.model ``` Registering the class does not construct it. `@function` reads the signature of `__init__` and packages the source, so the client never loads the model. On the cluster, each instance of the function calls `__init__` once. It then calls `__call__` for every row or batch it processes, and `close()`, if defined, once when it retires. Import heavy packages inside `__init__`, as above, so only the worker needs them installed, and declare them in `pip`. State belongs to one instance. An instance reuses it across every batch it serves, but instances do not share it, so each one holds its own copy of the model. Plan memory, or a GPU, for one copy per instance. Register it the same way as a plain function: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} embedder = db.create_function_async(embed).wait() ``` The annotated parameters of `__init__` are the function's initialization fields. Their values come from each binding rather than from the function, so one registered version can run with different settings on different columns: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import col application = embedder(text=col("text"), model="all-mpnet-base-v2") ``` Pass the application to `add_columns` as [above](#apply). Initialization values are fixed for every row of a binding and take booleans, integers, floats, strings, and lists or structs of them. A parameter with a default may be omitted. Initialization values are stored with the binding, so keep credentials out of them: pass `secrets=[EnvVarSecret(...)]` to `create_function` and read the variable in `__init__`. Calling the decorated class in your own process constructs it, the same as an undecorated class, so local tests can create an instance and call it directly. ## Blob v2 columns A Function can bind a [Blob v2 column](/oss/v0-41-0/management/table#managed-blobs) as input and return another. In row mode, a top-level blob parameter arrives as Python `bytes`, or `None` for a nullable input, after the worker has read the payload; annotate it `BlobReader` instead for seekable, incremental reads that avoid materializing the whole payload first. Return bytes and let the destination table store the Managed payload and descriptor -- `output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather than plain Arrow `binary`; a bare annotation persists as ordinary binary instead, skipping the Managed storage path and `fetch_blobs`. See [Read and produce blobs](/oss/v0-41-0/curation/create-function#blobs) for a full example: extracting a frame from a stored video, chaining a second Function onto its output, persisting both as columns or a materialized view, and reading a blob input incrementally. ## Declare the environment The function runs on the Enterprise service, not in your application, so its dependencies are part of its definition: | | | | - | - | | `pip` | requirements for the function's execution environment | | `conda`, `conda_channels` | conda packages instead of pip; channels in priority order | | `env` | environment variables | | `python_version` | Python major/minor for the execution environment, defaulting to yours | | `gpu` | whether every execution requires a GPU | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @function(gpu=True) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # runs only on a GPU-capable worker ``` These are part of the **immutable function version**. Changing a dependency produces a new version rather than altering the one already registered, so a column filled by version 1 is unaffected by version 2. Declaring them is not optional bookkeeping. If the worker environment differs from the one the function was written against, the failures are among the hardest to diagnose in the system, because the error rarely names the cause. ### Symptoms of an environment mismatch | Symptom | Likely cause | | - | - | | `TypeError: Enum.__new__() missing 1 required positional argument` | `attrs` version mismatch | | `TypeError: Can't instantiate abstract class` | package structure differs between versions | | `ArrowInvalid: cannot cast`, or serialization errors | NumPy 1.x against 2.x | | `ModuleNotFoundError` on the worker | package installed locally but not declared | | Model loading failures | PyTorch version mismatch | | Permission denied | an API key present locally but absent from `env` | The packages worth pinning explicitly, because a mismatch in them produces the errors above rather than a clear one: **numpy, torch, pyarrow, attrs, pydantic**. > [!NOTE] > > The client version defaults `python_version`, so a function registered from a > 3.11 environment runs on 3.11 unless you say otherwise. That default is usually > right and occasionally surprising. Pin it when the function is sensitive to it. ## Remote calls and credentials A function that calls an external API needs a credential without putting it in the function's source or its `env` map in plain text. A Secret is a database-scoped named credential; `db.create_secret` stores the value once, and an `EnvVarSecret` binds it to the environment variable the function reads. Binding is a registration-time decision, passed to `create_function_async`, not to `@function`. No API returns a Secret's value, and it never appears in the function's registration: the function reads the environment variable the way it always did, and the binding is what puts a value there. A mistyped Secret name is caught at registration; a mistyped environment variable name surfaces only on the first rows, since nothing records which variables a function reads. See [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret#specify) for the full worked example. ## Failure handling By default, a Function that raises fails the refresh job. Choose how the refresh handles row errors with its error policy: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') ``` `skip` writes null outputs for failing rows and records their errors. Inspect them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still apply, and initialization or infrastructure failures can still fail the job. See the [SQL refresh options](/oss/v0-41-0/sql/dml/refresh-column#options). A Function that calls a transiently failing external service can handle bounded retries inside its body. Letting the job fail is the other option: fix the cause and refresh again. The next unfiltered refresh [skips rows that are filled and current](/oss/v0-41-0/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not count on the retry costing only the rows that did not complete. A refresh with `WHERE` recomputes every matching live row, including already-filled outputs. ## What gets packaged > [!WARNING] > > The artifact is a **snapshot**: the function source, plus exactly the > module-level names it references (modules as imports, importable classes and > functions as imports, literals inlined). > > Code that reaches the module namespace another way is rejected where it can be > seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`, > `builtins`. Closures and a non-standard `__builtins__` are rejected outright. In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. Pass `code=[module, ...]` to ship additional helper modules into the same image, for logic the function imports but that does not belong inlined into it -- a model-loading helper shared by several Functions, for example. Continuing the [`caption` Function](/oss/v0-41-0/curation/create-function#chain), with its model-loading code factored into a sibling module instead of inlined: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import caption_worker # a sibling module with the model-loading logic @function(gpu=True, code=[caption_worker]) def caption(jpeg: bytes) -> str: return caption_worker.run(jpeg) ``` Each module in `code` is captured and shipped the same way the function itself is: as source, snapshotted at registration. Only `.py` source files are included; package data such as JSON, YAML, prompt, or tokenizer files is not copied. `@function` warns before registration when it skips such files from a package in `code`, naming the affected paths. To use a package that includes the required resources, install it with `pip=` or `conda=` and remove that package from `code`; otherwise the Python-only copied package shadows the installed distribution. ## Drop it ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.drop_function("double", version="1") ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # async fn drop_it(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> { let dropped = connection.drop_function("double", "1", &[]).await?; # Ok(()) # } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP FUNCTION double WITH (version = '1') ``` `db.drop_function(name, version=...)` removes only that published revision from lookup and listing, preserving other revisions and their grants. It returns `False` for a repeated drop or a name that is already gone. A revision never published under an existing name is an error. The last visible revision's drop releases the name and schedules object cleanup, which can finish after the call returns as a [background job](/oss/v0-41-0/basics/jobs#teardown). `drop_function_async` returns `(dropped, job)`, where `job` is a query-backed handle. Waiting confirms the revision's catalog removal; physical cleanup can continue afterward. When a deployment reports dependency warnings for a boolean drop, `db.drop_function` emits each warning as a `UserWarning`. This also applies to `await db.drop_function(...)` on an async connection. The warnings are emitted after catalog removal, and standard Python warnings filters apply. If warnings are configured as errors, the call can raise after the revision has been removed; the drop is not rolled back. Servers whose DROP response omits the warning field remain silent. A deployment refuses the drop unless it also allows changes to a function's lifecycle, which is a separate setting, off by default even where Functions are enabled. ## What to read next > [card] [Create a Function](/oss/v0-41-0/curation/create-function) > > Scalar, batch, stateful, GPU and remote-service examples for common curation tasks. > [card] [Computed columns](/oss/v0-41-0/feature-engineering/refresh-column) > > Refresh semantics, and the SQL alternative. > [card] [Embedding functions](/oss/v0-41-0/embedding) > > Built-in embedding providers, which need no registration. # Management Source: https://docs.lancedb.com/oss/v0-41-0/management/index Create, list, and drop the objects in a catalog, from Python, TypeScript, or SQL. Use the SDKs or SQL to manage [catalog objects](/oss/v0-41-0/basics/catalog), including tables, namespaces and views. The tables below provide a quick reference to the available methods; each object's guide covers its setup and behavior. Some long-running operations also provide a submission method that returns a [job](/oss/v0-41-0/basics/jobs). See the operation's guide for how to track completion. ## Management APIs > [!NOTE] > > SQL is available through the Enterprise Flight SQL endpoint. > See [SQL](/oss/v0-41-0/basics/sql#sql-is-remote). ### Namespaces | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_namespace` | `createNamespace` | -- | | list | `list_namespaces` | `listNamespaces` | -- | | describe | `describe_namespace` | `describeNamespace` | -- | | exists | `namespace_exists` | -- | -- | | drop | `drop_namespace` | `dropNamespace` | -- | See [Namespaces](/oss/v0-41-0/management/namespace). ### Tables | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_table` | `createTable` | `CREATE TABLE` | | create empty | `create_table(schema=)` | `createEmptyTable` | `CREATE TABLE` | | open | `open_table` | `openTable` | -- | | list | `table_names`, `list_tables` | `tableNames`, `listTables` | -- | | exists | `table_exists` | -- | -- | | rename | `rename_table` | `renameTable` | -- | | clone | `clone_table` | `cloneTable` | -- | | drop | `drop_table`, `drop_table_async` | `dropTable`, `dropTableAsync` | `DROP TABLE` | | drop all | `drop_all_tables` | `dropAllTables` | -- | See [Tables](/oss/v0-41-0/management/table) for creating one and shaping its schema. ### Materialized views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_materialized_view` | `createMaterializedView` | `CREATE MATERIALIZED VIEW` | | open | `open_materialized_view` | `openMaterializedView` | -- | | list | `list_materialized_views` | `listMaterializedViews` | `SHOW MATERIALIZED VIEWS` | | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_table` | `dropTable` | `DROP TABLE` | > [!NOTE] > > Local `list_materialized_views` reads table schemas to find views. On > Enterprise, it requests the server's view listing. See [Materialized views](/oss/v0-41-0/management/materialized-view) for creating one, and [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) for keeping it current. ### Views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_view` | `createView` | `CREATE VIEW` | | list | `list_views` | `listViews` | -- | | drop | `drop_view`, `drop_view_async` | `dropView`, `dropViewAsync` | `DROP VIEW` | Enterprise Views exist only on an Enterprise cluster that enables them; the SDK methods send the view's SQL query to the deployment. See [Views](/oss/v0-41-0/management/view). ### Functions | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | | get | `get_function` | -- | `DESCRIBE FUNCTION` | | list | `list_functions` | -- | `SHOW FUNCTIONS` | | drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on a deployment that enables functions, so there is no local form. The TypeScript SDK has no function methods; use Python or SQL. See [Functions](/oss/v0-41-0/management/function). ### Jobs | | Python | TypeScript | SQL | | - | - | - | - | | list | `list_jobs` | `listJobs` | `SHOW JOBS` | | open | `open_job` | `openJob` | -- | | cancel | `cancel_job` | `cancelJob` | -- | | errors | `job.events` | `job.events` | `SHOW ERRORS` | See [Job Framework](/oss/v0-41-0/basics/jobs). ### Indexes | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_index`, `create_index_async` | `createIndex`, `createIndexAsync` | `CREATE INDEX` | | list | `list_indices` | `listIndices` | -- | | stats | `index_stats` | `indexStats` | -- | | drop | `drop_index` | `dropIndex` | `DROP INDEX` | > [!NOTE] > > SQL `CREATE INDEX` covers one column and takes no user-chosen name: the server > names it. For a multi-column or named index, use the SDK. Indexes are a performance decision rather than a structural one, so they are covered under [Maintenance](/oss/v0-41-0/indexing). ## Work within a namespace Most connection-level operations take a `namespace_path` (`namespacePath`) to act inside a namespace rather than at the database root: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.table_names(namespace_path=["prod", "events"]) tbl = db.open_table("clicks", namespace_path=["prod", "events"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.tableNames(["prod", "events"]); const tbl = await db.openTable("clicks", ["prod", "events"]); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM `prod$events`.clicks ``` In SQL the path is written as a `$`-joined schema instead; see [Namespace](/oss/v0-41-0/basics/catalog#schema) for why it isn't dotted. ## Delete catalog objects > [!WARNING] > > `drop_table` removes the table and every version of it. Table > [versioning](/oss/v0-41-0/management/table#versioning) does not survive the table being dropped, and > neither `drop_database` nor `drop_all_tables` asks for confirmation. Dropping a **view** removes only the saved query. Dropping a **materialized view** removes stored rows, because a materialized view is a table. # Materialized view Source: https://docs.lancedb.com/oss/v0-41-0/management/materialized-view Create, open, list and drop a table whose contents are defined by a query. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view is a table whose contents are defined by a query over another table. The query is recorded in the view's schema, and a refresh brings its stored rows up to date with the source. The result is an ordinary table: queryable, indexable, searchable, and present in `table_names()`. Nothing about reading it is special. This page covers creating and managing one. Keeping it current is [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view). > [!NOTE] > > In SQL, see [`REFRESH MATERIALIZED VIEW`](/oss/v0-41-0/sql/dml/refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/oss/v0-41-0/sql/ddl/materialized-view#show). ## Create a materialized view A materialized view is defined by a SQL query: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true """).read_all() view = db.open_materialized_view("frames_captioned") ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_captioned AS SELECT frame_id, video_id, ts, caption FROM frames WHERE selected = true ``` See [Create a materialized view](/oss/v0-41-0/feature-engineering/materialized-views#create) for the full walkthrough, including joins and Functions in the query. ## Open, list and drop views | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_materialized_view` | `createMaterializedView` | `CREATE MATERIALIZED VIEW` | | open | `open_materialized_view` | `openMaterializedView` | -- | | list | `list_materialized_views` | `listMaterializedViews` | `SHOW MATERIALIZED VIEWS` | | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_materialized_view` | `dropMaterializedView` | `DROP MATERIALIZED VIEW` | Enterprise Creating, refreshing and dropping a materialized view each have an async, job-returning counterpart -- `create_materialized_view_async`, `view.refresh_async()`, `drop_materialized_view_async` -- the same pattern as [`refresh_column_async`](/oss/v0-41-0/feature-engineering/refresh-column#async): each returns a [job](/oss/v0-41-0/basics/jobs) you `wait()` on instead of blocking, with the same arguments as its synchronous counterpart, including `auto_refresh_enabled` and `auto_refresh_interval_seconds`; see [Auto Refresh](/oss/v0-41-0/enterprise/auto-refresh). > [!NOTE] > > On a local database, `list_materialized_views` reads table schemas to find > views. On Enterprise, it asks the server for the view listing, as > `SHOW MATERIALIZED VIEWS` does. A view is dropped with `drop_materialized_view`, a dedicated operation, even though a materialized view **is** a table underneath. That also means dropping one removes stored rows, unlike dropping a [view](/oss/v0-41-0/management/view), which removes only a saved query. ## Read the view and its definition `view.table` is the underlying table, for querying, indexing, or search. `view.definition` has a single field, `query` -- the defining query, in the canonical spelling the server stores. Both are properties; on an async view, the definition is read with `await view.definition()`. ## Enterprise compatibility Enterprise supports creating and refreshing materialized views on remote compute. Use the SDK version supported by your deployment, or the [SQL interface](/oss/v0-41-0/sql/ddl/materialized-view). ## Privileges A materialized view **is** a table (see [Dropping one](/oss/v0-41-0/sql/ddl/materialized-view#drop)), granted through the REST ACL API or SQL `GRANT`/`REVOKE` with the same privilege names as a table, but two of them mean something different here: the server refuses a direct `INSERT`, `UPDATE` or `DELETE` on a materialized view's rows -- only a refresh writes them. `UPDATE` is instead what authorizes calling refresh, and `OWNERSHIP` is what authorizes `ALTER` (auto-refresh settings): ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts ``` That grants `analysts` read access and the ability to refresh `daily_rollup`, not row-level write access. See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax and every target it reaches. ## Related guides > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > How a refresh works, and what it writes. > [card] [Views](/oss/v0-41-0/management/view) > > The non-materialized counterpart, defined in SQL. # Namespaces Source: https://docs.lancedb.com/oss/v0-41-0/management/namespace Grouping tables into a hierarchy, and addressing them through it. **Applies to:** Embedded ✅, Enterprise ✅ LanceDB organizes Lance tables through a catalog-level abstraction defined by the *namespace spec*. LanceDB Embedded is an embedded library for accessing those tables, and LanceDB Enterprise is a multimodal lakehouse that provides shared compute and catalog services on top of the Lance format. If you're coming from traditional databases or lakehouses, you can think of a namespace as the catalog path that says where a table name lives. Lance provides the **file** and **table** formats to store and manage your data and indexes. LanceDB operates at the catalog layer (used to organize, discover, and operate on many Lance tables) and provides a compute engine on top of the Lance format. This is why many SDK methods in LanceDB, like `create_table`, `open_table`, `drop_table`, and `rename_table`, accept namespace input. The SDK methods expose that input in the idiom of each language: Python uses `namespace_path`, Rust uses builder methods like `.namespace(...)`, and TypeScript uses `namespacePath` arguments. > [!NOTE] > > In LanceDB Enterprise SQL, a namespaced table is addressed by its > [schema](/oss/v0-41-0/basics/catalog#schema) -- the namespace path joined by `$`, not > by `.` -- [before the table name](/oss/v0-41-0/sql/dql/select#namespaces). ## Namespace hierarchy Namespaces are generalizations of catalog specs that give platform developers a clean way to present Lance tables in the structures users expect. The diagram below shows how the hierarchy can go beyond a single level. A namespace can contain a collection of tables, and it can also contain namespaces recursively. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/namespaces/lance-namespace.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=cca73b3ad4f3ac59e9d457ade87874d4) Before diving into examples, it helps to keep two terms in mind: the **namespace client** is the abstraction that presents a consistent namespace API, while the **namespace implementation** is the concrete backend that resolves namespaces and table locations (for example, a local directory or an external catalog). If you want to go deeper, see the Lance format [namespace documentation](https://lance.org/format/namespace/). ## Namespace paths and names A namespace path is a list of components. For example, `["prod", "search"]` means the `search` namespace inside the `prod` namespace. The empty path, `[]`, means the root namespace. Each component is a name, not a filesystem path segment, and can't be empty. Keep each one to letters, numbers, underscores, hyphens, and periods, so the same identifier is usable everywhere: a local directory namespace accepts other characters too, but other namespace implementations and deployments can refuse them. [Naming rules](/oss/v0-41-0/basics/naming) has the lengths and the other limits. ## Directory namespaces The simplest namespace model in LanceDB is a single root namespace, often represented by one directory. Namespaces can nest inside it, as in this hierarchy: ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ./local_lancedb (root) └── prod └── search └── user (table) └── data (table) ``` The hierarchy is logical, not a tree of folders: a directory namespace records it in a `__manifest` table in the root directory, and stores each table in a directory of its own there. As a user of LanceDB Embedded, you might never notice namespaces at first, because a plain connection uses only the root namespace, which is implicit. Connecting to this namespace is as simple as connecting to the namespace root: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Connect to the directory namespace root db = lancedb.connect("./local_lancedb") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Connect to the directory namespace root const db = await lancedb.connect("./local_lancedb"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use lancedb::connect; // Connect to the directory namespace root let db = connect("./local_lancedb").execute().await?; ``` A table created through this connection is stored directly under that path, as `<name>.lance`. You can also explicitly connect to a namespace using `lancedb.connect_namespace(...)` with the directory namespace implementation: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Local DirectoryNamespace root # See https://lance.org/format/namespace/dir/catalog-spec/ db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) table_name = "user" data = [{"id": 1, "vector": [0.1, 0.2], "name": "alice"}] table = db.create_table(table_name, data=data, mode="create") print(f"Created table: {table.name}") # Created table: user ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); const table = await db.createTable( "user", [{ id: 1, vector: [0.1, 0.2], name: "alice" }], { mode: "create" }, ); console.log(`Created table: ${table.name}`); // Created table: user ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; use std::sync::Arc; use arrow_schema::{DataType, Field, Schema}; // Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ let mut properties = HashMap::new(); properties.insert("root".to_string(), "./local_lancedb".to_string()); let db = lancedb::connect_namespace("dir", properties) .execute() .await?; let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), ])); let table = db .create_empty_table("user", schema) .execute() .await?; println!("Created table: {}", table.name()); // Created table: user ``` > [!NOTE] > > * For simple use cases in LanceDB Embedded, you don't need to go too deep into namespaces. > * To integrate LanceDB with external catalogs, understand how each namespace implementation resolves table names and locations in your organization's setup. ## Remote or external catalog namespaces The example above showed local directory-based namespaces. LanceDB also supports namespaces backed by remote object stores and external catalogs, via the REST namespace implementation. For remote object stores with central metadata or catalog services (either commercial or open source), use the REST namespace implementation. It is backed by REST routes (for example `POST /v1/namespace/{id}/create` and `GET /v1/namespace/{id}/list`) and server-provided table locations. For authentication, any property prefixed with `headers` is forwarded as an HTTP header (for example `headers.Authorization` becomes `Authorization`, and `headers.X-API-Key` becomes `X-API-Key`). LanceDB Enterprise REST requests use the `x-api-key` header for API-key authentication. Deployments that route multiple databases through the same endpoint can also use headers such as `x-lancedb-database` or `x-lancedb-database-prefix` for database context. Replace the catalog URL and credential placeholders below with your values. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remote RestNamespace root # See https://lance.org/format/namespace/rest/catalog-spec/ db = lancedb.connect_namespace( "rest", { "uri": "https://<your_catalog>.internal.<your_org>.com", "headers.x-api-key": "your-api-key", # or: # "headers.Authorization": "Bearer your-access-token", }, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; // Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ const db = await lancedb.connectNamespace("rest", { uri: "https://<your_catalog>.internal.<your_org>.com", headers: { "x-api-key": "your-api-key", // or: // Authorization: "Bearer your-access-token", }, }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; // Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ let mut properties = HashMap::new(); properties.insert( "uri".to_string(), "https://<your_catalog>.internal.<your_org>.com".to_string(), ); properties.insert( "headers.x-api-key".to_string(), "your-api-key".to_string(), ); // or: // properties.insert( // "headers.Authorization".to_string(), // "Bearer your-access-token".to_string(), // ); let db = lancedb::connect_namespace("rest", properties) .execute() .await?; ``` [LanceDB Enterprise](/oss/v0-41-0/index#architecture) operates a REST namespace server on top of the Lance format, so any REST client that can speak the REST namespace API contract can be used to interact with it. It does not serve the contract's `exists` routes, so existence checks made through a direct REST namespace client fail against it. Python remote connections created with `lancedb.connect("db://...")` or `lancedb.connect_async("db://...")` support `namespace_exists` and `table_exists` through the existing describe routes instead with Python 0.42.0b8. In Python 0.41.0, the sync remote methods raise `NotImplementedError` and the async connection has neither helper. For authentication examples in LanceDB Enterprise, visit the [Namespaces in SDKs](#namespaces-in-lancedb-enterprise) page. ## Best practices Below, we list some best practices for working with namespaces: * For simple use cases and single, stand-alone applications, the directory-based root namespace is sufficient and requires no special configuration. * For remote storage locations, introduce explicit namespaces when multiple teams, environments, or domains share the same catalog. * Treat namespace paths as stable identifiers (for example `"prod/search"`, `"staging/recs"`). * For maintainability reasons, avoid hard-coding object-store table paths in application code. Instead, prefer catalog identifiers + namespaces. ## Table operations with namespace paths Let's imagine a scenario where your table management needs have evolved, and you now have the following multi-level structure to organize your tables outside the root namespace. ``` ./local_lancedb (root) └── prod └── search └── user (table) └── data (table) └── recommendations └── user (table) └── data (data) ``` Below, we show how you would express table operations within that namespace. Each item in the namespace list (`["prod", "search"]`) represents a level in the namespace hierarchy, and the table name is specified when you create, open, list, or drop it. The SDK methods expose the namespace path in the idiom of each language: * Python: pass `namespace_path=["prod", "search"]` to table operations. * Rust: call builder methods such as `.namespace(vec!["prod".to_string(), "search".to_string()])`. * TypeScript: pass a `namespacePath` array, for example `await db.openTable("user", ["prod", "search"])`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) # Create namespace tree: prod/search db.create_namespace(["prod"], mode="exist_ok") db.create_namespace(["prod", "search"], mode="exist_ok") db.create_namespace(["prod", "recommendations"], mode="exist_ok") db.create_table( "user", data=[{"id": 1, "vector": [0.1, 0.2], "name": "alice"}], namespace_path=["prod", "search"], mode="create", # use "overwrite" only if you want to replace existing table ) db.create_table( "user", data=[{"id": 2, "vector": [0.3, 0.4], "name": "bob"}], namespace_path=["prod", "recommendations"], mode="create", # use "overwrite" only if you want to replace existing table ) # Verify: listings return a response with the names and a page token print(db.list_namespaces().namespaces) # ['prod'] print(db.list_namespaces(namespace_path=["prod"]).namespaces) # ['recommendations', 'search'] print(db.list_tables(namespace_path=["prod", "search"]).tables) # ['user'] print(db.list_tables(namespace_path=["prod", "recommendations"]).tables) # ['user'] ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function collectNames(items: AsyncIterable<string>): Promise<string[]> { const names: string[] = []; for await (const name of items) names.push(name); return names; } const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); // Create namespace tree: prod/search and prod/recommendations await db.createNamespace(["prod"], { mode: "exist_ok" }); await db.createNamespace(["prod", "search"], { mode: "exist_ok" }); await db.createNamespace(["prod", "recommendations"], { mode: "exist_ok" }); await db.createTable( "user", [{ id: 1, vector: [0.1, 0.2], name: "alice" }], ["prod", "search"], { mode: "create" }, // use "overwrite" only if you want to replace existing table ); await db.createTable( "user", [{ id: 2, vector: [0.3, 0.4], name: "bob" }], ["prod", "recommendations"], { mode: "create" }, ); // Verify console.log(await collectNames(db.listNamespaces())); // ["prod"] console.log(await collectNames(db.listNamespaces(["prod"]))); // ["recommendations", "search"] console.log(await db.tableNames(["prod", "search"])); // ["user"] console.log(await db.tableNames(["prod", "recommendations"])); // ["user"] ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let conn = connect(uri).execute().await?; let search_namespace = vec!["prod".to_string(), "search".to_string()]; let recommendations_namespace = vec!["prod".to_string(), "recommendations".to_string()]; let schema = std::sync::Arc::new(arrow_schema::Schema::new(vec![ arrow_schema::Field::new("id", arrow_schema::DataType::Int64, false), ])); conn.create_empty_table("user", schema.clone()) .namespace(search_namespace.clone()) .execute() .await?; conn.create_empty_table("user", schema) .namespace(recommendations_namespace.clone()) .execute() .await?; let search_table_names = conn .table_names() .namespace(search_namespace) .execute() .await?; let recommendation_table_names = conn .table_names() .namespace(recommendations_namespace) .execute() .await?; println!("{search_table_names:?}"); // ["user"] println!("{recommendation_table_names:?}"); // ["user"] ``` > [!NOTE] > > Using namespaces is **optional** in LanceDB, and most basic use cases do not require to work with them. > An empty namespace (`[]`), which is the default, means the root namespace, whose tables are stored > directly under the specified root path. ## Namespace management APIs You can open/create/drop tables inside a namespace path (like `["prod", "search"]`). All three SDKs expose namespace lifecycle operations directly. In Python, use `lancedb.connect_namespace(...)` when calling namespace lifecycle methods such as `create_namespace`, `list_namespaces`, `describe_namespace`, and `drop_namespace`. In TypeScript, use `lancedb.connectNamespace(...)` and call `createNamespace`, `listNamespaces`, `describeNamespace`, and `dropNamespace` on the returned `Connection`. In Rust, use `lancedb::connect_namespace(...)` and call `create_namespace`, `list_namespaces`, and `drop_namespace`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) namespace = ["prod", "search"] db.create_namespace(["prod"]) db.create_namespace(["prod", "search"]) child_namespaces = db.list_namespaces(namespace_path=["prod"]).namespaces print(f"Child namespaces under ['prod']: {child_namespaces}") # Child namespaces under ['prod']: ['search'] metadata = db.describe_namespace(["prod", "search"]) print(f"Metadata for namespace {namespace}: {metadata}") # Metadata for namespace ['prod', 'search']: properties=None db.drop_namespace(["prod", "search"], mode="skip") db.drop_namespace(["prod"], mode="skip") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} async function collectNames(items: AsyncIterable<string>): Promise<string[]> { const names: string[] = []; for await (const name of items) names.push(name); return names; } const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); const namespace = ["prod", "search"]; await db.createNamespace(["prod"]); await db.createNamespace(["prod", "search"]); const childNamespaces = await collectNames(db.listNamespaces(["prod"])); console.log( `Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces, ); // Child namespaces under ["prod","search"]: [ 'search' ] const metadata = await db.describeNamespace(["prod", "search"]); console.log(`Metadata for namespace ${JSON.stringify(namespace)}:`, metadata); await db.dropNamespace(["prod", "search"], { mode: "skip" }); await db.dropNamespace(["prod"], { mode: "skip" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let mut properties = std::collections::HashMap::new(); properties.insert("root".to_string(), "./local_lancedb".to_string()); let db = lancedb::connect_namespace("dir", properties).execute().await?; let namespace = vec!["prod".to_string(), "search".to_string()]; db.create_namespace(lance_namespace::models::CreateNamespaceRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; db.create_namespace(lance_namespace::models::CreateNamespaceRequest { id: Some(namespace.clone()), ..Default::default() }) .await?; let child_namespaces = db .list_namespaces(lance_namespace::models::ListNamespacesRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; println!( "Child namespaces under {:?}: {:?}", namespace, child_namespaces ); // Child namespaces under ["prod", "search"]: ["search"] db.drop_namespace(lance_namespace::models::DropNamespaceRequest { id: Some(namespace.clone()), ..Default::default() }) .await?; db.drop_namespace(lance_namespace::models::DropNamespaceRequest { id: Some(vec!["prod".to_string()]), ..Default::default() }) .await?; ``` Namespace creation and deletion have modes that control what happens when the target already exists, doesn't exist, or contains data: * Create mode: `create` fails if the namespace already exists, `exist_ok` keeps the existing namespace, and `overwrite` replaces it. * Drop mode: `fail` reports an error when the namespace doesn't exist, and `skip` treats a missing namespace as a successful no-op. * Drop behavior: `restrict` keeps non-empty namespaces from being dropped, and `cascade` drops child namespaces and tables first. Namespace path components can't be empty, and are best kept to letters, numbers, underscores, hyphens, and periods, as [above](#namespace-paths-and-names). Listing APIs return the immediate children of the requested namespace path. Use `limit` with the returned `page_token` to page through large catalogs; pass an empty namespace path (`[]`) when you want to list from the root namespace. In Python, a listing returns a response: the names are in its `namespaces` or `tables`, and `page_token` is set when there is another page. ## Namespaces in LanceDB Enterprise In LanceDB Enterprise deployments, configure namespace-backed federated databases in a TOML file under your deployment's `config` directory. LanceDB Enterprise supports both directory-based (`ns_impl = "dir"`) and REST-based (`ns_impl = "rest"`) namespace implementations. The example below shows how to configure a directory-based namespace implementation in LanceDB Enterprise. ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Federated database configuration for DirectoryNamespace # This example uses minio storage [federated_dbs.federated_dir_test] ns_impl = "dir" root = "s3://<your-deployment>/<your-dir>" "storage.region" = "us-east-1" "storage.endpoint" = "http://localhost:9000" "storage.access_key_id" = "minioadmin" "storage.secret_access_key" = "minioadmin" "storage.allow_http" = "true" # Far future expiration (year 2100) "storage.expires_at_millis" = "4102444800000" ``` The example above uses MinIO, but the same approach applies to other cloud object storage platforms based on your deployment. For REST-based namespace servers, you can specify the namespace implementation as `"rest"` with forwarding prefixed headers for authentication and context propagation. ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [federated_dbs.federated_rest_test] ns_impl = "rest" uri = "http://<your_org>.internal.catalog.com" forward_header_prefixes = ["X-forward"] ``` With `forward_header_prefixes = ["X-forward"]`, any incoming header starting with `X-forward` is forwarded to `http://<your_org>.internal.catalog.com`. This is useful for auth propagation, for example sending `X-forward-authorization: Bearer xxxx`. For the LanceDB REST API itself, requests use `x-api-key` for API-key authentication. If your endpoint serves more than one database, LanceDB can also use headers such as `x-lancedb-database` or `x-lancedb-database-prefix` to route the request to the right database context. ## Privileges A namespace's `USAGE`, and the `CREATE_TABLE`, `CREATE_VIEW`, `CREATE_MATERIALIZED_VIEW`, `CREATE_NAMESPACE`, `CREATE_SECRET`, `CREATE_STORAGE_INTEGRATION` and `CREATE_FUNCTION` privileges for what it can hold, are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE NAMESPACE, CREATE TABLE, CREATE VIEW ON SCHEMA platform TO ROLE writers ``` See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Secret Source: https://docs.lancedb.com/oss/v0-41-0/management/secret Create, rotate, list, describe and drop a named credential that Functions bind by reference. **Applies to:** Embedded ❌, Enterprise ✅ Early access A **Secret** is a catalog object, like a table or a namespace: a named credential, such as a model provider's API key, stored once and addressed by name. A [Function](/oss/v0-41-0/curation/create-function) binds a Secret by reference when you register it, never by value; see [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret) for how that binding reaches running code. The design rule is **bind by reference, resolve late**. A Function records *which* Secret it reads, never the value, and the value is looked up each time a job starts. That is what lets a credential be rotated or revoked without touching the Functions, columns or tables that use it. ## Create and manage Every call takes an optional `namespace_path`; the default is the root namespace. ```python Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.create_secret("model-api-key", value, namespace_path=["platform"]) db.alter_secret("model-api-key", new_value, namespace_path=["platform"]) for name in db.list_secrets(namespace_path=["platform"]): print(name) info = db.describe_secret("model-api-key", namespace_path=["platform"]) info.created_at_millis, info.updated_at_millis db.drop_secret("model-api-key", namespace_path=["platform"]) ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '<api-key>'; ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '<api-key>'; SHOW SECRETS IN platform; DESCRIBE SECRET platform.`model-api-key`; DROP SECRET platform.`model-api-key`; ``` ```rust theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use futures::TryStreamExt; let namespace = vec!["platform".to_string()]; db.create_secret("model-api-key", &value, &namespace).await?; db.alter_secret("model-api-key", &new_value, &namespace).await?; let mut names = db.list_secrets(&namespace, Default::default()); while let Some(name) = names.try_next().await? { println!("{name}"); } let info = db.describe_secret("model-api-key", &namespace).await?; println!("{} {}", info.created_at_millis, info.updated_at_millis); db.drop_secret("model-api-key", &namespace).await?; ``` A Secret's value is never returned by any interface: `create` and `alter` take it as input and return nothing, and `describe` reports only metadata. Python and Rust both expose the full lifecycle shown above; TypeScript does not yet, and is tracked separately. See the [SQL reference](/oss/v0-41-0/sql/ddl/secret) for the same operations' SQL syntax and result rows. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function. Register Functions that > bind Secrets through the Python SDK; see > [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret). ## Properties and guarantees LanceDB guarantees that: * No API returns a Secret's value. * Values do not appear in Function source, Function versions, jobs, logs, or error messages. Errors raised by Function code are redacted, within [limits](#redaction). * A Function receives only the Secrets bound to it. * Values are always [encrypted at rest](#encryption). Redaction is a safety net, not a boundary: Function code that logs, returns or sends a credential will leak it. ### Encryption at rest Every Secret's value is encrypted directly with your deployment's key in AWS KMS, Google Cloud KMS, or Azure Key Vault -- there is no separate application data key to manage. Storage, backups and replicas hold only ciphertext. Decryption goes through your KMS, which records it in your cloud's audit log. BYOC You are responsible for the network egress policy for the jobs that run Functions. ### Redaction If a Function raises an error or skips a row with a message that contains a bound value, LanceDB replaces each exact occurrence with `[REDACTED]` before the message is recorded. Redaction matches only the exact value: a value that is base64-encoded, sliced, or otherwise transformed is not caught. Function code that prints a credential, writes it into a column, or sends it elsewhere will leak it, so review a Function bound to a Secret as code that holds that credential. ## Limits | Item | Limit | | - | - | | Secret name | 1--128 characters from `A-Z a-z 0-9 _ . -`. `$` is reserved as the namespace delimiter. | | Value | One nonempty UTF-8 string, at most 4,096 bytes. On Azure, at most 158, 286 or 414 bytes for an RSA-2048, RSA-3072 or RSA-4096 key. | | Bindings per Function | 16 | | Environment variable name | `[A-Za-z_][A-Za-z0-9_]*`, and not [reserved](#reserved) | | Variables per Function | Each bound once. Two variables may bind the same Secret. | | `describe` history | The most recent 100 alterations | ### Reserved variables A Secret cannot be bound to a variable that LanceDB sets for Functions itself. These names are reserved: * Exact names: `HOME`, `PATH`, `TEMP`, `TMP`, `TMPDIR`, `LANG`, `LC_ALL`, `LC_CTYPE`, `TZ`, `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE`, `SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, `UV_CACHE_DIR`, `UV_NATIVE_TLS`, `UV_PYTHON_INSTALL_DIR`, `RUST_BACKTRACE` * Prefixes: `DYLD_`, `LANCE_`, `LANCEDB_`, `LD_`, `PYTHON`, and a few others LanceDB reserves for its own use. `create_function` refuses a reserved name and says which one. ## Troubleshooting **`Secret 'X', bound to VAR, does not exist`** when adding a column or refreshing one: the Secret was never created in that namespace, was dropped, or its name is misspelled in the binding. Create it, or register a new Function version with the right name. **501 from a Secret API call**: Secrets aren't enabled for this deployment. Contact [LanceDB support](/oss/v0-41-0/deployment/support). ## Privileges A Secret is its own object in the authorization model, a namespace child like a table, so a grant names one credential rather than a whole database. See [Privileges](/oss/v0-41-0/governance/privileges#secret-operations) for the privilege each operation above requires, and [GRANT and REVOKE](/oss/v0-41-0/sql/ddl/secret#grant) for the full SQL statement syntax. ## What to read next > [card] [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret) > > Bind a Secret when you register a Function, and how rotation reaches > code that is already running. > [card] [Privileges](/oss/v0-41-0/governance/privileges#sql) > > Grant and revoke privileges on a Secret. # Storage Integration Source: https://docs.lancedb.com/oss/v0-41-0/management/storage-integration A namespace-scoped, reusable credential for reading or importing from storage outside the deployment's own tables. **Applies to:** Embedded ❌, Enterprise ✅ A **storage integration** is a namespace-scoped catalog object, like a [Secret](/oss/v0-41-0/management/secret), that names a credential for reading or importing from one external storage location: an S3, GCS or Azure prefix, or a HuggingFace dataset repository. A query or import statement that reads a matching URI uses the integration automatically -- it is never named in the query itself. ## Create and manage Every provider takes a `storage_prefix` and `storage_provider`, plus provider-specific credential options. Credential options take a [Secret](/oss/v0-41-0/management/secret) reference, never a value directly -- either a bare name (resolved in the caller's own database, root namespace) or a `SecretReference` qualified with a database and namespace path: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token DESCRIBE STORAGE INTEGRATION hub SHOW STORAGE INTEGRATIONS DROP STORAGE INTEGRATION hub ``` See [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) for every provider's exact options, S3's two credential modes, and the full output schema -- this page covers the CRUD operations above at a glance; that one is the complete reference. | Operation | Python (not yet released) | SQL | Notes | | - | - | - | - | | Create | `create_storage_integration` | `CREATE STORAGE INTEGRATION` | Fails if the name is taken, so a create never silently replaces one. | | Describe | `describe_storage_integration` | `DESCRIBE` / `DESC` | One row: provider, prefix, credential references, and (for an AWS role integration) the generated trust policy. | | List | `list_storage_integrations` | `SHOW` / `LIST STORAGE INTEGRATIONS` | Optionally scoped to one namespace. | | Drop | `drop_storage_integration` | `DROP [IF EXISTS]` | Blocked while an attached database still depends on it. | The Python column names the methods landing in a future release (see the draft note above); use SQL today. There is no TypeScript or REST equivalent yet either. There is no `ALTER`. To rotate a credential, rotate the [Secret](/oss/v0-41-0/management/secret#manage) it references -- the integration's reference does not change, so nothing that reads through it needs updating. ## The S3 trust workflow An S3 integration created with `STORAGE_AWS_ROLE_ARN` (instead of a static access key pair) needs one more step outside LanceDB: `DESCRIBE` returns `trust_policy` and `permissions_policy`, the IAM policy documents your role needs, built from `aws_account_id`, `aws_iam_principal_arn` and `aws_external_id` in the same row. Attach `trust_policy` as the role's trust relationship and `permissions_policy` as its permissions, then check `access_verified` on a later `DESCRIBE` to confirm LanceDB can assume the role and read the prefix. ## Privileges A storage integration is its own object in the authorization model, a namespace child like a Secret: `CREATE_STORAGE_INTEGRATION` on the namespace to create one, `USAGE` on the integration for a query to read through it, `OWNERSHIP` for full control including dropping it. See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the privilege each operation requires and the full `GRANT`/`REVOKE` syntax. ## Troubleshooting **A query does not use the integration you expected**: integrations match by the most specific `STORAGE_PREFIX` covering the URI, not by name, and are scoped to native databases under the catalog root. Two integrations with equally specific prefixes make the query fail rather than guess; keep prefixes for the same bucket or dataset family unambiguous. **403 or access-denied reading a matching prefix**: confirm `USAGE` on the integration, and for an S3 role integration, confirm `access_verified` is `true` on `DESCRIBE` -- `false` usually means the trust policy from [above](#trust) is missing or misconfigured on the AWS side, not a LanceDB permission problem. **`DROP` refuses with a dependent database**: detach the database that still uses the integration first, then drop it. ## What to read next > [card] [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) > > The complete SQL reference: every provider's options, output columns, and GRANT syntax. > [card] [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) > > The most common use of a storage integration today: inspecting and importing HuggingFace datasets. > [card] [Secret](/oss/v0-41-0/management/secret) > > The credential a storage integration's `_SECRET` options reference. # Tables Source: https://docs.lancedb.com/oss/v0-41-0/management/table The object most operations act on: creating, opening, renaming, cloning and dropping one. **Applies to:** Embedded ✅, Enterprise ✅ A table stores data in rows and columns and keeps a history of committed versions. Queries read table data, writes update it, and indexes accelerate searches over its columns. This page covers table management, data types, schema changes and version history. For loading records, see [Ingestion](/oss/v0-41-0/ingestion). For changes to columns, see [Schema evolution](/oss/v0-41-0/management/table#schema). > [!NOTE] > > In LanceDB Enterprise, tables are also created and dropped in SQL with [`CREATE TABLE` and `DROP TABLE`](/oss/v0-41-0/sql/ddl/table). ## Table structure and metadata | | | | - | - | | **Columns** | including vectors, blobs, and [computed](/oss/v0-41-0/feature-engineering/add-computed-column) columns | | **Versions** | every write commits one, so reads can [travel back](/oss/v0-41-0/management/table#versioning) | | **Indexes** | vector, full-text and scalar, built over its columns | ## Create a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("documents", data) tbl = db.create_table("documents", schema=schema) # empty, typed ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.createTable("documents", data); const tbl = await db.createEmptyTable("documents", schema); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents (id BIGINT, title VARCHAR) ``` `data` can be a list of objects, an Arrow table or reader, a pandas or polars frame, or Pydantic models. [Ingesting data](/oss/v0-41-0/ingestion) covers each, plus `exist_ok` and `mode="overwrite"` for re-runnable scripts. > [!WARNING] > > An explicit schema is where nullability is decided. In the embedded library, > creation is also the only point at which a table can be given **stable row > ids**; in LanceDB Enterprise, whether a new table gets them is the deployment's > setting. See [Limits](/oss/v0-41-0/basics/limits#schema). ## Open and list tables ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.open_table("documents") db.table_names() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tbl = await db.openTable("documents"); await db.tableNames(); ``` Each accepts `namespace_path` to act inside a [namespace](/oss/v0-41-0/management/namespace) rather than at the database root. With Python 0.42.0b8, remote connections created with `lancedb.connect("db://...")` use `db.table_exists(["documents"])` to check whether a table exists. For an async remote connection, use `await db.table_exists(["documents"])`. Include namespace segments before the table name, for example `["analytics", "documents"]`. These checks return `False` when the table is missing and propagate other errors, including permission errors. In Python 0.41.0, the synchronous remote method raises `NotImplementedError` and the async connection has no `table_exists` method. Open the table and handle a missing-table error with that client. Local synchronous directory connections still raise `NotImplementedError` for `table_exists`. On a connection from `connect_namespace("dir", ...)` or `connect_namespace("rest", ...)`, it fails with an `AttributeError`. For these connections, open the table and handle the error, or look for its name in a listing. A missing table raises `ValueError` on a local directory and `lance_namespace.TableNotFoundError` on a connection from `connect_namespace`. A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. ## Rename and clone tables ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.rename_table("documents", "docs") db.clone_table( "docs_snapshot", source_uri="s3://bucket/db/documents.lance", source_version=42, # or source_tag="release-1" is_shallow=True, ) ``` Renaming is not supported on a local directory connection. In LanceDB Enterprise, whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training set to the exact version a model saw. > [!WARNING] > > A shallow clone depends on the source's files continuing to exist. If the source > is [compacted](/oss/v0-41-0/maintenance/compaction) past the retention window, the version > the clone points at can be pruned. LanceDB Embedded connections support shallow clones > only; `is_shallow=False` is not implemented. If the copy must outlive the > source's history, copy its data into an independent table instead. A deployment > that supports cloning also makes shallow clones only, and one whose catalog > does not support it refuses every clone. > [!NOTE] > > **Enterprise job type:** on an Enterprise cluster that drops tables in the background, > the teardown runs as a job: `drop_table`, which fences the table's directory > with a marker and deletes its content, or `drop_object`, depending on how the > deployment stores its catalog. See > [Object teardown](/oss/v0-41-0/basics/jobs#teardown). ## Drop a table ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.drop_table("documents") job = db.drop_table_async("documents") db.drop_all_tables() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await db.dropTable("documents"); const job = await db.dropTableAsync("documents"); await db.dropAllTables(); ``` ```sql SQL theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP TABLE documents ``` > [!WARNING] > > Dropping removes the table and **every version of it**. > [Versioning](/oss/v0-41-0/management/table#versioning) does not survive a drop, and neither > `drop_all_tables` nor `drop_database` asks for confirmation. Both work only on > a local database; on an Enterprise connection the SDK raises instead. On a large table the drop can take a while, so `drop_table_async` returns a [job](/oss/v0-41-0/basics/jobs) rather than blocking when the deployment drops tables in the background. In the embedded library, and on an Enterprise cluster that drops inline, the returned job has already finished. ## Table management APIs | | Python | TypeScript | SQL | | - | - | - | - | | create | `create_table` | `createTable` | `CREATE TABLE` | | create empty | `create_table(schema=)` | `createEmptyTable` | `CREATE TABLE` | | open | `open_table` | `openTable` | -- | | list | `table_names`, `list_tables` | `tableNames`, `listTables` | -- | | exists | `table_exists` | -- | -- | | rename | `rename_table` | `renameTable` | -- | | clone | `clone_table` | `cloneTable` | -- | | drop | `drop_table`, `drop_table_async` | `dropTable`, `dropTableAsync` | `DROP TABLE` | | drop all | `drop_all_tables` | `dropAllTables` | -- | ## Data types A table's schema is an **Arrow schema**: there is no separate LanceDB type system mapped onto storage, so a column is the same object to the query engine as it is to the format. | Category | Types | | - | - | | Numeric | `int8`-`int64` and unsigned, `float16`, `float32`, `float64` | | String and binary | `utf8`, `large_utf8`, `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp`, `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | | Lance extensions | vectors, [blobs](#multimodal), bfloat16 | A vector column is a `fixed_size_list<float32, dim>`, an ordinary Arrow type, which is why it is selectable and joinable but why arithmetic over it is list arithmetic rather than scalar. See [SQL data types](/oss/v0-41-0/sql/data-types) for the full reference, including the extension types and pseudo-columns. ## Multimodal data Store images, audio, video, and documents alongside structured columns and embeddings in the same versioned table. Use `blob` columns for these payloads. Small values stay inline in the data file, up to 64 KiB by default, and larger values are stored outside it. ### Blob columns Early access A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. Most queries return descriptors, which contain metadata about the blob instead of its bytes. You can [read the bytes in the query results](#multimodal-blob-query-results) or [fetch them by row ID](#multimodal-read-blobs). In Python, plain `to_pandas()` scans can also return `BlobFile` handles when `pylance` is installed. When you write raw bytes, Lance chooses a storage layout based on the payload size. A descriptor's `kind` tells you which one was used: | Storage mode | `kind` | Default placement | Storage behavior | | - | - | - | - | | `Inline` | `0` | Up to 64 KiB | Stored in the main data file. | | `Packed` | `1` | Above 64 KiB, up to 4 MiB | Packed with other blobs into a shared sidecar file, up to 1 GiB per file by default. | | `Dedicated` | `2` | Above 4 MiB | Stored in its own raw sidecar file. | | `Managed` | `4` or `5` | Out-of-line values when managed storage is enabled | Stored in a Lance-owned object independently of the data file. | Managed storage must be enabled separately. See [Managed blobs](#managed-blobs) for details. `kind=5` identifies a Managed object using an explicitly registered base. Lance uses the default thresholds unless you customize them. Explicitly configured thresholds are stored in the table schema and preserved on append. #### Setup Import the SDK and open a local database. The examples in this section use `db`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./blob_db") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; import { Buffer } from "node:buffer"; import * as lancedb from "@lancedb/lancedb"; const db = await lancedb.connect("./blob_db"); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use arrow_array::{ Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array, }; use arrow_schema::{DataType, Field, Schema}; use futures_util::TryStreamExt; use lancedb::blob::{BlobRangeRequest, blob}; use lancedb::connect; use lancedb::database::CreateTableMode; use lancedb::query::{ExecutableQuery, QueryBase}; let db = connect("./blob_db").execute().await.unwrap(); ``` #### Define a blob schema Declare a blob column with `lancedb.blob()` in Python and TypeScript, or `blob()` in Rust: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa schema = pa.schema( [ pa.field("id", pa.int64()), pa.field("label", pa.string()), lancedb.blob("image"), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const blobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field("label", new arrow.Utf8()), lancedb.blob("image"), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let blob_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("label", DataType::Utf8, true), blob("image", true), ])); ``` #### Ingest blobs Pass raw bytes for each blob value. In Python, a blob column accepts `bytes`. In TypeScript, it accepts a `Buffer`. The Python example creates two JPEGs with EXIF metadata, which we'll read using a blob handle below. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from PIL import Image def jpeg_with_make(color, make): image = Image.new("RGB", (8, 8), color=color) exif = Image.Exif() exif[0x010F] = make buf = io.BytesIO() image.save(buf, format="JPEG", exif=exif) return buf.getvalue() tbl = db.create_table( "photos", data=[ {"id": 1, "label": "red", "image": jpeg_with_make("red", "TestCam")}, {"id": 2, "label": "blue", "image": jpeg_with_make("blue", "OtherCam")}, ], schema=schema, mode="overwrite", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const blobTable = await db.createEmptyTable("photos", blobSchema, { mode: "overwrite", }); await blobTable.add([ { id: 1n, label: "door", image: Buffer.from("inline_image_bytes") }, { id: 2n, label: "window", image: Buffer.from("second_image_bytes") }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let blob_table = db .create_empty_table("photos", blob_schema) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); let input_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("label", DataType::Utf8, true), Field::new("image", DataType::LargeBinary, true), ])); let input_batch = RecordBatch::try_new( input_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1_i64, 2_i64])), Arc::new(StringArray::from(vec![Some("door"), Some("window")])), Arc::new(LargeBinaryArray::from_iter_values([ b"inline_image_bytes".as_slice(), b"second_image_bytes".as_slice(), ])), ], ) .unwrap(); let input_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema), ); blob_table.add(input_reader).execute().await.unwrap(); ``` #### Read bytes in query results Python and TypeScript can return blob bytes in query results without collecting `_rowid`. Rust uses [`fetch_blobs`](#multimodal-read-blobs) with row IDs instead. ##### Python `to_list(blob_mode="bytes")` returns the `image` bytes from the `photos` table above: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") ) ``` In the Python SDK, `Table.to_pandas()`, `Table.to_arrow()`, and the query builder methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a `blob_mode` argument. Sync and async query builders support the same modes: | `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | | - | - | - | | `"lazy"` | Default. Plain scans return seekable `BlobFile` handles. Vector, full-text, hybrid, and ordered queries return descriptor dicts. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | | `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | | `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and `to_pandas(blob_mode="descriptions")` use native Arrow conversion without pylance. In Python 0.41.0 and 0.42.0b8, legacy v1 blob bytes conversion through `to_pandas(blob_mode="bytes")` still requires the `pylance` extra. Those clients reject legacy v1 blobs in native Arrow/list/batch bytes queries. Pandas conversions that need the Lance scanner, including plain-scan `"lazy"` handles and scanner-only options, also require pylance. Native Arrow/list/batch conversion and the fetch methods do not require pylance for supported local v2 blob queries. `blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise and in-memory tables raise `NotImplementedError`. On an Enterprise table, `Table.to_pandas()` and `Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in the default `"lazy"` mode because it would open `BlobFile` handles. Query with `blob_mode="descriptions"`, then read bytes with `fetch_blobs` or `fetch_blob_files`. ###### Copy a subset of blob rows Blob query results describe the stored payload; they are not the bytes to insert into another table. These APIs return different values: | Read path | Value | | - | - | | SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | | `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | | A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | For an Enterprise source table, select the rows and fetch their bytes explicitly. The following example copies up to 100 rows from an existing `images` table with an integer `id` and a blob `image` column. Keep the source unchanged during this operation: selection and fetching are separate requests. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa source = db.open_table("images") hits = ( source.search() .where("id < 100") .select(["id"]) .with_row_id(True) .limit(100) .to_arrow() ) payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() subset = db.create_table( "image_subset", schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), ) if hits.num_rows: subset.add([ {"id": image_id, "image": payload} for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) ]) ``` Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches for larger subsets; `fetch_blobs` materializes all requested bytes in memory. For incremental decoding, use `fetch_blob_files` instead. `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs inside a list. Select those columns with `blob_mode="descriptions"`, or leave them out of the projection. Extra keyword arguments on `to_pandas()`, such as `split_blocks` and `self_destruct`, are forwarded to PyArrow. ###### Stream blob results In Python 0.41.0 and 0.42.0b8, `to_batches(blob_mode="bytes")` fetches row-addressable blob v2 payloads one batch at a time and returns them as Arrow `large_binary` values. Legacy v1 blob bytes are not supported by this native batch path in those clients. Iterate over the reader and call `batch.to_pandas()` to convert each batch to a DataFrame without collecting all payloads at once. For sync queries, call `query.to_batches(batch_size=64, blob_mode="bytes")` and iterate with `for`. For async queries, call `await query.to_batches(max_batch_length=64, blob_mode="bytes")` and iterate with `async for`. Sync full-text and hybrid queries do not support `to_batches()`. The default `"lazy"` mode returns blob v2 descriptors and keeps their automatic `_rowid` columns visible for manual fetches. `"descriptions"` returns the five-field descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; explicitly requested row IDs remain visible. Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, including no legacy blobs, blobs inside lists, Enterprise tables, namespace `QueryTable` pushdown, or query shapes that cannot preserve their row results. If concurrent writers can overwrite the table, use a separate reader checked out to a fixed version before querying. Otherwise, an overwrite can invalidate the row IDs used to fetch bytes and raise `ValueError`. ###### Optional pandas examples The lazy-handle calls below require pylance. The query example expects `tbl_async`, `query_vector`, and a `video` column, which the `photos` table does not define. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} df_lazy = tbl.to_pandas() df_bytes = tbl.to_pandas(blob_mode="bytes") df_desc = tbl.to_pandas(blob_mode="descriptions") arrow_bytes = tbl.to_arrow(blob_mode="bytes") df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) ``` Sync and async query builders accept the same `blob_mode` values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} df_lazy = ( tbl.search().where("id = 1").select(["id", "video"]).to_pandas(blob_mode="lazy") ) df_bytes = await ( tbl_async.query() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="bytes") ) df_vec = ( tbl.search(query_vector) .limit(2) .select(["id", "video"]) .to_pandas(blob_mode="bytes", split_blocks=True, self_destruct=True) ) ``` ##### TypeScript In TypeScript, `toArray()` and `toArrow()` accept a `blobMode` option: | `blobMode` | Result | | - | - | | `"descriptions"` | Default. Returns descriptors. | | `"bytes"` | Returns each top-level blob as bytes, or `null` for a null blob. Blobs nested in a struct or list keep their descriptors. | With `"bytes"`, the rows and the bytes come from the same table version. If the table changes while the query runs, the query runs again, up to three times: ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const withBytes = await blobTable .query() .select(["id", "image"]) .toArray({ blobMode: "bytes" }); const firstImage: Uint8Array | null = withBytes[0].image; ``` #### Read blobs on demand Query the rows you want and pass their `_rowid` values to a fetch method. `fetch_blob_files` opens a seekable handle and loads bytes only when you read. The Python example opens the JPEG from the ingest step and reads its EXIF Make tag with Pillow. TypeScript and Rust read the first bytes from the handle. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from PIL import ExifTags rows = tbl.search().where("id = 1").select(["label"]).with_row_id(True).to_list() with tbl.fetch_blob_files("image", [rows[0]["_rowid"]])[0] as image_file: make = Image.open(image_file).getexif().get(ExifTags.Base.Make) print(rows[0]["label"], make) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const rows = await blobTable .query() .select(["id", "label"]) .withRowId() .toArray(); const rowIds = rows.map((row) => row._rowid as bigint); const [image] = await blobTable.fetchBlobFiles("image", [rowIds[0]!]); const header = await image!.readRange(0n, 6n); await image!.close(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let batches = blob_table .query() .with_row_id() .execute() .await .unwrap() .try_collect::<Vec<_>>() .await .unwrap(); let row_ids = batches[0] .column_by_name("_rowid") .unwrap() .as_any() .downcast_ref::<UInt64Array>() .unwrap() .values() .to_vec(); let handles = blob_table .fetch_blob_files("image", &row_ids[..1]) .await .unwrap(); let header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap(); handles[0].as_ref().unwrap().close().await.unwrap(); ``` The other fetch methods load bytes directly: | Need | Python | TypeScript | Rust | | - | - | - | - | | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | | Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | * `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. * `fetch_blob_files` loads bytes when you call `read`, `read_range`, or `read_ranges`. Range reads don't move the file cursor. Null blobs produce null handles. * `fetch_blob_ranges` takes `(row_id, offset, length)` requests and returns one slice per request, in order. A request list can repeat a row to read more than one slice of that blob. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = tbl.search().select(["id"]).with_row_id(True).to_list() row_ids = [row["_rowid"] for row in rows] payloads = tbl.fetch_blobs("image", row_ids) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const payloads = await blobTable.fetchBlobs("image", rowIds); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let payloads = blob_table.fetch_blobs("image", &row_ids).await.unwrap(); ``` Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an exclusive `end`, and Rust takes `start..end` ranges: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} slices = tbl.fetch_blob_ranges("image", [(row_ids[0], 0, 2)]) with tbl.fetch_blob_files("image", [row_ids[0]])[0] as image_file: parts = image_file.read_ranges([(0, 2)]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); const parts = await secondImage!.readRanges([ { start: 0n, end: 6n }, { start: 7n, end: 12n }, ]); await secondImage!.close(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let slices = blob_table .fetch_blob_ranges( "image", [ BlobRangeRequest::new(row_ids[0], 0, 6), BlobRangeRequest::new(row_ids[1], 0, 6), BlobRangeRequest::new(row_ids[1], 7, 5), ], ) .await .unwrap(); let second_handles = blob_table .fetch_blob_files("image", &row_ids[1..2]) .await .unwrap(); let second_image = second_handles[0].as_ref().unwrap(); let parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap(); second_image.close().await.unwrap(); ``` #### Notes and limits Blob fetches fail if any requested row ID is missing or deleted. With stable row IDs enabled, IDs remain valid across compaction. A blob field can sit at the top level of the schema or inside a struct or list. Struct-nested blob columns use dotted paths such as `clip.video` in the fetch APIs. Blobs inside lists can be written and queried as descriptors. A table row ID does not address one list element, so `blob_columns()`, `fetch_blobs`, `fetch_blob_files`, and `blob_mode="bytes"` can't return those bytes. See the Lance [blob guide](https://lance.org/guide/blob/) for the storage format. ### Managed blobs (Blob v2) Set the table schema metadata `lance.blob.managed` to `true` on a table with [`lancedb.blob()`](#multimodal-blob-v2) columns to store small values inline and larger values in managed objects under the table's `_blobs/` directory. Medium values can share a packed object, and large values use a dedicated object. The table owns these objects. You do not upload them separately, keep an object catalog, or delete their files yourself. Compaction preserves each descriptor and its payload object, so merging table fragments does not rewrite the blob payloads. > [!WARNING] > > Use an SDK and Enterprise deployment that support Blob v2 Managed storage. > Upgrade every reader, writer, and maintenance worker before activating Managed > blobs on a table, and reopen existing table handles after the upgrade. Older > clients cannot safely maintain a table containing Managed blobs. #### Write and read blobs This example uses a local connection. The same schema, `add`, query, and `fetch_blobs` calls work with an Enterprise database connection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa db = lancedb.connect("./media") table = db.create_table( "images", schema=pa.schema([ pa.field("id", pa.int64(), nullable=False), lancedb.blob("image"), ], metadata={"lance.blob.managed": "true"}), ) table.add([ {"id": 1, "image": b""}, {"id": 2, "image": bytes(range(256)) * 400}, {"id": 3, "image": None}, ]) # Query descriptors first, then fetch only the selected rows' payloads. hits = ( table.search() .where("id <= 2") .select(["id", "image"]) .with_row_id(True) .to_arrow() ) images = table.fetch_blobs("image", hits).to_pylist() by_id = dict(zip(hits["id"].to_pylist(), images, strict=True)) assert by_id[1] == b"" assert len(by_id[2]) == 102400 ``` `fetch_blobs` materializes the selected payloads in memory, so fetch bounded batches when blobs are large. Row IDs belong to their table and snapshot. Keep descriptors opaque in application code, because their representation can differ between inline values and Managed objects. #### Derived blobs and maintenance Enterprise Functions can consume blob columns and return new blobs. Their output payloads are managed by the destination table. With published Embedded packages, derive blob values in your application and write them to the table. SQL computed-column declaration and refresh require an experimental source build. Deleting a row or replacing its blob does not immediately remove the old payload: retained table versions may still reference it. [Garbage Collection](/oss/v0-41-0/maintenance/cleanup#managed-blobs) reclaims objects after those references expire. A packed object remains while any of its contained blobs is still referenced. ### Legacy large-binary blobs Use [`lancedb.blob()`](#multimodal-blob-v2) for new tables. The sections below cover existing tables that use the V1 large-binary Blob API (`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and `DataType::LargeBinary` in Rust with `{"lance-encoding:blob": "true"}` field metadata). Changing a field's metadata alone does not migrate an existing V1 column to Blob v2. #### 1. Define a blob schema V1 blob columns use a `large_binary` field marked with `{"lance-encoding:blob": "true"}` metadata: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa # Define schema with Blob API metadata for lazy loading schema = pa.schema( [ pa.field("id", pa.int64()), pa.field( "video", pa.large_binary(), metadata={"lance-encoding:blob": "true"}, # Enable Blob API ), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const legacyBlobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "video", new arrow.LargeBinary(), true, new Map([["lance-encoding:blob", "true"]]), ), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let legacy_blob_metadata = HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]); let legacy_blob_schema = Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("video", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata), ]); ``` #### 2. Ingest large blobs Write raw bytes to a V1 blob column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./blob_db") # Create sample data data = [ {"id": 1, "video": b"fake_video_bytes_1"}, {"id": 2, "video": b"fake_video_bytes_2"}, ] # Create the table tbl = db.create_table("videos", data=data, schema=schema) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const legacyBlobData = lancedb.makeArrowTable( [ { id: 1, video: Buffer.from("fake_video_bytes_1") }, { id: 2, video: Buffer.from("fake_video_bytes_2") }, ], { schema: legacyBlobSchema }, ); const legacyBlobTable = await db.createTable( "legacy_videos", legacyBlobData, { mode: "overwrite", }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let legacy_blob_rows = vec![ (1_i64, b"fake_video_bytes_1".to_vec()), (2_i64, b"fake_video_bytes_2".to_vec()), ]; let legacy_blob_schema = Arc::new(legacy_blob_schema); let legacy_blob_batch = RecordBatch::try_new( legacy_blob_schema.clone(), vec![ Arc::new(Int64Array::from_iter_values( legacy_blob_rows.iter().map(|row| row.0), )), Arc::new(LargeBinaryArray::from_iter_values( legacy_blob_rows.iter().map(|row| row.1.as_slice()), )), ], ) .unwrap(); let legacy_blob_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema), ); let legacy_blob_table = db .create_table("legacy_videos", legacy_blob_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### 3. Convert blob tables to pandas On LanceDB Embedded tables with V1 blob columns, `to_pandas()` in Python accepts `blob_mode` (`"lazy"`, `"bytes"`, or `"descriptions"`). Enterprise tables raise `NotImplementedError`, and `"bytes"` is not supported on in-memory tables. Extra keyword arguments such as `split_blocks` or `self_destruct` are forwarded to the PyArrow / Lance pandas conversion: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Default: blob columns come back lazily df_lazy = tbl.to_pandas() # Materialize blob bytes eagerly df_bytes = tbl.to_pandas(blob_mode="bytes") # Return descriptors instead of payloads df_desc = tbl.to_pandas(blob_mode="descriptions") # Forward extra kwargs to PyArrow's to_pandas df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) ``` On query builders with V1 blob columns, plain scans support `"lazy"`, `"bytes"`, and `"descriptions"`. Vector, FTS, hybrid, and ordered queries cannot materialize V1 blob columns through `to_pandas()`, so omit those columns from the projection: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Plain scan query: blob_mode is supported end to end df_lazy = ( tbl.search() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="lazy") ) # Same call shape works on async query builders df_bytes = await ( tbl_async.query() .where("id = 1") .select(["id", "video"]) .to_pandas(blob_mode="bytes") ) # Vector / FTS / hybrid queries can't materialize blob columns, # so omit them from the projection df_vec = ( tbl.search(query_vector) .limit(10) .select(["id", "vector"]) .to_pandas(split_blocks=True, self_destruct=True) ) ``` ### Store binary data Use a `binary` column when the query should return the raw bytes. Declare it as `pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust. #### 1. Setup and imports Import LanceDB and Arrow in your SDK. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io import lancedb import numpy as np import pyarrow as pa from PIL import Image ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as arrow from "apache-arrow"; import { Buffer } from "node:buffer"; import * as lancedb from "@lancedb/lancedb"; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::collections::HashMap; use std::sync::Arc; use arrow_array::types::Float32Type; use arrow_array::{ Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, }; use arrow_schema::{DataType, Field, Schema}; use futures_util::TryStreamExt; use lancedb::connect; use lancedb::database::CreateTableMode; use lancedb::query::{ExecutableQuery, QueryBase}; ``` #### 2. Prepare data Encode each image or file into raw bytes before writing. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def create_dummy_image(color): img = Image.new("RGB", (100, 100), color=color) buf = io.BytesIO() img.save(buf, format="PNG") return buf.getvalue() data = [ { "id": 1, "filename": "red_square.png", "vector": np.random.rand(128).astype(np.float32), "image_blob": create_dummy_image("red"), "label": "red", }, { "id": 2, "filename": "blue_square.png", "vector": np.random.rand(128).astype(np.float32), "image_blob": create_dummy_image("blue"), "label": "blue", }, ] ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const createDummyImage = (color: string): Uint8Array => { const pngHeader = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]); return Buffer.concat([Buffer.from(pngHeader), Buffer.from(color, "utf8")]); }; const data = [ { id: 1, filename: "red_square.png", vector: Array.from({ length: 128 }, (_, i) => (i % 16) / 16), image_blob: createDummyImage("red"), label: "red", }, { id: 2, filename: "blue_square.png", vector: Array.from({ length: 128 }, (_, i) => ((i + 8) % 16) / 16), image_blob: createDummyImage("blue"), label: "blue", }, ]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let create_dummy_image = |color: u8| -> Vec<u8> { let mut png_like = vec![137, 80, 78, 71, 13, 10, 26, 10]; png_like.push(color); png_like }; let data = vec![ ( 1_i32, "red_square.png", vec![0.1_f32; 128], create_dummy_image(1), "red", ), ( 2_i32, "blue_square.png", vec![0.2_f32; 128], create_dummy_image(2), "blue", ), ]; ``` #### 3. Define the schema Declare the schema explicitly so Arrow and LanceDB store the field as `binary` instead of inferring a string or integer list. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} schema = pa.schema( [ pa.field("id", pa.int32()), pa.field("filename", pa.string()), pa.field("vector", pa.list_(pa.float32(), 128)), pa.field("image_blob", pa.binary()), pa.field("label", pa.string()), ] ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schema = new arrow.Schema([ new arrow.Field("id", new arrow.Int32()), new arrow.Field("filename", new arrow.Utf8()), new arrow.Field( "vector", new arrow.FixedSizeList( 128, new arrow.Field("item", new arrow.Float32(), true), ), ), new arrow.Field("image_blob", new arrow.Binary()), new arrow.Field("label", new arrow.Utf8()), ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema = Schema::new(vec![ Field::new("id", DataType::Int32, false), Field::new("filename", DataType::Utf8, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), Field::new("image_blob", DataType::Binary, false), Field::new("label", DataType::Utf8, false), ]); ``` #### 4. Ingest data Create the table from the rows and schema. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = db.create_table("images", data=data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const multimodalData = lancedb.makeArrowTable(data, { schema }); const tbl = await db.createTable("images", multimodalData, { mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema = Arc::new(schema); let image_batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))), Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( data.iter() .map(|row| Some(row.2.iter().copied().map(Some).collect::<Vec<_>>())), 128, ), ), Arc::new(BinaryArray::from_iter_values( data.iter().map(|row| row.3.as_slice()), )), Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))), ], ) .unwrap(); let image_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new( RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()), ); let table = db .create_table("images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` ### Retrieve binary data When you search the table, select the `binary` column alongside your metadata columns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_vector = np.random.rand(128).astype(np.float32) results = tbl.search(query_vector).limit(1).to_pandas() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const queryVector = Array.from({ length: 128 }, (_, i) => (i % 16) / 16); const results = await tbl.search(queryVector).limit(1).toArray(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let query_vector = vec![0.1_f32; 128]; let results = table .query() .nearest_to(query_vector) .unwrap() .limit(1) .execute() .await .unwrap() .try_collect::<Vec<_>>() .await .unwrap(); ``` #### Convert bytes back to objects Decode the returned bytes into an image or media buffer in your application. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for _, row in results.iterrows(): image_bytes = row["image_blob"] image = Image.open(io.BytesIO(image_bytes)) print(f"Retrieved image: {row['filename']}, Size: {image.size}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for (const row of results) { const imageBytes = row.image_blob as Uint8Array; console.log( `Retrieved image: ${row.filename}, Byte length: ${imageBytes.length}`, ); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for batch in &results { let filenames = batch .column_by_name("filename") .unwrap() .as_any() .downcast_ref::<StringArray>() .unwrap(); let images = batch .column_by_name("image_blob") .unwrap() .as_any() .downcast_ref::<BinaryArray>() .unwrap(); for row in 0..batch.num_rows() { let image_bytes = images.value(row); println!( "Retrieved image: {}, Byte length: {}", filenames.value(row), image_bytes.len() ); } } ``` ### Other modalities For PDFs, audio recordings, and other files, keep searchable fields in separate columns so you can filter rows before fetching blob bytes. ### bfloat16 Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. ## Schema evolution Schema evolution enables non-breaking modifications to a database table's structure (such as adding columns, altering data types, or dropping fields) to adapt to evolving data requirements without service interruptions. LanceDB supports ACID-compliant schema evolution through granular operations (add/alter/drop columns), allowing you to: * Iterate Safely: Modify schemas in production with versioned datasets and backward compatibility * Scale Seamlessly: Handle ML model iterations, regulatory changes, or feature additions * Optimize Continuously: Remove unused fields or enforce new constraints without downtime > [!NOTE] > > In SQL, schema changes are [`ALTER TABLE`](/oss/v0-41-0/sql/ddl/table#alter). ### Schema evolution operations LanceDB supports four primary schema evolution operations: 1. **Adding new columns**: Extend your table with additional attributes 2. **Altering existing columns**: Change column names, data types, or nullability 3. **Updating field metadata**: Attach or change per-column Arrow metadata 4. **Dropping columns**: Remove unnecessary columns from your schema > [!TIP] > > Schema evolution operations are applied immediately but do not typically require rewriting all data. However, data type changes may involve more substantial operations. Each schema evolution operation commits a new table version and returns status metadata such as the committed `version`. Run these operations from a mutable table handle; if you checked out an older version for reads, call `checkout_latest` / `checkoutLatest` before modifying the schema. ### Add new columns You can add new columns to a table with the [`add_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.add_columns) method in Python, [`addColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#addcolumns) in TypeScript/JavaScript, or `add_columns` in Rust. New columns are populated based on SQL expressions you provide. On local tables, the Python SDK also accepts precomputed values from DataFrames and Arrow readers; see [Create a computed column](/oss/v0-41-0/feature-engineering/add-computed-column#computed-vs-transforms) for the supported inputs and row-order requirements. #### Set up the example table First, let's create a sample table with product data to demonstrate schema evolution: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_add_example", data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaAddData = [ { id: 1, name: "Laptop", price: 1200.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 3, name: "Headphones", price: 150.0, vector: Array.from({ length: 128 }, () => Math.random()), }, ]; const schemaAddTable = await db.createTable( "schema_evolution_add_example", schemaAddData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_add_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Float64, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_add_batch = RecordBatch::try_new( schema_add_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone", "Headphones"])), Arc::new(Float64Array::from(vec![1200.0, 800.0, 150.0])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128]), Some(vec![Some(0.3_f32); 128]), ], 128, ), ), ], ) .unwrap(); let schema_add_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_add_batch)].into_iter(), schema_add_schema.clone(), )); let schema_add_table = db .create_table("schema_evolution_add_example", schema_add_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` > [!NOTE] > > Columns derived from existing data (SQL expressions over other columns) are > covered in [Create a computed column](/oss/v0-41-0/feature-engineering/add-computed-column), > because deriving values is a feature-engineering job rather than a schema one. #### Add columns with default values Add boolean columns with default values for status tracking: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a stock status column with default value table.add_columns({"in_stock": "cast(true as boolean)"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a stock status column with default value await schemaAddTable.addColumns([ { name: "in_stock", valueSql: "cast(true as boolean)", }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a stock status column with default value schema_add_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "in_stock".to_string(), "cast(true as boolean)".to_string(), )]), None, ) .await .unwrap(); ``` #### Add nullable columns Add timestamp columns that can contain NULL values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Add a nullable timestamp column table.add_columns({"last_ordered": "cast(NULL as timestamp)"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a nullable timestamp column await schemaAddTable.addColumns([ { name: "last_ordered", valueSql: "cast(NULL as timestamp)", }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Add a nullable timestamp column schema_add_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "last_ordered".to_string(), "cast(NULL as timestamp)".to_string(), )]), None, ) .await .unwrap(); ``` > [!WARNING] > > When adding columns that should contain NULL values, be sure to cast the NULL to the appropriate type, e.g., `cast(NULL as timestamp)`. ### Alter existing columns You can alter columns using the [`alter_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.alter_columns) method in Python, [`alterColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#altercolumns) in TypeScript/JavaScript, or `alter_columns` in Rust. This allows you to: * Rename a column * Change a column's data type * Modify nullability (whether a column can contain NULL values) #### Set up the example table Create a table with a custom schema to demonstrate column alterations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "schema_evolution_alter_example" if data is None: data = [ { "id": 1, "name": "Laptop", "price": 1200, "discount_price": 1080.0, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800, "discount_price": 720.0, "vector": np.random.random(128).tolist(), }, ] schema = pa.schema( { "id": pa.int64(), "name": pa.string(), "price": pa.int32(), "discount_price": pa.float64(), "vector": pa.list_(pa.float32(), 128), } ) table = db.create_table(table_name, data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaAlter = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field("name", new arrow.Utf8()), new arrow.Field("price", new arrow.Int32()), new arrow.Field("discount_price", new arrow.Float64()), new arrow.Field( "vector", new arrow.FixedSizeList( 128, new arrow.Field("item", new arrow.Float32(), true), ), ), ]); const schemaAlterData = lancedb.makeArrowTable( [ { id: 1, name: "Laptop", price: 1200, discount_price: 1080.0, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800, discount_price: 720.0, vector: Array.from({ length: 128 }, () => Math.random()), }, ], { schema: schemaAlter }, ); const schemaAlterTable = await db.createTable( "schema_evolution_alter_example", schemaAlterData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_alter_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Int32, false), Field::new("discount_price", DataType::Float64, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_alter_batch = RecordBatch::try_new( schema_alter_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone"])), Arc::new(Int32Array::from(vec![1200, 800])), Arc::new(Float64Array::from(vec![1080.0, 720.0])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128])], 128, ), ), ], ) .unwrap(); let schema_alter_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_alter_batch)].into_iter(), schema_alter_schema.clone(), )); let schema_alter_table = db .create_table("schema_evolution_alter_example", schema_alter_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### Rename columns Change column names to better reflect their purpose: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Rename discount_price to sale_price table.alter_columns({"path": "discount_price", "rename": "sale_price"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename discount_price to sale_price await schemaAlterTable.alterColumns([ { path: "discount_price", rename: "sale_price" }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename discount_price to sale_price schema_alter_table .alter_columns(&[ColumnAlteration::new("discount_price".to_string()) .rename("sale_price".to_string())]) .await .unwrap(); ``` #### Change data types Convert column data types for better performance or compatibility: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Change price from int32 to int64 for larger numbers table.alter_columns({"path": "price", "data_type": pa.int64()}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Change price from int32 to int64 for larger numbers await schemaAlterTable.alterColumns([ { path: "price", dataType: new arrow.Int64() }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Change price from int32 to int64 for larger numbers schema_alter_table .alter_columns(&[ColumnAlteration::new("price".to_string()).cast_to(DataType::Int64)]) .await .unwrap(); ``` #### Make columns nullable You can alter columns to contain NULL values: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Make the name column nullable table.alter_columns({"path": "name", "nullable": True}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Make the name column nullable await schemaAlterTable.alterColumns([{ path: "name", nullable: true }]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Make the name column nullable schema_alter_table .alter_columns(&[ColumnAlteration::new("name".to_string()).set_nullable(true)]) .await .unwrap(); ``` Changing a column to nullable affects future writes and merges too: missing values are accepted only when the target column is nullable. #### Multiple changes at once Apply several alterations in a single operation: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Rename, change type, and make nullable in one operation table.alter_columns( { "path": "sale_price", "rename": "final_price", "data_type": pa.float64(), "nullable": True, } ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename, change type, and make nullable in one operation await schemaAlterTable.alterColumns([ { path: "sale_price", rename: "final_price", dataType: new arrow.Float64(), nullable: true, }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Rename, change type, and make nullable in one operation schema_alter_table .alter_columns(&[ColumnAlteration::new("sale_price".to_string()) .rename("final_price".to_string()) .cast_to(DataType::Float64) .set_nullable(true)]) .await .unwrap(); ``` #### Expression-based type changes For transformations that are not simple casts (for example, converting `"$100"` to an integer), use a SQL-expression column add, then drop and rename: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # For custom transforms, create a new column from a SQL expression. expression_table = db.create_table( "schema_evolution_expression_example", [{"id": 1, "price_text": "$100"}], mode="overwrite", ) expression_table.add_columns( {"price_numeric": "cast(replace(price_text, '$', '') as int)"} ) expression_table.drop_columns(["price_text"]) expression_table.alter_columns({"path": "price_numeric", "rename": "price"}) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // For custom transforms, create a new column from a SQL expression. const expressionTable = await db.createTable( "schema_evolution_expression_example", [{ id: 1, price_text: "$100" }], { mode: "overwrite" }, ); await expressionTable.addColumns([ { name: "price_numeric", valueSql: "cast(replace(price_text, '$', '') as int)", }, ]); await expressionTable.dropColumns(["price_text"]); await expressionTable.alterColumns([ { path: "price_numeric", rename: "price" }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // For custom transforms, create a new column from a SQL expression. let expression_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("price_text", DataType::Utf8, false), ])); let expression_batch = RecordBatch::try_new( expression_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1])), Arc::new(StringArray::from(vec!["$100"])), ], ) .unwrap(); let expression_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(expression_batch)].into_iter(), expression_schema.clone(), )); let expression_table = db .create_table("schema_evolution_expression_example", expression_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); expression_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "price_numeric".to_string(), "cast(replace(price_text, '$', '') as int)".to_string(), )]), None, ) .await .unwrap(); expression_table.drop_columns(&["price_text"]).await.unwrap(); expression_table .alter_columns(&[ColumnAlteration::new("price_numeric".to_string()) .rename("price".to_string())]) .await .unwrap(); ``` #### Alter embedding types and dimensions It's quite common to need to change an embedding column's schema, in case a new model becomes available with a different embedding dimension. * In Python, the example shows an in-place type update when the cast is compatible. * In TypeScript and Rust, the example shows a dimension change (`384 -> 1024`), which cannot be cast in-place. For dimension changes, use this 3-step pattern: add a new column with the target type, drop the old column, then rename the new column to the original name. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} data = [ { "id": 1, "embedding": np.random.random(vector_dim).tolist(), }, ] table = db.create_table(table_name, data, mode="overwrite") table.alter_columns( dict(path="embedding", data_type=pa.list_(pa.float32(), vector_dim)) ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const oldDim = 384; const newDim = 1024; const vectorSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "embedding", new arrow.FixedSizeList( oldDim, new arrow.Field("item", new arrow.Float16(), true), ), true, ), ]); const vectorData = lancedb.makeArrowTable( [{ id: 1, embedding: Array.from({ length: oldDim }, () => Math.random()) }], { schema: vectorSchema }, ); const vectorTable = await db.createTable("vector_alter_example", vectorData, { mode: "overwrite", }); // Changing FixedSizeList dimensions (384 -> 1024) is not supported via alterColumns. // Use addColumns + dropColumns + alterColumns(rename) to replace the column. await vectorTable.addColumns([ { name: "embedding_v2", valueSql: `arrow_cast(NULL, 'FixedSizeList(${newDim}, Float16)')`, }, ]); await vectorTable.dropColumns(["embedding"]); await vectorTable.alterColumns([{ path: "embedding_v2", rename: "embedding" }]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let old_dim = 384; let new_dim = 1024; let vector_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new( "embedding", DataType::FixedSizeList( Arc::new(Field::new("item", DataType::Float32, true)), old_dim, ), true, ), ])); let vector_batch = RecordBatch::try_new( vector_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![Some(vec![Some(0.1_f32); old_dim as usize])], old_dim, ), ), ], ) .unwrap(); let vector_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(vec![Ok(vector_batch)].into_iter(), vector_schema.clone())); let vector_table = db .create_table("vector_alter_example", vector_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); // Changing FixedSizeList dimensions (384 -> 1024) is not supported via alter_columns. // Use add_columns + drop_columns + alter_columns(rename) to replace the column. vector_table .add_columns( NewColumnTransform::SqlExpressions(vec![( "embedding_v2".to_string(), format!("arrow_cast(NULL, 'FixedSizeList({}, Float32)')", new_dim), )]), None, ) .await .unwrap(); vector_table.drop_columns(&["embedding"]).await.unwrap(); vector_table .alter_columns(&[ColumnAlteration::new("embedding_v2".to_string()) .rename("embedding".to_string())]) .await .unwrap(); ``` > [!WARNING] > > **`FixedSizeList` Dimension Changes in TypeScript and Rust** > > `alterColumns` / `alter_columns` can cast between compatible types, but changing `FixedSizeList` dimensions (for example `384 -> 1024`) is not a compatible cast. > For such cases, use `addColumns` / `add_columns` (with `arrow_cast`), then `dropColumns` / `drop_columns`, then rename the replacement column. > [!WARNING] > > Changing data types requires rewriting the column data and may be resource-intensive for large tables. Renaming columns or changing nullability is more efficient as it only updates metadata. ### Update field metadata Each column in a LanceDB table can carry a small key/value map of Arrow field metadata, which is useful for annotating columns with units, provenance, PII flags, embedding model versions, or any other schema-level context your application needs. Use [`update_field_metadata`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.update_field_metadata) in Python, [`updateFieldMetadata`](https://lancedb.github.io/lancedb/js/classes/Table/#updatefieldmetadata) in TypeScript/JavaScript, or `update_field_metadata` in Rust to add, change, or remove these key/value pairs without rewriting the column data. Each call commits a new table version and returns the new `version`. Each update targets one field by **dot-path**: top-level columns are addressed by name (for example `"embedding"`), and nested fields by their full path (for example `"address.zip"`). By default, the keys you pass are **merged** into the field's existing metadata: keys you do not mention are preserved, and passing `None` (Python) or `null` (TypeScript) deletes a key. Set `replace: true` to swap the field's entire metadata map instead of merging. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Set two metadata keys on the `category` field. res = table.update_field_metadata( {"path": "category", "metadata": {"unit": "label", "pii": "false"}} ) print(res.version) # Merge: add a new key, delete one with None, keep the rest. table.update_field_metadata( {"path": "category", "metadata": {"source": "import", "pii": None}} ) # Arrow stores field metadata as bytes. assert table.schema.field("category").metadata == { b"unit": b"label", b"source": b"import", } ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Set two metadata keys on the `category` field. const res = await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { unit: "label", pii: "false" } }, ]); console.log(res.version); // Merge: add a new key, delete one via null, keep the rest. await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { source: "import", pii: null } }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Set two metadata keys on the `category` field. let res = field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("unit", "label") .set("pii", "false")]) .await .unwrap(); println!("version: {}", res.version); // Merge: add a new key, delete one with `.remove`, keep the rest. field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("source", "import") .remove("pii")]) .await .unwrap(); ``` To overwrite a field's metadata entirely instead of merging, set `replace` to `true`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.update_field_metadata( { "path": "category", "metadata": {"owner": "search-team"}, "replace": True, } ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await fieldMetadataTable.updateFieldMetadata([ { path: "category", metadata: { owner: "search-team" }, replace: true, }, ]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} field_metadata_table .update_field_metadata(&[FieldMetadataUpdate::new("category") .set("owner", "search-team") .replace()]) .await .unwrap(); ``` > [!TIP] > > You can pass multiple updates in a single call to change metadata on several fields at once. > Each call commits a single new table version. #### Canonical metadata keys You can use any string as a metadata key. By convention, LanceDB treats keys prefixed with `lancedb:` as canonical. LanceDB Enterprise displays these keys in the UI, and agents can rely on finding this information in a consistent place. Use them when they fit your use case: | Key | Purpose | Example | | - | - | - | | `lancedb:description` | Human-readable description of the field. | `"CLIP embedding of the product image"` | | `lancedb:tag:<name>` | User-defined key/value tag, where the suffix names the tag category. | `"lancedb:tag:model": "clip"` | | `lancedb:status` | Life cycle state of the column: `production`, `candidate`, `deprecated`, or `archived`. | `"lancedb:status": "production"` | > [!NOTE] > > These keys are conventions, not enforced constraints. LanceDB does not validate their values, > but following the conventions keeps your tables consistent with Enterprise tooling. ### Drop columns You can remove columns using the [`drop_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.drop_columns) method in Python, [`dropColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#dropcolumns) in TypeScript/JavaScript, or `drop_columns` in Rust. #### Set Up the example table Create a table with temporary columns that we'll remove: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} if data is None: data = [ { "id": 1, "name": "Laptop", "price": 1200.00, "temp_col1": "X", "temp_col2": 100, "vector": np.random.random(128).tolist(), }, { "id": 2, "name": "Smartphone", "price": 800.00, "temp_col1": "Y", "temp_col2": 200, "vector": np.random.random(128).tolist(), }, { "id": 3, "name": "Headphones", "price": 150.00, "temp_col1": "Z", "temp_col2": 300, "vector": np.random.random(128).tolist(), }, ] table = db.create_table("schema_evolution_drop_example", data, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const schemaDropData = [ { id: 1, name: "Laptop", price: 1200.0, temp_col1: "X", temp_col2: 100, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 2, name: "Smartphone", price: 800.0, temp_col1: "Y", temp_col2: 200, vector: Array.from({ length: 128 }, () => Math.random()), }, { id: 3, name: "Headphones", price: 150.0, temp_col1: "Z", temp_col2: 300, vector: Array.from({ length: 128 }, () => Math.random()), }, ]; const schemaDropTable = await db.createTable( "schema_evolution_drop_example", schemaDropData, { mode: "overwrite" }, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let schema_drop_schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false), Field::new("price", DataType::Float64, false), Field::new("temp_col1", DataType::Utf8, false), Field::new("temp_col2", DataType::Int32, false), Field::new( "vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 128), false, ), ])); let schema_drop_batch = RecordBatch::try_new( schema_drop_schema.clone(), vec![ Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(StringArray::from(vec!["Laptop", "Smartphone", "Headphones"])), Arc::new(Float64Array::from(vec![1200.0, 800.0, 150.0])), Arc::new(StringArray::from(vec!["X", "Y", "Z"])), Arc::new(Int32Array::from(vec![100, 200, 300])), Arc::new( FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( vec![ Some(vec![Some(0.1_f32); 128]), Some(vec![Some(0.2_f32); 128]), Some(vec![Some(0.3_f32); 128]), ], 128, ), ), ], ) .unwrap(); let schema_drop_reader: Box<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new( vec![Ok(schema_drop_batch)].into_iter(), schema_drop_schema.clone(), )); let schema_drop_table = db .create_table("schema_evolution_drop_example", schema_drop_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` #### Drop single columns Remove individual columns that are no longer needed: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remove the first temporary column table.drop_columns(["temp_col1"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the first temporary column await schemaDropTable.dropColumns(["temp_col1"]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the first temporary column schema_drop_table.drop_columns(&["temp_col1"]).await.unwrap(); ``` #### Drop multiple columns Remove several columns at once for efficiency: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Remove the second temporary column table.drop_columns(["temp_col2"]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the second temporary column await schemaDropTable.dropColumns(["temp_col2"]); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Remove the second temporary column schema_drop_table.drop_columns(&["temp_col2"]).await.unwrap(); ``` > [!WARNING] > > Dropping a column changes the latest version only. Until > [cleanup](/oss/v0-41-0/maintenance/cleanup) prunes the versions from before the drop, > [restoring](#versioning) one of them brings the column and its values back, > along with the rest of the table as it was then. Once those versions are > pruned, the drop cannot be undone, so check before dropping a column you may > need. ## Versioning This page shows the core table-versioning APIs used in the code snippets for Python, TypeScript, and Rust. Each operation below maps directly to methods shown in the examples. ### Basic Versioning Example Let's create a table with sample data to demonstrate LanceDB's versioning capabilities: #### Set Up the Table First, let's create a table with some sample data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table_name = "quotes_versioning_example" data = [ {"id": 1, "author": "Richard", "quote": "Wubba Lubba Dub Dub!"}, {"id": 2, "author": "Morty", "quote": "Rick, what's going on?"}, { "id": 3, "author": "Richard", "quote": "I turned myself into a pickle, Morty!", }, ] # Define schema schema = pa.schema( [ pa.field("id", pa.int64()), pa.field("author", pa.string()), pa.field("quote", pa.string()), ] ) table = db.create_table(table_name, data, schema=schema, mode="overwrite") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tableName = "quotes_versioning_example"; const data = [ { id: 1, author: "Richard", quote: "Wubba Lubba Dub Dub!" }, { id: 2, author: "Morty", quote: "Rick, what's going on?" }, { id: 3, author: "Richard", quote: "I turned myself into a pickle, Morty!", }, ]; const table = await db.createTable(tableName, data, { mode: "overwrite" }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let table_name = "quotes_versioning_example"; let data = vec![ (1, "Richard", "Wubba Lubba Dub Dub!"), (2, "Morty", "Rick, what's going on?"), (3, "Richard", "I turned myself into a pickle, Morty!"), ]; let table = db .create_table(table_name, make_quotes_reader(data)) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); ``` **Rust helper used in this page** ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fn make_quotes_reader(rows: Vec<(i64, &str, &str)>) -> Box<dyn RecordBatchReader + Send> { let ids: Vec<i64> = rows.iter().map(|(id, _, _)| *id).collect(); let authors: Vec<&str> = rows.iter().map(|(_, author, _)| *author).collect(); let quotes: Vec<&str> = rows.iter().map(|(_, _, quote)| *quote).collect(); let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), Field::new("author", DataType::Utf8, false), Field::new("quote", DataType::Utf8, false), ])); let batch = RecordBatch::try_new( schema.clone(), vec![ Arc::new(Int64Array::from(ids)), Arc::new(StringArray::from(authors)), Arc::new(StringArray::from(quotes)), ], ) .unwrap(); let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema); Box::new(reader) } ``` #### Check Initial Version After creating the table, let's check the initial version information: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() current_version = table.version print(f"Number of versions after creation: {len(versions)}") print(f"Current version: {current_version}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const versions = await table.listVersions(); const currentVersion = await table.version(); console.log(`Number of versions after creation: ${versions.length}`); console.log(`Current version: ${currentVersion}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let versions = table.list_versions().await.unwrap(); let current_version = table.version().await.unwrap(); println!("Number of versions after creation: {}", versions.len()); println!("Current version: {}", current_version); ``` ### Modify Data When you modify data through operations like update or delete, LanceDB automatically creates new versions. #### Update Existing Data Let's update some existing records to see versioning in action: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.update(where="author='Richard'", values={"author": "Richard Daniel Sanchez"}) rows_after_update = table.count_rows("author = 'Richard Daniel Sanchez'") print(f"Rows updated to Richard Daniel Sanchez: {rows_after_update}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.update({ where: "author = 'Richard'", values: { author: "Richard Daniel Sanchez" }, }); const rowsAfterUpdate = await table.countRows( "author = 'Richard Daniel Sanchez'", ); console.log(`Rows updated to Richard Daniel Sanchez: ${rowsAfterUpdate}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table .update() .only_if("author = 'Richard'") .column("author", "'Richard Daniel Sanchez'") .execute() .await .unwrap(); let rows_after_update = table .count_rows(Some("author = 'Richard Daniel Sanchez'".to_string())) .await .unwrap(); println!( "Rows updated to Richard Daniel Sanchez: {}", rows_after_update ); ``` #### Add New Data Now let's add more records to the table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} more_data = [ { "id": 4, "author": "Richard Daniel Sanchez", "quote": "That's the way the news goes!", }, {"id": 5, "author": "Morty", "quote": "Aww geez, Rick!"}, ] table.add(more_data) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const moreData = [ { id: 4, author: "Richard Daniel Sanchez", quote: "That's the way the news goes!", }, { id: 5, author: "Morty", quote: "Aww geez, Rick!" }, ]; await table.add(moreData); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let more_data = vec![ (4, "Richard Daniel Sanchez", "That's the way the news goes!"), (5, "Morty", "Aww geez, Rick!"), ]; table .add(make_quotes_reader(more_data)) .execute() .await .unwrap(); ``` #### Check Version Changes Let's see how the versions have changed after our modifications: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() version_count_after_mod = len(versions) version_after_mod = table.version print(f"Number of versions after modifications: {version_count_after_mod}") print(f"Current version: {version_after_mod}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const versionsAfterMod = await table.listVersions(); const versionCountAfterMod = versionsAfterMod.length; const versionAfterMod = await table.version(); console.log( `Number of versions after modifications: ${versionCountAfterMod}`, ); console.log(`Current version: ${versionAfterMod}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let versions_after_mod = table.list_versions().await.unwrap(); let version_count_after_mod = versions_after_mod.len(); let version_after_mod = table.version().await.unwrap(); println!( "Number of versions after modifications: {}", version_count_after_mod ); println!("Current version: {}", version_after_mod); ``` ### Rollback to Previous Versions LanceDB supports fast rollbacks to any previous version without data duplication. #### View All Versions First, let's see all the versions we've created: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} versions = table.list_versions() for v in versions: print(f"Version {v['version']}, created at {v['timestamp']}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const allVersions = await table.listVersions(); for (const v of allVersions) { console.log(`Version ${v.version}, created at ${v.timestamp}`); } ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let all_versions = table.list_versions().await.unwrap(); for v in &all_versions { println!("Version {}, created at {}", v.version, v.timestamp); } ``` #### Restore a Version Snapshot Now let's restore a captured version snapshot: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.restore(version_after_mod) versions = table.list_versions() version_count_after_rollback = len(versions) print(f"Total number of versions after rollback: {version_count_after_rollback}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.checkout(versionAfterMod); await table.restore(); const versionsAfterRollback = await table.listVersions(); const versionCountAfterRollback = versionsAfterRollback.length; console.log( `Total number of versions after rollback: ${versionCountAfterRollback}`, ); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout(version_after_mod).await.unwrap(); table.restore().await.unwrap(); let versions_after_rollback = table.list_versions().await.unwrap(); let version_count_after_rollback = versions_after_rollback.len(); println!( "Total number of versions after rollback: {}", version_count_after_rollback ); ``` ### Tag-Based Versioning Numeric table versions like `v3` or `v17` are precise but hard to remember. Tags let you attach human-readable labels (e.g., `"prod"`, `"baseline"`, `"q3-evaluation"`) to specific versions and check those out by name. They are conceptually similar to git tags, and unlike numeric versions, **tagged versions are never pruned**. A tagged version that is older than the retention window and is not the latest stops cleanup instead (see the cleanup note at the bottom of this page). The tags API supports the standard CRUD operations (create, list, update, delete), plus checking out by tag name. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Create a tag pointing at a specific version table.tags.create("baseline", 1) table.tags.create("with-edits", table.version) # List all tags on this table print(table.tags.list()) # Look up the version a tag points at print(table.tags.get_version("baseline")) # Move an existing tag to a different version table.tags.update("baseline", 2) # Check out a version by tag name table.checkout("baseline") print(table.version) # Delete a tag (does not delete the underlying version) table.tags.delete("with-edits") # Return to the latest version table.checkout_latest() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const tags = await tagsTable.tags(); // Create a tag pointing at a specific version await tags.create("baseline", 1); await tags.create("with-edits", await tagsTable.version()); // List all tags on this table console.log(await tags.list()); // Look up the version a tag points at console.log(await tags.getVersion("baseline")); // Move an existing tag to a different version await tags.update("baseline", 2); // Check out a version by tag name await tagsTable.checkout("baseline"); console.log(await tagsTable.version()); // Delete a tag (does not delete the underlying version) await tags.delete("with-edits"); // Return to the latest version await tagsTable.checkoutLatest(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} let mut tags = tags_table.tags().await.unwrap(); // Create a tag pointing at a specific version tags.create("baseline", 1).await.unwrap(); let current_version = tags_table.version().await.unwrap(); tags.create("with-edits", current_version).await.unwrap(); // List all tags on this table let all_tags = tags.list().await.unwrap(); println!("Tags: {:?}", all_tags); // Look up the version a tag points at let baseline_version = tags.get_version("baseline").await.unwrap(); println!("baseline -> v{}", baseline_version); // Move an existing tag to a different version tags.update("baseline", 2).await.unwrap(); // Check out a version by tag name (separate method in Rust) tags_table.checkout_tag("baseline").await.unwrap(); println!("Current version: {}", tags_table.version().await.unwrap()); // Delete a tag (does not delete the underlying version) tags.delete("with-edits").await.unwrap(); // Return to the latest version tags_table.checkout_latest().await.unwrap(); ``` > [!NOTE] > > Deleting a tag only removes the label, not the version it points to. After > deletion, the underlying table version becomes eligible for cleanup again. ### Delete Data From the Table Let's demonstrate how deletions also create new versions: #### Go Back to Latest Version First, let's return to the latest version: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout_latest() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.checkoutLatest(); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.checkout_latest().await.unwrap(); ``` #### Delete Data Now let's delete some data to see how it affects versioning: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.delete("author = 'Morty'") rows_after_deletion = table.count_rows() print(f"Number of rows after deletion: {rows_after_deletion}") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await table.delete("author = 'Morty'"); const rowsAfterDeletion = await table.countRows(); console.log(`Number of rows after deletion: ${rowsAfterDeletion}`); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.delete("author = 'Morty'").await.unwrap(); let rows_after_deletion = table.count_rows(None).await.unwrap(); println!("Number of rows after deletion: {}", rows_after_deletion); ``` #### Version History and Operations On a fresh table, the snippets in this guide produce this version sequence: 1. `v1`: create table (`create_table` / `createTable` / `create_table`) 2. `v2`: update rows (`update`) 3. `v3`: add rows (`add`) 4. `v4`: restore snapshot (`restore`) from `version_after_mod`/`versionAfterMod` 5. `v5`: delete rows (`delete`) Read-only and checkout operations shown here (`list_versions`/`listVersions`, `version`, `checkout`, `checkout_latest`/`checkoutLatest`) do not create new versions. The version metadata fields can differ by backend. Direct table-backed version listing exposes a timestamp, while namespace-backed listing may expose fields such as `manifest_path`, `manifest_size`, `e_tag`, and `timestamp_millis`. In deployments that use managed versioning, prefer the table version APIs exposed by LanceDB Enterprise or the namespace service instead of mixing in lower-level Lance file operations. > [!NOTE] > > **System Operations** > > System operations like `optimize()`, index updates, and table compaction also increment table version numbers. > In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), > which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background > when its configuration enables [cleanup](/oss/v0-41-0/maintenance/cleanup); `optimize()` is not available there. > > **Tagged versions are never pruned.** A version with a tag pointing at it is > retained regardless of age. When a tagged version is older than the retention window and > is not the latest, cleanup refuses to run instead of pruning around it: `optimize()` raises > an error naming the tag and prunes nothing. A tag on the latest version does not cause > this, but `optimize()` compacts before it prunes, and compacting commits a new version > whenever it merges files, so a tag on what was the latest version can become an older > one by the time cleanup runs; the error then comes after compacting, and the index > update does not run. To let cleanup proceed, [move the tag](#versioning-tag-based-versioning) > to a version inside the retention window, delete it, or widen the window. ## Privileges A table's `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl ``` See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # Views Source: https://docs.lancedb.com/oss/v0-41-0/management/view A saved query, evaluated when read. **Applies to:** Embedded ❌, Enterprise ✅ A view saves a query that you can refer to by name. Reading the view executes that query against the source tables, using their read-consistency behavior. Views do not store a separate copy of the result. It is the counterpart to a [materialized view](/oss/v0-41-0/management/materialized-view), which stores rows and is brought up to date by a refresh. Both are [catalog objects](/oss/v0-41-0/basics/catalog) defined by a query; choose a materialized view when you need to store and reuse the result. | | View | Materialized view | | - | - | - | | Stores | the query | the rows | | Freshness | follows source-table reads | as of the last refresh | | Read cost | executes the saved query | queries the stored result | | Write cost | none | a refresh | Views are created in LanceDB Enterprise, either in SQL over the [Flight SQL endpoint](/oss/v0-41-0/sql#connecting) or with the SDKs' `create_view` / `createView`, which send the query to the deployment. Either way, the deployment must have views enabled. See [View](/oss/v0-41-0/sql/ddl/view) for `CREATE VIEW`, `DROP VIEW`, and listing. ## Privileges A view's `OWNERSHIP` and `SELECT` are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT SELECT ON VIEW dashboard TO ROLE analysts ``` See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax and every target it reaches. # SQL data types Source: https://docs.lancedb.com/oss/v0-41-0/sql/data-types How Lance columns appear to SQL, including the types SQL has no name for. **Applies to:** Embedded ❌, Enterprise ✅ There is no SQL type layer over Lance storage. The table provider hands DataFusion the dataset's Arrow schema directly, so a column is the same object to the query engine as it is to the format. The consequence is that SQL type names here are **spellings of Arrow types**, not a system that maps onto them. [Data types](/oss/v0-41-0/sql/data-types) documents the storage side; this page covers what changes when you reach a column from SQL. ## The Arrow types a column can be | Category | Types | | - | - | | Null | `null` | | Boolean | `bool` | | Integer | `int8`, `int16`, `int32`, `int64` and their `uint` counterparts | | Floating point | `float16`, `float32`, `float64` | | String | `utf8`, `large_utf8` | | Binary | `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp` (with or without timezone), `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | | Dictionary | `dictionary(key, value)` | Two limits are worth stating because they surface as schema errors rather than as documentation: * A `map` with `keys_sorted = true` is rejected. Sorted-key maps do not survive the round trip through the Python bindings, so they are refused rather than silently unsorted. * Not every type is legal as a `fixed_size_list` child. The vector case is, which is what matters in practice. ## SQL names for Arrow types | SQL | Arrow | | - | - | | `BOOLEAN` | `Boolean` | | `TINYINT` `SMALLINT` `INT` `BIGINT` | `Int8` `Int16` `Int32` `Int64` | | `UTINYINT` … `UBIGINT` | the unsigned counterparts | | `REAL` / `FLOAT` | `Float32` | | `DOUBLE` | `Float64` | | `VARCHAR` / `TEXT` / `STRING` | `Utf8` | | `BYTEA` / `BINARY` | `Binary` | | `DATE` | `Date32` | | `TIME` | `Time64` | | `TIMESTAMP` | `Timestamp`, with or without a timezone | | `INTERVAL` | `Interval` | | `STRUCT` / `LIST` / `MAP` | the nested equivalents | DataFusion's [type reference](https://datafusion.apache.org/user-guide/sql/data_types.html) describes the full mapping. ## Types SQL has no name for Some column kinds have no SQL type name. ### Vectors A dense vector column has a fixed dimension, commonly represented as `FixedSizeList<Float32, dim>`. Other supported vector element types are possible; inspect the column with [`arrow_typeof`](/oss/v0-41-0/sql/dql/scalar-functions#type) rather than assuming Float32. It is selectable and testable for nullness: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents WHERE vector IS NOT NULL ``` > [!WARNING] > > A list representation does not imply that ordinary arithmetic operators > perform vector arithmetic. Use supported distance functions for similarity > calculations. SQL vector search depends on the Enterprise server version and query > plan; see [SQL](/oss/v0-41-0/basics/sql#no-vector-sql). ### bfloat16 Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. ## Pseudo-columns Availability depends on the SQL table provider. The ordinary table provider exposes the stored dataset schema; naming a Lance scan metadata field does not make it available as a SQL column. The `fts()` provider adds `_score` to its schema, so `_score` is included in `SELECT * FROM fts(...)`. | Column | Type | | | - | - | - | | `_rowid` | `UInt64` | Lance scan row identifier; stability requires stable row ids | | `_rowaddr` | `UInt64` | physical row address | | `_rowoffset` | `UInt64` | offset within the fragment | | `_score` | `Float32` | relevance, from [`fts()`](/oss/v0-41-0/sql/dql/fts) | `_rowid`, `_rowaddr`, and `_rowoffset` describe Lance scan metadata, not columns automatically registered on an ordinary SQL table. Select `_score` from an `fts()` relation explicitly when you want a projection containing it. ## Casting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT CAST(identifier AS VARCHAR) FROM documents SELECT TRY_CAST(maybe_number AS BIGINT) FROM raw ``` `TRY_CAST` yields null rather than failing the query on a value that will not convert. See [Operators](/oss/v0-41-0/sql/dql/operators#casting). # Database Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/database Create, describe, list, attach, and drop databases with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A database is the catalog's top-level container: it holds [namespaces](/oss/v0-41-0/sql/ddl/namespace), which hold tables, views and other objects. Database statements name one database, independently of the session's current database. Database creation uses the deployment's native catalog and storage settings. ## CREATE DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE DATABASE analytics CREATE DATABASE IF NOT EXISTS "team/search" ``` Creates a persistent database. Requires `CREATE DATABASE` on the system, and ownership of the database name if it already has an owner. The caller becomes the owner of a new name, following the same rules as the REST API. The result has `operation`, `name`, and `status` columns. Status is `created`, or `already_exists` with `IF NOT EXISTS`. Without that clause, an existing database is an error. Creation never overwrites an existing database. > [!NOTE] > > `WITH` options are unsupported on `CREATE DATABASE`. Use `ATTACH DATABASE` > [below](#attach) to register a database at an existing location. The > `system` database and reserved storage names cannot be created. ## DESCRIBE DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE DATABASE analytics DESC DATABASE "team/search" ``` Requires `USAGE` on the database. Returns one row with `name` and `properties`. Properties are the catalog's metadata encoded as a JSON object; a database without metadata returns `{}`, and a database mid `CASCADE` drop reports a transient property marking it as dropping. A missing database is an error. `DESCRIBE DATABASE system` returns empty properties and requires system `USAGE`. ## SHOW DATABASES ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW DATABASES ``` Returns a sorted `name` column containing the databases the caller has `USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters are unsupported. ## ATTACH DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH DATABASE analytics WITH (location = 'analytics') ATTACH DATABASE IF NOT EXISTS analytics WITH (location = 'analytics') ATTACH DATABASE analytics WITH (location = 's3://customer-bucket/raw/analytics/') ATTACH DATABASE analytics WITH (location = 'az://customer-data@customeraccount.blob.core.windows.net/raw/analytics') ``` Registers an existing database at a path relative to the catalog's storage root, or at an external S3, GCS or Azure location, instead of creating a new one. `location` is the only supported option -- naming a storage integration explicitly is refused. For an external location, the deployment automatically binds the most specific [storage integration](/oss/v0-41-0/sql/ddl/storage-integration) whose prefix covers it; one must already exist. An Azure location must be account-qualified (`az://container@account.blob.core.windows.net/path`); a bare `az://container/path` is refused. `ATTACH DATABASE` requires the same creation privileges as `CREATE DATABASE`. For an external location, it also requires `USAGE` on the storage integration that binds it, and on that integration's own database and namespace; the integration itself must live in a native, root-backed database under the catalog root. Attaching writes Enterprise's own tracking metadata into the location to bring it under management -- it does not rewrite, move, or re-encode any existing table's data. > [!WARNING] > > A relative-path location never accepts an absolute path (`/tmp/db`), a > `file://` URI, a Windows path (`C:/db`), a `..` segment, an empty string, > or a doubled slash (`sub//db`). An S3 or GCS location must be a concrete > prefix, not a bare scheme (`s3://`) on its own. `IF NOT EXISTS` makes the statement a no-op rather than an error when the database is already attached. > [!NOTE] > > A quoted name reaches characters a bare identifier cannot, such as > `ATTACH DATABASE "team/search" WITH (location = 'team-search')`. > Removing an externally attached database with `DROP DATABASE` unregisters > the attachment and releases its storage-integration reference, without > deleting the underlying data. ## DROP DATABASE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP DATABASE analytics DROP DATABASE IF EXISTS analytics RESTRICT DROP DATABASE analytics CASCADE ``` Requires `USAGE` and `OWNERSHIP` on the database. The default, `RESTRICT`, refuses a database that still contains objects. `CASCADE` refuses new objects in the database, revokes every grant in it, and starts a job that drops its contents; deployments without cascade support reject it. An externally attached database cannot be dropped with `CASCADE`. `RESTRICT` returns `operation`, `name`, and `status` columns: `dropped`, or `not_found` with `IF EXISTS` for a missing database. `CASCADE` returns `operation`, `job_id`, and `status` columns: the job's id with `dropping`, or an empty `job_id` with `not_found`. The name stays taken until the job finishes and the dropped storage is cleaned up. The `system` database and federated databases cannot be dropped. > [!NOTE] > > `ALTER DATABASE` is unsupported. ## What to read next > [card] [Namespace](/oss/v0-41-0/sql/ddl/namespace) > > CREATE SCHEMA inside an attached database. > [card] [Table](/oss/v0-41-0/sql/ddl/table) > > Creating tables once a database and namespace exist. > [card] [Database](/oss/v0-41-0/management/database) > > The SDK equivalent, and connection settings. # Function Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/function Create, describe, alter, list, and drop registered functions with SQL. **Applies to:** Embedded ❌, Enterprise ✅ Early access [SQL runs in LanceDB Enterprise.](/oss/v0-41-0/sql) ## CREATE FUNCTION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION f(x int64) RETURNS int64 LANGUAGE python AS 'def f(x): return x * 2' WITH (pip = 'numpy==1.26.4', python_version = '3.11') ``` A function takes more than one parameter; each one binds a separate column or literal where the function is called: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE FUNCTION ratio(numerator float64, denominator float64) RETURNS float64 LANGUAGE python AS 'def ratio(numerator, denominator): return numerator / denominator' ``` Parameter and result types are Arrow type names, not SQL ones: `int64`, `float64`, `utf8`, `bool`, `date32`, and lists such as `list<float32>` or `fixed_size_list<float32, 768>`. `BIGINT` is refused. A parameter accepts nulls unless it is declared `NOT NULL`. The body is Python source. Its dependencies are declared with it and are part of the **immutable function version**. Changing one produces a new version rather than altering the registered one, so a column filled by an earlier version is unaffected. | Option | | | - | - | | `pip` | pip requirements for the worker environment | | `conda` | conda packages instead of pip | | `conda_channels` | channels in priority order; requires `conda` | | `apt` | OS packages to install in the worker environment | | `image` | a specific container image to run the worker in, such as `'host/repo@sha256:...'` | | `python_version` | worker Python version; `3.12` when omitted, whatever Python you send the statement from | | `gpu` | `'true'` when every execution needs a GPU | | `gpu_class` | which configured GPU class to run on, when `gpu = 'true'` | | `result_stability` | `'input_and_context'` or `'per_call'` | | `batch_size` | maximum rows per Function call | | `row_timeout_seconds` | per-row (or per-batch, for a vectorized Function) execution timeout | **Errors and limits** | | | | - | - | | `LANGUAGE` other than `python` | refused | | `pip` and `conda` together | refused (pick one) | | `conda_channels` without `conda` | refused | | `gpu` set to anything but `'true'` | refused | | An empty body | refused | | Any other option | refused, and the message lists what is supported | > [!NOTE] > > **Enterprise job type:** `create_function`. Registration returns a job because > the function is baked into an image before the version becomes usable. ## Artifact registration `CREATE FUNCTION name FROM '<registration JSON>'` accepts the artifact, signature, runtime, optional secret bindings, and result stability produced by the SDK's registration request. Omit its `name` property because the SQL identifier supplies it. Escape apostrophes in the JSON as doubled apostrophes. By default, the command waits for its internal image-build job to publish the version, then returns one UTF-8 `definition` column containing FunctionVersion JSON. `WITH (wait = false)` instead returns the existing image-build registry job ID in `job_id`, with `operation` and `status` columns. The SDK's ordinary registration handle has type `query` and uses the SQL query UUID as its single `id`; the internal image-build job has type `create_function`. ## DESCRIBE and ALTER FUNCTION ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE FUNCTION embed WITH (version = '1', include_source = true) ``` DESCRIBE returns one `definition` JSON column for the exact version. Enterprise 1.12.0 requires `version`; omitting it is an error. `include_source` defaults to false; source-inclusive reads report an omission when the stored artifact exceeds the inline source limit. `ALTER FUNCTION name FROM '<pinned update JSON>'` accepts a `reference` with name, namespace, object ID, location, version, and manifest digest, plus optional `metadata` and `disabled` updates. The command checks that reference before appending a revision and returns the resulting `definition` JSON. ## Call it Once registered, a function is callable by name in any query, the same as a built-in scalar function: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, f(x) AS doubled FROM my_table ``` This is also the fastest way to check a new registration before binding it to a column: call it over a few rows, or over literal arguments, before committing to [a computed column](/oss/v0-41-0/sql/ddl/table#computed-column) that fills from it. ## SHOW FUNCTIONS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW FUNCTIONS SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) ``` `SHOW FUNCTIONS` returns the highest published numeric revision for each name. Add `HISTORY` to list every published revision, as Python's `list_functions()` does. Rows are ordered by name and numeric revision, so `2` comes before `10`. `after_name` and `after_version` must be supplied together for keyset pagination. `limit` bounds the response; `include_definition = false` omits the optional definition JSON. ## DROP FUNCTION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP FUNCTION embed WITH (version = '1') DROP FUNCTION IF EXISTS embed WITH (version = '1') ``` DROP removes only the requested revision from lookup and listing. Other published revisions and their grants remain available. Dropping the last visible revision releases the name and object binding; physical cleanup continues separately. The result reports `dropped` or `not_found`. `IF EXISTS` allows a missing name or a repeated drop of a previously published revision. A revision that was never published under an existing name is an error. All function object commands retain shared results even when general query-result copying is disabled, so asynchronous polling can resume on another query node. ## What to read next > [card] [Function](/oss/v0-41-0/management/function) > > Registering one from the SDK, and diagnosing environment mismatches. > [card] [Computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) > > Filling a column with a function instead of an expression. # Grant Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/grant GRANT and REVOKE: privileges on every catalog object, from a database down to a Function. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT <privilege>[, <privilege>...] ON <target> TO <grantee>[, <grantee>...] REVOKE <privilege>[, <privilege>...] ON <target> FROM <grantee>[, <grantee>...] <target> ::= SYSTEM | DATABASE <name> | SCHEMA <namespace> | NAMESPACE <name> [IN <schema>] | TABLE <name> | VIEW <name> | MATERIALIZED VIEW <name> | SECRET <name> | STORAGE INTEGRATION <name> | FUNCTION <name> <grantee> ::= [ROLE] <role> | [USER] { <name> | ID '<id>' } | [GROUP] { <name> | ID '<id>' } ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice, GROUP ID 'g1' GRANT USAGE ON FUNCTION platform.embed TO ROLE research GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins REVOKE USAGE ON FUNCTION platform.embed FROM ROLE research ``` ## Privileges | Target | Privileges it accepts | | - | - | | `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | | `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | | `SCHEMA` (a namespace) | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | | `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | | `VIEW` | `OWNERSHIP`, `SELECT` | | `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | | `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | | `FUNCTION` | `OWNERSHIP`, `USAGE` (call it in a query, bind it to a column, or refresh a column it computes) | > [!WARNING] > > `OWNERSHIP` cannot be revoked, only granted to someone else, which transfers > it: an object always has exactly one owner. `GRANT OWNERSHIP` is refused with > more than one grantee for the same reason. See [Privileges](/oss/v0-41-0/governance/privileges) for what each privilege allows in full, and how a creation privilege resolves against an object's parent when the object doesn't exist yet. ## Grantees A grantee is a role, or a user or group named by its identity-directory name or its directory ID. A grantee with no leading `ROLE`/`USER`/`GROUP` keyword takes the kind of the one before it, so `TO ROLE a, b` names two roles -- but the first grantee in the list always needs its keyword. An unquoted name is folded to lowercase before it is looked up; quote one that has capitals, such as `TO ROLE "DataEng"`. ## Naming the target A `SECRET` or `FUNCTION` target can be qualified with its namespace and database, the same as anywhere else: `SECRET analytics.api_key`, `SECRET db1.analytics.api_key`. `SCHEMA` and `NAMESPACE` both target a namespace but aren't interchangeable: `SCHEMA <namespace>` takes the namespace's complete path, while `NAMESPACE <name> [IN <schema>]` takes one unqualified component, resolved under an explicit parent schema or the session's current namespace when `IN` is omitted -- `NAMESPACE a.b` (a qualified name with no `IN`) is refused. A `MATERIALIZED VIEW` is a table for authorization purposes: the same privileges apply, and granting one does not reach the non-materialized `VIEW` beside it. ## How a statement is applied * A statement applies all of its changes or none of them. * The caller must already hold `OWNERSHIP` on the object to change any grant on it. * Granting a privilege a grantee already holds, or revoking one it does not hold, is a no-op. * `GRANT` requires the object to exist; `REVOKE` does not, so an entry left on a dropped object can still be removed. A role need not exist beforehand, but a `USER` or `GROUP` name must resolve to exactly one identity in your identity provider -- checked only after the caller's `OWNERSHIP` -- or the statement fails. The `ID '<id>'` form is not looked up. * `GRANT ... ON ... FROM ...` and `REVOKE ... ON ... TO ...` are both refused; `GRANT` always takes `TO`, `REVOKE` always takes `FROM`. * Returns one row per privilege and grantee, with status `granted`, `already_granted`, `revoked` or `not_granted`. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function; that's a > registration-time argument to `create_function` in the Python SDK. See > [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret). ## SHOW GRANTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GRANTS [ON <target>] [TO <grantee>[, <grantee>...]] [LIMIT n] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GRANTS SHOW GRANTS ON TABLE events TO ROLE readers LIMIT 2 SHOW GRANTS ON NAMESPACE features IN analytics.team SHOW GRANTS TO USER ID 'p1' ``` Lists grants as rows of `subject_id`, `subject_name`, `object` and `privilege`. `ON` filters to one target's own grants; `TO` filters to one or more grantees; combine both, or omit both for every grant the caller can see. `ON <target>` requires `USAGE` on that target; a target-less call requires system `USAGE` instead, since it can surface grants across the whole catalog. `SHOW ROLE BINDINGS` is the counterpart for role membership rather than object privileges -- see [Role membership in SQL](/oss/v0-41-0/governance/principals#membership). ## What to read next > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > The full privilege model, and how creation privileges resolve upward. > [card] [Namespace](/oss/v0-41-0/sql/ddl/namespace) > > Creating the schemas these privileges apply to. # Index Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/index CREATE INDEX and DROP INDEX: one column, with the algorithm chosen by USING. **Applies to:** Embedded ❌, Enterprise ✅ ## CREATE INDEX ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE INDEX ON documents USING btree (title) CREATE INDEX text_search ON documents USING fts (text) ``` `USING` is required: it names the algorithm. The scalar algorithms are `btree`, `bitmap` and `label_list`; `fts` builds a full-text index; and the vector algorithms are `ivf_pq`, `ivf_rq`, `ivf_flat`, `ivf_hnsw_sq` and `ivf_hnsw_pq`, where the deployment supports them. Index options go in a `WITH (...)` clause. > [!NOTE] > > In LanceDB Enterprise, SQL `CREATE INDEX` covers **one column**. A name between > `INDEX` and `ON` names the index, where the deployment's configuration allows > it; without one, the server names it after the column, as in `title_idx`. For a > multi-column index, use the SDK's [`create_index`](/oss/v0-41-0/indexing). > [!NOTE] > > **Enterprise job type:** `reindex_` followed by the algorithm, such as > `reindex_btree` or `reindex_ivf_pq`; the name says which algorithm is building, > not a different feature. An SDK build that must not replace an existing index > runs as `create_` followed by the algorithm instead. See > [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing). ## DROP INDEX ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP INDEX documents.title_idx ``` Takes the qualified `table.index` name. Find it with the SDK's [`list_indices`](/oss/v0-41-0/indexing) if you created the index without naming it yourself. A deployment builds the index in the background after `CREATE INDEX` returns; until that build finishes, the index is not listed and `DROP INDEX` reports it as not found. ## What to read next > [card] [Indexing](/oss/v0-41-0/indexing) > > Choosing an index type from the SDK. > [card] [Incremental Indexing](/oss/v0-41-0/indexing/incremental-indexing) > > Keeping an index current as data arrives. # Job Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/job SHOW JOBS, SHOW JOB EVENTS, DESCRIBE JOB, SHOW ERRORS, and controlling a running job with PAUSE, RESUME and CANCEL. **Applies to:** Embedded ❌, Enterprise ✅ A [job](/oss/v0-41-0/basics/jobs) is not a catalog object (it has no schema and is not namespaced), but it has its own SQL statements, grouped here the same way the catalog objects are. ## SHOW JOBS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOBS SHOW JOBS FOR TABLE documents SHOW JOBS FOR JOB '<parent_job_id>' [LIMIT n] ``` The unfiltered command lists jobs in the connected database, newest first: id, type, state, creation time -- the SQL counterpart of `list_jobs`. `FOR TABLE` filters that listing by the current namespace's table name. `FOR JOB` lists the parent's direct child jobs using the REST API's child model. Child rows expose their ID, kind, phase, row progress and attempt; unknown values remain NULL. Children are read-only diagnostic identities. `FOR JOB` defaults to 1,000 children and accepts `LIMIT` from 1 to 10,000, following backend continuation pages up to that limit. Child history can be `available`, `not_yet_recorded`, or `unavailable` after archival. > [!NOTE] > > A job you completed weeks ago eventually stops appearing here -- it was > archived, not deleted. Two deployment-scheduled jobs sweep the registry on a > per-database schedule: `job_registry_archive` moves terminal jobs out of the > active registry into archival storage, and `job_events_export` separately > copies terminal jobs' event histories into a curated system table for > metering, where the deployment enables it. A job's events can survive in > that exported table after the job itself is archived. ## SHOW JOB EVENTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOB EVENTS '<parent_or_child_job_id>' [LIMIT n] ``` Events are returned newest first. Parent history does not include child history. The default limit is 1,000; valid limits range from 1 to 10,000. The result includes event sequence, state, timestamps, origin, claim and resource/work fields. Child `kind` and `details` expose the REST API's allowlisted diagnostics; raw parent payloads are excluded. ## DESCRIBE JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE JOB '<job_id>' [FORMAT TEXT | TABLE | JSON] DESC JOB '<job_id>' [FORMAT TEXT | TABLE | JSON] ``` Both spellings show a finished root job's timing profile. `TEXT` is the default; `TABLE` returns typed phase/step rows and `JSON` returns the profile as one document. A running job has no profile rows. ## SHOW ERRORS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW ERRORS ON <table> [FOR JOB '<job-id>'] [LIMIT <n>] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW ERRORS ON documents SHOW ERRORS ON documents FOR JOB 'job-abc' LIMIT 100 ``` Why rows failed. Reach for this when a [refresh](/oss/v0-41-0/sql/dml/refresh-column) reports fewer filled rows than you expected. ### Errors and limits | | | | - | - | | `LIMIT` | defaults to 10,000; must be between 1 and 100,000 | | Failed jobs scanned without `FOR JOB` | 32 most recent | | Tables the server does not open directly | not supported | Without `FOR JOB` this surveys recent failures and stops at 32 jobs. When the listing stops at your `LIMIT`, the message says so. Narrow with `FOR JOB` rather than raising the limit blindly. > [!NOTE] > > `SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB` and `SHOW ERRORS` require > system `USAGE`, as do the equivalent REST diagnostics. Explicit table > listings additionally use the table-list authorization policy. ## PAUSE JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} PAUSE JOB 'j-ci-abc-def' ``` ## RESUME JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} RESUME JOB 'j-ci-abc-def' ``` ## CANCEL JOB ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CANCEL JOB 'j-ci-abc-def' ``` The job id is always a quoted string literal. All three take exactly one and nothing after it: a second token on the line is a syntax error rather than being ignored. Pause requires the deployment's pause-write opt-in and a resumable job type; it may return `pausing` while workers drain, and resume may return `still_pausing` until drain finishes. > [!NOTE] > > `PAUSE JOB`, `RESUME JOB` and `CANCEL JOB` require system `OPERATE` -- a > broader privilege than the `USAGE` that reading job state needs, since > these change what a running job does. > [!NOTE] > > Cancellation is a request, matching the SDK's > [`cancel()`](/oss/v0-41-0/basics/jobs#managing): it does not guarantee the job stops before > doing more work, and asking twice or cancelling a finished job does nothing. > `CANCEL JOB` itself can be unavailable on an Enterprise cluster with no job registry > configured, which is a deployment condition rather than something you can work > around from SQL. ## Compatibility `SHOW JOBS FOR <table>` (without the `TABLE` keyword), `SHOW JOB SUMMARY`, and `SHOW JOB SPLITS` retain their existing behavior as compatibility forms. Prefer `SHOW JOBS FOR TABLE`/`FOR JOB` and `DESCRIBE JOB` going forward. See [`SHOW JOBS FOR JOB`](#show) for the per-split diagnostics form -- each split is a child job, listed with its own phase and progress. See [Watching a refresh](/oss/v0-41-0/sql/dml/refresh#watching) for `SHOW JOB SPLITS`'s full column reference and a `DESCRIBE JOB` example. ## What to read next > [card] [Query and job](/oss/v0-41-0/basics/jobs) > > The handle these statements are the SQL view of. > [card] [Intelligent Auto-Maintenance](/oss/v0-41-0/enterprise/intelligent-auto-maintenance#cleanup) > > A job type the deployment schedules on its own, without a call. # Materialized View Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/materialized-view CREATE MATERIALIZED VIEW and SHOW MATERIALIZED VIEWS; refreshing is a REFRESH statement. **Applies to:** Embedded ❌, Enterprise ✅ A materialized view stores a query's result as rows, kept current by a refresh. It is the counterpart to a [view](/oss/v0-41-0/sql/ddl/view), which stores only the query. > [!NOTE] > > Materialized views are off by default in LanceDB Enterprise and have to be enabled > there. Which statements and query shapes a deployment accepts, whether it needs > the source table to have stable row ids, and how it refreshes a view depend on > its LanceDB Enterprise version and configuration. ## CREATE MATERIALIZED VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW <name> AS SELECT ... ``` Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/oss/v0-41-0/management/materialized-view#create). ## SHOW MATERIALIZED VIEWS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW MATERIALIZED VIEWS ``` > [!NOTE] > > This asks the server for its views, as the SDK's `list_materialized_views` does > on a `db://` connection. ## Refreshing one ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks ``` See [REFRESH MATERIALIZED VIEW](/oss/v0-41-0/sql/dml/refresh-materialized-view) for the full syntax, and compatibility notes for older server versions. ## Dropping one ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP MATERIALIZED VIEW <name> ``` A dedicated statement; the SDKs emit it rather than [`DROP TABLE`](/oss/v0-41-0/sql/ddl/table#drop), even though a materialized view **is** a table underneath. For the same reason, dropping one removes stored rows, unlike dropping a [view](/oss/v0-41-0/sql/ddl/view#drop). > [!NOTE] > > **Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the > same underlying job as dropping any table, `drop_table` or `drop_object`. ## What to read next > [card] [Materialized View](/oss/v0-41-0/management/materialized-view) > > Creating one from the SDK. > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > How a refresh works, in LanceDB Enterprise. # Namespace Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/namespace Create, alter, describe, list, and drop namespace paths with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A [namespace](/oss/v0-41-0/management/namespace) is addressed in SQL as a `SCHEMA`, the standard's name for the same concept. A **schema** is a complete namespace path, optionally qualified by a database; a nested path occupies one backtick-quoted identifier with `$` between components, such as `` analytics.`team$features` ``. A **namespace**, as a separate keyword, names one path component, relative to an explicit parent schema or the session's current schema -- it cannot contain `$` or be qualified with a database. `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete schema identifier. Names are lowercased unless quoted. ## CREATE SCHEMA and CREATE NAMESPACE Create a namespace using its complete schema path: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SCHEMA analytics CREATE SCHEMA db1.`ns1$ns2` CREATE SCHEMA IF NOT EXISTS `ns1$ns2` ``` Alternatively, create the same namespace by naming its component and parent: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE NAMESPACE features IN team ``` To supply creation metadata and tolerate an existing namespace: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE NAMESPACE IF NOT EXISTS features IN analytics.team WITH (owner = 'search-team', purpose = 'retrieval') ``` A nested namespace is one backtick-quoted name with `$` between its components: `` db1.`ns1$ns2` `` creates `ns2` inside `ns1` in database `db1`. Both forms create namespaces in the same catalog, and missing ancestors are created automatically -- the part before the first dot is always the database. `public` is the database's root namespace, which is never created or dropped. `IF NOT EXISTS` makes the statement a no-op rather than an error when the namespace is already there, though it does not replace an existing namespace's properties. Without it, an existing target is an error. Properties are string values stored on the target only; implicitly created ancestors receive no properties, and duplicate property keys are errors. The result has `operation`, `name`, and `status` columns. The operation is `CREATE SCHEMA` for either spelling; the name is the resolved path and the status is `created`. > [!NOTE] > > Creation requires `CREATE NAMESPACE` on the database and the parent > namespace -- the same privileges the > [namespace REST API](/oss/v0-41-0/management/namespace) checks. The caller becomes the > owner of each newly created namespace, including implicitly created > ancestors. See [Grant](/oss/v0-41-0/sql/ddl/grant#privileges) for the full privilege > list a namespace accepts. ## ALTER SCHEMA and ALTER NAMESPACE | Operation | SCHEMA syntax | NAMESPACE syntax | | - | - | - | | Set metadata | ``ALTER SCHEMA `team$features` SET (purpose = 'retrieval')`` | `ALTER NAMESPACE features IN team SET (purpose = 'retrieval')` | | Remove metadata | ``ALTER SCHEMA `team$features` UNSET (purpose)`` | `ALTER NAMESPACE features IN team UNSET (purpose)` | `SET` adds or replaces the listed string properties, preserving other keys. `UNSET` removes the listed keys; a missing key is ignored. Lists must be nonempty, and duplicate keys are errors. Quote a key containing punctuation, for example `SET ("owner.team" = 'search')`. Each statement updates metadata atomically and preserves unrelated concurrent changes. Metadata changes do not change ownership or grants. Use `DESCRIBE` to read the updated properties. A missing namespace is an error. > [!NOTE] > > Requires `USAGE` on the database and the namespace, and `OWNERSHIP` on the > namespace itself. > [!NOTE] > > `ALTER` metadata is supported by native manifest-backed databases. Legacy > directory and external catalogs report an unsupported-operation error. The > implicit `public` root and the read-only `system` database cannot be > altered. The result has `operation`, `name`, and `status` columns, with operation `ALTER SCHEMA` for either spelling and status `altered`. ## DESCRIBE SCHEMA and DESCRIBE NAMESPACE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE SCHEMA analytics.`team$features` DESCRIBE NAMESPACE features IN analytics.team DESC NAMESPACE features IN team ``` Returns one row with `name` (the complete `$`-joined schema path) and `properties` (a JSON object). An unannotated namespace returns `{}`. A missing namespace is an error. `DESC` is an alias for `DESCRIBE`. > [!NOTE] > > Requires `USAGE` on the database and the namespace. ## SHOW SCHEMAS and SHOW NAMESPACES ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW SCHEMAS SHOW NAMESPACES SHOW NAMESPACES IN analytics.team ``` `SHOW SCHEMAS` returns complete paths in the current database, recursively, including `public` when the caller can use it. It does not accept `IN`. `SHOW NAMESPACES` lists only immediate child names under the session's current schema. `IN` selects a different parent schema, optionally in another database -- use `IN public` for the current database's root, or `IN analytics.public` for another database's root. A missing parent is an error. Both forms return a sorted `name` column and omit namespaces the caller cannot use. Large listings that exceed 10,000 namespaces, or recursive listings deeper than 32 levels, return an error suggesting a narrower listing. ## DROP SCHEMA and DROP NAMESPACE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP SCHEMA analytics.`team$features` DROP NAMESPACE IF EXISTS features IN analytics.team RESTRICT DROP NAMESPACE team CASCADE ``` The default, `RESTRICT`, refuses a namespace with children or objects -- tables, views and other objects inside must be dropped explicitly first. In native manifest-backed databases, `CASCADE` instead removes the namespace and all descendant bindings atomically in one catalog commit, then submits a background job that cleans up their storage; deployments without cascade support reject it. A storage integration used by an attached database blocks the drop of its namespace. > [!NOTE] > > Requires `USAGE` and `OWNERSHIP` on the namespace. A dropped Secret is > eligible for immediate deletion even when jobs still reference it: a > process that already holds the value keeps it for the rest of its run, but > a later launch that needs the Secret can fail once it's gone. `RESTRICT` returns `operation`, `name`, and `status`, with status `dropped` or `not_found`. `CASCADE` returns `operation`, `job_id`, and `status`, with status `dropping`, or an empty job ID and `not_found` for a missing target with `IF EXISTS`. Inspect a cascade drop's child jobs with [`SHOW JOBS FOR JOB`](/oss/v0-41-0/sql/ddl/job#show). Both spellings report operation `DROP SCHEMA`. ## Correcting invalid syntax | Invalid form | Use instead | | - | - | | `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | | `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | | `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | | `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next > [card] [Database](/oss/v0-41-0/sql/ddl/database) > > Attaching the database a namespace lives in. > [card] [Namespace](/oss/v0-41-0/management/namespace) > > The SDK equivalent, and how a namespace fits the catalog hierarchy. > [card] [Table](/oss/v0-41-0/sql/ddl/table) > > Creating tables inside a namespace. # Secret Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/secret CREATE, ALTER, DROP, SHOW and DESCRIBE SECRET, and granting privileges on Secrets. Early access Enterprise [SQL runs in LanceDB Enterprise.](/oss/v0-41-0/sql) A [Secret](/oss/v0-41-0/management/secret) is a named credential that Functions bind by reference. These statements store, rotate, list, describe and drop Secrets. A Secret is addressed like a table: `[db.][namespace.]name`. An unqualified name uses the session's database and namespace. A nested namespace is one backtick-quoted name with `$` between its components, and `public` is the database's root namespace. A Secret name may contain letters, digits, `_`, `.` and `-`, so quote one that contains `.` or `-`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} api_key platform.`model-api-key` analytics.`ml$vision`.`model-api-key` ``` `CREATE`, `ALTER` and `DROP` return one row of `operation`, `name` and `status`. Without `IF [NOT] EXISTS`, a taken name (for `CREATE`) or a missing Secret (for `ALTER` and `DROP`) is an error rather than a status. ## CREATE SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '<api-key>' CREATE SECRET IF NOT EXISTS api_key TYPE = GENERIC_STRING SECRET_STRING = $$<api-key>$$ ``` Stores a new Secret. `TYPE = GENERIC_STRING` is required; it is currently the only supported type. The value may be single-quoted or dollar-quoted, or a bound `$1` parameter -- the same choice `ALTER SECRET` offers below -- so the value never has to appear in the SQL text itself: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query( "CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = $1", parameters=["<api-key>"], ) ``` Requires `CREATE SECRET` on the namespace; the caller becomes the Secret's owner. The status is `created`, or `already_exists` with `IF NOT EXISTS`. It never overwrites an existing Secret; use `ALTER SECRET`. ## ALTER SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '<api-key>' ALTER SECRET IF EXISTS api_key SET SECRET_STRING = $$<api-key>$$ ``` Replaces the Secret's value -- `SECRET_STRING` takes the same single-quoted, dollar-quoted, or bound `$1` parameter forms `CREATE SECRET` does. Every Function bound to it gets the latest value the next time a job starts -- a job already running, and its retries, keep the value they captured at their own start -- without a new Function version. Requires `UPDATE` on the Secret. The status is `altered`, or `not_found` with `IF EXISTS`. ## DROP SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP SECRET platform.`model-api-key` DROP SECRET IF EXISTS api_key ``` Deletes the Secret and every grant on it. Functions bound to it fail at their next job, naming the Secret. Requires `OWNERSHIP` on the Secret. The status is `dropped`, or `not_found` with `IF EXISTS`. > [!WARNING] > > `DROP SECRET` cannot be undone. A new Secret created under the same name is > picked up by every Function still bound to that name. ## SHOW SECRETS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW SECRETS SHOW SECRETS IN platform SHOW SECRETS IN analytics.`ml$vision` SHOW SECRETS IN public SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 ``` Lists the Secret names in one namespace as a sorted `name` column. Without `IN`, it lists the session's namespace; `IN public` lists the root. `WHERE name > '<cursor>'` pages past the last name already seen, and `LIMIT` bounds the page size; `WHERE` must compare `name` with `>`. Requires `USAGE` on the database and the namespace. ## DESCRIBE SECRET ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE SECRET platform.`model-api-key` DESC SECRET api_key ``` Returns one row: | Column | Type | Meaning | | - | - | - | | `name` | string | The Secret's name | | `created_at_millis` | int64 | When it was created, in milliseconds since the Unix epoch | | `updated_at_millis` | int64 | When its value was last set. Watch this change to confirm a rotation landed. | | `history` | list of struct `{generation: uint64, at_millis: int64}` | Creation and each rotation since, oldest first, up to the most recent 100 | A missing Secret is an error. Requires `USAGE` on the Secret. ## GRANT and REVOKE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE SECRET ON SCHEMA platform TO ROLE platform_admins GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` `CREATE SECRET` on the containing `SCHEMA` creates one; `OWNERSHIP`, `USAGE` (bind it to a Function) and `UPDATE` (rotate it) apply to the Secret itself. See [GRANT and REVOKE](/oss/v0-41-0/sql/ddl/grant) for the full statement grammar, every target type, and the shared mechanics -- grantee forms, no-op rules, and the status a statement returns -- which apply the same way to a Secret as to any other object. ## The value stays out of output A Secret's value never appears in a statement's result, an error message, `EXPLAIN` output, or the query log. The query log masks everything after the name in `CREATE SECRET`, and everything after `SET` in `ALTER SECRET`. > [!NOTE] > > SQL has no syntax for binding a Secret to a Function. Register Functions that > bind Secrets through the Python SDK; see > [Vend a Secret to a Function](/oss/v0-41-0/curation/vend-secret). ## What to read next > [card] [Secret](/oss/v0-41-0/management/secret) > > Create, rotate, list and drop the credential from the Python SDK and SQL. > [card] [Privileges](/oss/v0-41-0/governance/privileges#sql) > > Every object's privileges, and how grants resolve. # Storage Integration Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/storage-integration CREATE, DESCRIBE, SHOW and DROP STORAGE INTEGRATION: a namespace-scoped, reusable credential for reading or importing from external storage. **Applies to:** Embedded ❌, Enterprise ✅ A storage integration is a namespace-scoped catalog object that lets a query read from, or import from, a storage location outside the deployment's own tables -- an S3, GCS or Azure prefix, or a HuggingFace dataset repository -- without embedding a credential in the query itself. It is addressed and scoped the same way a [Secret](/oss/v0-41-0/sql/ddl/secret) is: a 1-3 part identifier, `name`, `namespace.name` or `database.namespace.name`, with a nested namespace path `$`-joined into that middle part. ## CREATE STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION <name> STORAGE_PROVIDER = 'S3' | 'AZURE' | 'GCP' | 'HUGGINGFACE' STORAGE_PREFIX = '<uri-prefix>' [ <provider option> = <value> [...] ] ``` `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. Options ending in `_SECRET` take a [Secret](/oss/v0-41-0/sql/ddl/secret) identifier, not a quoted string: `name`, `namespace.name` or `database.namespace.name`, with a nested namespace path `$`-joined in the middle part (``db.`team$prod`.key``). Omitted parts default to the session's current database and namespace. Creating the integration requires `USAGE` on each referenced Secret and on its database and namespace. Passing an option a provider does not accept, such as an Azure option on an `S3` integration, is refused. ### S3 ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' CREATE STORAGE INTEGRATION raw STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = 's3://customer-data/raw/' STORAGE_AWS_ACCESS_KEY_ID_SECRET = bootstrap.credentials.aws_key_id STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = bootstrap.credentials.aws_key_secret ``` | Option | Type | Meaning | | - | - | - | | `STORAGE_AWS_ROLE_ARN` | string | an IAM role to assume, by cross-account trust (see [below](#trust)) | | `STORAGE_AWS_ACCESS_KEY_ID_SECRET` | Secret ref | a static access key ID, paired with the secret key below | | `STORAGE_AWS_SECRET_ACCESS_KEY_SECRET` | Secret ref | the matching static secret access key | | `STORAGE_AWS_REGION` | string, optional | the bucket's region | | `STORAGE_AWS_ENDPOINT` | string, optional | an S3-compatible endpoint URL (MinIO, Tigris, ...) instead of AWS itself | Give either `STORAGE_AWS_ROLE_ARN` alone, or both key-pair options together \-- mixing the two, or supplying only one half of the key pair, is refused. ### Azure ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION blobs STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = 'az://customer-data/raw/' STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' STORAGE_AZURE_TENANT_ID_SECRET = bootstrap.credentials.tenant STORAGE_AZURE_CLIENT_ID_SECRET = bootstrap.credentials.client STORAGE_AZURE_CLIENT_SECRET_SECRET = bootstrap.credentials.credential ``` | Option | Type | Meaning | | - | - | - | | `STORAGE_AZURE_STORAGE_ACCOUNT` | string | the storage account name | | `STORAGE_AZURE_TENANT_ID_SECRET` | Secret ref | Entra ID tenant | | `STORAGE_AZURE_CLIENT_ID_SECRET` | Secret ref | service principal client ID | | `STORAGE_AZURE_CLIENT_SECRET_SECRET` | Secret ref | service principal client secret | All four are required together; there is no role-based alternative for Azure. ### GCP ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION gcs STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = 'gs://customer-data/raw/' GCP_CREDENTIALS_JSON_SECRET = bootstrap.credentials.gcp ``` `GCP_CREDENTIALS_JSON_SECRET` -- note the option name has no `STORAGE_` prefix, unlike every other provider's options -- names a Secret holding the full service-account JSON key. It is required; GCP has no role-based alternative here. ### HuggingFace ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE STORAGE INTEGRATION hub STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token ``` `HUGGINGFACE_TOKEN_SECRET` is the only HuggingFace option, and it is required: creating an integration without it is refused. For anonymous access, at HuggingFace's default anonymous rate limits, register no integration for that prefix at all. See [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) for the full read and import workflow this integration unlocks. ### The S3 trust policy Creating an `STORAGE_AWS_ROLE_ARN` integration does not finish the AWS side of the setup. The result row's `trust_policy`, `permissions_policy` and `configuration_instructions` columns -- also visible from [`DESCRIBE`](#describe) -- are the IAM policy documents your role needs: attach `trust_policy` as the role's trust relationship, scoped to `aws_account_id`, `aws_iam_principal_arn` and `aws_external_id` from the same row, and attach `permissions_policy` to grant that role read access to the bucket. `access_verified` reports whether the deployment already confirmed it can assume the role and read the prefix; `false` typically means the trust policy has not been attached yet. ## Reading and importing through the integration A query or `CREATE TABLE ... AS SELECT` can reference a matching URI directly, once an integration covers it -- the integration is never named in the statement. What the URI reads depends on the provider: * **HuggingFace** (`hf://datasets/...`) reads Parquet files from a dataset repository. See [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) for the full workflow, including how a CTAS import distributes across plan executors. * **S3, GCS and Azure** (`s3://`, `gs://`, `az://`) read an existing Lance dataset at that prefix, the same way as a managed table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM 's3://customer-data/raw/events.lance' LIMIT 10 CREATE TABLE events_copy AS SELECT * FROM 's3://customer-data/raw/events.lance' ``` A CTAS import distributes the same way regardless of provider: disjoint file and row-group ranges go to plan-executor workers, each writes uncommitted Lance files, and a coordinator commits the table once every worker finishes. See [`CREATE TABLE`](/oss/v0-41-0/sql/ddl/table#create) for `CREATE TABLE AS SELECT` syntax in general. ## DESCRIBE STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE STORAGE INTEGRATION raw DESC STORAGE INTEGRATION platform.hub ``` Returns one row with every column `CREATE` returns: the provider, prefix, the Secret references and plain-string options that apply to its provider (the rest are null), `created_at_millis`, `access_verified`, and \-- for an `STORAGE_AWS_ROLE_ARN` integration -- the generated AWS policy documents from [above](#trust). No call ever returns a Secret's value, only the reference naming it. ## SHOW STORAGE INTEGRATIONS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW STORAGE INTEGRATIONS SHOW STORAGE INTEGRATIONS IN platform LIST STORAGE INTEGRATIONS ``` `LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` narrows the listing to one namespace. ## DROP STORAGE INTEGRATION ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP STORAGE INTEGRATION raw DROP STORAGE INTEGRATION IF EXISTS raw ``` Returns `dropped`, `true` or `false`. There is no `ALTER STORAGE INTEGRATION`: to rotate a credential, rotate the Secret it references (see [Secret](/oss/v0-41-0/sql/ddl/secret)) rather than dropping and recreating the integration. A storage integration an attached database still depends on blocks the drop; detach the database first. ## GRANT and REVOKE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} GRANT CREATE STORAGE INTEGRATION ON SCHEMA platform TO ROLE platform_admins GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research GRANT OWNERSHIP ON STORAGE INTEGRATION platform.hub TO ROLE platform_admins REVOKE USAGE ON STORAGE INTEGRATION platform.hub FROM ROLE research ``` `CREATE_STORAGE_INTEGRATION` on the namespace creates one; `USAGE` on the integration itself lets a query match and read through it; `OWNERSHIP` grants full control, including dropping it. See [Privileges](/oss/v0-41-0/governance/privileges#sql) for the full statement syntax, every grantee form, and how a query picks a matching integration without naming one. ## What to read next > [card] [Inspect Datasets](/oss/v0-41-0/curation/inspect-datasets) > > Query and import HuggingFace or object-storage datasets, the most common use of a storage integration today. > [card] [Secret](/oss/v0-41-0/sql/ddl/secret) > > The credential storage integration options reference. > [card] [Privileges](/oss/v0-41-0/governance/privileges) > > Every privilege, and the grant and revoke syntax that covers each one. # Table Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/table CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE. **Applies to:** Embedded ❌, Enterprise ✅ ## CREATE TABLE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents (id BIGINT, title VARCHAR, created_at TIMESTAMP) CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ``` Column types are Arrow types under SQL names. See [Data types](/oss/v0-41-0/sql/data-types). A table inside a [namespace](/oss/v0-41-0/sql/ddl/namespace) is written with its [schema](/oss/v0-41-0/basics/catalog#schema) before the name: `` `prod$events`.clicks ``. ## DESCRIBE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE documents ``` The table's columns and types, without a plan. The SQL counterpart of `table.schema`. ## ALTER TABLE What `ALTER TABLE ... ADD COLUMN` does depends on what follows the column name. ### A plain column SQL `ADD COLUMN` requires an `AS` binding, so a plain column such as `ALTER TABLE t ADD COLUMN c INT` is rejected. Add an empty, nullable column with the SDK instead. See [Add nullable columns](/oss/v0-41-0/management/table#schema-add-nullable-columns). ### A computed column ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN doubled AS value * 2 ``` `AS <expression>` declares a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column). The column is committed empty and the expression is stored, not evaluated: declaring one on a billion-row table costs what declaring one on an empty table costs. [`REFRESH COLUMN`](/oss/v0-41-0/sql/dml/refresh-column) fills it. ### A function column ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN embedded AS embed(name) WITH (version = 'fv_1') ``` When the expression calls a [registered function](/oss/v0-41-0/sql/ddl/function), the column is filled by running that function on workers. `version` pins which immutable function version fills it, so a later registration does not silently change what the column means. Several modifiers narrow what gets computed: | | | | - | - | | `FILTER (WHERE pred)` | only rows matching `pred` are computed | | `IGNORE NULLS` | rows with null inputs are skipped | | `OVER (PARTITION BY col)` | the function sees rows grouped by `col` | A function returning several values fills several columns at once: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN (label, score) AS classify(text) WITH (version = 'fv_1') ``` ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t ADD COLUMN c AS f(x) FILTER (WHERE keep) WITH (version = 'fv_1') REFRESH COLUMN c ON t WITH (num_workers = 2) ``` > [!NOTE] > > Declaration `WITH` accepts `auto_refresh_enabled` and > `auto_refresh_interval_seconds`. Function bindings also accept `version` and > `branch`. Worker resource options such as `num_workers` belong on > `REFRESH COLUMN ... WITH (...)`. ### Table properties ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t SET UNENFORCED PRIMARY KEY (id) ``` Records which column identifies a row. **Unenforced** is not a hedge in the naming: uniqueness is not checked on write, and declaring it does not make duplicates impossible. It tells the planner what to assume. The column must be declared `NOT NULL`. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ALTER TABLE t SET RTE ALTER TABLE t SET RTE WITH (sharding = 'bucket', column = 'id', buckets = 4) ALTER TABLE t SET RTE WITH (maintained_indexes = '') ALTER TABLE t UNSET RTE ``` The [real time engine](/oss/v0-41-0/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be the table's unenforced primary key, and inserts into the table then need a scalar index on that key. `maintained_indexes` chooses which indexes are kept current against WAL rows; omitted, every supported index is kept current, including ones created later. A table with a computed column cannot take a write-ahead log. See [RTE Compaction](/oss/v0-41-0/enterprise/realtime-engine-compaction) for how the log gets folded back into the table. > [!WARNING] > > [`TABLESAMPLE`](/oss/v0-41-0/sql/dql/sampling) is refused on a WAL-backed table, because > rows a sample would draw from are not all in the fragments yet. ### Errors and limits | | | | - | - | | `ALTER TABLE ... DROP COLUMN` | not supported | Dropping, renaming, or retyping a column is an SDK operation ([`drop_columns`](/oss/v0-41-0/management/table#schema) and [`alter_columns`](/oss/v0-41-0/management/table#schema)), not a SQL statement. ## CLONE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE docs_snapshot CLONE documents CREATE TABLE docs_at_v42 CLONE documents AT 42 CREATE TABLE docs_at_release CLONE documents AT TAG 'release-1' CREATE TABLE docs_yesterday CLONE documents AT TIMESTAMP '2026-09-01T00:00:00Z' ``` A **shallow clone**: the new table shares the source's data files rather than copying them, so it costs one metadata commit regardless of the source's size. `AT` pins the point in the source's history to clone. A bare integer is a version and a bare quoted string is a timestamp; `VERSION`, `TAG` and `TIMESTAMP` say so explicitly, and a tag always needs its keyword: a bare quoted string cannot be both a tag name and a timestamp. > [!WARNING] > > The clone depends on the source's files continuing to exist. If the source is > [compacted](/oss/v0-41-0/maintenance/cleanup) past the retention window, the version the > clone points at can be pruned. The SDK's > [`clone_table`](/oss/v0-41-0/management/table#rename-clone) also offers a deep clone for > when the copy has to outlive the source's history. ## DROP TABLE ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP TABLE documents ``` > [!WARNING] > > Removes the table and every version of it. There is no undrop. > [!NOTE] > > **Enterprise job type:** `drop_table` or `drop_object`, depending on how the > deployment stores its catalog. See > [Object teardown](/oss/v0-41-0/basics/jobs#teardown). ## What to read next > [card] [Table](/oss/v0-41-0/management/table) > > The SDK equivalent, and what a table carries. > [card] [Schema evolution](/oss/v0-41-0/management/table#schema) > > Renaming, retyping and dropping columns from the SDK. # View Source: https://docs.lancedb.com/oss/v0-41-0/sql/ddl/view Create, describe, list, and drop saved queries with SQL. **Applies to:** Embedded ❌, Enterprise ✅ A view stores a **query**, not rows. Reading it runs the query against current data, so a view is never stale, and never faster than the query it wraps. It is the counterpart to a [materialized view](/oss/v0-41-0/sql/ddl/materialized-view), which stores rows and is brought up to date by a refresh; both are [catalog objects](/oss/v0-41-0/basics/catalog) defined by a query, differing only in when that query runs. The SDK methods `create_view`, `describe_view`, `list_views`, and `drop_view` submit SQL through the connection's Flight endpoint. `drop_view_async` returns a job of type `query` whose single `id` is the SQL query UUID. Waiting confirms catalog removal; physical cleanup can continue afterward. ## CREATE VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE VIEW "recent_matches" AS SELECT t1.floats FROM "documents" AS t1 INNER JOIN "categories" AS t2 ON t1.ints = t2.ints ``` The statement returns one row with UTF-8 `name`, `query`, and `schema` columns. `query` contains the stored query, including any declared column aliases, and `schema` contains its Arrow schema as JSON. The schema metadata keys `lancedb::view::default_db` and `lancedb::view::default_namespace` identify the defining database and namespace. The root namespace is `public`; nested namespace components are separated by `$`. `DESCRIBE VIEW "recent_matches"` returns the same metadata shape. Anything the [dialect](/oss/v0-41-0/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions. ## Reading one A view is queried like a table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM "recent_matches" WHERE floats > 0.5 ``` Predicates applied to the view compose with the query inside it rather than filtering its output afterwards, so a selective filter does not pay for rows the view would have produced and then discarded. ## DROP VIEW ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DROP VIEW "recent_matches" ``` Removes the saved query. Unlike dropping a table, no data is removed: there was none to begin with. ## Listing ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW VIEWS SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 ``` `SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to the selected namespace. Object commands retain their small results in shared storage even when general query-result copying is disabled, so asynchronous polling can use any query node. Views and tables share a namespace, and both are things you can query. The catalog distinguishes them: | | | | - | - | | view names | the views in the database | | table names | the tables | | relation names | everything queryable (both) | Use the relation listing when the question is "what can I select from," and the separate listings when the distinction matters: before dropping, for instance, since dropping a view removes only the saved query while dropping a table removes data. ## Choosing between a view and a materialized view | | View | Materialized view | | - | - | - | | Stores | the query | the rows | | Freshness | always current | as of the last refresh | | Read cost | the full query, every read | a table scan | | Write cost | none | a refresh | Reach for a **view** when the query is cheap, or when reading stale rows would be wrong. Reach for a **materialized view** when the query is expensive and the data changes less often than it is read. The privileges are separate too: `CREATE_VIEW` and `CREATE_MATERIALIZED_VIEW` are distinct grants on a namespace, so the ability to create one does not imply the other. See [Authorization](/oss/v0-41-0/governance/authorization). ## What to read next > [card] [Materialized View](/oss/v0-41-0/sql/ddl/materialized-view) > > The stored-rows counterpart. > [card] [Management](/oss/v0-41-0/management) > > Where views fit among the other catalog objects. # Copy Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/copy COPY ... TO: writing a query result to object storage as files. > [!WARNING] > > Recent deployment versions refuse `COPY` over the SQL endpoint with "COPY is not > supported". On those, export a result by reading it through a Flight SQL client > or an SDK and writing the files from your application. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} COPY (SELECT id, title FROM documents) TO 's3://bucket/export/' STORED AS PARQUET ``` Writes a query result to object storage. This is the export path when the consumer is another engine rather than an application: results land as files rather than streaming to a client. ## What to read next > [card] [Insert](/oss/v0-41-0/sql/dml/insert) > > Bringing rows in, rather than exporting them. # Delete Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/delete DELETE FROM ... WHERE: rows are marked, not erased. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DELETE FROM documents WHERE created_at < TIMESTAMP '2025-01-01 00:00:00' ``` Compare a timestamp column with a typed literal, as above, or with `CAST('2025-01-01' AS TIMESTAMP)`. A bare string such as `'2025-01-01'` is rejected in a `DELETE` predicate, even though a `SELECT` accepts it. Deletion marks rows rather than erasing them, so the data remains recoverable for as long as the version holding it survives [retention](/oss/v0-41-0/maintenance/cleanup). Commits a new table version, so [versioning](/oss/v0-41-0/management/table#versioning) and the [write guarantees](/oss/v0-41-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Delete](/oss/v0-41-0/ingestion/delete) > > The SDK equivalent. # Insert Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/insert INSERT INTO, including INSERT ... SELECT to move rows server-side. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSERT INTO documents (id, title) VALUES (1, 'Merlin'), (2, 'Arthur') INSERT INTO archive SELECT * FROM documents WHERE created_at < '2026-01-01' ``` `INSERT ... SELECT` is the form worth knowing: it moves rows between tables server-side, without a round trip through your process. Commits a new table version, so [versioning](/oss/v0-41-0/management/table#versioning) and the [write guarantees](/oss/v0-41-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Insert](/oss/v0-41-0/ingestion/insert) > > The SDK equivalent. > [card] [Merge Insert](/oss/v0-41-0/ingestion/merge-insert) > > Upsert (matching incoming rows against existing keys) has no SQL form. # Update Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/update UPDATE ... SET ... WHERE, and why it does not recompute derived columns. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} UPDATE documents SET title = upper(title) WHERE category = 'film' ``` Assignments take any expression the [dialect](/oss/v0-41-0/sql/dql/functions) supports, including references to other columns of the same row. Without a `WHERE` clause every row is updated. > [!WARNING] > > An update does not recompute [computed columns](/oss/v0-41-0/feature-engineering/add-computed-column) > that derive from the column you changed. Those rows keep the value computed from > the old input until the next refresh recomputes them. See > [Guarantees](/oss/v0-41-0/basics/guarantees#jobs). Commits a new table version, so [versioning](/oss/v0-41-0/management/table#versioning) and the [write guarantees](/oss/v0-41-0/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next > [card] [Update](/oss/v0-41-0/ingestion/update) > > The SDK equivalent. # SQL reference Source: https://docs.lancedb.com/oss/v0-41-0/sql/index SQL statements, expressions and data types supported by LanceDB Enterprise. LanceDB Enterprise supports SQL through an Arrow Flight SQL endpoint. This reference covers statement syntax, data types and expressions. To set up a client and run your first query, see [SQL](/oss/v0-41-0/basics/sql). ## The dialect LanceDB uses [Apache DataFusion](https://datafusion.apache.org) for SQL planning and execution. These pages describe LanceDB's supported statements and extensions. DataFusion's reference is useful for expression syntax, but does not establish that every DataFusion statement or feature is exposed by LanceDB. ## Connecting Use Python's `execute_query` or a Flight SQL client after configuring the [Enterprise connection](/oss/v0-41-0/basics/sql#sql-is-remote). TypeScript applications use a Flight SQL client for SQL queries. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} reader = db.execute_query("SELECT id, text FROM my_docs LIMIT 10") for batch in reader: print(batch) ``` SQL results arrive as Arrow record batches. Iterating over the reader avoids collecting the entire result in application memory. See [Read and manage results](/oss/v0-41-0/basics/sql#results) for more. ## Usage The endpoint executes one statement per request and is meant for the queries and DDL/DML pages below. Reach for the SDKs instead for table-management operations that have no SQL form, such as a merge insert. See [What SQL cannot do](#cannot). ## Reference ### DDL, by object | | | | - | - | | [Database](/oss/v0-41-0/sql/ddl/database) | `CREATE`, `DESCRIBE`, `SHOW`, `ATTACH`, `DROP DATABASE` | | [Namespace](/oss/v0-41-0/sql/ddl/namespace) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SCHEMA`/`NAMESPACE` | | [Table](/oss/v0-41-0/sql/ddl/table) | `CREATE`, `DESCRIBE`, `ALTER`, `CLONE`, `DROP TABLE` | | [View](/oss/v0-41-0/sql/ddl/view) | `CREATE VIEW`, `DROP VIEW` | | [Materialized view](/oss/v0-41-0/sql/ddl/materialized-view) | `CREATE MATERIALIZED VIEW`, `SHOW MATERIALIZED VIEWS` | | [Secret](/oss/v0-41-0/sql/ddl/secret) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SECRET` | | [Storage Integration](/oss/v0-41-0/sql/ddl/storage-integration) | `CREATE`, `DESCRIBE`, `SHOW`, `DROP STORAGE INTEGRATION` | | [Index](/oss/v0-41-0/sql/ddl/index) | `CREATE INDEX`, `DROP INDEX` | | [Function](/oss/v0-41-0/sql/ddl/function) | `CREATE FUNCTION`, `SHOW FUNCTIONS`, `DROP FUNCTION` | | [Job](/oss/v0-41-0/sql/ddl/job) | `SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB`, `SHOW ERRORS`, `PAUSE`/`RESUME`/`CANCEL JOB` | ### DML | | | | - | - | | [Insert](/oss/v0-41-0/sql/dml/insert) | `INSERT INTO`, including `INSERT ... SELECT` | | [Update](/oss/v0-41-0/sql/dml/update) | `UPDATE ... SET` | | [Delete](/oss/v0-41-0/sql/dml/delete) | `DELETE FROM` | | [Copy](/oss/v0-41-0/sql/dml/copy) | `COPY` (refused by recent deployment versions) | | [Refresh column](/oss/v0-41-0/sql/dml/refresh-column) | filling a computed column | | [Refresh materialized view](/oss/v0-41-0/sql/dml/refresh-materialized-view) | bringing a view's stored result up to date | ### DQL | | | | - | - | | [Data types](/oss/v0-41-0/sql/data-types) | how Lance columns appear to SQL, and pseudo-columns | | [Select](/oss/v0-41-0/sql/dql/select) | projection, filtering, ordering, set operations, CTEs | | [Subqueries](/oss/v0-41-0/sql/dql/subqueries) | scalar, `IN`, `EXISTS`, correlated, derived tables | | [Joins](/oss/v0-41-0/sql/dql/join) | inner, outer, cross, and namespace-qualified paths | | [Aggregation](/oss/v0-41-0/sql/dql/aggregation) | `GROUP BY`, `HAVING`, the aggregate set | | [Window functions](/oss/v0-41-0/sql/dql/window) | `OVER`, framing, ranking and offset functions | | [Sampling](/oss/v0-41-0/sql/dql/sampling) | `TABLESAMPLE`, by rows or by fragments | | [Changes](/oss/v0-41-0/sql/dql/changes) | `CHANGES`: rows appended since an earlier version | | [Full-Text Search](/oss/v0-41-0/sql/dql/fts) | the `fts()` table function, and its query forms | | [Operators](/oss/v0-41-0/sql/dql/operators) | comparison, logical, arithmetic, literals, precedence | | [Functions](/oss/v0-41-0/sql/dql/functions) | where to find each kind, and table functions | | [Scalar functions](/oss/v0-41-0/sql/dql/scalar-functions) | the per-row catalogue, and what Lance accelerates | | [Explain](/oss/v0-41-0/sql/dql/explain) | `EXPLAIN`, `EXPLAIN ANALYZE`, `EXPLAIN VERBOSE` | ## SQL limitations and alternatives | | | | - | - | | Vector search | See [SQL vector search](/oss/v0-41-0/basics/sql#no-vector-sql) for supported query forms and server-version requirements. The [SDK query builder](/oss/v0-41-0/search/vector-search) also supports vector search. | | Merge insert | no SQL form: it needs a source relation and a per-match policy | | `information_schema` | not enabled, so `SHOW TABLES` and `SHOW COLUMNS` fail | | `COPY` | refused by recent deployment versions (see [Copy](/oss/v0-41-0/sql/dml/copy)) | | `PREPARE` / `EXECUTE` | preparation is a [protocol feature](/oss/v0-41-0/basics/sql#prepared-statements), not a statement | | Run on a local database | no engine to plan the statement | See [Limits](/oss/v0-41-0/basics/limits#sql) for the bounds these pages enforce. # Checkpointing Source: https://docs.lancedb.com/oss/v0-41-0/training/checkpointing Save StreamingDataset's read position alongside your model, so a failed run can pick back up. **Applies to:** Embedded ✅, Enterprise ✅ [`StreamingDataset`](/oss/v0-41-0/training/data-loading) provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, save it alongside your model weights, and `load_state_dict()` to restore the last saved position -- see [Resuming](/oss/v0-41-0/training/resuming) for the load side. This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` terminology from [Distributed Training](/oss/v0-41-0/training/distributed-training#parallelism-and-elasticity). A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset global_batch_size = 48 # one sample per split in each global step batch_size = global_batch_size // world_size dataset = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, num_workers=0, ) for step, batch in enumerate(dataloader): train_step(batch) if (step + 1) % checkpoint_interval == 0: torch.save( {"model": model.state_dict(), "dataset": dataset.state_dict()}, f"checkpoint_{step + 1}.pt", ) ``` ## Checkpointing with Multiple DataLoader Workers Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.streaming import StreamingDataset, StreamingDataLoader dataset = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) dataloader = StreamingDataLoader( dataset, batch_size=batch_size, num_workers=4, ) for step, batch in enumerate(dataloader): train_step(batch) if (step + 1) % checkpoint_interval == 0: torch.save( {"model": model.state_dict(), "dataset": dataset.state_dict()}, f"checkpoint_{step + 1}.pt", ) ``` `StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: * `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). * `in_order = True` is required so that consumer-committed checkpoints stay deterministic. * `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. * `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches first. ## Next steps > [card] [Resuming](/oss/v0-41-0/training/resuming) > > Load a saved checkpoint back, on the same or a different topology. > [card] [Distributed Training](/oss/v0-41-0/training/distributed-training) > > The rank, world size and split terminology checkpointing builds on. # PyTorch Data Loader Source: https://docs.lancedb.com/oss/v0-41-0/training/data-loading Stream, shuffle, transform, and resume model training data with StreamingDataset. **Applies to:** Embedded ✅, Enterprise ✅ Advanced data loading scenarios can be handled by the `StreamingDataset`. This object allows you to apply preprocessing before training, pipelined reads, and more. Use this when the training data does not fit in memory, or when you need deterministic global batches across cluster sizes. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset db = lancedb.connect("file://some/db/path") table = db.open_table("some_table") dataset = StreamingDataset(table, shuffle_seed=42) dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, num_workers=0, ) for batch in dataloader: train_step(batch) ``` The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. > [!NOTE] > > `StreamingDataset` is built on the [`Permutation`](/oss/v0-41-0/training/permutation) API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage. ## Filtering The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. You can also use the `columns` parameter to load only a subset of columns. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ds = StreamingDataset( table, shuffle_seed=42, columns=["image", "label"], # skip all other columns filter="category = 'train'", # only training rows ) ``` ## Shuffling Rows In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. > [!NOTE] > > `StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs > with the same inputs remain reproducible. Set `shuffle_seed = None` to generate a random seed upon pipeline initialization. ### Row-Level Shuffle By default, `shuffle_clump_size` is `None` and rows are shuffled individually: the rows of the source dataset are shuffled according to a pseudorandom permutation, then fed in batches to the accelerator. This gives the best possible randomness, but can exhibit low throughput. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1-phase shuffled read: rows shuffled individually. for epoch in range(num_epochs): ds = StreamingDataset( table, shuffle_seed=42, epoch=epoch, # changes the permutation each epoch ) for sample in ds: train_step(sample) #Evaluation: deterministic sequential order, no shuffle. eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` ### Clumped Shuffle Setting `shuffle_clump_size` to an integer shuffles contiguous groups ("clumps") of that many rows instead of single rows. Each clump keeps its rows in storage order and moves as a unit, so storage I/O consists mostly of contiguous reads rather than single-row fetches. Larger clumps improve I/O locality, which matters most on object storage, at the cost of randomness. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Clumped shuffled read: rows are shuffled in groups of contiguous rows # instead of individually, trading a bit of randomness for much cheaper I/O. for epoch in range(num_epochs): ds = StreamingDataset( table, shuffle_seed=42, epoch=epoch, shuffle_clump_size=1024, # contiguous rows that move together ) for sample in ds: train_step(sample) # Evaluation: deterministic sequential order, no shuffle. eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` ## Fetching Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). In addition to batching requests, the prefetching mechanism reads ahead in the background. While one batch is being processed, `StreamingDataset` reads several subsequent batches. The `io_queue_depth` parameter specifies the number of batches simultaneously kept in flight per split (default = `4`); it replaces `prefetch_batches`, which still works but is deprecated. A larger value provides more buffering against jittery workloads, but also increases memory use and I/O concurrency. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ds = StreamingDataset( table, shuffle_seed=42, read_batch_size=256, # rows fetched per LanceDB call per split io_queue_depth=8, # batches to keep in flight per split ) ``` ## Transforming Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. A transformation function must receive a PyArrow `RecordBatch` and return an iterable. For example, the default transform function returns a list of Python dictionaries. Furthermore, the input expected by PyTorch must match the collation function used in the PyTorch data loader. PyTorch's default collation function accepts a Python dictionary and several other types, and is thus compatible with the default `StreamingDataset` transform function. If your custom transform function returns something different (for example, Arrow record batches), you may need to provide a compatible PyTorch collation function. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa def normalize(batch: pa.RecordBatch) -> list[dict]: # This pure-Python loop holds the GIL and is shown for illustration only. # In practice, prefer a library like torchvision or numpy that releases the # GIL so the ThreadPoolExecutor can run transforms in parallel. rows = batch.to_pylist() for row in rows: row["image"] = [v / 255.0 for v in row["image"]] return rows ds = StreamingDataset(table, shuffle_seed=42, transform=normalize) ``` `StreamingDataset` manages expensive transforms through a `ThreadPoolExecutor` whose worker count equals the number of available CPUs (`transform_parallelism`). Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. Heavier per-sample work belongs in the same function, such as decoding video. Store each clip in a Blob v2 column (`lancedb.blob("video")`). A scan returns small descriptors instead of the video bytes, so reading other columns never pulls video in. `fetch_blob_files` opens the clips for a batch of rows as file handles, and `torchcodec`'s `VideoDecoder` decodes just the frames you ask for. `ExtractFrames` samples 8 evenly spaced frames from each clip: ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import functools from torchcodec.decoders import VideoDecoder class ExtractFrames: def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: self.uri, self.name, self.num_frames = uri, name, num_frames @functools.cached_property def table(self) -> lancedb.table.Table: return lancedb.connect(self.uri).open_table(self.name) def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: samples = [] for blob in self.table.fetch_blob_files("video", rb["_rowid"]): decoder = VideoDecoder(blob) idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) return samples # `clips` is the table "clips" in the database at `uri`, with a Blob v2 column "video" train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) ``` Real data has bad rows, such as a truncated frame. Raise inside the transform and set `on_transform_error="skip"` (or `"warn"` to log each failure). `StreamingDataset` re-runs the failing batch one row at a time, drops only the rows that raise, and counts them in `dataset.rows_skipped`. When the bad rows match a SQL predicate, prefer `filter=` instead: it runs before the splits are built, so every split keeps the same length. ### DataLoader Workers The thread-based transformation model that `StreamingDataset` uses by default is only effective when the transform function releases the GIL. This is true for many Python scientific libraries, including NumPy, PyArrow, and TorchVision, but not for pure-Python transforms. PyTorch can launch multiple DataLoader worker processes per rank, and `StreamingDataset` uses `get_worker_info()` to give each worker a non-overlapping group of splits. Multiprocessing adds pickling and transfer overhead and increases memory use. Start with `num_workers=0`, which keeps loading in the rank's main process, and add workers only after confirming an unavoidable GIL bottleneck. If you use workers, `num_splits` must be divisible by `world_size * num_workers`. Use the `forkserver` or `spawn` multiprocessing context because LanceDB uses internal threads. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, num_workers=2, multiprocessing_context="forkserver", persistent_workers=True, ) ``` By default, `StreamingDataset` serializes enough table state to reopen the table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the same way: workers reopen the table from the pickled connection state. Replace the URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager: ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.util import tbl_to_tensor db = lancedb.connect( "db://my-database", api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", ) table = db.open_table("my_table") dataloader = torch.utils.data.DataLoader( table, batch_size=512, num_workers=4, multiprocessing_context="forkserver", collate_fn=tbl_to_tensor, ) ``` > [!NOTE] > > This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. #### Providing a custom connection factory For custom connection setup, pass a picklable `connection_factory` callable that accepts a table name and returns an open table. This avoids serializing connection credentials into worker state: it loads the API key inside each worker instead. Set it in the shell before starting the Python program, then replace the database URI, region and endpoint in the factory with your deployment details: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_API_KEY="your-api-key" ``` ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import torch from lancedb.permutation import Permutation def open_table(name: str): db = lancedb.connect( "db://my-database", api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-endpoint", ) return db.open_table(name) table = open_table("my_table") permutation = ( Permutation.identity(table) .with_connection_factory(open_table) ) dataloader = torch.utils.data.DataLoader( permutation, batch_size=512, num_workers=4, multiprocessing_context="forkserver", ) ``` ## Next steps > [card] [Permutation](/oss/v0-41-0/training/permutation) > > The lower-level row ordering StreamingDataset is built on. > [card] [Observability](/oss/v0-41-0/training/observability) > > Pipeline counters for diagnosing loader bottlenecks. > [card] [Distributed Training](/oss/v0-41-0/training/distributed-training) > > Multi-GPU sharding and elastic determinism. > [card] [Checkpointing](/oss/v0-41-0/training/checkpointing) > > Save progress so a failed run can pick back up. > [card] [Training Cache](/oss/v0-41-0/training/training-cache) > > How an Enterprise connection speeds up repeated epochs. # Distributed Training Source: https://docs.lancedb.com/oss/v0-41-0/training/distributed-training Shard StreamingDataset across ranks and workers, with elastic determinism across topologies. **Applies to:** Embedded ✅, Enterprise ✅ To understand the wide range of scenarios handled by [`StreamingDataset`](/oss/v0-41-0/training/data-loading) across a distributed job, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism (DDP). In this example, we need to load batches onto multiple GPUs across multiple servers. After each batch is processed, the GPUs exchange weights and the next batch is loaded. We fix the following terminology: * **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ GPUs each, the world size is $8$. * **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. Each rank is allocated a disjoint portion of the source data. * **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. * **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. Other concepts, such as read batch size and `num_workers`, are introduced in [PyTorch Data Loader](/oss/v0-41-0/training/data-loading). ## Parallelism & Elasticity When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` (the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, and `epoch`. The following constraints apply: * `num_splits` must be divisible by `world_size`. * With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. * For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of `num_splits`. * The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to `num_splits - 1` surplus rows are dropped so that every split has the same length. For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch.distributed as dist from lancedb.streaming import StreamingDataset dist.init_process_group("nccl") rank = dist.get_rank() world_size = dist.get_world_size() # num_splits=48 is divisible by many integers, # so this dataset works unchanged as you add or remove GPUs. ds = StreamingDataset( table, num_splits=48, shuffle_seed=42, epoch=current_epoch, rank=rank, world_size=world_size, ) for sample in ds: train_step(sample) ``` ## Next steps > [card] [Checkpointing](/oss/v0-41-0/training/checkpointing) > > Save progress so a failed run can pick back up. > [card] [Resuming](/oss/v0-41-0/training/resuming) > > Load a saved checkpoint back, on the same or a different topology. # Observability Source: https://docs.lancedb.com/oss/v0-41-0/training/observability Pipeline counters for diagnosing StreamingDataset bottlenecks. **Applies to:** Embedded ✅, Enterprise ✅ Optimizing data loader performance can be tricky, as runtime bottlenecks are often difficult to locate across various stages of the I/O and CPU pipelines. To help distinguish bottlenecks, [`StreamingDataset`](/oss/v0-41-0/training/data-loading) exposes several pipeline counters: `raw_queue_depth` shows the number of loaded rows waiting to be transformed, and `prefetch_queue_depth` is the number of transformed rows ready to be consumed. `unscanned_rows` and `consumed_rows` show how far the current iterator has progressed. If the `prefetch_queue_depth` is consistently zero but the `raw_queue_depth` is not, then you likely have a CPU transformation bottleneck. You should investigate GIL bottlenecks or look for ways to optimize your transformation. This can often be done by batching the compute work. If both `prefetch_queue_depth` and `raw_queue_depth` are consistently zero while the consumer is waiting, I/O is the likely bottleneck. A larger read batch size or clumped shuffling could help. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import threading, time from lancedb.streaming import StreamingDataset ds = StreamingDataset(table, shuffle_seed=42) def log_pipeline_health(): while True: print( f"unscanned={ds.unscanned_rows} " f"raw={ds.raw_queue_depth} " f"cooked={ds.prefetch_queue_depth} " f"consumed={ds.consumed_rows}" ) time.sleep(1.0) monitor = threading.Thread(target=log_pipeline_health, daemon=True) monitor.start() for sample in ds: train_step(sample) print( f"bytes loaded: {ds.bytes_loaded} " f"fetch time: {ds.fetch_time:.2f}s " f"transform time: {ds.transform_time:.2f}s" ) ``` `bytes_loaded` measures raw Arrow buffer bytes before transformation. `bytes_loaded`, `fetch_time`, and `transform_time` are cumulative across iterations of the same dataset instance; because work runs concurrently, the summed stage times can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters reflect the latest iterator snapshot. ## Next steps > [card] [PyTorch Data Loader](/oss/v0-41-0/training/data-loading) > > Stream, shuffle and transform training data with StreamingDataset. > [card] [Checkpointing](/oss/v0-41-0/training/checkpointing) > > Save progress so a failed run can pick back up. # Permutation Source: https://docs.lancedb.com/oss/v0-41-0/training/permutation The low-level, customizable row ordering that StreamingDataset is built on. **Applies to:** Embedded ✅, Enterprise ✅ Most model training frameworks feed data into a model by sequencing through successive batches, a process often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation db = lancedb.connect("file://some/db/path") table = db.open_table("some_table") for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): print(batch.to_pydict()) ``` In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full [`StreamingDataset`](/oss/v0-41-0/training/data-loading) object. In these cases, use `Permutation`, the lower-level functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` and batched access through `__getitems__()`. ## Version Pinning A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows that existed when it was built, and rows appended to the base table afterwards are not visible through the existing permutation. To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) against the updated table. Permutations written before this behavior shipped continue to read as they did before. ## Output formats By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a column-major `torch.Tensor` with shape `(columns, rows)`. `Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` with one of the transform formats described below. To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, `pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and `torch` formats will all require at least one full copy of the data and are the slowest options. ### Using the torch column format with a torch data loader The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the entire Arrow batch to a *column-major* `torch.Tensor`. In other words, given C columns and R rows, the resulting Tensor will have shape `(C, R)`. However, this format generates an error if you are using a `torch.utils.data.DataLoader` with the default collation function: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor ``` This error occurs because the default collation function does not currently expect a single two-dimensional tensor. It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function in addition to specifying the `torch_col` format. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation permutation = Permutation.identity(table).with_format("torch_col") dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` This will now output a single two-dimensional tensor for each batch. ## Selecting columns By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need a subset of columns, you can significantly reduce your I/O requirements by selecting only the columns you need. The `Permutation` class provides a `select_columns` method that provides this functionality. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import torch from lancedb.permutation import Permutation db = lancedb.connect("memory://") prompts = db.create_table( "prompts", pa.table( { "id": range(4), "prompt": ["north", "south", "east", "west"], "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], } ), ) permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) dataloader = torch.utils.data.DataLoader( permutation, batch_size=1024, shuffle=True ) for batch in dataloader: print(sorted(batch)) # ['id', 'prompt']: the embedding is never read ``` Each batch is a dict of the selected columns, the default `Permutation` format described above. # Resuming Source: https://docs.lancedb.com/oss/v0-41-0/training/resuming Load a saved StreamingDataset checkpoint back, on the same topology or a different one. **Applies to:** Embedded ✅, Enterprise ✅ Resuming loads a `StreamingDataset` checkpoint saved by [Checkpointing](/oss/v0-41-0/training/checkpointing) back into a fresh dataset and `DataLoader`, so a failed or restarted run picks up where it left off rather than rereading from the start. This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` terminology from [Distributed Training](/oss/v0-41-0/training/distributed-training#parallelism-and-elasticity). ## Resuming on the same topology ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch from lancedb.streaming import StreamingDataset checkpoint = torch.load("checkpoint_100.pt") model.load_state_dict(checkpoint["model"]) dataset_state = checkpoint["dataset"] dataset = StreamingDataset( table, num_splits=dataset_state["num_splits"], shuffle_seed=dataset_state["shuffle_seed"], epoch=dataset_state["epoch"], rank=rank, world_size=world_size, # same as the run that saved the checkpoint ) dataset.load_state_dict(dataset_state) # The combined batch size across every rank, the same value used when the # checkpoint was saved; each rank's DataLoader gets its world_size share of it. global_batch_size = 48 dataloader = torch.utils.data.DataLoader( dataset, batch_size=global_batch_size // world_size, num_workers=0, ) for batch in dataloader: train_step(batch) ``` `load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings, and keep `world_size` the same -- changing it is a topology change, covered next. The number of DataLoader workers may still change as long as the batch-size divisibility constraints from [Distributed Training](/oss/v0-41-0/training/distributed-training#parallelism-and-elasticity) hold. ## Resuming Across Different Topologies When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with `StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, regardless of whether the topology grew, shrank, or stayed the same. ```py Python icon=Python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # On each rank of the previous run: state = dataset.state_dict() # ...gather `state` from every rank into a single list `states` (for example # via torch.distributed all-gather or by saving one file per rank). merged = StreamingDataset.merge_state_dicts(states) # On each rank of the resumed run (world_size may differ): dataset = StreamingDataset( table, num_splits=merged["num_splits"], shuffle_seed=merged["shuffle_seed"], epoch=merged["epoch"], rank=rank, world_size=new_world_size, ) dataset.load_state_dict(merged) ``` ## Next steps > [card] [Checkpointing](/oss/v0-41-0/training/checkpointing) > > Save progress, including with multiple DataLoader workers. > [card] [Distributed Training](/oss/v0-41-0/training/distributed-training) > > The rank, world size and split terminology resuming builds on. # Training Cache Source: https://docs.lancedb.com/oss/v0-41-0/training/training-cache Connect the PyTorch data loader to LanceDB Enterprise and training reads automatically benefit from the plan executor's data page cache. **Applies to:** Embedded ❌, Enterprise ✅ The [PyTorch data loader](/oss/v0-41-0/training/data-loading) reads training data the same way any other query does -- there is no training-specific read path. Point `StreamingDataset` or a `DataLoader` at a table opened through an Enterprise connection instead of a local one, and every read it makes flows through the same [plan executors](/oss/v0-41-0/enterprise/data-page-cache) that serve every other query, with the same data page cache in front of object storage. No training-specific configuration turns this on; it's a consequence of connecting to Enterprise at all. ```mermaid theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader<br/>/ StreamingDataset"] --> T["Enterprise-connected table"] T --> PE["Plan executor"] PE --> C{"In data page cache?"} C -->|hit| Fast["Served from memory<br/>or local disk"] C -->|miss| O[("Object storage")] O --> Fill["Fills the cache,<br/>served"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 class Fast accent ``` This covers the ordinary tabular columns a query reads -- the data page cache's unit is a fixed-size page of table data. A [Blob v2](/oss/v0-41-0/management/table#managed-blobs) column's payload is fetched through a separate range-request path keyed to its own descriptor, not through this cache, so a training table mixing plain feature columns with Blob v2 images or video gets this benefit only for the former. A custom collate function or transform that does its own file or network I/O -- decoding an image, say -- is also outside this cache; only reads that go through the table query path benefit. ## Why this matters for training specifically Training reads the same rows repeatedly: once per epoch, often for many epochs. The first epoch's reads behave like any cold cache -- a miss per page, each one filling the cache on the way. Every epoch after that reads the same pages again, so a dataset that fits the cache's budget serves almost entirely from memory or local disk after the first pass, instead of re-reading object storage every epoch. A local-file or Embedded connection has no equivalent remote cache to warm this way -- its locality comes from whatever the local filesystem or OS page cache already does. [Cache Prewarm](/oss/v0-41-0/enterprise/cache-prewarm) extends this further: a plan executor can warm its cache at startup, before training even begins, instead of paying the first-epoch cold-cache cost during the run itself. ## What to read next > [card] [PyTorch Data Loader](/oss/v0-41-0/training/data-loading) > > Connecting a DataLoader to an Enterprise table. > [card] [Data Page Cache](/oss/v0-41-0/enterprise/data-page-cache) > > How the cache a training read benefits from actually works. > [card] [Cache Prewarm](/oss/v0-41-0/enterprise/cache-prewarm) > > Warming the cache before the first epoch instead of during it. # CIFAR-10 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/cifar10 A Lance-formatted version of CIFAR-10 covering 60,000 32×32 RGB images across ten balanced object classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/cifar10-lance) > > Source dataset card and downloadable files for `lance-format/cifar10-lance`. Each row carries inline PNG bytes, the integer label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/cifar10-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so class filters and class-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 50,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (32×32 RGB) | | `label` | `int32` | Class id (0–9) | | `label_name` | `string` | One of `airplane`, `automobile`, `bird`, `cat`, `deer`, `dog`, `frog`, `horse`, `ship`, `truck` | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the class id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/cifar10-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/cifar10-lance --repo-type dataset --local-dir ./cifar10-lance > ``` > > Then point LanceDB at `./cifar10-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query image (or, for cross-modal text→image lookup, a tokenized prompt) through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query class:", seed["label_name"]) for r in hits: print(f" id={r['id']:>5} {r['label_name']}") ``` Because CIFAR-10 has only ten classes and the embeddings are cosine-normalized, near-neighbors of a seed image cluster tightly inside the seed's own class. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for a classification workflow narrows the table to a single class (or a small set of confusable classes) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label_name IN ('cat', 'dog')", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} cat/dog candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_animal` flag and an `is_target_class` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./cifar10-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_animal": "label_name IN ('bird', 'cat', 'deer', 'dog', 'frog', 'horse')", "is_target_class": "label = 3", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([3, 8, 0], type=pa.int32()), "pred_conf": pa.array([0.91, 0.74, 0.99]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, apply augmentations, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./cifar10-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/cifar10-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('cat', 'dog')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./cifar10-cats-dogs") local_db.create_table("train", batches) ``` The resulting `./cifar10-cats-dogs` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/cifar10-lance/data` for `./cifar10-cats-dogs`. ## Source & license Converted from [`uoft-cs/cifar10`](https://huggingface.co/datasets/uoft-cs/cifar10). CIFAR-10 was collected by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton at the University of Toronto. ## Citation ``` @techreport{krizhevsky2009cifar10, title={Learning multiple layers of features from tiny images}, author={Krizhevsky, Alex and Hinton, Geoffrey}, year={2009}, institution={University of Toronto} } ``` # Fashion-MNIST Source: https://docs.lancedb.com/oss/v0-41-0/datasets/fashion-mnist A Lance-formatted version of Fashion-MNIST covering 70,000 28×28 grayscale clothing images across ten balanced apparel classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/fashion-mnist-lance) > > Source dataset card and downloadable files for `lance-format/fashion-mnist-lance`. Each row carries inline PNG bytes, the integer label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/fashion-mnist-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so apparel-class filters and class-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 60,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) | | `label` | `int32` | Class id (0–9) | | `label_name` | `string` | One of `T-shirt_top`, `Trouser`, `Pullover`, `Dress`, `Coat`, `Sandal`, `Shirt`, `Sneaker`, `Bag`, `Ankle_boot` | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | > The original Fashion-MNIST class strings `T-shirt/top` and `Ankle boot` are sanitized to `T-shirt_top` and `Ankle_boot` for use as filename-safe identifiers, so SQL filters on `label_name` should reference the underscored form. ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the class id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/fashion-mnist-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/fashion-mnist-lance --repo-type dataset --local-dir ./fashion-mnist-lance > ``` > > Then point LanceDB at `./fashion-mnist-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query image (or, for cross-modal text→image lookup, a tokenized prompt like "a black ankle boot") through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query class:", seed["label_name"]) for r in hits: print(f" id={r['id']:>5} {r['label_name']}") ``` Because the embeddings are cosine-normalized and CLIP separates apparel categories cleanly, near-neighbors of a seed image are typically dominated by the seed's own class, with the most confusable garments (Shirt vs T-shirt_top, Sneaker vs Sandal) showing up next. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for an apparel-classification workflow narrows the table to a confusable subset of classes (for example, the three upper-body garments that share silhouettes) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label_name IN ('Shirt', 'T-shirt_top', 'Pullover')", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} upper-body-garment candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_footwear` flag that groups the three shoe-like classes and an `is_target_class` flag for one-vs-rest experiments, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fashion-mnist-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_footwear": "label_name IN ('Sandal', 'Sneaker', 'Ankle_boot')", "is_target_class": "label = 6", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([9, 0, 3], type=pa.int32()), "pred_conf": pa.array([0.94, 0.81, 0.77]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, normalize to [0, 1], forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./fashion-mnist-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/fashion-mnist-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('Shirt', 'T-shirt_top', 'Pullover')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./fashion-mnist-upper-body") local_db.create_table("train", batches) ``` The resulting `./fashion-mnist-upper-body` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/fashion-mnist-lance/data` for `./fashion-mnist-upper-body`. ## Source & license Converted from [`zalando-datasets/fashion_mnist`](https://huggingface.co/datasets/zalando-datasets/fashion_mnist). Released under the MIT license. ## Citation ``` @online{xiao2017fashionmnist, title={Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms}, author={Xiao, Han and Rasul, Kashif and Vollgraf, Roland}, year={2017}, eprint={1708.07747}, archivePrefix={arXiv}, primaryClass={cs.LG} } ``` # Food-101 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/food101 A Lance-formatted version of Food-101, the fine-grained dish-classification benchmark of 101,000 photos spread evenly across 101 dish classes, sourced from ethz/food101. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/food101-lance) > > Source dataset card and downloadable files for `lance-format/food101-lance`. Each row carries the inline JPEG bytes, the integer `label`, the human-readable `label_name`, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/food101-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both numeric and string labels** (`label`, `label_name`) so filters can target either the class id or the dish name without an external mapping table. * **Scalar indices on both label columns** so class-based curation is a quick predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 75,750 | Canonical Food-101 train split (750 images per class) | | `validation.lance` | 25,250 | Canonical Food-101 test split (250 images per class) | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (256x256, quality 92) | | `label` | `int32` | Class id (0–100) | | `label_name` | `string` | One of 101 dish names, underscore-spaced (`apple_pie`, `baby_back_ribs`, …) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast lookup by class id * `BITMAP` on `label_name` — fast lookup by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/food101-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/food101-lance --repo-type dataset --local-dir ./food101-lance > ``` > > Then point LanceDB at `./food101-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without a model loaded; the first hit is expected to be the seed image itself, which is a useful sanity check on the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print("seed dish:", seed["label_name"]) for r in hits: print(f" {r['id']:>6} {r['label_name']}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a fine-grained classifier combines a class-based filter with the bundled vector search to assemble a small, focused candidate set. The `BITMAP` index on `label_name` makes the predicate effectively free, and the bounded `.limit(200)` keeps the result small enough to inspect or hand off to a training run. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where("label_name IN ('sushi', 'sashimi', 'ramen')") .select(["id", "label", "label_name"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidate Japanese-cuisine rows; first: {candidates[0]['label_name']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read by this query, so the network traffic is dominated by the small label fields rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse cuisine bucket and an `is_target_dish` flag for a focused training run, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./food101-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_target_dish": "label_name IN ('sushi', 'ramen', 'pho')", "is_dessert": "label_name IN ('apple_pie', 'cheesecake', 'tiramisu', 'ice_cream', 'donuts')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, a second classifier's predictions, human-verified taste tags), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2]), "model_v2_pred": pa.array(["sushi", "sashimi", "sushi"]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second embedding model over the JPEG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch image classifier, project the JPEG bytes and the integer label; for a linear probe or reranker on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward, cross-entropy against `label`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./food101-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="clip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/food101-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('sushi', 'sashimi', 'ramen', 'pho', 'dumplings')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./food101-asian-subset") local_db.create_table("train", batches) ``` The resulting `./food101-asian-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/food101-lance/data` for `./food101-asian-subset`. ## Source & license Converted from [`ethz/food101`](https://huggingface.co/datasets/ethz/food101). The Food-101 dataset is by Bossard et al. (ETH Zurich) — see the [original dataset page](https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/) for licensing details. ## Citation ``` @inproceedings{bossard2014food, title={Food-101 -- Mining Discriminative Components with Random Forests}, author={Bossard, Lukas and Guillaumin, Matthieu and Van Gool, Luc}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # Datasets Source: https://docs.lancedb.com/oss/v0-41-0/datasets/index Browse Lance-format datasets ready to query directly from the Hugging Face Hub. The [`lance-format`](https://huggingface.co/lance-format) organization on Hugging Face publishes a growing catalog of multimodal datasets in Lance format. Each one bundles the raw data (images, audio, video, or text), pre-computed embeddings, and on-disk vector / full-text indices as first-class columns in the same dataset — so vector search, full-text search, and filtered scans work directly via `hf://` URIs without downloading. This is powered under the hood by the [Lance format's native Hugging Face integration](https://lance.org/integrations/huggingface/). LanceDB sits on top of Lance and gives you a convenient table-style interface to query these datasets straight from the Hub: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/<dataset-name>/data") tbl = db.open_table("train") # Vector search, full-text search, or filtered scans — directly on the Hub results = tbl.search(query).limit(10).to_list() ``` Click any card below for usage examples, schema, and pre-built indices. For a complete walkthrough of the integration itself, see the [Hugging Face Hub integration page](/oss/v0-41-0/integrations/ai/huggingface). ## Image Classification > [card] [MNIST](/oss/v0-41-0/datasets/mnist) > > `lance-format/mnist-lance` — A Lance-formatted version of the classic MNIST handwritten-digit dataset covering 70,000 28×28 grayscale digits across ten balanced classes. > [card] [CIFAR-10](/oss/v0-41-0/datasets/cifar10) > > `lance-format/cifar10-lance` — A Lance-formatted version of CIFAR-10 covering 60,000 32×32 RGB images across ten balanced object classes. > [card] [Fashion-MNIST](/oss/v0-41-0/datasets/fashion-mnist) > > `lance-format/fashion-mnist-lance` — A Lance-formatted version of Fashion-MNIST covering 70,000 28×28 grayscale clothing images across ten balanced apparel classes. > [card] [Food-101](/oss/v0-41-0/datasets/food101) > > `lance-format/food101-lance` — A Lance-formatted version of Food-101, the fine-grained dish-classification benchmark of 101,000 photos spread evenly across 101 dish classes, sourced from ethz/food101. > [card] [Oxford-IIIT Pet](/oss/v0-41-0/datasets/oxford-pets) > > `lance-format/oxford-pets-lance` — A Lance-formatted version of the Oxford-IIIT Pet dataset — 7,390 cat and dog photos across 37 breeds — sourced from pcuenq/oxford-pets. > [card] [Stanford Cars](/oss/v0-41-0/datasets/stanford-cars) > > `lance-format/stanford-cars-lance` — A Lance-formatted version of the Stanford Cars fine-grained benchmark — 8,144 photographs across 196 make/model/year classes — sourced from Multimodal-Fatima/StanfordCars_train. > [card] [ImageNet-1k Validation](/oss/v0-41-0/datasets/imagenet-1k-val) > > `lance-format/imagenet-1k-val-lance` — A Lance-formatted version of the canonical 50,000-image ImageNet-1k (ILSVRC2012) validation split, sourced from benjamin-paine/imagenet-1k. > [card] [EuroSAT](/oss/v0-41-0/datasets/eurosat) > > `lance-format/eurosat-lance` — A Lance-formatted version of EuroSAT, the canonical Sentinel-2 RGB land-cover benchmark, sourced from blanchon/EuroSAT_RGB. ## OCR & Handwriting > [card] [Handwriting OCR](/oss/v0-41-0/datasets/handwriting-ocr) > > `lance-format/handwriting-ocr` — This Lance-formatted version of the Doctor's Handwritten Prescription BD dataset contains 4,680 cropped PNG images of handwritten medicine names from Bangladesh. ## Object Detection & Segmentation > [card] [COCO 2017 Detection](/oss/v0-41-0/datasets/coco-detection-2017) > > `lance-format/coco-detection-2017-lance` — A Lance-formatted version of the COCO 2017 object detection benchmark, sourced from detection-datasets/coco. > [card] [Pascal VOC 2012 Segmentation](/oss/v0-41-0/datasets/pascal-voc-2012-segmentation) > > `lance-format/pascal-voc-2012-segmentation-lance` — A Lance-formatted version of the Pascal VOC 2012 semantic segmentation split, sourced from nateraw/pascal-voc-2012. > [card] [ADE20K](/oss/v0-41-0/datasets/ade20k) > > `lance-format/ade20k-lance` — A Lance-formatted version of the full ADE20K scene parsing benchmark, sourced from 1aurent/ADE20K. > [card] [KITTI 2D Detection](/oss/v0-41-0/datasets/kitti-2d-detection) > > `lance-format/kitti-2d-detection-lance` — A Lance-formatted version of the KITTI 2D Object Detection benchmark, sourced from nateraw/kitti so no manual signup or download from cvlibs.net is required. ## Image Retrieval > [card] [COCO Captions 2017](/oss/v0-41-0/datasets/coco-captions-2017) > > `lance-format/coco-captions-2017-lance` — A Lance-formatted version of the COCO Captions 2017 corpus, redistributed via lmms-lab/COCO-Caption2017. > [card] [Flickr30k](/oss/v0-41-0/datasets/flickr30k) > > `lance-format/flickr30k-lance` — A Lance-formatted version of Flickr30k, redistributed via lmms-lab/flickr30k. > [card] [LAION-1M](/oss/v0-41-0/datasets/laion-1m) > > `lance-format/laion-1m` — A Lance-formatted slice of the LAION image-text corpus (\~1M rows) with inline JPEG bytes, CLIP image embeddings (img_emb), full metadata, and a pre-built ANN index — all available directly from the Hub at hf://datasets/lance-format/laion-1m/data/train.lance. ## Visual Question Answering > [card] [ChartQA](/oss/v0-41-0/datasets/chartqa) > > `lance-format/chartqa-lance` — A Lance-formatted version of ChartQA, a benchmark for question answering over scientific and business charts that demands a mix of logical and visual reasoning, redistributed via lmms-lab/ChartQA. > [card] [DocVQA](/oss/v0-41-0/datasets/docvqa) > > `lance-format/docvqa-lance` — A Lance-formatted version of DocVQA, a benchmark for visual question answering over document images such as industry and government scans, multi-page reports, forms, and receipts, redistributed via lmms-lab/DocVQA (DocVQA config). > [card] [TextVQA](/oss/v0-41-0/datasets/textvqa) > > `lance-format/textvqa-lance` — A Lance-formatted version of TextVQA — visual question answering where the question requires reading text in the image (street signs, product labels, screen captures) — sourced from lmms-lab/textvqa. > [card] [VQAv2](/oss/v0-41-0/datasets/vqav2) > > `lance-format/vqav2-lance` — A Lance-formatted version of VQAv2 — open-ended visual question answering on COCO images — sourced from lmms-lab/VQAv2. > [card] [GQA testdev-balanced](/oss/v0-41-0/datasets/gqa-testdev-balanced) > > `lance-format/gqa-testdev-balanced-lance` — A Lance-formatted version of the canonical GQA testdev_balanced slice — 12,578 compositional VQA questions joined against the matching 398 images — sourced from lmms-lab/GQA. ## Text QA > [card] [SQuAD v2](/oss/v0-41-0/datasets/squad-v2) > > `lance-format/squad-v2-lance` — A Lance-formatted version of SQuAD v2 — the Stanford Question Answering Dataset with both answerable and deliberately unanswerable questions over Wikipedia passages — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/squad-v2-lance/data. > [card] [TriviaQA](/oss/v0-41-0/datasets/trivia-qa) > > `lance-format/trivia-qa-lance` — A Lance-formatted version of TriviaQA (rc.nocontext config) — a large reading-comprehension dataset of trivia questions paired with a canonical answer, accepted aliases, and entity-type metadata — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/trivia-qa-lance/data. > [card] [HotpotQA distractor](/oss/v0-41-0/datasets/hotpotqa-distractor) > > `lance-format/hotpotqa-distractor-lance` — A Lance-formatted version of HotpotQA using the distractor config — multi-hop reading-comprehension questions where each answer requires combining facts from two Wikipedia paragraphs, with 10 candidate paragraphs per question (gold + 8 distractors). > [card] [Natural Questions Validation](/oss/v0-41-0/datasets/natural-questions-val) > > `lance-format/natural-questions-val-lance` — A Lance-formatted version of the Natural Questions validation split — 7,830 real Google search queries paired with the full Wikipedia article a human used to answer them, plus 1–5 annotator labels per question. > [card] [MS MARCO v2.1](/oss/v0-41-0/datasets/ms-marco-v2) > > `lance-format/ms-marco-v2.1-lance` — A Lance-formatted version of MS MARCO v2.1 — Microsoft's machine-reading-comprehension benchmark built from anonymized Bing query logs. ## Text Corpora > [card] [FineWeb-Edu](/oss/v0-41-0/datasets/fineweb-edu) > > `lance-format/fineweb-edu` — A Lance-formatted version of FineWeb-Edu — over 1.5 billion educational web passages with cleaned text, source metadata, language detection signals, and 384-dim text embeddings — available directly from the Hub at hf://datasets/lance-format/fineweb-edu/data/train.lance. ## Speech > [card] [LibriSpeech clean](/oss/v0-41-0/datasets/librispeech-clean) > > `lance-format/librispeech-clean-lance` — A Lance-formatted version of the LibriSpeech ASR clean configuration, sourced from openslr/librispeech_asr. ## Video > [card] [OpenVid-1M](/oss/v0-41-0/datasets/openvid) > > `lance-format/openvid-lance` — A Lance-formatted version of the OpenVid-1M corpus — 937,957 high-quality clips with inline MP4 bytes, 1024-dim video embeddings, captions, and rich per-clip quality signals — available directly from the Hub at hf://datasets/lance-format/openvid-lance/data/train.lance. ## Robotics > [card] [LeRobot PushT](/oss/v0-41-0/datasets/lerobot-pusht) > > `lance-format/lerobot-pusht-lance` — A Lance-formatted version of lerobot/pusht — the canonical PushT benchmark from the Diffusion Policy paper — packaged using the same three-table layout as lance-format/lerobot-xvla-soft-fold so consumers can flip between datasets without changing code. > [card] [LeRobot X-VLA Soft-Fold](/oss/v0-41-0/datasets/lerobot-xvla-soft-fold) > > `lance-format/lerobot-xvla-soft-fold` — A Lance-formatted version of lerobot/xvla-soft-fold — a multi-camera robotics dataset from the X-VLA project — packaged as three Lance tables for efficient frame-level training, episode-level trajectory loading, and direct access to the original encoded videos. ## Share your own dataset Got a multimodal dataset you want to publish? Convert it to Lance and push it to the Hub! Anyone who opens it gets vector search, full-text search, and filtered scans on the data out of the box, without recreating the embeddings or indexes on their end. > [card] [Upload Lance datasets to the Hugging Face Hub](https://www.lancedb.com/blog/upload-lance-datasets-to-hf-hub) > > A step-by-step walkthrough on the LanceDB blog covering CLI setup, packaging your dataset, pushing to your namespace, and writing a dataset card. Or browse the [latest trending Lance datasets](https://huggingface.co/datasets?format=format:lance\&sort=trending) on Hugging Face. # LeRobot PushT Source: https://docs.lancedb.com/oss/v0-41-0/datasets/lerobot-pusht A Lance-formatted version of lerobot/pusht — the canonical PushT benchmark from the Diffusion Policy paper — packaged using the same three-table layout as lance-format/lerobot-xvla-soft-fold so consumers can flip between datasets without changing code. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/lerobot-pusht-lance) > > Source dataset card and downloadable files for `lance-format/lerobot-pusht-lance`. Available directly from the Hub at `hf://datasets/lance-format/lerobot-pusht-lance/data`. ## Key features * **Three-table layout** — `frames`, `episodes`, `videos` — so frame-level training, episode-level trajectory work, and raw video access live side-by-side without scattered parquet shards or sidecar MP4 directories. * **Inline MP4 segments** in `episodes.lance` (one blob per camera, with `from_timestamp` / `to_timestamp` bounds) and full source MP4s in `videos.lance`, all surfaced as lazy `BlobFile` handles via `fetch_blob_files` so metadata scans never read the bytes. * **Frame-level observations and actions** in `frames.lance` with stable `episode_index`, `frame_index`, and `index` columns for joining or temporal iteration. * **Schema-evolution friendly** — add alternate camera streams, language annotations, or model predictions later without rewriting the data. ## Tables | Table | Rows \~ | Purpose | | - | - | - | | `frames.lance` | one row per frame | Per-frame observations, actions, episode/task indices | | `episodes.lance` | one row per episode | Full per-episode trajectories plus per-camera MP4 segment blobs and timestamp bounds | | `videos.lance` | one row per source MP4 | Raw source video blobs and file-level provenance (path, size, sha256) | Use `frames.lance` for low-level training (loss-per-timestep, state-conditioned policies). Use `episodes.lance` when you need the full trajectory and the matching video segments together. Use `videos.lance` when you want direct access to the original encoded video files. ## Schemas ### `frames.lance` | Column | Type | Notes | | - | - | - | | `observation_state` | `list<float32>` | Robot state vector for that frame | | `action` | `list<float32>` | Action vector for that frame | | `timestamp` | `float` | Canonical frame timestamp (seconds) | | `frame_index` | `int64` | Frame index within episode | | `episode_index` | `int64` | Parent episode id | | `index` | `int64` | Global frame index | | `task_index` | `int64` | Task id | ### `episodes.lance` | Column | Type | Notes | | - | - | - | | `episode_index` | `int64` | Episode id | | `task_index` | `int64` | Task id | | `fps` | `int32` | Frame rate of the episode video segments | | `timestamps` | `list<float32>` | Per-frame timestamps | | `actions` | `list<list<float32>>` | Per-frame action vectors | | `observation_state` | `list<list<float32>>` | Per-frame robot state vectors | | `<camera>_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for each camera, read lazily via `fetch_blob_files` | | `<camera>_from_timestamp` | `float64` | Segment start time | | `<camera>_to_timestamp` | `float64` | Segment end time | ### `videos.lance` | Column | Type | Notes | | - | - | - | | `camera_angle` | `string` | Camera key | | `chunk_index`, `file_index` | `int32` | IDs parsed from the source path | | `relative_path`, `filename` | `string` | Provenance | | `file_size_bytes` | `int64` | Source MP4 size | | `sha256` | `string` | SHA256 of the MP4 bytes | | `video_blob` | `large_binary` (blob-encoded) | Raw source MP4 bytes | ## Pre-built indices None bundled. Build indices on a local copy if a workload calls for them — e.g., a `BTREE` on `frames.episode_index` for fast episode lookup, or a vector index after attaching observation embeddings via Evolve. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. Each Lance table is a separate `datasets` config. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/lerobot-pusht-lance", split="frames", streaming=True) for row in hf_ds.take(3): print(row["episode_index"], row["frame_index"], row["action"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name. The same handles are used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") episodes = db.open_table("episodes") videos = db.open_table("videos") print(len(frames), len(episodes), len(videos)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access to video segments and any kind of indexed search are dramatically faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/lerobot-pusht-lance --repo-type dataset --local-dir ./lerobot-pusht > ``` > > Then point LanceDB at `./lerobot-pusht/data`. ## Search PushT does not ship a vector index out of the box — observation states are low-dimensional and most robotics workflows look up by index rather than by similarity. The bundled identifier columns (`episode_index`, `task_index`, `frame_index`) make exact lookups a single filtered scan. The example below pulls the first few frames of episode 0 from the frames table. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") slice_ = ( frames.search() .where("episode_index = 0 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(10) .to_list() ) for r in slice_: print(r["frame_index"], r["timestamp"], r["action"]) ``` For similarity-style search across states or actions, attach an embedding column via Evolve and build an `IVF_PQ` index on it (see Evolve below). For visual similarity over rendered frames, the pre-extracted-frames pattern in Train below produces a table that can carry a learned image embedding alongside the pixels. ## Curate A typical curation pass for a robotics workflow starts with an episode-level filter — pick episodes with a particular task, length, or initial condition — and then drops down to the frames within those episodes. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(...)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") episodes = db.open_table("episodes") frames = db.open_table("frames") # Pick a handful of episodes for the default task. ep_rows = ( episodes.search() .where("task_index = 0", prefilter=True) .select(["episode_index", "fps", "observation_images_image_from_timestamp", "observation_images_image_to_timestamp"]) .limit(10) .with_row_id(True) .to_list() ) ep_ids = [r["episode_index"] for r in ep_rows] # Pull the frames belonging to those episodes for the next stage. frame_rows = ( frames.search() .where(f"episode_index IN ({', '.join(map(str, ep_ids))})", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(2000) .to_list() ) print(f"{len(ep_rows)} episodes, {len(frame_rows)} frames selected") ``` Neither scan reads any video bytes. The MP4 segments live in the blob-encoded `_video_blob` columns and stay on disk until something explicitly asks for them. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `action_magnitude` and a `large_action` flag to the frames table, either of which can then be used directly in `where` clauses. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./lerobot-pusht/data") # local copy required for writes frames = db.open_table("frames") frames.add_columns({ "action_magnitude": "SQRT(action[1] * action[1] + action[2] * action[2])", "large_action": "SQRT(action[1] * action[1] + action[2] * action[2]) > 5.0", }) ``` The original columns and the inline video blobs are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reward labels, classifier predictions, learned observation embeddings), add the new fields and update matching rows by the appropriate key — `index` for frames or `episode_index` for episodes: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa rewards = pa.table({ "index": pa.array([0, 1, 2]), "reward_to_go": pa.array([1.4, 1.3, 1.2]), }) frames.add_columns([f for f in rewards.schema if f.name != "index"]) frames.merge_insert("index").when_matched_update_all().execute(rewards) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a visual encoder over the decoded video frames), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for vision-conditioned policy training is to pre-extract decoded frame pixels once into a derived LanceDB table — one row per frame, with the per-frame `action` and `observation_state` already joined in — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each episode's MP4 segment is randomly addressable in `episodes.lance` (the `from_timestamp` / `to_timestamp` columns give the segment bounds), so the pass can subset bytes on demand and write decoded frames into a fresh table without an external file store. Other workflows project the `_video_blob` columns from `episodes.lance` directly and decode at the batch boundary, or skip pixels entirely and train a state-only policy on `frames.lance` — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. For a state-only policy, the frames table is already in the right shape — no pre-extraction needed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") train_ds = Permutation.identity(frames).select_columns(["observation_state", "action"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) ``` For a vision-conditioned policy, train against a pre-extracted frames-with-pixels table that joins each frame's decoded image to its `action` and `observation_state`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./lerobot-pusht-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "observation_state", "action"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) ``` The inline `_video_blob` storage and `fetch_blob_files` still earn their place outside of the training loop — visualizing an episode in a notebook, sampling for human review, one-off evaluation against a held-out task, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance table, whether it adds a column, merges labels, or builds an index, commits a new version. Each of `frames`, `episodes`, and `videos` is versioned independently, so a column added to `frames` does not bump the version of `episodes`. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") frames = db.open_table("frames") print("frames version:", frames.version) print("history:", frames.list_versions()) print("tags:", frames.tags.list()) ``` Once you have a local copy, tag the table for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./lerobot-pusht/data") local_frames = local_db.open_table("frames") local_frames.tags.create("pusht-v1", local_frames.version) ``` Reopen by tag or by version number against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames_v1 = db.open_table("frames", version="pusht-v1") frames_v5 = db.open_table("frames", version=5) ``` Pinning supports two workflows. A policy locked to `pusht-v1` keeps reproducing the same behavior while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same frames, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation, index builds) need a writable backing store, and a training pipeline benefits from a local copy with fast random access into the video blobs. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") remote_frames = remote_db.open_table("frames") batches = ( remote_frames.search() .where("task_index = 0 AND episode_index < 50") .select(["episode_index", "frame_index", "index", "timestamp", "action", "observation_state"]) .to_batches() ) local_db = lancedb.connect("./pusht-task0-subset") local_db.create_table("frames", batches) ``` The resulting `./pusht-task0-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/lerobot-pusht-lance/data` for `./pusht-task0-subset`. The same pattern applies to `episodes` and `videos` — narrow each table to the rows your workload needs, and the resulting database stays small enough to index and iterate cheaply. ## Source & license Converted from [`lerobot/pusht`](https://huggingface.co/datasets/lerobot/pusht) (LeRobot v3.0 dataset format). PushT is released under the Apache 2.0 license by the LeRobot project and the Diffusion Policy authors. ## Citation ``` @misc{cadene2024lerobot, title={LeRobot: State-of-the-art Machine Learning for Real-World Robotics in PyTorch}, author={R{\'e}mi Cadene and Simon Alibert and Alexander Soare and Quentin Gallou{\'e}dec and Adil Zouitine and Steven Palma and Pepijn Kooijmans and Michel Aractingi and Mustafa Shukor and Martino Russi and Francesco Capuano and Caroline Pascal and Jade Choghari and Jess Moss and Thomas Wolf}, year={2024}, url={https://github.com/huggingface/lerobot} } @inproceedings{chi2023diffusion, title={Diffusion Policy: Visuomotor Policy Learning via Action Diffusion}, author={Chi, Cheng and Feng, Siyuan and Du, Yilun and Xu, Zhenjia and Cousineau, Eric and Burchfiel, Benjamin and Song, Shuran}, booktitle={Robotics: Science and Systems}, year={2023} } ``` # LeRobot X-VLA Soft-Fold Source: https://docs.lancedb.com/oss/v0-41-0/datasets/lerobot-xvla-soft-fold A Lance-formatted version of lerobot/xvla-soft-fold — a multi-camera robotics dataset from the X-VLA project — packaged as three Lance tables for efficient frame-level training, episode-level trajectory loading, and direct access to the original encoded videos. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/lerobot-xvla-soft-fold) > > Source dataset card and downloadable files for `lance-format/lerobot-xvla-soft-fold`. Available directly from the Hub at `hf://datasets/lance-format/lerobot-xvla-soft-fold/data`. * **1,542 episodes** * **2,852,512 frames** at **20 FPS** * **3 camera streams per episode** — `cam_high`, `cam_left_wrist`, `cam_right_wrist` * **Robot state and action vectors** aligned to frame timestamps ## Key features * **Three-table layout** — `frames`, `episodes`, `videos` — so frame-level training, episode-level trajectory work, and raw video access live side-by-side without scattered parquet shards or sidecar MP4 directories. * **Per-camera inline MP4 segments** in `episodes.lance`, with `from_timestamp` / `to_timestamp` bounds per camera and per episode, surfaced as lazy `BlobFile` handles via `fetch_blob_files` so metadata scans never read the bytes. * **Frame-level observations and actions** in `frames.lance` with stable `episode_index`, `frame_index`, and `index` columns for joining or temporal iteration. * **Source MP4 provenance** in `videos.lance` (`relative_path`, `filename`, `file_size_bytes`, `sha256`) alongside the raw bytes, for integrity checks or custom decode pipelines. ## Tables | Table | Rows | Purpose | | - | - | - | | `frames.lance` | 2,852,512 | Per-frame observations, actions, episode/task indices | | `episodes.lance` | 1,542 | Full per-episode trajectories plus per-camera MP4 segment blobs and timestamp bounds | | `videos.lance` | 104 | Raw source MP4 files (one row per source MP4) with file-level provenance | Use `frames.lance` for low-level training (loss-per-timestep, state-conditioned policies). Use `episodes.lance` when you need the full trajectory and the matching per-camera video segments together. Use `videos.lance` when you want direct access to the original encoded video files. ## Schemas ### `frames.lance` | Column | Type | Notes | | - | - | - | | `observation_state` | `list<float32>` | Robot state vector for that frame | | `action` | `list<float32>` | Action vector for that frame | | `time_stamp` | `float` | Original source timestamp field | | `timestamp` | `float` | Canonical frame timestamp (seconds) | | `frame_index` | `int64` | Frame index within episode | | `episode_index` | `int64` | Parent episode id | | `index` | `int64` | Global frame index | | `task_index` | `int64` | Task id | ### `episodes.lance` | Column | Type | Notes | | - | - | - | | `episode_index` | `int64` | Episode id | | `task_index` | `int64` | Task id | | `fps` | `int32` | Frame rate of the episode video segments | | `timestamps` | `list<float32>` | Per-frame timestamps | | `actions` | `list<list<float32>>` | Per-frame action vectors | | `observation_state` | `list<list<float32>>` | Per-frame robot state vectors | | `observation_images_cam_high_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_high` | | `observation_images_cam_high_from_timestamp` | `float64` | `cam_high` segment start time | | `observation_images_cam_high_to_timestamp` | `float64` | `cam_high` segment end time | | `observation_images_cam_left_wrist_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_left_wrist` | | `observation_images_cam_left_wrist_from_timestamp` | `float64` | `cam_left_wrist` segment start time | | `observation_images_cam_left_wrist_to_timestamp` | `float64` | `cam_left_wrist` segment end time | | `observation_images_cam_right_wrist_video_blob` | `large_binary` (blob-encoded) | Inline MP4 segment for `cam_right_wrist` | | `observation_images_cam_right_wrist_from_timestamp` | `float64` | `cam_right_wrist` segment start time | | `observation_images_cam_right_wrist_to_timestamp` | `float64` | `cam_right_wrist` segment end time | ### `videos.lance` | Column | Type | Notes | | - | - | - | | `camera_angle` | `string` | Camera key (e.g. `cam_high`) | | `chunk_index`, `file_index` | `int32` | IDs parsed from the source path | | `relative_path`, `filename` | `string` | Provenance | | `file_size_bytes` | `int64` | Source MP4 size | | `sha256` | `string` | SHA256 of the MP4 bytes | | `video_blob` | `large_binary` (blob-encoded) | Raw source MP4 bytes | ## Pre-built indices None bundled. Build indices on a local copy if a workload calls for them — e.g., a `BTREE` on `frames.episode_index` for fast per-episode lookup, or a vector index after attaching observation embeddings via Evolve. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. Each Lance table is a separate `datasets` config. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/lerobot-xvla-soft-fold", split="frames", streaming=True) for row in hf_ds.take(3): print(row["episode_index"], row["frame_index"], row["action"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name. The same handles are used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") episodes = db.open_table("episodes") videos = db.open_table("videos") print(len(frames), len(episodes), len(videos)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access to video segments and any kind of indexed search are dramatically faster against a local copy. The full dataset is **>50 GB**, so ensure you have sufficient disk space: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/lerobot-xvla-soft-fold --repo-type dataset --local-dir ./lerobot-xvla-soft-fold > ``` > > Then point LanceDB at `./lerobot-xvla-soft-fold/data`. For most workflows, the Materialize-a-subset section at the end of this card is a better starting point than downloading the full corpus. ## Search This dataset does not ship a vector index out of the box — observation states are low-dimensional and most robotics workflows look up by index rather than by similarity. The bundled identifier columns (`episode_index`, `task_index`, `frame_index`) make exact lookups a single filtered scan. The example below pulls the first few frames of episode 30 from the frames table. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") slice_ = ( frames.search() .where("episode_index = 30 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action", "observation_state"]) .limit(10) .to_list() ) for r in slice_: print(r["frame_index"], r["timestamp"], r["action"]) ``` For similarity-style search across states or actions, attach an embedding column via Evolve and build an `IVF_PQ` index on it. For visual similarity over rendered frames, the pre-extracted-frames pattern in Train below produces a table that can carry a learned image embedding alongside the pixels. ## Curate A typical curation pass for a robotics workflow starts with an episode-level filter — pick episodes with a particular task, length, or initial condition — and then either iterates frames or pulls the matching video segments. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(...)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") episodes = db.open_table("episodes") ep_rows = ( episodes.search() .where("task_index = 0 AND fps = 20", prefilter=True) .select([ "episode_index", "observation_images_cam_high_from_timestamp", "observation_images_cam_high_to_timestamp", ]) .limit(20) .with_row_id(True) .to_list() ) print(f"{len(ep_rows)} episodes selected") for r in ep_rows[:3]: print( f" ep {r['episode_index']} " f"{r['observation_images_cam_high_from_timestamp']:.2f}s → " f"{r['observation_images_cam_high_to_timestamp']:.2f}s" ) ``` Neither this scan nor any of the per-camera segment columns are read. The MP4 segments live in the blob-encoded `_video_blob` columns and stay on disk until something explicitly asks for them — which makes "find me the right episodes" a metadata-only operation against a multi-million-frame corpus. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `episode_duration` column to the episodes table from the existing `cam_high` timestamp bounds. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./lerobot-xvla-soft-fold/data") # local copy required for writes episodes = db.open_table("episodes") episodes.add_columns({ "episode_duration_s": ( "observation_images_cam_high_to_timestamp - " "observation_images_cam_high_from_timestamp" ), "is_long_episode": ( "(observation_images_cam_high_to_timestamp - " " observation_images_cam_high_from_timestamp) > 120.0" ), }) ``` The original columns and the inline video blobs are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reward labels, classifier predictions, learned observation embeddings), add the new fields and update matching rows by the appropriate key — `index` for frames or `episode_index` for episodes: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa ep_labels = pa.table({ "episode_index": pa.array([0, 1, 2]), "outcome": pa.array(["success", "partial", "success"]), }) episodes.add_columns([f for f in ep_labels.schema if f.name != "episode_index"]) episodes.merge_insert("episode_index").when_matched_update_all().execute(ep_labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a visual encoder over the decoded video frames), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for vision-language-action training is to pre-extract decoded frame pixels once into a derived LanceDB table — one row per frame, with the per-frame `action` and `observation_state` already joined in, and one column per camera holding the decoded image — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each episode's per-camera MP4 segment is randomly addressable in `episodes.lance` (the `*_from_timestamp` / `*_to_timestamp` columns give the segment bounds), so the pass can subset bytes on demand and write decoded frames into a fresh table without an external file store. Other workflows project the `*_video_blob` columns from `episodes.lance` directly and decode at the batch boundary, or skip pixels entirely and train a state-only policy on `frames.lance` — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. For a state-only policy, the frames table is already in the right shape — no pre-extraction needed: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") train_ds = Permutation.identity(frames).select_columns(["observation_state", "action"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` For a vision-language-action policy, train against a pre-extracted frames-with-pixels table that joins each frame's three decoded camera images to its `action` and `observation_state`. Picking the cameras the model actually conditions on is then a column projection — `cam_high` alone, all three, or any subset: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./lerobot-xvla-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["cam_high", "cam_left_wrist", "cam_right_wrist", "observation_state", "action"] ) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) ``` The inline `_video_blob` storage and `fetch_blob_files` still earn their place outside of the training loop — visualizing an episode in a notebook, sampling for human review, one-off evaluation, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance table, whether it adds a column, merges labels, or builds an index, commits a new version. Each of `frames`, `episodes`, and `videos` is versioned independently, so a column added to `frames` does not bump the version of `episodes`. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") frames = db.open_table("frames") print("frames version:", frames.version) print("history:", frames.list_versions()) print("tags:", frames.tags.list()) ``` Once you have a local copy, tag the table for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./lerobot-xvla-soft-fold/data") local_frames = local_db.open_table("frames") local_frames.tags.create("xvla-v1", local_frames.version) ``` Reopen by tag or by version number against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frames_v1 = db.open_table("frames", version="xvla-v1") frames_v5 = db.open_table("frames", version=5) ``` Pinning supports two workflows. A policy locked to `xvla-v1` keeps reproducing the same behavior while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same frames and segments, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset At >50 GB across three tables and millions of frames, few workflows want the full corpus on local disk. The practical entry point is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the per-camera `_video_blob` columns on `episodes.lance`, which stream through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/lerobot-xvla-soft-fold/data") remote_episodes = remote_db.open_table("episodes") batches = ( remote_episodes.search() .where("task_index = 0 AND episode_index < 50") .select([ "episode_index", "task_index", "fps", "timestamps", "actions", "observation_state", "observation_images_cam_high_video_blob", "observation_images_cam_high_from_timestamp", "observation_images_cam_high_to_timestamp", ]) .to_batches() ) local_db = lancedb.connect("./xvla-task0-subset") local_db.create_table("episodes", batches) ``` The resulting `./xvla-task0-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/lerobot-xvla-soft-fold/data` for `./xvla-task0-subset`. The same pattern applies to `frames` and `videos` — narrow each table to the rows your workload needs, and the resulting database stays small enough to index and iterate cheaply. ## Source & license Converted from [`lerobot/xvla-soft-fold`](https://huggingface.co/datasets/lerobot/xvla-soft-fold) (LeRobot v3.0 dataset format), originally released as part of the [X-VLA](https://thu-air-dream.github.io/X-VLA/) project. Apache 2.0. ## Citation ``` @article{zheng2025xvla, title={X-VLA: Soft-Prompted Transformer as Scalable Cross-Embodiment Vision-Language-Action Model}, author={Zheng and others}, journal={arXiv preprint arXiv:2510.10274}, year={2025} } @misc{cadene2024lerobot, title={LeRobot: State-of-the-art Machine Learning for Real-World Robotics in PyTorch}, author={R{\'e}mi Cadene and Simon Alibert and Alexander Soare and Quentin Gallou{\'e}dec and Adil Zouitine and Steven Palma and Pepijn Kooijmans and Michel Aractingi and Mustafa Shukor and Martino Russi and Francesco Capuano and Caroline Pascal and Jade Choghari and Jess Moss and Thomas Wolf}, year={2024}, url={https://github.com/huggingface/lerobot} } ``` # MNIST Source: https://docs.lancedb.com/oss/v0-41-0/datasets/mnist A Lance-formatted version of the classic MNIST handwritten-digit dataset covering 70,000 28×28 grayscale digits across ten balanced classes. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/mnist-lance) > > Source dataset card and downloadable files for `lance-format/mnist-lance`. Each row carries inline PNG bytes, the digit label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/mnist-lance/data`. ## Key features * **Inline PNG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index. * **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` — so digit filters and digit-conditioned search are constant-time lookups. * **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want. ## Splits | Split | Rows | | - | - | | `train.lance` | 60,000 | | `test.lance` | 10,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) | | `label` | `int32` | Digit class id (0–9) | | `label_name` | `string` | Human-readable class (`"0"`..`"9"`) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality and range filters on the digit id * `BITMAP` on `label_name` — fast filters across the ten class names ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/mnist-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/mnist-lance --repo-type dataset --local-dir ./mnist-lance > ``` > > Then point LanceDB at `./mnist-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query digit through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "label_name"]) .limit(10) .to_list() ) print("query digit:", seed["label"]) for r in hits: print(f" id={r['id']:>5} label={r['label']}") ``` Because the embeddings are cosine-normalized and MNIST digits cluster tightly in CLIP space, near-neighbors of a seed image are dominated by the seed's own digit class — a useful sanity check before swapping in a real query encoder. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency. ## Curate A typical curation pass for a digit-classification workflow narrows the table to a single digit (or a small set of confusable digits like 4/9 or 3/8) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("label IN (4, 9)", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} 4/9 candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_target_class` flag for binary one-vs-rest experiments and an `is_curvy_digit` flag that groups digits with curved strokes, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./mnist-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_target_class": "label = 7", "is_curvy_digit": "label IN (0, 3, 6, 8, 9)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_label": pa.array([5, 0, 4], type=pa.int32()), "pred_conf": pa.array([0.97, 0.88, 0.82]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the PNG bytes, normalize to [0, 1], forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./mnist-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same digits and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label IN (4, 9)") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./mnist-4-vs-9") local_db.create_table("train", batches) ``` The resulting `./mnist-4-vs-9` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/mnist-lance/data` for `./mnist-4-vs-9`. ## Source & license Converted from [`ylecun/mnist`](https://huggingface.co/datasets/ylecun/mnist). MNIST is released under the MIT license. The original dataset is by Yann LeCun, Corinna Cortes, and Christopher J.C. Burges. ## Citation ``` @article{lecun1998mnist, title={The MNIST database of handwritten digits}, author={LeCun, Yann and Cortes, Corinna and Burges, CJ}, url={http://yann.lecun.com/exdb/mnist/}, year={1998} } ``` # Large scale vector search (1.5B) Source: https://docs.lancedb.com/oss/v0-41-0/demos/fineweb-edu-search Semantic search over 1.5B+ FineWeb EDU embeddings. vector-searcheducationbge-embeddings > [card] [Large Scale Vector Search (1.5B)](https://lancedb-demos.vercel.app/demo/fineweb-edu-search) > > Semantic search over curated FineWeb EDU pages, represented as 1.5B+ BGE embeddings. Inspect the > query plan to see how LanceDB serves vector search at billion scale. # Demo application gallery Source: https://docs.lancedb.com/oss/v0-41-0/demos/index End-to-end applications built with LanceDB. Applications built on LanceDB, each with a live demo and a write-up of how it works. | App | What it shows | | - | - | | [Semantic.art](/oss/v0-41-0/demos/semantic-art) | Multimodal art discovery using feelings, phrases, and images. | | [Wikipedia 41M hybrid search](/oss/v0-41-0/demos/wikipedia-search) | Full-text and vector search combined, over 41M+ entries. | | [Video search](/oss/v0-41-0/demos/video-search) | Natural-language search across a video library. | | [Large scale vector search (1.5B)](/oss/v0-41-0/demos/fineweb-edu-search) | Semantic search over 1.5B+ FineWeb EDU embeddings. | | [Robot data curation (DROID)](/oss/v0-41-0/demos/robot-data-curation) | Searching, scoring, and selecting robotics training examples. | # Robot data curation (DROID) Source: https://docs.lancedb.com/oss/v0-41-0/demos/robot-data-curation Search, score, and select robotics training examples from DROID. multimodalroboticsvector-searchfts > [card] [Robot Data Curation (DROID)](https://lancedb-demos.vercel.app/demo/robot-data-curation) > > Search robot video frames from the DROID dataset, compute features, and select training examples in LanceDB. > Add captions and quality scores as columns, then write model errors back to guide the next training run. # Semantic.art Source: https://docs.lancedb.com/oss/v0-41-0/demos/semantic-art Multimodal art discovery through feelings, phrases, and images. multimodalhybrid-searchvector-searchsemantic-routing > [card] [Semantic.art](https://www.semantic.art/) > > Semantic.art turns real, human-made art discovery into a multimodal search experience using > feelings, phrases, and images. It's built with LanceDB hybrid search and semantic routing. > > > [card] [Learn how it's built](https://lancedb.com/blog/semanticdotart/) > > > > Read in detail about how Semantic.art is built in this blog post. # Video search Source: https://docs.lancedb.com/oss/v0-41-0/demos/video-search Search a video library with natural language queries. multimodalvideo-searchvector-search > [card] [Video Search](https://lancedb-demos.vercel.app/demo/video-search) > > Search through a library of videos using natural language queries. This demo showcases how to use LanceDB > to perform semantic search on video content. # Wikipedia 41M hybrid search Source: https://docs.lancedb.com/oss/v0-41-0/demos/wikipedia-search Hybrid full-text and vector search across 41M+ Wikipedia entries. multimodalhybrid-searchvector-searchfts > [card] [Wikipedia 41M Hybrid Search](https://lancedb-demos.vercel.app/demo/wikipedia-search) > > Interactive hybrid search, full-text search (FTS) and vector search demo with 41M+ Wikipedia entries. > Explore the power of combining FTS with vector search for more relevant results. > > > [card] [Learn how it's built](https://lancedb.com/blog/feature-full-text-search/) > > > > Read in detail about how the Wikipedia 41M hybrid search demo is built in this blog post. # Managing Embeddings Source: https://docs.lancedb.com/oss/v0-41-0/embedding/index Use the embedding API in LanceDB: registry, functions, schemas, and multi-language SDK support. **Applies to:** Embedded ✅, Enterprise ✅ Modern machine learning models can be trained to convert raw data into embeddings, which are vectors of floating point numbers. The position of an embedding in vector space captures the semantics of the data, so vectors that are close to each other are considered similar. LanceDB provides an embedding function registry in LanceDB Embedded as well as LanceDB Enterprise ([see below](#embeddings-in-lancedb-enterprise)) that automatically generates vector embeddings during data ingestion. Query text is embedded automatically too, in the client, for local and Enterprise tables alike, with SDK-specific query ergonomics. The API abstracts embedding generation, allowing you to focus on your application logic. ## Embedding Registry You can get a supported embedding function from the registry, and then use it in your table schema. Once configured, the embedding function will automatically generate embeddings when you insert data into the table. Query-time behavior depends on SDK: Python/TypeScript can query with text directly, while Rust examples typically compute query embeddings explicitly before vector search. In the Rust examples, replace `your-openai-api-key` with your OpenAI API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create(name="text-embedding-ada-002") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add([{"text": "hello world"}, {"text": "goodbye world"}]) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect(databaseDir); const func = getRegistry() .get("openai") ?.create({ model: "text-embedding-ada-002" }) as EmbeddingFunction; const wordsSchema = LanceSchema({ text: func.sourceField(new Utf8()), vector: func.vectorField(), }); const tbl = await db.createEmptyTable("words", wordsSchema, { mode: "overwrite", }); await tbl.add([{ text: "hello world" }, { text: "goodbye world" }]); const query = "greetings"; const actual = (await tbl.search(query).limit(1).toArray())[0]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::{iter::once, sync::Arc}; use arrow_array::{record_batch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::StreamExt; use lancedb::{ connect, embeddings::{openai::OpenAIEmbeddingFunction, EmbeddingDefinition, EmbeddingFunction}, query::{ExecutableQuery, QueryBase}, Result, }; #[tokio::main] async fn main() -> Result<()> { let db = connect("./mydb").execute().await?; let api_key = "your-openai-api-key".to_string(); let embedding = Arc::new(OpenAIEmbeddingFunction::new_with_model( api_key, "text-embedding-3-large", )?); db.embedding_registry().register("openai", embedding.clone())?; let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); let table = db .create_empty_table("mytable", schema) .add_embedding(EmbeddingDefinition::new("text", "openai", Some("vector")))? .execute() .await?; table .add(record_batch!(("text", Utf8, ["This is a test.", "Another example."]))?) .execute() .await?; let query = Arc::new(StringArray::from_iter_values(once("test example"))); let query_vector = embedding.compute_query_embeddings(query)?; let mut results = table.vector_search(query_vector)?.limit(5).execute().await?; while let Some(batch) = results.next().await { println!("{:?}", batch?); } Ok(()) } ``` ### Using an embedding function Create an embedding function before you attach it to table or schema metadata. Python and TypeScript fetch provider implementations from the embedding registry, while Rust constructs the provider embedding function directly and registers it on the connection before using it in an `EmbeddingDefinition`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} func = get_registry().get("openai").create( name="text-embedding-3-small", max_retries=7, ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const func = getRegistry().get("openai")!.create({ model: "text-embedding-3-small", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::sync::Arc; use lancedb::embeddings::openai::OpenAIEmbeddingFunction; let api_key = "your-openai-api-key".to_string(); let embedding = Arc::new( OpenAIEmbeddingFunction::new_with_model(api_key, "text-embedding-3-small") .expect("failed to create OpenAI embedding function"), ); ``` Provider configuration is SDK-specific, so copy the option names from the provider page for the SDK you use. For example, the OpenAI model is selected with `name` in Python, `model` in TypeScript, and the model argument to `OpenAIEmbeddingFunction::new_with_model` in Rust. | Concept | Python | TypeScript | Rust | | - | - | - | - | | Model | `name="text-embedding-3-small"` | `{ model: "text-embedding-3-small" }` | `new_with_model(api_key, "text-embedding-3-small")` | | Retry count | `max_retries=7` | Provider/client-specific | Provider/client-specific | | API key | `api_key="..."`, environment variables, or `$var:` | `apiKey: "..."`, environment variables, or `$var:` | Constructor argument or environment variable | | Device | Provider-specific, for example `device="cuda"` | Provider-specific | Provider-specific | When ingesting data with an embedding definition, LanceDB only computes the vector column if that column is missing from the incoming batch or present but entirely null. If you provide any non-null values in the vector column, LanceDB treats the column as user-supplied and does not backfill the remaining rows in that batch. For reusable runtime configuration, the registry also supports `$var:` placeholders in embedding-function config. This is useful for provider secrets and environment-specific settings in Python and TypeScript. * Python uses `registry.set_var(...)`. * TypeScript uses `registry.setVar(...)`. * You can provide a fallback with `$var:name:default`. * Sensitive values such as API keys should be passed through registry variables instead of hardcoding them in config. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} registry = get_registry() registry.set_var("api_key", "sk-...") func = registry.get("openai").create(api_key="$var:api_key") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const registry = getRegistry(); registry.setVar("api_key", "sk-..."); const func = registry.get("openai")!.create({ apiKey: "$var:api_key", }); ``` For non-sensitive settings such as inference device selection, you can also use a default fallback: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch registry = get_registry() if torch.cuda.is_available(): registry.set_var("device", "cuda") func = registry.get("huggingface").create(device="$var:device:cpu") ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const registry = getRegistry(); registry.setVar("openai_model", "text-embedding-3-large"); const func = registry.get("openai")!.create({ model: "$var:openai_model:text-embedding-3-small", }); ``` Find the full list of arguments for each provider in the [integrations](/oss/v0-41-0/integrations/embedding) section. ### Trusting remote code and custom endpoints In Python, the embedding definition is stored in the table, so anyone who can write to the table can change it. To keep a table from running code or sending data where you didn't intend, two kinds of settings are only honored when this process has approved them: * `trust_remote_code=True`, which runs code from the model's HuggingFace repository. * Custom endpoints such as OpenAI `base_url`, Ollama `host`, or watsonx `url`, which receive your data and API keys. Embedding functions you create in the current process are approved automatically. When you open a table in a new process, approve these settings explicitly before computing embeddings: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.embeddings import get_registry registry = get_registry() # Pinning a commit hash is recommended, since the code at a branch can change. registry.allow_remote_code("nomic-ai/nomic-embed-text-v1.5", revision="<commit-hash>") registry.allow_endpoint("http://my-ollama-host:11434") ``` Until then, computing embeddings raises `UntrustedEmbeddingConfigError`. Other operations on the table still work. ## Multiple embedding columns A single table can include more than one embedding definition when you want to store multiple semantic views of the same data, or generate embeddings from different source columns. In practice, each embedding definition maps one source column to one vector column, and the table schema can contain multiple such pairs. The exact setup differs by SDK, but the underlying pattern is the same: define a distinct source/vector pair for each embedding function you want applied during ingest. In TypeScript, automatic query embedding currently uses the first embedding function stored in the table metadata. If a table has multiple embedding definitions and you need to query a specific vector column, compute the query embedding explicitly and pass the vector to the search builder. ## Embedding model providers LanceDB supports most popular embedding providers. ### Text embeddings | Provider | Model ID | Default Model | | - | - | - | | OpenAI | `openai` | `text-embedding-ada-002` | | Sentence Transformers | `sentence-transformers` | `all-MiniLM-L6-v2` | | HuggingFace | `huggingface` | `colbert-ir/colbertv2.0` | | Cohere | `cohere` | `embed-multilingual-v3.0` | | ... | ... | ... | ### Multimodal embedding | Provider | Model ID | Supported Inputs | | - | - | - | | OpenCLIP | `open-clip` | Text, Images | | ImageBind | `imagebind` | Text, Images, Audio, Video | | ... | ... | ... | You can find all supported embedding models in the [integrations](/oss/v0-41-0/integrations/embedding) section. ## Embeddings in LanceDB Enterprise Enterprise In LanceDB Enterprise, embedding generation during data ingestion is client-side and the resulting vectors are stored in the Enterprise table. > [!NOTE] > > The Enterprise server does not currently generate embeddings from query text on its own. Any automatic > query-time embedding happens on the client side. ### How string queries are interpreted When the Python SDK connects to Enterprise, `table.search("hello")` can take two different paths: * If the selected vector column has embedding metadata (i.e., the table schema stores the source-column, vector-column, and embedding-function mapping created from fields like `SourceField()` and `VectorField()` during table creation), then the embeddings are computed in the Python client process. The client uses the same local LanceDB embedding registry used by LanceDB Embedded tables to reconstruct the embedding function from schema metadata, compute the query vector in the client process, and send that vector to Enterprise for search. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = table.search("hello").limit(1).to_list() # The Python client computes the query embedding locally, then sends a vector search. ``` * If the table does not have embedding metadata for that search, `table.search("hello")` in `auto` mode is treated as an FTS query instead. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = table.search("hello").limit(5).to_list() # In auto mode this is treated as an FTS query, not a vector query. ``` If you want explicit vector or hybrid behavior and the client cannot resolve an embedding function from the table metadata, generate the query embedding yourself and pass the vector directly. TypeScript has a similar string-query distinction in `auto` mode: if no embedding providers have been registered in the process, `search("text")` falls back to FTS. Once an embedding provider has been imported and registered, the client expects table embedding metadata for automatic vector search and raises an error if the table has none. The manual query-embedding flow below works across Enterprise SDKs and is an explicit path you can use when you want full control over query-time behavior. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # query_vector is assumed to already be generated by your embedding function actual = table.search(query_vector).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // queryVector is assumed to already be generated by your embedding function const actual = (await tbl.search(queryVector).limit(1).toArray())[0]; ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // query_vector is assumed to already be generated by your embedding function let mut results = table.vector_search(query_vector)?.limit(5).execute().await?; while let Some(batch) = results.next().await { println!("{:?}", batch?); } ``` ## Custom Embedding Functions You can always implement your own embedding function: * Python/TypeScript: subclass `TextEmbeddingFunction` (text) or `EmbeddingFunction` (multimodal). * Rust: implement the `EmbeddingFunction` trait. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from functools import cached_property from lancedb.embeddings import TextEmbeddingFunction, register class MyEmbeddingModel: def __init__(self, model_name: str): self.model_name = model_name def encode(self, texts: list[str]) -> list[list[float]]: return [[1.0, 2.0, 3.0] for _ in texts] @register("my-embedder") class MyTextEmbedder(TextEmbeddingFunction): model_name: str = "my-model" def generate_embeddings(self, texts: list[str]) -> list[list[float]]: # Your embedding logic here return self._model.encode(texts) def ndims(self) -> int: # Return the dimensionality of the embeddings return len(self.generate_embeddings(["test"])[0]) @cached_property def _model(self) -> MyEmbeddingModel: # Initialize your model once return MyEmbeddingModel(self.model_name) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect(databaseDir); @register("my_embedding") class MyEmbeddingFunction extends EmbeddingFunction<string> { constructor(optionsRaw = {}) { super(); const options = this.resolveVariables(optionsRaw); // Initialize using options } ndims() { return 3; } protected getSensitiveKeys(): string[] { return []; } embeddingDataType(): Float { return new Float32(); } async computeQueryEmbeddings(_data: string) { // This is a placeholder for a real embedding function return [1, 2, 3]; } async computeSourceEmbeddings(data: string[]) { // This is a placeholder for a real embedding function return Array.from({ length: data.length }).fill([ 1, 2, 3, ]) as number[][]; } } const func = new MyEmbeddingFunction(); const data = [{ text: "pepperoni" }, { text: "pineapple" }]; // Option 1: manually specify the embedding function const table = await db.createTable("vectors", data, { embeddingFunction: { function: func, sourceColumn: "text", vectorColumn: "vector", }, mode: "overwrite", }); // Option 2: provide the embedding function through a schema const schema = LanceSchema({ text: func.sourceField(new Utf8()), vector: func.vectorField(), }); const table2 = await db.createTable("vectors2", data, { schema, mode: "overwrite", }); ``` ```rust Rust icon="rust" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} use std::{borrow::Cow, sync::Arc}; use arrow_array::{Array, FixedSizeListArray, Float32Array}; use arrow_schema::{DataType, Field, Schema}; use lancedb::{ connect, embeddings::{EmbeddingDefinition, EmbeddingFunction}, Result, }; #[derive(Debug, Clone)] struct MyTextEmbedder { dim: usize, } impl EmbeddingFunction for MyTextEmbedder { fn name(&self) -> &str { "my-embedder" } fn source_type(&self) -> Result<Cow<'_, DataType>> { Ok(Cow::Owned(DataType::Utf8)) } fn dest_type(&self) -> Result<Cow<'_, DataType>> { Ok(Cow::Owned(DataType::new_fixed_size_list( DataType::Float32, self.dim as i32, true, ))) } fn compute_source_embeddings(&self, source: Arc<dyn Array>) -> Result<Arc<dyn Array>> { let values = Arc::new(Float32Array::from(vec![1.0f32; source.len() * self.dim])); let field = Arc::new(Field::new("item", DataType::Float32, true)); Ok(Arc::new(FixedSizeListArray::new( field, self.dim as i32, values, None, ))) } fn compute_query_embeddings(&self, _input: Arc<dyn Array>) -> Result<Arc<dyn Array>> { unimplemented!() } } #[tokio::main] async fn main() -> Result<()> { let db = connect("./mydb").execute().await?; db.embedding_registry() .register("my-embedder", Arc::new(MyTextEmbedder { dim: 3 }))?; let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); db.create_empty_table("mytable", schema) .add_embedding(EmbeddingDefinition::new( "text", "my-embedder", Some("vector"), ))? .execute() .await?; Ok(()) } ``` # Embeddings: Quickstart Source: https://docs.lancedb.com/oss/v0-41-0/embedding/quickstart Quickstart guide for generating and working with embeddings. LanceDB will automatically vectorize the data both at ingestion and query time. All you need to do is specify which model to use. Popular embedding models like OpenAI, HuggingFace, Sentence Transformers, CLIP, and more, are supported. ## Step 1: Import Required Libraries First, import the necessary LanceDB components: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import LanceModel, Vector from lancedb.embeddings import get_registry ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/transformers"; import { Utf8 } from "apache-arrow"; ``` * `lancedb`: The main database connection and operations * `LanceModel`: Pydantic model for defining table schemas * `Vector`: Field type for storing vector embeddings * `get_registry()`: Access to the embedding function registry. It has all the supported as well as custom embedding functions registered by the user * TypeScript uses `lancedb.embedding.getRegistry()` and `lancedb.embedding.LanceSchema()` for the same registry/schema workflow * In TypeScript, import the provider module before calling `getRegistry().get(...)`; the provider import is what registers names such as `"huggingface"` or `"openai"` ## Step 2: Connect to LanceDB Establish a connection to your LanceDB Embedded directory or Enterprise cluster: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Enter your LanceDB connection URI for LanceDB Embedded or Enterprise here db = lancedb.connect(...) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const db = await lancedb.connect("data/sample-lancedb"); ``` ## Step 3: Initialize the Embedding Function Choose and configure your embedding model: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} model = get_registry().get("sentence-transformers").create(name="BAAI/bge-small-en-v1.5", ) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const model = (await lancedb.embedding .getRegistry() .get("huggingface") ?.create()) as lancedb.embedding.EmbeddingFunction; ``` This creates an embedding function from the local embedding registry. The Python snippet uses the `sentence-transformers` provider with the BGE model; the TypeScript snippet uses the Transformers-backed `huggingface` provider. You can: * Change `"sentence-transformers"` to other providers like `"openai"`, `"cohere"`, etc. * Modify the model name for different embedding models * Set `device="cuda"` for GPU acceleration if available ## Step 4: Define Your Schema Create a Pydantic model that defines your table structure: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class Words(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const wordsSchema = lancedb.embedding.LanceSchema({ text: model.sourceField(new Utf8()), vector: model.vectorField(), }); ``` * `SourceField()`: This field will be embedded * `VectorField()`: This stores the embeddings * `model.ndims()`: Sets vector dimensions for your model * In TypeScript, use `model.sourceField(...)` and `model.vectorField()` inside `LanceSchema(...)` ## Step 5: Create Table and Ingest Data Create a table with your schema and add data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("words", schema=Words) table.add([ {"text": "hello world"}, {"text": "goodbye world"} ]) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const table = await db.createEmptyTable("words", wordsSchema, { mode: "overwrite", }); await table.add([{ text: "hello world" }, { text: "goodbye world" }]); ``` The `table.add()` call automatically: * Takes the text from each document * Generates embeddings using your chosen model * Stores both the original text and the vector embeddings If your input already includes the vector column, automatic embedding only runs when that column is absent or entirely null for the batch. Partially supplied vectors are treated as manual data, so LanceDB preserves them instead of filling only the missing rows. ## Step 6: Query with Automatic Embedding Note: On LanceDB Enterprise, the server does not generate embeddings from query text. When the Python SDK connects to Enterprise, `table.search("greetings")` can still work when the table schema includes embedding metadata, because the client computes the query embedding before sending the vector search. If there is no embedding metadata for that search, `search("greetings")` in `auto` mode is treated as FTS instead. Search your data using natural language queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} const query = "greetings"; const actual = (await table.search(query).limit(1).toArray())[0]; console.log(actual.text); ``` The search process: 1. Automatically converts your query text to embeddings 2. Finds the most similar vectors in your table 3. Returns the matching documents Automatic text search depends on the table's embedding metadata. If the client cannot reconstruct an embedding function from that metadata, compute the query embedding yourself and search with the vector directly. # MinHash SQL functions Source: https://docs.lancedb.com/oss/v0-41-0/enterprise/sql-minhash Create lexical text signatures and probabilistic duplicate candidates. **Applies to:** Embedded ❌, Enterprise ✅ MinHash compares the sets of token shingles in two texts. Use it to find lexical near duplicates, such as copies with small edits. Embedding distance measures a different kind of similarity; use vector deduplication when semantic similarity is the desired criterion. Use exact hashes when only identical values count as duplicates. > [!NOTE] > > These experimental functions require an Enterprise server with native MinHash > SQL support. Check the server release you run; installing a newer client does > not add server capabilities. The shared SQL and Functions execution context uses the same implementation. Persisted signatures retain their version, tokenizer profile, hash count and shingle size. Recompute signatures when upgrading to an incompatible signature version. Raw index values do not carry the SQL field metadata required to establish a compatible tokenizer and shingle configuration. ## Create a signature ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash('the quick brown fox') AS signature; SELECT minhash(body) AS signature FROM documents; SELECT minhash(body, 256, 3) AS signature FROM documents; ``` `minhash(text[, num_hashes[, shingle_size]])` returns `FixedSizeList<UInt16>` with exactly `num_hashes` elements per signature. The defaults are 128 hashes and shingles of 3 consecutive tokens. `num_hashes` must be a constant integer from 1 through 4096; `shingle_size` must be a constant integer from 1 through 4294967295. More hashes increase storage and computation and reduce sampling error. The integer values occupy `2 * num_hashes` bytes per row before Arrow validity and storage encoding overhead; there is no per-row header. The fixed tokenizer splits text into alphanumeric tokens and lowercases them. It retains stop words, accents and long tokens, and does not stem words. A text with fewer tokens than `shingle_size` contributes a single shingle containing all its tokens. `NULL`, empty text and text with no tokens return `NULL`. The result field carries the logical-type marker and configuration. The configuration is also attached to its `UInt16` item field: Lance storage preserves the outer metadata, while worker function-type transport preserves the item metadata. Readers accept either and reject conflicts. Default metadata: ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "field_metadata": { "lancedb:logical_type": "minhash_signature", "lancedb:minhash:signature_version": "0", "lancedb:minhash:tokenizer": "simple_lowercase_v1", "lancedb:minhash:shingle_size": "3" }, "item_metadata": { "lancedb:minhash:signature_version": "0", "lancedb:minhash:tokenizer": "simple_lowercase_v1", "lancedb:minhash:shingle_size": "3" } } ``` Aliases and `CREATE TABLE ... AS SELECT` preserve this marker, including for empty or all-null results. It identifies the output of `minhash`, regardless of the column's name. Distance and band-key results use their ordinary numeric and list types. Consumers require the configuration metadata and validate the list width and element type. Preserve both levels of field metadata when copying or exporting signatures; Python Arrow fields expose metadata keys and values as byte strings. An ordinary integer list is not automatically a MinHash signature. Earlier experimental `BINARY` signatures must be regenerated from their source text. ## Store signatures in a new table Use a fresh table name to materialize the source columns and their signatures: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE documents_with_signatures AS SELECT *, minhash(body) AS signature FROM documents; ``` Preserve the generated values and field metadata when storing signatures. Use `minhash_distance` to compare compatible signatures. Storing this column does not build a MinHash LSH index. ## Add a signature column with the Python SDK On an Enterprise server with native MinHash column-transform support, an eager column addition uses the same SQL expression as a query: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table.add_columns({"signature": "minhash(body)"}) ``` This fills the new column for existing rows, using only the input columns the expressions reference. It supports the ordinary eager expression form of `add_columns`. Deferred `computed=` declarations and SQL `ALTER TABLE ... ADD COLUMN ... AS` use a separate planner and still require their own MinHash support. Earlier servers can accept `SELECT minhash(body)` while rejecting a column addition; use CTAS with an unused destination name on those versions. Verify the column-writing path on the deployed server version. ## Estimate Jaccard distance ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash_distance( minhash('the red fox jumps', 128, 1), minhash('the red fox runs', 128, 1) ) AS distance; ``` `minhash_distance(left, right)` returns `FLOAT`: one minus the fraction of hash positions that agree. Zero means identical signatures; one means no matching positions. This is an estimate of token-shingle Jaccard distance, with sampling error and possible hash collisions. A threshold on this value is not an exact Jaccard threshold. Exact token-shingle comparison is needed when exact threshold decisions are required. Both signatures must use the same version, tokenizer profile, hash count and shingle size. Missing or incompatible metadata is rejected, even for empty inputs. `UNION`, `CASE` and `COALESCE` reject incompatible signature configurations before execution. Individual hash elements must not be NULL. If either valid operand is `NULL`, the result is `NULL`. ## One entry point for text and vectors `dedupe` and `duplicate_pairs` select the algorithm from the column at the requested dataset snapshot. Top-level string columns use MinHash; supported vector columns retain the vector-index workflow and its metric. A text distance threshold is estimated Jaccard distance in `[0, 1]`; vector thresholds retain their metric's units. Options are validated by the selected implementation. `dedupe` and `duplicate_pairs` also accept stored `FixedSizeList<UInt16>` MinHash columns with the configuration metadata described above: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe('documents', 'signature', distance_threshold => 0.2); SELECT * FROM duplicate_pairs('documents', 'signature', distance_threshold => 0.2); ``` This path reads the saved hashes instead of tokenizing and hashing text again. Hash count and shingle size come from the column; conflicting explicit options are rejected. `num_bands` defaults to 16 and must divide the signature width. An ordinary integer list without MinHash metadata is not a signature column. `EXPLAIN ANALYZE` reports `column_signatures` and `computed_signatures` so the input path can be verified. Producing candidate pairs reads the signature column; returning retained rows still reads the original rows. Eager `add_columns` calculates existing rows once. Keep the saved signatures in sync when text changes. NULL signatures stay in deduplicated output. Compare the two paths on the same source data and with matching signature settings. `text_dedupe` and `text_duplicate_pairs` remain supported for raw-text queries. Use the shared names above for signature-column dispatch and configuration inference. ## Generate candidate keys ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT minhash_lsh_keys(minhash(body), 16) AS band_keys FROM documents; ``` `minhash_lsh_keys(signature[, num_bands])` returns a list of `UINT64` keys. The default is 16 bands. The band count must be a constant integer from 1 through 256 and divide the signature's hash count. Each key includes its band number; matching keys identify potential duplicate pairs. A null signature returns a null list. Generate candidates only among signatures with the same configuration and band count. Deduplicate pairs that share several bands, then score the candidates with `minhash_distance`. LSH can miss pairs that meet the distance threshold; increasing the number of bands improves coverage but increases candidate work. For ideal independent MinHash values, similarity `s`, `b` bands and `r` hashes per band give candidate probability `1 - (1 - s^r)^b`. This is a tuning model, not a completeness guarantee for the implementation. Identical or heavily templated documents can produce quadratic numbers of candidate pairs. A SQL self-join over keys does not by itself impose a memory, pair-count or concurrency bound. A per-row nearest-neighbor query with a top-k limit also does not enumerate all batch duplicate pairs. ## Run complete batch text deduplication ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_id_a, row_id_b, distance, dataset_version FROM duplicate_pairs( 'documents', 'body', distance_threshold => 0.2, num_hashes => 128, shingle_size => 3, num_bands => 16 ); CREATE MATERIALIZED VIEW documents_clean AS SELECT * FROM dedupe( 'documents', 'body', distance_threshold => 0.2 ); REFRESH MATERIALIZED VIEW documents_clean; ``` Both relations bind one immutable source snapshot, scan live rows across all fragments, generate LSH collisions and apply the estimated distance threshold. They require a native table without WAL and a threshold from zero through one. The top-level input column can contain strings or `FixedSizeList<UInt16>` MinHash signatures with valid configuration metadata. No MinHash or vector index is required. The source remains intact. These names preserve the vector meaning of the existing `duplicate_pairs` and `dedupe` relations. The optional `num_hashes`, `shingle_size` and `num_bands` arguments have the same limits as the scalar functions. Text-column queries use the scalar defaults; saved-signature queries infer omitted `num_hashes` and `shingle_size` from column metadata. All arguments must be literals. `dataset_version => 7` pins an explicit version; without it, each query or refresh binds the latest snapshot again. Keep that snapshot's files available throughout execution. Pair row IDs belong to the reported snapshot version; physical row IDs can change across compaction, while stable row IDs remain stable when that table feature is enabled. `duplicate_pairs` emits each unordered candidate pair at most once, with `row_id_a < row_id_b`. It does not silently limit a bucket or apply a per-row neighbor cap. Completeness means all collisions in the declared LSH configuration, not all pairs that meet an exact or estimated distance threshold. `dedupe` returns retained original rows and columns. The default `resolution => 'connected_components'` keeps the smallest snapshot row ID in each transitive component. A chain A–B–C can remove C even when A and C do not match directly. `resolution => 'direct_representative'` visits canonical edges in ascending row-ID order and removes only rows that directly match a retained representative; the same chain retains A and C. Neither policy recovers LSH misses. Rows with NULL or no-token text are retained as isolated rows. For connected components, equal signatures form a clique with identical neighbours. Execution connects each such group with a star and compares one representative per signature group. These edges preserve the same connected components and smallest original row IDs. The pair relation and direct-representative resolution enumerate all matching pairs. A refresh recomputes the complete result because an appended row can connect previously separate components. It does not append new representatives to an old result. Functions SQL jobs and distributed SQL use the ordinary result publication path; incomplete worker output is not a successful materialization. ## Resource limits The initial batch implementation assigns the complete candidate stage to one plan executor. A global stage preserves matches across source fragments. It uses the ordinary streaming transport with backpressure, not one worker per bucket. The executor fleet must advertise `streaming_datafusion` and the capability for the input type: `minhash_pairs_v1` for text-column queries, or `minhash_signature_pairs_v1` for saved-signature-column queries. Signatures and band membership spill to a temporary redb database with a 64 MiB cache. The stage reserves 192 MiB from the query memory pool for that cache and working buffers. Input batches target at most 128 rows and 8 MiB, with 16 MiB of storage I/O buffering and one batch/fragment read ahead. These are processing budgets, not a process RSS limit; storage readers, shared caches and decoding a single large value also use memory. A document larger than 4 MiB fails the operation explicitly. It is never shortened silently. Candidate output has batches of at most 1,024 pairs and a two-batch queue. The final retained-row scan also uses an 8 MiB byte target, 16 MiB of I/O buffering, and one batch/fragment read ahead. Temporary disk use is charged to the query's disk manager and exceeding its budget fails the operation. Representative selection can also spill; it reserves additional memory for the final row masks based on source cardinality, plus a 256 MiB sorting allowance for direct-representative resolution. An insufficient memory pool fails before representative processing. Cancellation closes the output queue and releases temporary state. Dense groups of different signatures can still require quadratic comparisons. Complete pair output is also quadratic for a duplicate clique. The operator reports input rows, signed rows, stored signatures, collapsed signature rows, band entries, band comparisons, output rows and peak staging file bytes. In connected-components mode, `candidate_signature_pairs` counts comparisons between signature groups; full-pair mode reports `unique_candidates` between source rows. Stage, scan-wait, signature and enumeration timers help locate costs; enumeration time includes output backpressure. Evaluate candidate recall and these costs on representative data before increasing workload size or band count. # Agno Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/agno Build a search assistant using the Agno agent framework with LanceDB as the knowledge backend. [Agno](https://docs.agno.com/introduction) is a framework for building agentic AI applications. It supports LanceDB as a knowledge backend, allowing you to easily ingest and retrieve external content for your agents. When you pair Agno's `Knowledge` system with LanceDB, you get a clean Agentic RAG setup. We'll walk through the steps below to build a YouTube transcript-aware Agno assistant that can: * Ingest a transcript from a YouTube video via the YouTube API * Store embeddings and metadata in LanceDB * Retrieve context during responses with hybrid search * Ask questions about the video content in a CLI chat loop ## Prerequisites Install dependencies: ```bash pip icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install -U agno openai lancedb youtube-transcript-api beautifulsoup4 ``` ```bash uv icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv add agno openai lancedb youtube-transcript-api beautifulsoup4 ``` ## Step 1: Configure LanceDB-backed knowledge First, you can initialize the core `Knowledge` object that your agent will use for retrieval. It configures LanceDB as the vector store, enables hybrid search with native LanceDB FTS, and sets the embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import re from agno.agent import Agent from agno.knowledge.embedder.openai import OpenAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.models.openai import OpenAIResponses from agno.vectordb.lancedb import LanceDb, SearchType from youtube_transcript_api import YouTubeTranscriptApi if "OPENAI_API_KEY" not in os.environ: os.environ["OPENAI_API_KEY"] = "sk-..." def extract_video_id(youtube_url: str) -> str: match = re.search(r"(?<=v=)[\w-]+", youtube_url) or re.search( r"(?<=be/)[\w-]+", youtube_url ) if not match: raise ValueError("Could not parse YouTube video ID from URL") return match.group(0) knowledge = Knowledge( vector_db=LanceDb( uri="./tmp/lancedb", table_name="youtube_transcripts", search_type=SearchType.hybrid, embedder=OpenAIEmbedder(id="text-embedding-3-small"), ), ) ``` ## Step 2: Fetch and ingest the YouTube transcript Next, extract a YouTube video ID, fetch the full transcript, and flatten it into text for indexing. The snippet shown below then inserts that transcript text into the Agno knowledge base, which writes vectors and metadata to LanceDB. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} youtube_url = "https://www.youtube.com/watch?v=wl6mFyXoxos" video_id = extract_video_id(youtube_url) ytt = YouTubeTranscriptApi() transcript_segments = ytt.fetch(video_id, languages=["en", "en-US"]).to_raw_data() transcript_text = " ".join(segment["text"] for segment in transcript_segments) knowledge.insert( name=f"YouTube Transcript ({video_id})", text_content=transcript_text, metadata={"source": "youtube", "video_id": video_id, "video_url": youtube_url}, ) ``` > [!NOTE] > > This path explicitly fetches the transcript first, then inserts transcript text into LanceDB through Agno. ## Step 3: Create an Agno agent with knowledge search The next step is to construct an Agno `Agent` and attach the knowledge base you just populated. With `search_knowledge=True`, the agent performs retrieval before answering, so responses stay grounded in transcript context. In Agno, retrieval is exposed as a tool call that the model can invoke at runtime. When `search_knowledge=True`, Agno makes a knowledge-search tool (shown in output as `search_knowledge_base(...)`) available to the model; the model decides when to call it, Agno executes the tool, and the returned context is fed back into the final answer. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} agent = Agent( model=OpenAIResponses(id="gpt-5-mini"), knowledge=knowledge, search_knowledge=True, instructions="Search the transcript and answer only from retrieved context.", markdown=True, ) ``` ## Step 4: Start a CLI chat loop You can now ask an initial question and then start an interactive loop for follow-up queries. Each prompt runs through the same retrieval pipeline, so you can iteratively inspect what the transcript contains. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} agent.print_response( "Summarize the loaded video transcript in 5 concise bullet points.", stream=True, ) while True: question = input("You: ").strip() if question.lower() in {"exit", "quit", "bye"}: break agent.print_response(question, stream=True) ``` > [!NOTE] > > Want local-first inference? Replace OpenAI model/embedder classes with Agno's Ollama providers. See Agno's Ollama knowledge examples: [docs.agno.com/examples/models/ollama/chat/knowledge](https://docs.agno.com/examples/models/ollama/chat/knowledge). ### Question 1 The following question is asked in the CLI chat loop: ``` ┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ Q: What kinds of data can LanceDB handle? ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Tool Calls ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ • search_knowledge_base(query=What kinds of data can LanceDB handle?) ┃ ┃ • search_knowledge_base(query=LanceDB images audio video handle kinds of data ┃ ┃ can handle 'LanceDB can handle' 'kinds of data' 'images audio video' transcript) ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Response (19.1s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ ┃ ┃ • Images, audio, video — i.e., multimodal AI data and “all manners of things ┃ ┃ you don't put into traditional databases” (per the transcript). ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` We get the response based on the transcript's contents as expected. ### Question 2 Let's ask a more specific question about the CEO of LanceDB, which is also in the transcript: ``` You: What is the name of the CEO of LanceDB? INFO Found 10 documents ┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ What is the name of the CEO of LanceDB? ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Tool Calls ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ • search_knowledge_base(query=CEO of LanceDB) ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┏━ Response (16.7s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ ┃ ┃ • According to the retrieved YouTube transcript/title, the CEO of LanceDB is ┃ ┃ Chang She. ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` We get the response based on the transcript's contents and title as expected. ## Why this works well To start, LanceDB Embedded can run from a local directory, so transcript data can stay on your machine. * You do not need to maintain a separate transcript parser in your application code. * You do not need to hand-roll chunking and retrieval orchestration across multiple modules. * One explicit Agno `Knowledge` object, backed by LanceDB, defines both ingestion and search behavior in one place. * Fewer moving parts means the tutorial stays readable and the same pattern is easier to carry into production code. As your application needs grow, you can migrate to LanceDB [Enterprise](/oss/v0-41-0/index#architecture) for convenience features like automatic compaction and reindexing and the ability to scale to really large datasets. # GenKit Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/genkit ### genkitx-lancedb Genkit is an open-source framework for building end-to-end AI and RAG pipelines with a clean, TypeScript-first developer experience. The genkitx-lancedb plugin lets you use LanceDB as a high-performance vector store inside your Genkit flows, so you can index, search, and retrieve data efficiently as part of your AI applications. ### Installation ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pnpm install genkitx-lancedb ``` ### Usage Adding LanceDB plugin to your genkit instance. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import { lancedbIndexerRef, lancedb, lancedbRetrieverRef, WriteMode } from "genkitx-lancedb"; import { textEmbedding004, vertexAI } from "@genkit-ai/vertexai"; import { gemini } from "@genkit-ai/vertexai"; import { z, genkit } from "genkit"; import { Document } from "genkit/retriever"; import { chunk } from "llm-chunk"; import { readFile } from "fs/promises"; import path from "path"; import pdf from "pdf-parse/lib/pdf-parse"; const ai = genkit({ plugins: [ // vertexAI provides the textEmbedding004 embedder vertexAI(), // the local vector store requires an embedder to translate from text to vector lancedb([ { dbUri: ".db", // optional lancedb uri, default to .db tableName: "table", // optional table name, default to table embedder: textEmbedding004, }, ]), ], }); ``` You can run this app with the following command: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} genkit start -- tsx --watch src/index.ts ``` This'll add LanceDB as a retriever and indexer to the genkit instance. You can see it in the GUI view ![Screenshot 2025-05-11 at 7 21 05 PM](https://github.com/user-attachments/assets/e752f7f4-785b-4797-a11e-72ab06a531b7) ### Testing retrieval on a sample table To see the raw retrieval results, open the LanceDB retriever in the Genkit Developer UI, enter a query and run it: ![Screenshot 2025-05-11 at 7 21 05 PM](https://github.com/user-attachments/assets/b8d356ed-8421-4790-8fc0-d6af563b9657) The retriever returns 5 results from the LanceDB table. Each result looks something like this: ![Screenshot 2025-05-11 at 7 21 18 PM](https://github.com/user-attachments/assets/77429525-36e2-4da6-a694-e58c1cf9eb83) ## Creating a custom RAG flow Now that we've seen how you can use LanceDB in a Genkit pipeline, let's refine the flow and create a RAG. A RAG flow will consist of an index and a retriever with its outputs postprocessed and fed into an LLM for final response ### Creating custom indexer flows You can also create custom indexer flows, using more options and features provided by LanceDB. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export const menuPdfIndexer = lancedbIndexerRef({ // Using all defaults, for dbUri, tableName, and embedder, etc }); const chunkingConfig = { minLength: 1000, maxLength: 2000, splitter: "sentence", overlap: 100, delimiters: "", } as any; async function extractTextFromPdf(filePath: string) { const pdfFile = path.resolve(filePath); const dataBuffer = await readFile(pdfFile); const data = await pdf(dataBuffer); return data.text; } export const indexMenu = ai.defineFlow( { name: "indexMenu", inputSchema: z.string().describe("PDF file path"), outputSchema: z.void(), }, async (filePath: string) => { filePath = path.resolve(filePath); // Read the pdf. const pdfTxt = await ai.run("extract-text", () => extractTextFromPdf(filePath)); // Divide the pdf text into segments. const chunks = await ai.run("chunk-it", async () => chunk(pdfTxt, chunkingConfig)); // Convert chunks of text into documents to store in the index. const documents = chunks.map((text) => { return Document.fromText(text, { filePath }); }); // Add documents to the index. await ai.index({ indexer: menuPdfIndexer, documents, options: { writeMode: WriteMode.Overwrite, } as any, }); }, ); ``` ![Screenshot 2025-05-11 at 8 35 56 PM](https://github.com/user-attachments/assets/e2a20ce4-d1d0-4fa2-9a84-f2cc26e3a29f) In your console, you can see the logs ![Screenshot 2025-05-11 at 7 19 14 PM](https://github.com/user-attachments/assets/243f26c5-ed38-40b6-b661-002f40f0423a) ### Creating custom retriever flows You can also create custom retriever flows, using more options and features provided by LanceDB. ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export const menuRetriever = lancedbRetrieverRef({ tableName: "table", // Use the same table name as the indexer. displayName: "Menu", // Use a custom display name. }); export const menuQAFlow = ai.defineFlow( { name: "Menu", inputSchema: z.string(), outputSchema: z.string() }, async (input: string) => { // retrieve relevant documents const docs = await ai.retrieve({ retriever: menuRetriever, query: input, options: { k: 3, }, }); const extractedContent = docs.map((doc) => { if (doc.content && Array.isArray(doc.content) && doc.content.length > 0) { if (doc.content[0].media && doc.content[0].media.url) { return doc.content[0].media.url; } } return "No content found"; }); console.log("Extracted content:", extractedContent); const { text } = await ai.generate({ model: gemini("gemini-2.0-flash"), prompt: ` You are acting as a helpful AI assistant that can answer questions about the food available on the menu at Genkit Grub Pub. Use only the context provided to answer the question. If you don't know, do not make up an answer. Do not add or change items on the menu. Context: ${extractedContent.join("\n\n")} Question: ${input}`, docs, }); return text; }, ); ``` Now using our retrieval flow, we can ask a question about the ingested PDF ![Screenshot 2025-05-11 at 7 18 45 PM](https://github.com/user-attachments/assets/86c66b13-7c12-4d5f-9d81-ae36bfb1c346) # Hermes Agent Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/hermes-agent Use LanceDB as a persistent, semantic memory backend for Hermes Agent. Get durable recall across sessions with vector and hybrid search. [Hermes Agent](https://github.com/NousResearch/hermes-agent) is a self-hosted, open-source personal agent from [Nous Research](https://nousresearch.com). You can talk to it from a terminal UI or reach the same agent from Telegram, Discord, and Slack, and it exposes a dedicated slot for external *memory providers* that run alongside its built-in notes. The [LanceDB memory plugin](https://github.com/lancedb/hermes-agent-memory) fills that slot. It gives Hermes durable, semantic recall across sessions: state a preference or a project convention once, and the agent can retrieve it weeks later in a brand-new session, even when you ask for it in completely different words. Everything runs inside Hermes' own Python process, storing a single LanceDB table on local disk. There's no memory server to operate. > [!NOTE] > > **The mental model is clean** > > * Hermes owns the agent loop > * LanceDB manages the durable long-term memory and offers semantic recall. ## Why LanceDB fits agent memory Out of the box, Hermes remembers with a small curated notes file frozen into the system prompt, plus lexical (keyword) search over past sessions. Both are useful, but keyword search misses paraphrases of what you originally typed, the exact thing you need when recalling a fact you phrased differently months ago. LanceDB Embedded is a retrieval library that runs inside your application, which makes it a natural fit here: * **No server to stand up**: it reads and writes a table on local disk, so the plugin ships as a dependency rather than a service to operate. * **One table holds everything**: content, metadata, and embeddings live together. A memory becomes a structured row with a category, tags, timestamps, and provenance, not just a text blob. * **Query it any way you need**: vector similarity for meaning, BM25 full-text for exact names and jargon, a hybrid of the two, or plain metadata filters to keep recall scoped to the right workspace. * **It scales up**: the same table abstraction carries over to larger LanceDB deployments later, so the local setup is never a dead end. ## Install and activate > [!TIP] > > Want to try this without touching your existing Hermes setup? Run everything in an isolated > profile: `hermes profile create demo`, then add `-p demo` to the commands below. When you're > done, `rm -rf ~/.hermes/profiles/demo` removes all trace. **1. Install Hermes Agent** Skip this if you already have Hermes installed. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash ``` **2. Install the plugin** This shallow-clones the plugin into `~/.hermes/plugins/lancedb/`. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes plugins install lancedb/hermes-agent-memory ``` **3. Install runtime dependencies into Hermes' environment** Hermes loads plugins inside its own Python interpreter, so the dependencies go *there*, not into a separate virtualenv. (This interpreter is shared across profiles, so you only install once.) ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv pip install --python ~/.hermes/hermes-agent/venv/bin/python3 lancedb openai pyyaml ``` **4. Set your embeddings API key** The plugin turns conversations into embeddings, so it needs an embeddings key. By default that is OpenAI, so set `OPENAI_API_KEY` in your environment or in `~/.hermes/.env`. > [!NOTE] > > Prefer a local or non-OpenAI model? The plugin uses an OpenAI-compatible client, so you can > point it at any compatible endpoint (OpenRouter, Ollama, vLLM, …) in your config, with no code > change needed. See [Configuration](#configuration) below. **5. Activate and verify** Switch memory on and pick this plugin: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes memory setup # choose "lancedb" ``` Then confirm it's actually active before you start chatting. This is the one step worth not skipping, because Hermes quietly falls back to its built-in notes if the provider isn't set: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes memory status ``` ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} Memory status ──────────────────────────────────────── Built-in: always active Provider: lancedb Plugin: installed ✓ Status: available ✓ ``` You want to see `Provider: lancedb` with both `installed ✓` and `available ✓`. ## The memory tools Once activated, the agent has four tools for working with long-term memory: | Tool | What it does | | :- | :- | | `lancedb_recall` | Semantic (vector, the default) or hybrid search over your workspace memory. Returns matching facts with scores and provenance. | | `lancedb_remember` | Stores a durable fact when you explicitly ask. Deduplicated by content hash, so remembering the same thing twice doesn't pile up rows. | | `lancedb_read` | Fetches a single memory by ID, optionally with the original conversation messages it was distilled from. | | `lancedb_forget` | Deletes safely: previews candidates first, then deletes by exact ID, so nothing disappears by accident. | Beyond these tools, the plugin also captures durable facts from your conversations automatically: an auxiliary model distills them before context is compressed and again when a session ends, so insights survive even when the raw messages are summarized away. ## Walkthrough "*Teach it your project preferences*" Let's make this concrete with the pain we opened on: re-explaining your setup to the agent every session. We'll save a convention once and then prove a brand-new session can recall it. This example will touch all four tools along the way. ### Remember Ask Hermes to commit a convention to long-term memory. Saying "remember in long-term memory" makes sure it lands in the LanceDB store, which shows up as the `⚡ lancedb_r` (`lancedb_remember`) line below: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● Remember in long-term memory: for this project I only use uv, never pip, and I always add type hints to Python functions. ┊ 🧠 memory +memory: "For this project, the user only uses uv for Python package management, never pip, and always adds type hints to Python functions." ┊ ⚡ lancedb_r 0.0s ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── Remembered. I've stored that project convention: use uv only, never pip, and always add type hints to Python functions. ``` ### Recall First, take Hermes' built-in notes out of the picture so recall can *only* come from LanceDB (the two layers run side by side otherwise, and either could answer): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hermes config set memory.memory_enabled false ``` Now start a fresh session (`/new`) and ask for the convention back, worded completely differently from how you saved it: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● /new ● Look through your long-term memory for my Python project preferences. ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── I found one durable memory about Python project preferences: - Project Python tooling preference is uv; pip is not used; type hints are required. ``` This is the whole point in one exchange. You asked about your *preferences* using none of the words you stored the fact with (no *uv*, no *pip*, no *type hints*), yet a fresh session, with none of the earlier conversation in context, pulls it straight back. Semantic search matches on meaning rather than exact wording, which is precisely where keyword search falls short. > [!TIP] > > Turn the built-in layer back on for everyday use with `hermes config set memory.memory_enabled true`. > The two memory layers happily coexist. We only disabled it here to prove the recall came from > LanceDB. ### Read You can also ask where a fact came from. Hermes attributes the answer to its stored memory rather than guessing from a file in the repo (under the hood, `lancedb_read` can also return the exact source messages a fact was distilled from): ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● Where did that uv preference come from? ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── It came from the project's persistent memory, not from a codebase file I inspected. Specifically, the recalled memory says: - "For this project, the user only uses uv for Python package management, never pip, and always adds type hints to Python functions." ``` ### Forget When a preference changes, ask Hermes to drop the old fact. The tool calls tell the whole story: the two `⚡ lancedb_f` (`lancedb_forget`) lines are it previewing matches and then deleting, and the trailing `⚡ lancedb_r` is it saving the replacement in the same breath: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ● I've switched from uv to pixi. Forget the uv preference. ┊ ⚡ lancedb_f uv preference python package management never pip type hints 0.3s ┊ ⚡ lancedb_f 0.0s ┊ ⚡ lancedb_r 0.2s ─ ⚕ Hermes ──────────────────────────────────────────────────────────────── Done — I removed the uv preference from memory and replaced it with: - This project uses pixi for Python package management - Type hints on Python functions are still preferred ``` Remember, recall, read, forget: four small operations that between them cover the entire lifecycle of a durable memory. ## Retrieval modes Recall ships in `vector` mode by default: pure semantic search, which is what survives the paraphrasing you saw above. If you also need exact name or jargon matching, switch to `hybrid` (vector + BM25) and choose how the two legs are fused: RRF, a vector-biased linear blend, or a cross-encoder reranker. Mode is set per call; fusion is a config setting. ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml plugins: lancedb: retrieval: mode: hybrid # vector (default) | hybrid reranker: type: rrf # how the vector + BM25 legs are fused # Swap RRF for a reranking pass (pulls in sentence-transformers + torch): # type: cross-encoder # model: cross-encoder/ettin-reranker-17m-v1 # rerank_top_n: 50 ``` The cross-encoder is the one path that pulls in a local ML stack, so it stays opt-in. It defaults to the compact 17M-parameter [ettin reranker](https://huggingface.co/cross-encoder/ettin-reranker-17m-v1). ## Inspect the store Everything lives in one table named `memories` at `~/.hermes/lancedb/memories.lance`. Because it's a plain LanceDB table, you can open it directly and see exactly what the agent has stored. A `kind` column separates extracted `fact` rows from the raw `turn` rows they were drawn from: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("~/.hermes/lancedb") tbl = db.open_table("memories") print(tbl.to_pandas()[["kind", "category", "content"]].head()) ``` ## Configuration The plugin runs on sensible defaults once activated: you don't have to configure anything. `~/.hermes/config.yaml` is purely for overrides. Two common ones: Use a cheaper model for the auxiliary fact-extraction calls: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml auxiliary: lancedb_extraction: provider: openrouter model: google/gemini-3-flash ``` Point embeddings at a fully local endpoint (for example, Ollama) so nothing leaves your machine: ```yaml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # ~/.hermes/config.yaml plugins: lancedb: embedding: model: nomic-embed-text base_url: http://localhost:11434/v1 api_key_env: OLLAMA_API_KEY # any value works for local Ollama ``` > [!NOTE] > > Changing the embedding model (or its dimension) against an existing store requires recreating > the table. The plugin fails loudly on a dimension mismatch rather than silently returning > nothing. Every option is documented in the plugin's [`default_config.yaml`](https://github.com/lancedb/hermes-agent-memory/blob/main/src/default_config.yaml). ## Benchmark On [LongMemEval-S](https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned), a long-conversation QA benchmark, LanceDB's semantic recall clearly beat Hermes' built-in lexical search (0.66 vs. 0.53 answer accuracy) by finding the right messages even when the question was worded differently from the original conversation. For the full methodology, the per-question-type breakdown, and a reproducible harness, see the [blog post](https://www.lancedb.com/blog/semantic-memory-for-hermes-agent-with-lancedb) and the [benchmark harness](https://github.com/lancedb/hermes-agent-memory/tree/main/benchmarks). ## Why this works well * **It's local-first and embedded.** The LanceDB memory table lives on your disk with no server to run; the plugin installs as a dependency of Hermes' own environment. * **Recall survives paraphrasing.** Semantic search matches meaning, not spelling, which is the failure mode that sinks keyword-only session search. * **Memories are structured and traceable.** Each fact is a row with metadata and a link back to the messages it came from, and `forget` always previews before it deletes. * **Nothing about it is a dead end.** As your needs grow, the same table abstraction carries over to LanceDB [Enterprise](/oss/v0-41-0/index#architecture) for automatic compaction, reindexing, and scale. To try it, install the plugin, enable it with `hermes memory setup`, and run the kind of workflow we walked through above. # HuggingFace Hub Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/huggingface Use LanceDB directly on Lance datasets hosted on the HuggingFace Hub for multimodal search and retrieval. **Applies to:** Embedded ✅, Enterprise ✅ [HuggingFace Hub](https://huggingface.co/datasets?format=format:lance\&sort=trending) is a popular platform for sharing machine learning datasets, models, and other resources. LanceDB can directly scan Lance datasets hosted on the [HuggingFace Hub](https://huggingface.co/datasets?format=format:lance) with `hf://` URIs. This is enabled under the hood by the [lance-huggingface](https://lance.org/integrations/huggingface/) integration that allows users to stream Lance datasets directly from HuggingFace without needing to download them first. For ML and AI engineers working in LanceDB, this capability is incredibly useful for quickly exploring multimodal datasets and reusing Lance datasets shared by others, without writing custom data loaders or preprocessing pipelines. The snippets below use the [`lance-format/laion-1m`](https://huggingface.co/datasets/lance-format/laion-1m) dataset published in Lance format. The dataset includes a million image-caption pairs, and the Lance dataset can package image embeddings alongside the metadata. This makes it useful for demonstrating LanceDB's multimodal search capabilities in combination with easy sharing via the HuggingFace Hub. The LAION table includes multimodal columns such as: * `image` (inline JPEG bytes) * `caption` (text) * `img_emb` (image embedding vector) * metadata fields such as `url` and `similarity` ## Install dependencies ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install lancedb pillow ``` ## Open the dataset with LanceDB LanceDB can open the dataset directly from the Hub, without needing to download it first. Note that in LanceDB, you need to specify the table name when opening a Lance dataset, and the HuggingFace convention is to use `train` and `test` splits for datasets. The LAION dataset is uploaded as a single split named `train`, so we specify the table name that contains the `*.lance` files when opening the dataset. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") table = db.open_table("train") print(f"Opened table: {table.name}") print(f"Rows: {len(table)}") ``` ## Inspect schema and available indexes ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(table.schema) ``` This prints the schema of the LAION table. Note that there's an image embedding column that's a fixed-size list of 768-dimensional floats, and a binary column containing the raw JPEG bytes of the image. ``` image_path: string caption: string NSFW: string similarity: double LICENSE: string url: string key: string status: string error_message: null width: int64 height: int64 original_width: int64 original_height: int64 exif: string md5: string img_emb: fixed_size_list<item: float>[768] child 0, item: float image: binary ``` When inspecting Lance datasets from HuggingFace, it's also a good idea to check whether the dataset author included any pre-built indexes that you can use for search. You can check the available indexes with: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} print(table.list_indices()) ``` ``` [ Index(IvfPq, columns=["img_emb"], name="img_emb_idx"), Index(FTS, columns=["caption"], name="caption_idx") ] ``` In this case, we see that we have an IVF_PQ vector index on the `img_emb` column, and an FTS index on the `caption` column, which means we can directly do vector search on the image embeddings and keyword search on the captions without needing to build the indexes ourselves! > [!NOTE] > > If you see an empty list, it may be because the dataset author did not include the index files when uploading > to HuggingFace. You can download the dataset locally, and build the indexes yourself. See the [indexing guide](/oss/v0-41-0/indexing/) > for instructions on building different types of indexes with LanceDB. ## Projection scan Run a simple scan by projecting relevant columns to get a feel for the dataset. For example, we can run a search without any filters or input parameters to get a small subset of the data: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( table.search() .select(["caption", "url", "similarity"]) .limit(3) .to_list() ) for i, row in enumerate(rows, start=1): print(f"{i}. {row['caption']}") print(f" url={row['url']}") print(f" similarity={row['similarity']}") ``` We get the first three rows and their metadata printed out, which look like this: ``` 1. Cordelia and Dudley on their wedding day last year url=https://i.dailymail.co.uk/i/pix/2012/01/05/article-2082728-0EF8956600000578-53_233x315.jpg similarity=0.2926466464996338 2. Statistics on challenges for automation in 2021 url=https://verloop.io/wp-content/uploads/2021/02/Challenges.jpg similarity=0.30174341797828674 3. Teacher Gifts / Great gifts for your child's teacher. Don't know what to get? Take a look at these gifts that the teacher in your life will love! url=https://i.pinimg.com/custom_covers/216x146/550494823141083777_1487893945.jpg similarity=0.3362061381340027 ``` ## Scan and filter data Filtered search is a common pattern to narrow down interesting subsets of the data during early exploration. Here's an example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} filtered = ( table.search() .where("height > 600") .select(["caption", "url", "width", "height"]) .limit(3) .to_list() ) for row in filtered: print(row["caption"], row["url"], row["width"], row["height"]) ``` This prints out the metadata for large images with height greater than 600 pixels: ``` Luca Trousers, mustard stripe https://cdn.shopify.com/s/files/1/0151/5333/products/IMG_0791_1024x1024.jpg?v=1585142190 384 766 Baby Blue Fitted Short Sleeve T Shirt 3 https://cdn-img.prettylittlething.com/a/d/d/1/add198cab3ec30a61102437275573f4963642528_cmf6022_3.jpg 384 612 pattern cutting made easy pdf https://i.pinimg.com/736x/7c/6c/a7/7c6ca7361815a8929b3dd6ad34a03ab9.jpg 384 1045 ``` ## Export image bytes to local files To work with a subset of the data locally, you can export the image bytes from the table and save them as JPEG files. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from pathlib import Path sample = ( table.search() .select(["image", "caption"]) .limit(3) .to_list() ) out_dir = Path("samples") out_dir.mkdir(exist_ok=True) for i, row in enumerate(sample): out_path = out_dir / f"laion_{i}.jpg" with open(out_path, "wb") as f: f.write(row["image"]) print(f"Saved {out_path} | caption={row['caption']}") ``` You can now preview the images you just exported on your local machine to get a better sense of the data. ## Vector search You can use LanceDB to run vector search directly on the data on the Hub, **without needing to download the dataset or build your own vector index**. This makes it incredibly easy to explore the dataset and iterate on your search queries before you decide to download a local copy for further experimentation on your end. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Pick an arbitrary image embedding from the dataset query_embedding = ( table.search() .select(["img_emb"]) .limit(1) .to_list()[0]["img_emb"] ) results = ( table.search(query_embedding, vector_column_name="img_emb") .select(["caption", "url", "_distance"]) .limit(3) .to_list() ) for row in results: print(row["_distance"], row["caption"]) ``` | distance | caption | | - | - | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | | 0.17765313386917114 | Cordelia and Dudley on their wedding day last year | > [!WARNING] > > Note that the LAION dataset is known to contain a lot of duplicate images, so you may see the same image > showing up multiple times in the search results. ## Full-text search Run an FTS search query that uses BM25 ranking on the `caption` column (on which we already have an FTS index): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} fts_results = ( table.search("dog running on beach", query_type="fts") .select(["caption", "url", "_score"]) .limit(3) .to_list() ) ``` | caption | url | \_score | | - | - | - | | running with dog | [https://www.doggytastic.com/wp…](https://www.doggytastic.com/wp…) | 15.73168 | | Dog Running in Water | [https://static.wixstatic.com/m…](https://static.wixstatic.com/m…) | 14.756516 | | Dogs on the run by heidiannemo… | [http://ih2.redbubble.net/image…](http://ih2.redbubble.net/image…) | 14.756516 | ## Download the full dataset > [!WARNING] > > You may hit HuggingFace rate limits when streaming large samples from `hf://`, despite using a HuggingFace token. > For repeated queries or queries that operate on the full dataset, it's recommended to > download the dataset locally and query from disk. Here's how to download the entire dataset via the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} huggingface-cli download lance-format/laion-1m --repo-type dataset --local-dir ./laion-1m ``` ## Upload your own datasets to HuggingFace in Lance format This section shows how you can upload your own Lance datasets to the HuggingFace Hub to share with the community. First, install the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) and export both `OPENAI_API_KEY` and `HF_TOKEN`. Then, create a Lance dataset using LanceDB on a local machine, and then proceed to upload it to the Hub via a CLI command. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export OPENAI_API_KEY=... export HF_TOKEN=hf_... hf auth login --token "$HF_TOKEN" ``` A typical sequence of steps is given below. ### 1. Upload your local directory to the Hub Upload the full local directory to a specified repository on the HuggingFace Hub. The command below uploads the contents of your local LanceDB directory at `/path/to/your_local_dir` to a new repository named `your_hf_org/repo_name` under your HuggingFace account. ```bash bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` > [!NOTE] > > The `upload-large-folder` command is designed for [uploading large datasets](https://huggingface.co/docs/huggingface_hub/en/guides/upload) (potentially terabytes in size) and will handle multipart uploads, retries, and resuming interrupted uploads. ### 2. Inspect dataset versions Because you can query your remote dataset directly from HuggingFace with `hf://` URIs in LanceDB, you can easily inspect the dataset versions and updates on the Hub without needing to download the data locally. This is very useful to keep track of changes to the dataset and iterate on your data collection and curation process. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db = lancedb.connect("hf://datasets/your_hf_org/repo_name") table = db.open_table("table_name") versions = table.list_versions() print(versions) ``` This will print out the list of versions available for the dataset on the Hub, along with their metadata such as creation date and description. ### 3. Add a dataset card The Hub dataset card allows you to communicate the schema and usage of the dataset to other developers. It sits at the repo's root in a file named `README.md` on the Hub. This project keeps the source card text in `HF_DATASET_CARD.md`, so you can publish updates to the dataset there and upload it as `README.md` using the following command on the HF CLI: this requires a regular `hf upload` because it is a single-file upload to a specific target path (a custom commit message can be added if you wish). ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload lancedb/magical_kingdom HF_DATASET_CARD.md README.md \ --repo-type dataset \ --commit-message "Update dataset card" ``` ### 4. Update the dataset Over time, you may want to add new rows (append) or columns (backfill) to your dataset as your needs evolve. You can make the necessary updates to your local dataset using LanceDB, and then upload the updated version back to the Hub with the same `hf upload-large-folder` command. ```bash bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` The CLI will only upload the new data that has changed since the last upload, avoiding wasted I/O while making it easy to keep your dataset up-to-date on the Hub. That's it! Your dataset is now updated on the Hub with the new data and schema changes, and other users can query the latest version of the dataset directly from HuggingFace with `hf://` URIs in LanceDB. ## Explore more Lance datasets on HuggingFace The LanceDB team is actively uploading useful and interesting datasets in Lance format to the HuggingFace Hub under the [lance-format](https://huggingface.co/lance-format) organization. We actively encourage the HuggingFace and LanceDB communities to upload their own Lance datasets to the Hub to share with others! In the meantime, feel free to check out the HuggingFace Hub to discover more Lance datasets uploaded by the community. > [card] > > Click here to explore the latest trending Lance datasets on 🤗 HuggingFace! > > [Open](https://huggingface.co/datasets?format=format:lance\&sort=trending) # Kiln AI Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/kiln [**Kiln**](https://kiln.tech) is a free tool for building production-ready AI systems, combining an intuitive desktop application and an open-source Python library. It supports RAG pipelines, evaluations, agents, MCP tool-calling, synthetic data generation, and fine-tuning. Kiln provides deep integration with LanceDB for vector search, full-text search (BM25), and hybrid search. ## Quick Start: Build a RAG Pipeline in 5 Minutes with Kiln and LanceDB Watch the [quick start overview on Vimeo](https://vimeo.com/1119945690). Kiln's [app](https://kiln.tech/download) makes it easy to: * Build a RAG pipeline with a simple drag-and-drop interface * [Compare](#find-the-best-rag-pipeline-for-your-use-case) search index options (powered by LanceDB), document extractors, embedding models, and chunking strategies * Create end-to-end [evaluations](https://docs.kiln.tech/docs/evaluations) to determine which search configuration works best for your use case * Load your data from Kiln into [LanceDB Enterprise](/oss/v0-41-0/index#architecture) for production use * Iterate with confidence by evaluating new content, prompts, models, and embeddings in minutes instead of weeks ## Find the Best RAG Pipeline for Your Use Case There is no universal best RAG solution, only the best solution for your specific use case. Kiln makes it easy to compare state-of-the-art configurations and find which works best for you. Start with pre-configured templates for state-of-the-art RAG at various performance/quality/cost levels, or experiment with any combination of options: | Area | Technologies | Description | | :- | :- | :- | | Search Index | LanceDB | Compare LanceDB's vector search, full-text search (BM25), and hybrid search to find the best approach for your use case. | | Content | Kiln Document Library | Collaborate on a document library with your team to find the best content for your RAG. Track every revision and tag document sets. | | Document Extraction | Gemini, OpenAI GPT, Qwen VL, and more | Find the most accurate document extraction models for converting PDFs, images, audio, video, and other formats into textual data for RAG. | | Embeddings | Embedding models from Gemini, OpenAI, Nomic, Qwen, and more | Find the embedding model best suited to your use case. | | Chunking | LlamaIndex | Find the ideal chunk size and method. | ## Get Started To get started, download the [Kiln App](https://kiln.tech/download), create a project, and navigate to "Docs & Search". See the [Kiln documentation for creating a RAG system](https://docs.kiln.tech/docs/documents-and-search-rag) for details on each step of the process. ## More Information * [Kiln Homepage](https://kiln.tech) * [Download the Kiln App](https://kiln.tech/download) * [Kiln GitHub Repository](https://github.com/Kiln-AI/Kiln) * [Building RAG Systems - Kiln Documentation](https://docs.kiln.tech/docs/documents-and-search-rag) * [Python Library](https://pypi.org/project/kiln-ai/) or `pip install kiln_ai` # LangChain Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/langchain **LangChain** is a framework designed for building applications with large language models (LLMs) by chaining together various components. It supports a range of functionalities including memory, agents, and chat models, enabling developers to create context-aware applications. ![Illustration](https://raw.githubusercontent.com/lancedb/assets/refs/heads/main/docs/assets/integration/langchain_rag.png) LangChain streamlines these stages (in figure above) by providing pre-built components and tools for integration, memory management, and deployment, allowing developers to focus on application logic rather than underlying complexities. Integration of **LangChain** with **LanceDB** enables applications to retrieve the most relevant data by comparing query vectors against stored vectors, facilitating effective information retrieval. It results in better and context aware replies and actions by the LLMs. ## Quick Start You can load your document data using langchain's loaders, for this example we are using `TextLoader` and `OpenAIEmbeddings` as the embedding model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os from langchain.document_loaders import TextLoader from langchain.vectorstores import LanceDB from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter os.environ["OPENAI_API_KEY"] = "sk-..." loader = TextLoader( "../../modules/state_of_the_union.txt" ) # Replace with your data path documents = loader.load() documents = CharacterTextSplitter().split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = LanceDB.from_documents(documents, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) print(docs[0].page_content) ``` ## Documentation In the above example `LanceDB` vector store class object is created using `from_documents()` method which is a `classmethod` and returns the initialized class object. You can also use `LanceDB.from_texts(texts: List[str],embedding: Embeddings)` class method. The exhaustive list of parameters for `LanceDB` vector store are : | Name | type | Purpose | default | | :- | :- | :- | :- | | `connection` | (Optional) `Any` | `lancedb.db.LanceDBConnection` connection object to use. If not provided, a new connection will be created. | `None` | | `embedding` | (Optional) `Embeddings` | LangChain embedding model. | Provided by user. | | `uri` | (Optional) `str` | It specifies the directory location of **LanceDB database** and establishes a connection that can be used to interact with the database. | `/tmp/lancedb` | | `vector_key` | (Optional) `str` | Column name to use for vector's in the table. | `'vector'` | | `id_key` | (Optional) `str` | Column name to use for id's in the table. | `'id'` | | `text_key` | (Optional) `str` | Column name to use for text in the table. | `'text'` | | `table_name` | (Optional) `str` | Name of your table in the database. | `'vectorstore'` | | `api_key` | (Optional `str`) | API key to use for LanceDB Enterprise deployment. | `None` | | `region` | (Optional) `str` | Region to use for LanceDB Enterprise deployment. | Only for LanceDB Enterprise : `None`. | | `mode` | (Optional) `str` | Mode to use for adding data to the table. Valid values are "append" and "overwrite". | `'overwrite'` | | `table` | (Optional) `Any` | You can connect to an existing table of LanceDB, created outside of LangChain, and use it. | `None` | | `distance` | (Optional) `str` | The choice of distance metric used to calculate the similarity between vectors. | `'l2'` | | `reranker` | (Optional) `Any` | The reranker to use for LanceDB. | `None` | | `relevance_score_fn` | (Optional) `Callable[[float], float]` | LangChain relevance score function to be used. | `None` | | `limit` | `int` | Set the maximum number of results to return. | `DEFAULT_K` (it is 4) | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db_url = "db://lang_test" # url of db you created api_key = "xxxxx" # your API key region = "us-east-1-dev" # your selected region vector_store = LanceDB( uri=db_url, api_key=api_key, # (dont include for local API) region=region, # (dont include for local API) embedding=embeddings, table_name="langchain_test", # Optional ) ``` ### Methods ##### `add_texts()` This method turn texts into embedding and add it to the database. | Name | Purpose | defaults | | :- | :- | :- | | `texts` | `Iterable` of strings to add to the vectorstore. | Provided by user | | `metadatas` | Optional `list[dict()]` of metadatas associated with the texts. | `None` | | `ids` | Optional `list` of ids to associate with the texts. | `None` | | `kwargs` | Other keyworded arguments provided by the user. | - | It returns list of ids of the added texts. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} vector_store.add_texts(texts=["test_123"], metadatas=[{"source": "wiki"}]) # Additionally, to explore the table you can load it into a df or save it in a csv file: tbl = vector_store.get_table() print("tbl:", tbl) pd_df = tbl.to_pandas() pd_df.to_csv("docsearch.csv", index=False) # you can also create a new vector store object using an older connection object: vector_store = LanceDB(connection=tbl, embedding=embeddings) ``` With LanceDB Enterprise, `tbl.to_pandas()` raises in the synchronous Python client; read the rows with a query instead, such as `tbl.search().limit(100).to_pandas()`. *** ##### create_index() This method creates a scalar(for non-vector cols) or a vector index on a table. | Name | type | Purpose | defaults | | :- | :- | :- | :- | | `vector_col` | `Optional[str]` | Provide if you want to create index on a vector column. | `None` | | `col_name` | `Optional[str]` | Provide if you want to create index on a non-vector column. | `None` | | `metric` | `Optional[str]` | Provide the metric to use for vector index. choice of metrics: 'l2', 'dot', 'cosine'. | `l2` | | `num_partitions` | `Optional[int]` | Number of partitions to use for the index. | `256` | | `num_sub_vectors` | `Optional[int]` | Number of sub-vectors to use for the index. | `96` | | `index_cache_size` | `Optional[int]` | Size of the index cache. | `None` | | `name` | `Optional[str]` | Name of the table to create index on. | `None` | For index creation make sure your table has enough data in it. An ANN index is usually not needed for datasets \~100K vectors. For large-scale (>1M) or higher dimension vectors, it is beneficial to create an ANN index. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # for creating vector index vector_store.create_index(vector_col="vector", metric="cosine") # for creating scalar index(for non-vector columns) vector_store.create_index(col_name="text") ``` *** ##### similarity_search() This method performs similarity search based on **text query**. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | A `str` representing the text query that you want to search for in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `fts` | `Optional[bool]` | It indicates whether to perform a full-text search (FTS). | `False` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. If not provided, it uses the default table set during the initialization of the LanceDB instance. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | Return documents most similar to the query **without relevance scores**. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search(query) print(docs[0].page_content) ``` *** ##### similarity_search_by_vector() The method returns documents that are most similar to the specified **embedding (query) vector**. | Name | Type | Purpose | Default | | - | - | - | - | | `embedding` | `List[float]` | The embedding vector you want to use to search for similar documents in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. If not provided, it uses the default table set during the initialization of the LanceDB instance. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | **It does not provide relevance scores.** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search_by_vector(query) print(docs[0].page_content) ``` *** ##### similarity_search_with_score() Returns documents most similar to the **query string** along with their relevance scores. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | A `str` representing the text query you want to search for in the vector store. This query will be converted into an embedding using the specified embedding function. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. This allows you to narrow down the search results based on certain metadata attributes associated with the documents. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | It gets called by base class's `similarity_search_with_relevance_scores` which selects relevance score based on our `_select_relevance_score_fn`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docs = docsearch.similarity_search_with_relevance_scores(query) print("relevance score - ", docs[0][1]) print("text- ", docs[0][0].page_content[:1000]) ``` *** ##### similarity_search_by_vector_with_relevance_scores() Similarity search using **query vector**. | Name | Type | Purpose | Default | | - | - | - | - | | `embedding` | `List[float]` | The embedding vector you want to use to search for similar documents in the vector store. | N/A | | `k` | `Optional[int]` | It specifies the number of documents to return. | `None` | | `filter` | `Optional[Dict[str, str]]` | It is used to filter the search results by specific metadata criteria. | `None` | | `name` | `Optional[str]` | It is used for specifying the name of the table to query. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | The method returns documents most similar to the specified embedding (query) vector, along with their relevance scores. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_embedding = embeddings.embed_query("text") docs = docsearch.similarity_search_by_vector_with_relevance_scores(query_embedding) print("relevance score - ", docs[0][1]) print("text- ", docs[0][0].page_content[:1000]) ``` *** ##### max_marginal_relevance_search() This method returns docs selected using the maximal marginal relevance(MMR). Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. | Name | Type | Purpose | Default | | - | - | - | - | | `query` | `str` | Text to look up documents similar to. | N/A | | `k` | `Optional[int]` | Number of Documents to return. | `4` | | `fetch_k` | `Optional[int]` | Number of Documents to fetch to pass to MMR algorithm. | `None` | | `lambda_mult` | `float` | Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. | `0.5` | | `filter` | `Optional[Dict[str, str]]` | Filter by metadata. | `None` | | `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | Similarly, `max_marginal_relevance_search_by_vector()` function returns docs most similar to the embedding passed to the function using MMR. instead of a string query you need to pass the embedding to be searched for. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} result = docsearch.max_marginal_relevance_search(query="text") result_texts = [doc.page_content for doc in result] print(result_texts) # search by vector : result = docsearch.max_marginal_relevance_search_by_vector( embeddings.embed_query("text") ) result_texts = [doc.page_content for doc in result] print(result_texts) ``` *** ##### add_images() This method adds images by automatically creating their embeddings and adds them to the vectorstore. | Name | Type | Purpose | Default | | - | - | - | - | | `uris` | `List[str]` | File path to the image | N/A | | `metadatas` | `Optional[List[dict]]` | Optional list of metadatas | `None` | | `ids` | `Optional[List[str]]` | Optional list of IDs | `None` | It returns list of IDs of the added images. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} image_uris = ["./assets/image-1.png", "./assets/image-2.png"] vector_store.add_images(uris=image_uris) # here image_uris are local fs paths to the images. ``` # LlamaIndex Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/llamaIndex ## Quickstart LlamaIndex is a well-known framework for building LLM-powered agents over your data with LLMs and workflows. You can build your LlamaIndex pipeline and persist your metadata and embeddings in LanceDB via the `LanceDBVectorStore` class. First, install the LlamaIndex-LanceDB integration. pip install llama-index-vector-stores-LanceDB Run the below script as an example. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import logging import sys import textwrap import openai # Uncomment to see debug logs # logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) # logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( Document, SimpleDirectoryReader, StorageContext, VectorStoreIndex, ) from llama_index.vector_stores.lancedb import LanceDBVectorStore openai.api_key = "sk-..." documents = SimpleDirectoryReader("./data/your-data-dir/").load_data() print("Document ID:", documents[0].doc_id, "Document Hash:", documents[0].hash) ## For LanceDB Enterprise : # vector_store = LanceDBVectorStore( # uri="db://db_name", # your remote DB URI # api_key="sk_..", # lancedb enterprise api key # region="your-region" # the region you configured # host_override="https://your-host.com" # if you have a custom host, otherwise omit this # ) vector_store = LanceDBVectorStore( uri="./lancedb", mode="overwrite", query_type="vector" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents(documents, storage_context=storage_context) lance_filter = "metadata.file_name = 'paul_graham_essay.txt' " retriever = index.as_retriever(vector_store_kwargs={"where": lance_filter}) response = retriever.retrieve("What did the author do growing up?") ``` The vector store connector will open an existing LanceDB directory or create the directory if it does not exist. ### Filtering For metadata filtering, you can use a Lance SQL-like string filter as demonstrated in the example above. Additionally, you can also filter using the `MetadataFilters` class from LlamaIndex: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from llama_index.core.vector_stores import ( FilterCondition, FilterOperator, MetadataFilter, MetadataFilters, ) query_filters = MetadataFilters( filters=[ MetadataFilter( key="creation_date", operator=FilterOperator.EQ, value="2024-05-23" ), MetadataFilter(key="file_size", value=75040, operator=FilterOperator.GT), ], condition=FilterCondition.AND, ) ``` ### Hybrid Search For complete documentation, refer [here](/oss/v0-41-0/search/hybrid-search). This example uses the `colbert` reranker. Make sure to install necessary dependencies for the reranker you choose. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.rerankers import ColbertReranker reranker = ColbertReranker() vector_store._add_reranker(reranker) query_engine = index.as_query_engine( filters=query_filters, vector_store_kwargs={ "query_type": "hybrid", }, ) response = query_engine.query("How much did Viaweb charge per month?") ``` In the snippet above, you can change/specify `query_type` when creating the engine/retriever to use different search strategies, such as vector search or FTS. ## API reference > [card] [LlamaIndex Vector Stores API reference](https://developers.llamaindex.ai/python/framework-api-reference/storage/vector_store/lancedb/) > > See the official LlamaIndex Vector Stores API reference for more details. # PromptTools Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/prompttools [PromptTools](https://github.com/hegelai/prompttools) offers a set of free, open-source tools for testing and experimenting with models, prompts, and configurations. The core idea is to enable developers to evaluate prompts using familiar interfaces like code and notebooks. You can use it to experiment with different configurations of LanceDB, and test how LanceDB integrates with the LLM of your choice. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/prompttools-eval-prompts/main.ipynb) ![Alt text](https://prompttools.readthedocs.io/en/latest/_images/demo.gif "a title") # Meta Llama Synthetic Data Kit Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/synthetic-data-kit Use Meta Llama's Synthetic Data Kit with LanceDB to generate high-quality synthetic datasets for LLM fine-tuning and training. [Synthetic Data Kit](https://github.com/meta-llama/synthetic-data-kit) is a tool from Meta LLAMA that helps you generate high-quality synthetic datasets for fine-tuning large language models (LLMs). It simplifies the process of preparing data for fine-tuning by providing a command-line interface (CLI) with a modular four-command flow. One of the key features of the `synthetic-data-kit` is its use of the Lance format for storing and ingesting datasets. This allows for efficient storage and retrieval of data, which is crucial when working with large datasets. ### Key Features: * **Data Ingestion:** The toolkit can ingest various file formats, including PDF, HTML, YouTube transcripts, DOCX, PPT, and TXT. * **Fine-tuning Format Creation:** It can create different fine-tuning formats, such as question-answer (QA) pairs, QA pairs with Chain-of-Thought (CoT), and summarization formats. * **Data Curation:** The tool uses Llama as a judge to curate high-quality examples, ensuring the quality of the generated dataset. * **Flexible Saving Options:** You can save the generated datasets in various formats compatible with your fine-tuning workflow, including HuggingFace, JSONL, and JSON. ### How it Works: The synthetic-data-kit follows a simple four-step process: 1. **Ingest:** Import your input files into the toolkit. The data is stored in the Lance format for efficient processing. 2. **Create:** Generate diverse fine-tuning datasets, such as reasoning, summarization, and QA pairs, from the ingested documents. 3. **Curate:** Use Llama to filter and select high-quality examples from the generated dataset. 4. **Save-as:** Export the curated dataset in your preferred format. ### Usage The `synthetic-data-kit` uses Lance format to store and manage the data that you ingest. The workflow is a series of commands that build on each other, starting with the `ingest` command. Here is an example of the end-to-end workflow: 1. **Ingest Data into a LanceDB dataset** This command reads a source document and creates a Lance dataset from it. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit ingest docs/report.pdf --multimodal # This will create a Lance dataset at data/parsed/report.lance # with 'text' and 'image' columns. ``` 2. **Create fine-tuning data** This command uses the Lance dataset created in the previous step to generate multimodal question-answer pairs. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit create data/parsed/report.lance --type multimodal-qa # This writes data/generated/report.json ``` 3. **Curate the data** This step uses a language model to curate the generated data and ensure its quality. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit curate data/generated/report.json # This writes data/curated/report_cleaned.json ``` 4. **Save the final dataset** Finally, save the curated data in the format you need: `jsonl`, `alpaca`, `ft` or `chatml`. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} synthetic-data-kit save-as data/curated/report_cleaned.json -f jsonl -o ./my_finetuning_data.jsonl ``` This workflow allows you to go from a collection of documents to a high-quality, fine-tuning dataset with just a few commands. The use of LanceDB in the background makes the process efficient and scalable. ### Getting Started: To get started with the synthetic-data-kit, you can clone the [GitHub Repository](https://github.com/meta-llama/synthetic-data-kit) and install the necessary dependencies. > **Note:** You will also need access to a Llama model, either running locally or via a hosted API. # VS Code extensions Source: https://docs.lancedb.com/oss/v0-41-0/integrations/ai/vscode Embed LanceDB in a VS Code extension to search a workspace by meaning, with no server, and bundle and package its native binaries correctly. A VS Code extension runs in the *extension host*, a Node.js process, so LanceDB's TypeScript SDK (`@lancedb/lancedb`) runs inside it like any other npm package. There's no database server to start: the extension opens a table on local disk and queries it in-process. That makes LanceDB a good fit for features such as semantic search over a workspace, retrieval for an AI assistant, or a cache of embeddings that survives restarts. The extension host differs from a plain Node.js script in three ways that trip people up: * **Where you can write.** Relative paths resolve against the extension host's working directory, not the workspace, and that directory may be read-only. * **Bundling.** The default extension template bundles everything with esbuild, which can't bundle LanceDB's native `.node` binary. * **Packaging.** LanceDB installs a native binary for the current platform only, so a VSIX built on one OS doesn't run on another. This guide builds a small extension that handles all three. It indexes the Markdown files in a workspace and searches them by meaning, using a local embedding model, so no API key is needed. > [!NOTE] > > **What you'll build** > > * **LanceDB: Index Markdown in Workspace** splits every `*.md` file into paragraphs and stores > them in a LanceDB table, with embeddings from `Xenova/all-MiniLM-L6-v2` run locally through > Transformers.js. > * **LanceDB: Search Markdown** embeds your query, shows the five closest paragraphs, and opens > the one you pick. ## Create the extension **1. Scaffold a TypeScript extension** Use the official generator. Choose **New Extension (TypeScript)** and **esbuild** as the bundler. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx --package yo --package generator-code -- yo code ``` **2. Install LanceDB** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @lancedb/lancedb apache-arrow@18.1.0 ``` Your code imports Arrow types directly, so add `apache-arrow` as a dependency, pinned inside LanceDB's peer dependency range (`>=15.0.0 <=18.1.0`). If the project already depends on a newer `apache-arrow`, installing LanceDB fails with `ERESOLVE`. LanceDB also needs `@types/node` 22 or later. The generator's template already uses a recent version; an old one causes `Cannot find module 'node:stream'` errors. You don't need to install `@huggingface/transformers` yourself. LanceDB pins it as an optional dependency, and installing a different version gives your code a copy that LanceDB doesn't use. **3. Skip type checking of dependencies** The type declarations of `apache-arrow` and the ONNX runtime used by Transformers.js refer to browser types such as `ReadableStreamReadResult` and `HTMLCanvasElement`. The template's `tsconfig.json` doesn't include the DOM library, so `tsc` reports errors inside `node_modules`. Turn on `skipLibCheck`: ```json tsconfig.json icon="brackets-curly" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "compilerOptions": { "skipLibCheck": true } } ``` ## Store the database in extension storage Give LanceDB an absolute path inside the storage VS Code reserves for your extension: * `context.storageUri`: a folder for the current workspace. It's `undefined` when no folder is open. Use it for anything derived from the workspace, such as this index. * `context.globalStorageUri`: a folder shared by all workspaces. Use it for things like downloaded models. Neither folder is guaranteed to exist, so create it before connecting. Both live outside the user's project, so the index never shows up in their files or in version control. Don't pass a relative path such as `lancedb.connect("data")`. It resolves against the extension host's working directory, which isn't the workspace and may be read-only: this causes the `Read-only file system (os error 30)` error on macOS. Put the LanceDB code in its own module, `src/search.ts`: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as path from "node:path"; import * as lancedb from "@lancedb/lancedb"; import "@lancedb/lancedb/embedding/transformers"; import { Int32, Utf8 } from "apache-arrow"; ``` ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} // Pass an absolute directory, such as `context.storageUri.fsPath`. A relative // path resolves against the extension host's working directory, which is not // your workspace and may be read-only (on macOS it is usually `/`). export async function openDatabase(storageDir: string) { return lancedb.connect(path.join(storageDir, "lancedb")); } ``` ## Index and search Split each file into paragraphs, and keep the line each one starts on so a result can open the file at the right place: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export type Chunk = { path: string; line: number; text: string }; // Split a Markdown file into paragraphs, keeping the line each one starts on // so a search result can jump straight to it. export function chunkMarkdown(filePath: string, content: string): Chunk[] { const lines = content.split(/\r?\n/); const chunks: Chunk[] = []; let start = 0; for (let i = 0; i <= lines.length; i++) { if (i === lines.length || lines[i].trim() === "") { const text = lines.slice(start, i).join("\n").trim(); if (text) { chunks.push({ path: filePath, line: start, text }); } start = i + 1; } } return chunks; } ``` Create the table with LanceDB's built-in `huggingface` [embedding function](/oss/v0-41-0/embedding/quickstart). Because the `text` column is declared as the function's source field, LanceDB computes the `vector` column for you as the rows are written: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) { // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed. const embedder = (await lancedb.embedding .getRegistry() .get("huggingface") ?.create()) as lancedb.embedding.EmbeddingFunction; const schema = lancedb.embedding.LanceSchema({ path: new Utf8(), line: new Int32(), text: embedder.sourceField(new Utf8()), vector: embedder.vectorField(), }); // LanceDB fills in the `vector` column from `text` as the rows are written. return db.createTable("chunks", chunks, { schema, mode: "overwrite" }); } ``` The table remembers its embedding function, so you can search it with plain text after VS Code restarts: ```typescript src/search.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export async function searchChunks( db: lancedb.Connection, query: string, limit = 5, ) { // The table stores its embedding function in its metadata, so a text query // is embedded with the same model that embedded the rows. const table = await db.openTable("chunks"); return table .search(query) .select(["path", "line", "text", "_distance"]) .limit(limit) .toArray(); } ``` `mode: "overwrite"` rebuilds the index each time, which is fine for a few thousand paragraphs. For larger workspaces, update only the files that changed with [`mergeInsert`](/oss/v0-41-0/ingestion/merge-insert). ## Wire up the commands Declare the two commands in `package.json`: ```json package.json icon="brackets-curly" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} "contributes": { "commands": [ { "command": "lancedbSearch.index", "title": "Index Markdown in Workspace", "category": "LanceDB" }, { "command": "lancedbSearch.search", "title": "Search Markdown", "category": "LanceDB" } ] } ``` Then register them in `src/extension.ts`: ```typescript src/extension.ts icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import * as vscode from "vscode"; import { type Chunk, chunkMarkdown, indexChunks, openDatabase, searchChunks, } from "./search"; export async function activate(context: vscode.ExtensionContext) { // One index per workspace. `storageUri` is undefined when no folder is open. const storage = context.storageUri ?? context.globalStorageUri; // Transformers.js downloads the embedding model on first use. Keep it in // global storage so every workspace shares one copy and it survives // extension updates. Use `import()`: LanceDB loads the ES module build, and // `require()` would return a separate copy whose settings LanceDB never sees. const { env } = await import("@huggingface/transformers"); env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, "models").fsPath; context.subscriptions.push( vscode.commands.registerCommand("lancedbSearch.index", async () => { const files = await vscode.workspace.findFiles( "**/*.md", "**/node_modules/**", ); const chunks: Chunk[] = []; for (const file of files) { const bytes = await vscode.workspace.fs.readFile(file); // Store the file's URI, not a path relative to its folder: in a // multi-root workspace `findFiles` searches every folder, and only the // URI says which one a result came from. chunks.push( ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)), ); } if (chunks.length === 0) { vscode.window.showWarningMessage("No Markdown files to index."); return 0; } await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: `Indexing ${files.length} Markdown files`, }, async () => { await vscode.workspace.fs.createDirectory(storage); await indexChunks(await openDatabase(storage.fsPath), chunks); }, ); vscode.window.showInformationMessage( `Indexed ${chunks.length} paragraphs from ${files.length} files.`, ); return chunks.length; }), // Called with a query (for example from a test or another extension), the // command returns the matching rows instead of showing a picker. vscode.commands.registerCommand( "lancedbSearch.search", async (query?: string) => { const text = query ?? (await vscode.window.showInputBox({ prompt: "Search Markdown by meaning", })); if (!text) { return []; } const results = await searchChunks( await openDatabase(storage.fsPath), text, ); if (query !== undefined) { return results; } const picked = await vscode.window.showQuickPick( results.map((row) => { const uri = vscode.Uri.parse(row.path); return { label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`, description: `distance ${row._distance.toFixed(3)}`, detail: row.text, uri, line: row.line, }; }), { placeHolder: text, matchOnDetail: true }, ); if (picked) { const editor = await vscode.window.showTextDocument(picked.uri); const start = new vscode.Position(picked.line, 0); editor.selection = new vscode.Selection(start, start); editor.revealRange( new vscode.Range(start, start), vscode.TextEditorRevealType.InCenter, ); } return results; }, ), ); } export function deactivate() {} ``` A few details in this file are specific to running inside VS Code: * The index goes in `storageUri`, so each workspace gets its own table. * The embedding model (about 90 MB) downloads on first use. By default Transformers.js caches it inside `node_modules` in the installed extension, which is replaced on every update. Setting `env.cacheDir` keeps it in global storage. Load the module with `import()`, not `require()`: LanceDB loads the ES module build of `@huggingface/transformers`, and `require()` returns a separate copy whose settings LanceDB never sees. * Each paragraph is stored with its file's URI, not a path relative to a workspace folder. In a multi-root workspace, `findFiles` searches every folder and two folders can hold the same relative path, so only the URI opens the right file. `asRelativePath` turns it back into a short label, which names the folder when there's more than one. * When another extension or a test passes a query to `lancedbSearch.search`, it returns the rows instead of opening a picker. That's how the results below were produced, with each URI shown through `asRelativePath`. ## Sample results Here are the results of running the extension in VS Code against a small workspace of six Markdown files that document a fictional CLI. The columns are the vector distance (lower is closer), the file and line, and the paragraph. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query: my credentials were exposed, what should I do? 33.100 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. 40.091 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. 42.334 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. 43.105 docs/auth.md:3 Acme uses personal access tokens. Create one under Settings > Tokens. 45.664 README.md:5 Install it with `npm install -g acme-cli`, then run `acme login`. query: uploads are stuck behind the company firewall 38.420 docs/troubleshooting.md:3 If `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443. 39.212 docs/sync.md:3 Run `acme sync` to upload changed notes. Only files modified since the last sync are sent. 40.859 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. 42.537 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. 45.853 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. ``` Neither top result shares a keyword with its query: "credentials were exposed" matches "a token leaks", and "stuck behind the company firewall" matches "hangs … proxy". Picking a result in the search box opens the file at that paragraph. ## Bundle with esbuild The template bundles your code and its dependencies into `dist/extension.js`. esbuild can't bundle native binaries, so building with LanceDB fails with `No loader is configured for ".node" files`. Mark the packages that load native code as external so they're loaded from `node_modules` at runtime: ```javascript esbuild.js icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} external: [ "vscode", "@lancedb/lancedb", "@huggingface/transformers", // LanceDB loads apache-arrow from node_modules anyway; bundling it ships a second copy. "apache-arrow", ], ``` External packages must be in the VSIX, but the template's `.vscodeignore` excludes `node_modules/**`. Delete that line. `vsce` then includes your production dependencies and leaves out the dev dependencies. If you skip this step, the packaged extension fails to activate with `Cannot find module '@lancedb/lancedb'`, and its commands report `command 'lancedbSearch.index' not found`. ## Package a VSIX for each platform npm installs LanceDB's native binary only for the machine it runs on, such as `@lancedb/lancedb-win32-x64-msvc` on 64-bit Windows. Build one VSIX per platform, each on a matching machine or CI runner, and publish them all. The Marketplace serves each user the right one. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npx @vscode/vsce package --target win32-x64 ``` | `vsce` target | LanceDB native package | | :- | :- | | `win32-x64` | `@lancedb/lancedb-win32-x64-msvc` | | `win32-arm64` | `@lancedb/lancedb-win32-arm64-msvc` | | `linux-x64` | `@lancedb/lancedb-linux-x64-gnu` | | `linux-arm64` | `@lancedb/lancedb-linux-arm64-gnu` | | `alpine-x64` | `@lancedb/lancedb-linux-x64-musl` | | `alpine-arm64` | `@lancedb/lancedb-linux-arm64-musl` | | `darwin-arm64` | `@lancedb/lancedb-darwin-arm64` | LanceDB doesn't publish a binary for Intel Macs (`darwin-x64`). The table covers LanceDB's own binaries. This sample's local model also needs `onnxruntime-node`, which Transformers.js loads when the extension activates. Its Linux binaries link against glibc and it publishes no musl build, so the sample as written doesn't run on Alpine, whatever `--target` you pass. To ship the `alpine-*` targets, embed with a hosted API or use [full-text search](/oss/v0-41-0/search/full-text-search) instead, or build ONNX Runtime for musl yourself. > [!TIP] > > Native binaries make the VSIX large: the `win32-x64` build of this extension is about 200 MB. > `onnxruntime-node`, which Transformers.js uses, ships binaries for every platform. Excluding > the ones a target doesn't need brings the `win32-x64` build to about 150 MB. Keep one ignore > file per target and pass it with `--ignoreFile`: > > ```text .vscodeignore.win32-x64 theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > node_modules/onnxruntime-node/bin/napi-v3/darwin/** > node_modules/onnxruntime-node/bin/napi-v3/linux/** > node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/** > ``` > > If you don't need a local model, embed text with a hosted API instead, or use > [full-text search](/oss/v0-41-0/search/full-text-search), which needs no model at all. ## Keep the extension host responsive All extensions share one extension host, and loading the model and computing embeddings in it can stall the others. While the sample indexes, VS Code may briefly report that the extension host is unresponsive. That's fine for a handful of files. For a large workspace, move indexing into a [worker thread](https://nodejs.org/api/worker_threads.html) or a child process, and index in batches as files change instead of all at once. ## Troubleshooting | Error | Cause | Fix | | :- | :- | :- | | `Read-only file system (os error 30)` | A relative database path resolved against the extension host's working directory | Connect to an absolute path under `context.storageUri` or `context.globalStorageUri` | | `No loader is configured for ".node" files` | esbuild tried to bundle a native binary | Mark `@lancedb/lancedb` and `@huggingface/transformers` as `external` | | `Cannot find module '@lancedb/lancedb'`, or `command '…' not found` | The VSIX doesn't contain `node_modules` | Remove `node_modules/**` from `.vscodeignore` | | A native module isn't found on another OS | The VSIX was built on a different platform | Package one VSIX per `--target` on a matching machine | | `Cannot find module 'node:stream' or its corresponding type declarations` | `@types/node` is too old | Use `@types/node` 22 or later | | `Cannot find name 'HTMLCanvasElement'` and similar errors in `node_modules` | Dependency typings refer to DOM types | Set `"skipLibCheck": true` | | `ERESOLVE` with `peer apache-arrow@">=15.0.0 <=18.1.0"` | The project depends on a newer `apache-arrow` | Install `apache-arrow@18.1.0` | | The model downloads again after an update | Transformers.js caches inside the extension's `node_modules` | Set `env.cacheDir` through `import("@huggingface/transformers")` | # dlt Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/dlt [dlt](https://dlthub.com/docs/intro) is an open-source library that you can add to your Python scripts to load data from various and often messy data sources into well-structured, live datasets. dlt's [integration with LanceDB](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb) lets you ingest data from any source (databases, APIs, CSVs, dataframes, JSONs, and more) into LanceDB with a few lines of simple python code. The integration enables automatic normalization of nested data, schema inference, incremental loading and embedding the data. dlt also has integrations with several other tools like dbt, airflow, dagster etc. that can be inserted into your LanceDB workflow. ## How to ingest data into LanceDB In this example, we will be fetching movie information from the [Open Movie Database (OMDb) API](https://www.omdbapi.com/) and loading it into a local LanceDB instance. To implement it, you will need an API key for the OMDb API (which can be created freely [here](https://www.omdbapi.com/apikey.aspx)). 1. **Install `dlt` with LanceDB extras:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install dlt[lancedb] ``` 2. **Inside an empty directory, initialize a `dlt` project with:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dlt init rest_api lancedb ``` This will add all the files necessary to create a `dlt` pipeline that can ingest data from any REST API (ex: OMDb API) and load into LanceDB. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ├── .dlt │ ├── config.toml │ └── secrets.toml ├── rest_api ├── rest_api_pipeline.py └── requirements.txt ``` dlt has a list of pre-built [sources](https://dlthub.com/docs/dlt-ecosystem/verified-sources/) like [SQL databases](https://dlthub.com/docs/dlt-ecosystem/verified-sources/sql_database), [REST APIs](https://dlthub.com/docs/dlt-ecosystem/verified-sources/rest_api), [Google Sheets](https://dlthub.com/docs/dlt-ecosystem/verified-sources/google_sheets), [Notion](https://dlthub.com/docs/dlt-ecosystem/verified-sources/notion) etc., that can be used out-of-the-box by running `dlt init <source_name> lancedb`. Since dlt is a python library, it is also very easy to modify these pre-built sources or to write your own custom source from scratch. 3. **Specify necessary credentials and/or embedding model details:** To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB Embedded or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. dlt's LanceDB integration also allows you to automatically embed the data during ingestion. Depending on the embedding model chosen, you may need to paste the necessary credentials inside `.dlt/secrets.toml`: ```toml theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [sources.rest_api] api_token = "api_token" # Enter the API key for the OMDb API [destination.lancedb] embedding_model_provider = "sentence-transformers" embedding_model = "all-MiniLM-L6-v2" [destination.lancedb.credentials] uri = ".lancedb" api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB Embedded. embedding_model_provider_api_key = "embedding_model_provider_api_key" # Not needed for providers that don't need authentication (ollama, sentence-transformers). ``` See [here](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb#configure-the-destination) for more information and for a list of available models and model providers. 4. **Write the pipeline code inside `rest_api_pipeline.py`:** The following code shows how you can configure dlt's REST API source to connect to the [OMDb API](https://www.omdbapi.com/), fetch all movies with the word "godzilla" in the title, and load it into a LanceDB table. The REST API source allows you to pull data from any API with minimal code, to learn more read the [dlt docs](https://dlthub.com/docs/dlt-ecosystem/verified-sources/rest_api). ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Import necessary modules import dlt from rest_api import rest_api_source # Configure the REST API source movies_source = rest_api_source( { "client": { "base_url": "https://www.omdbapi.com/", "auth": { # authentication strategy for the OMDb API "type": "api_key", "name": "apikey", "api_key": dlt.secrets[ "sources.rest_api.api_token" ], # read API credentials directly from secrets.toml "location": "query", }, "paginator": { # pagination strategy for the OMDb API "type": "page_number", "base_page": 1, "total_path": "totalResults", "maximum_page": 5, }, }, "resources": [ # list of API endpoints to request { "name": "movie_search", "endpoint": { "path": "/", "params": { "s": "godzilla", "type": "movie", }, }, } ], } ) if __name__ == "__main__": # Create a pipeline object pipeline = dlt.pipeline( pipeline_name="movies_pipeline", destination="lancedb", # this tells dlt to load the data into LanceDB dataset_name="movies_data_pipeline", ) # Run the pipeline load_info = pipeline.run(movies_source) # pretty print the information on data that was loaded print(load_info) ``` The script above will ingest the data into LanceDB as it is, i.e. without creating any embeddings. If we want to embed one of the fields (for example, `"Title"` that contains the movie titles), then we will use dlt's `lancedb_adapter` and modify the script as follows: * Add the following import statement: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from dlt.destinations.adapters import lancedb_adapter ``` * Modify the pipeline run like this: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} load_info = pipeline.run( lancedb_adapter( movies_source, embed="Title", ) ) ``` This will use the embedding model specified inside `.dlt/secrets.toml` to embed the field `"Title"`. 5. **Install necessary dependencies:** ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install -r requirements.txt ``` Note: You may need to install the dependencies for your embedding models separately. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install sentence-transformers ``` 6. **Run the pipeline:** Finally, running the following command will ingest the data into your LanceDB instance. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python rest_api_pipeline.py ``` For more information and advanced usage of dlt's LanceDB integration, read [the dlt documentation](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb). # DuckDB Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/duckdb Learn how to use the DuckDB-Lance extension to query Lance tables with SQL. LanceDB integrates with [DuckDB](https://duckdb.org/) through the [Lance extension](https://github.com/lance-format/lance-duckdb) for DuckDB. In this page, we'll show how LanceDB manages table lifecycle, and DuckDB provides SQL analytics (including joins) and search over those tables. Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for LanceDB Embedded tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. ## Install Install the DuckDB CLI as per [their docs](https://duckdb.org/install) and alternatively, their Python package with `pip install duckdb`. Then, open the DuckDB CLI and install and load the Lance extension as follows: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} INSTALL lance; LOAD lance; ``` ## Attach the directory namespace in DuckDB Attach the LanceDB root directory as a Lance namespace: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ATTACH './local_lancedb' AS lance_ns (TYPE LANCE); ``` In this page, tables are referenced using `lance_ns.main.<table_name>`, so the table path is `lance_ns.main.lance_duck`. ## Write Lance table Create the `lance_duck` table using SQL and populate it with sample data: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE OR REPLACE TABLE lance_ns.main.lance_duck AS SELECT * FROM ( VALUES ('duck', 'quack', [0.9, 0.7, 0.1]::FLOAT[]), ('horse', 'neigh', [0.3, 0.1, 0.5]::FLOAT[]), ('dragon', 'roar', [0.5, 0.2, 0.7]::FLOAT[]) ) AS t(animal, noise, vector); ``` This table is the source of truth for all DuckDB queries below. > [!NOTE] > > The examples below show SQL entered in the DuckDB CLI. You can run the same SQL from > Python as well, using LanceDB and DuckDB's Python clients in your application code. ## Query the table with SQL ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM lance_ns.main.lance_duck LIMIT 5; ``` ## Vector search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _distance FROM lance_vector_search( 'lance_ns.main.lance_duck', 'vector', [0.8, 0.7, 0.2]::FLOAT[], k = 1, prefilter = true ) ORDER BY _distance ASC; ``` ## Full-text search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _score FROM lance_fts( 'lance_ns.main.lance_duck', 'animal', 'the brave knight faced the dragon', k = 1, prefilter = true ) ORDER BY _score DESC; ``` ## Hybrid search ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT animal, noise, vector, _hybrid_score, _distance, _score FROM lance_hybrid_search( 'lance_ns.main.lance_duck', 'vector', [0.8, 0.7, 0.2]::FLOAT[], 'animal', 'the duck surprised the dragon', k = 2, prefilter = false, alpha = 0.5, oversample_factor = 4 ) ORDER BY _hybrid_score DESC; ``` ## Directory namespace model A directory namespace maps a LanceDB namespace root -- there's no catalog in Embedded -- to namespace-qualified table identifiers in DuckDB. This keeps table discovery and table naming stable as your project grows. To learn more about the namespace and catalog model, see [Namespaces and the Catalog Model](/oss/v0-41-0/management/namespace). ## Advanced usage See the [docs](https://github.com/lance-format/lance-duckdb) directory in the Lance-DuckDB extension repo for more advanced usage on SQL and REST API clients. # Pandas and PyArrow Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/pandas_and_pyarrow **Applies to:** Embedded ✅, Enterprise ✅ Because Lance is built on top of [Apache Arrow](https://arrow.apache.org/), LanceDB fits naturally into Pandas-first workflows. You can ingest a `DataFrame`, query it with LanceDB's vector operators, and keep working in Pandas without any glue code. ## Create a dataset Start by importing LanceDB alongside your usual Pandas utilities and connect to a temporary database. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import asyncio import tempfile from pathlib import Path import lancedb import pandas as pd ``` Use the familiar `pd.DataFrame` API to prepare your rows, then pass the entire frame to `db.create_table`. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb pandas_df = pd.DataFrame( [ {"id": "1", "text": "dragon", "vector": [0.9, 0.1, 0.3]}, {"id": "2", "text": "griffin", "vector": [0.4, 0.5, 0.2]}, {"id": "3", "text": "phoenix", "vector": [0.7, 0.3, 0.6]}, ] ) pandas_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pandas-demo")) pandas_table = pandas_db.create_table("creatures", data=pandas_df, mode="overwrite") ``` ## Vector search Queries can return Pandas frames as well, so you can immediately inspect the results or pipe them into downstream analytics. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pandas_results = ( pandas_table.search([0.9, 0.1, 0.3]) .select(["text", "_distance"]) .limit(1) .to_pandas() ) print(pandas_results) ``` ## Async API For web services or background jobs that already rely on `asyncio`, use the asynchronous helpers to keep everything non-blocking. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb async def run_pandas_async_example() -> pd.DataFrame: async_db = await lancedb.connect_async( str(Path(tempfile.mkdtemp()) / "pandas-async") ) async_df = pd.DataFrame( [ {"id": "10", "text": "sage", "vector": [0.6, 0.4, 0.8]}, {"id": "11", "text": "bard", "vector": [0.2, 0.7, 0.3]}, ] ) async_table = await async_db.create_table( "creatures_async", data=async_df, mode="overwrite" ) # An async search returns its query builder from an await query = await async_table.search([0.6, 0.4, 0.8]) async_results = await query.select(["text", "_distance"]).limit(1).to_pandas() print(async_results) return async_results async_results = asyncio.run(run_pandas_async_example()) ``` # Polars Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/polars_arrow **Applies to:** Embedded ✅, Enterprise ✅ LanceDB supports [Polars](https://github.com/pola-rs/polars), a blazingly fast DataFrame library for Python written in Rust. Under the hood, both Lance and Polars speak Arrow, so passing data back and forth stays zero-copy and ergonomic. ## Create and Query a Table Import the required libraries, including the optional Pydantic helpers if you plan to define schemas. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import polars as pl from lancedb.pydantic import LanceModel, Vector ``` Build a Polars `DataFrame`, convert it to Arrow, and use it directly when creating a LanceDB table. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb birds = pl.DataFrame( { "text": ["phoenix", "sparrow"], "vector": [ [0.1, 0.2, 0.3], [0.8, 0.6, 0.5], ], } ) polars_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "polars-demo")) polars_table = polars_db.create_table( "birds", data=birds.to_arrow(), mode="overwrite" ) ``` Run vector search and keep the results as a Polars `DataFrame` for further processing or visualization. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} polars_results = ( polars_table.search([0.1, 0.2, 0.3]) .select(["text", "_distance"]) .limit(1) .to_polars() ) print(polars_results) ``` ## Work with LazyFrames When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for LanceDB Embedded tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lazy_frame = polars_table.to_polars().lazy() print(lazy_frame.select(["text"]).collect()) ``` ## Define Schemas with Pydantic You can also describe your table via `LanceModel` and continue ingesting data from Polars. This is useful when multiple teams share a schema or when you want validation. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class BirdModel(LanceModel): text: str vector: Vector(3) schema_table = polars_db.create_table( "birds_schema", schema=BirdModel, mode="overwrite" ) schema_table.add(birds.to_dicts()) ``` # Pydantic Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/pydantic **Applies to:** Embedded ✅, Enterprise ✅ [Pydantic](https://docs.pydantic.dev/latest/) is a data validation library in Python. LanceDB integrates with Pydantic for schema inference, data ingestion, and query result casting. Using `lancedb.pydantic.LanceModel`, users can seamlessly integrate Pydantic with the rest of the LanceDB APIs. First, import the necessary LanceDB and Pydantic modules: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.pydantic import LanceModel, Vector ``` Next, define your Pydantic model by inheriting from `LanceModel` and specifying your fields including a vector field: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} class LanceDocs(LanceModel): text: str vector: Vector(2) ``` Set the database connection URL: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pydantic-docs")) ``` Now you can create a table, add data, and perform vector search operations: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} table = db.create_table("docs", schema=LanceDocs, mode="overwrite") table.add( [ {"text": "hello world", "vector": [1.0, 0.0]}, {"text": "goodbye world", "vector": [0.0, 1.0]}, ] ) results = table.search([1.0, 0.0]).limit(1).to_pydantic(LanceDocs) print(results[0].text) # hello world ``` ## Vector Field LanceDB provides a `lancedb.pydantic.Vector` method to define a vector Field in a Pydantic Model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa import pydantic from lancedb.pydantic import Vector, pydantic_to_schema class MyModel(pydantic.BaseModel): id: int url: str embeddings: Vector(768) schema = pydantic_to_schema(MyModel) assert schema == pa.schema( [ pa.field("id", pa.int64(), False), pa.field("url", pa.utf8(), False), pa.field("embeddings", pa.list_(pa.float32(), 768)), ] ) ``` This example demonstrates how LanceDB automatically converts Pydantic field types to their corresponding Apache Arrow data types. The `pydantic_to_schema()` function takes a Pydantic model and generates an Arrow schema where: * `int` fields become `pa.int64()` (64-bit integers) * `str` fields become `pa.utf8()` (UTF-8 encoded strings) * `Vector(768)` becomes `pa.list_(pa.float32(), 768)` (fixed-size list of 768 float32 values) * The `False` parameter indicates that the fields are not nullable ## Type Conversion LanceDB automatically convert Pydantic fields to [Apache Arrow DataType](https://arrow.apache.org/docs/python/generated/pyarrow.DataType.html#pyarrow.DataType). Current supported type conversions: | Pydantic Field Type | PyArrow Data Type | | - | - | | `int` | `pyarrow.int64` | | `float` | `pyarrow.float64` | | `bool` | `pyarrow.bool` | | `str` | `pyarrow.utf8()` | | `list` | `pyarrow.List` | | `BaseModel` | `pyarrow.Struct` | | `Vector(n)` | `pyarrow.FixedSizeList(float32, n)` | LanceDB supports to create Apache Arrow Schema from a `pydantic.BaseModel` via `lancedb.pydantic.pydantic_to_schema` method. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from typing import List, Optional import pyarrow as pa import pydantic from lancedb.pydantic import Vector, pydantic_to_schema class FooModel(pydantic.BaseModel): id: int s: str vec: Vector(1536) # fixed_size_list<item: float32>[1536] li: List[int] schema = pydantic_to_schema(FooModel) assert schema == pa.schema( [ pa.field("id", pa.int64(), False), pa.field("s", pa.utf8(), False), pa.field("vec", pa.list_(pa.float32(), 1536)), pa.field("li", pa.list_(pa.int64()), False), ] ) ``` This example shows a more complex Pydantic model with various field types and demonstrates how LanceDB handles: * Basic types: `int` and `str` fields * Vector fields: `Vector(1536)` creates a fixed-size list of 1536 float32 values * List fields: `List[int]` becomes a variable-length list of int64 values * Schema generation: The `pydantic_to_schema()` function automatically converts all these types to their Arrow equivalents # Voxel51 Source: https://docs.lancedb.com/oss/v0-41-0/integrations/data/voxel51 # FiftyOne [FiftyOne](https://docs.voxel51.com/) is an open source toolkit that enables users to curate better data and build better models. It includes tools for data exploration, visualization, and management, as well as features for collaboration and sharing. Any developers, data scientists, and researchers who work with computer vision and machine learning can use FiftyOne to improve the quality of their datasets and deliver insights about their models. ![example](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/integrations/voxel.gif?s=482923f3f137db0286c7a22e3b1b1968) **FiftyOne** provides an API to create LanceDB tables and run similarity queries, both **programmatically in Python** and via **point-and-click in the App**. Let's get started and see how to use **LanceDB** to create a **similarity index** on your FiftyOne datasets. ## Overview [Embeddings](/oss/v0-41-0/embedding/) are foundational to all of the **vector search** features. In FiftyOne, embeddings are managed by the [**FiftyOne Brain**](https://docs.voxel51.com/user_guide/brain.html) that provides powerful machine learning techniques designed to transform how you curate your data from an art into a measurable science. > *Have you ever wanted to find the images most similar to an image in your dataset?* The **FiftyOne Brain** makes computing **visual similarity** really easy. You can compute the similarity of samples in your dataset using an embedding model and store the results in the **brain key**. You can then sort your samples by similarity or use this information to find potential duplicate images. We'll be doing the following : 1. **Create Index** - To run similarity queries against our media, we need to **index** the data. We can do this via the `compute_similarity()` function. * In the function, specify the **model** you want to use to generate the embedding vectors, and what **vector search engine** you want to use on the **backend** (here LanceDB). > [!TIP] > > You can also give the similarity index a name(`brain_key`), which is useful if you want to run vector searches against multiple indexes. 2. **Query** - Once you have generated your similarity index, you can query your dataset with `sort_by_similarity()`. The query can be any of the following: * An ID (sample or patch) * A query vector of same dimension as the index * A list of IDs (samples or patches) * A text prompt (search semantically) ## Prerequisites: install necessary dependencies 1. **Create and activate a virtual environment** Install virtualenv package and run the following command in your project directory. python -m venv fiftyone\_ From inside the project directory run the following to activate the virtual environment. source fiftyone\_/Scripts/activate fiftyone\_/Scripts/activate 2. **Install the following packages in the virtual environment** To install FiftyOne, ensure you have activated any virtual environment that you are using, then run pip install fiftyone ## Understand basic workflow The basic workflow shown below uses LanceDB to create a similarity index on your FiftyOne datasets: 1. Load a dataset into FiftyOne. 2. Compute embedding vectors for samples or patches in your dataset, or select a model to use to generate embeddings. 3. Use the `compute_similarity()` method to generate a LanceDB table for the samples or object patches embeddings in a dataset by setting the parameter `backend="lancedb"` and specifying a `brain_key` of your choice. 4. Use this LanceDB table to query your data with `sort_by_similarity()`. 5. If desired, delete the table. ## Quick Example Let's jump on a quick example that demonstrates this workflow. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone as fo import fiftyone.brain as fob import fiftyone.zoo as foz # Step 1: Load your data into FiftyOne dataset = foz.load_zoo_dataset("quickstart") ``` Make sure you install torch ([guide here](https://pytorch.org/get-started/locally/)) before proceeding. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Steps 2 and 3: Compute embeddings and create a similarity index lancedb_index = fob.compute_similarity( dataset, model="clip-vit-base32-torch", brain_key="lancedb_index", backend="lancedb", ) ``` > [!NOTE] > > Running the code above downloads the CLIP model (2.6 GB). Once the similarity index has been generated, we can query our data in FiftyOne by specifying the `brain_key`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Step 4: Query your data query = dataset.first().id # query by sample ID view = dataset.sort_by_similarity( query, brain_key="lancedb_index", k=10, # limit to 10 most similar samples ) ``` The returned result are of type - `DatasetView`. > [!NOTE] > > `DatasetView` does not hold its contents in-memory. Views simply store the rule(s) that are applied to extract the content of interest from the underlying Dataset when the view is iterated/aggregated on. > > This means, for example, that the contents of a `DatasetView` may change as the underlying Dataset is modified. > *Can you query a view instead of dataset?* Yes, you can also query a view. Performing a similarity search on a `DatasetView` will only return results from the view; if the view contains samples that were not included in the index, they will never be included in the result. This means that you can index an entire Dataset once and then perform searches on subsets of the dataset by constructing views that contain the images of interest. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Step 5 (optional): Cleanup # Delete the LanceDB table lancedb_index.cleanup() # Delete run record from FiftyOne dataset.delete_brain_run("lancedb_index") ``` ## Using LanceDB backend By default, calling `compute_similarity()` or `sort_by_similarity()` will use an sklearn backend. To use the LanceDB backend, simply set the optional `backend` parameter of `compute_similarity()` to `"lancedb"`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone.brain as fob # Re-run similarity creation using the LanceDB backend explicitly fob.compute_similarity( dataset, model="clip-vit-base32-torch", brain_key="lancedb_index", backend="lancedb", ) ``` Alternatively, you can configure FiftyOne to use the LanceDB backend by setting the following environment variable. In your terminal, set the environment variable using: export FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND=lancedb \$Env:FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND="lancedb" //powershell set FIFTYONE_BRAIN_DEFAULT_SIMILARITY_BACKEND=lancedb //cmd > [!WARNING] > > This will only run during the terminal session. Once terminal is closed, environment variable is deleted. Alternatively, you can **permanently** configure FiftyOne to use the LanceDB backend creating a `brain_config.json` at `~/.fiftyone/brain_config.json`. The JSON file may contain any desired subset of config fields that you wish to customize. ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "default_similarity_backend": "lancedb" } ``` This will override the default `brain_config` and will set it according to your customization. You can check the configuration by running the following code : ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import fiftyone.brain as fob # Print your current brain config print(fob.brain_config) ``` ## LanceDB config parameters The LanceDB backend supports query parameters that can be used to customize your similarity queries. These parameters include: | Name | Purpose | Default | | :- | :- | :- | | **table_name** | The name of the LanceDB table to use. If none is provided, a new table will be created | `None` | | **metric** | The embedding distance metric to use when creating a new table. The supported values are ("cosine", "euclidean") | `"cosine"` | | **uri** | The database URI to use. In this Database URI, tables will be created. | `"/tmp/lancedb"` | There are two ways to specify/customize the parameters: 1. **Using `brain_config.json` file** ```json theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} { "similarity_backends": { "lancedb": { "table_name": "your-table", "metric": "euclidean", "uri": "/tmp/lancedb" } } } ``` 2. **Directly passing to `compute_similarity()` to configure a specific new index** : ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lancedb_index = fob.compute_similarity( dataset, model="clip-vit-base32-torch", backend="lancedb", brain_key="lancedb_index", table_name="your-table", metric="euclidean", uri="/tmp/lancedb", ) ``` For a much more in depth walkthrough of the integration, visit the LanceDB x Voxel51 [docs page](https://docs.voxel51.com/integrations/lancedb.html). # AWS Bedrock Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/aws AWS Bedrock supports multiple base models for generating text embeddings. You need to setup the AWS credentials to use this embedding function. You can do so by using `awscli` and also add your session_token: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws configure aws configure set aws_session_token "<your_session_token>" ``` to ensure that the credentials are set up correctly, you can run the following command: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} aws sts get-caller-identity ``` Supported Embedding modelIDs are: * `amazon.titan-embed-text-v1` * `cohere.embed-english-v3` * `cohere.embed-multilingual-v3` Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | **name** | str | "amazon.titan-embed-text-v1" | The model ID of the bedrock model to use. Supported base models for Text Embeddings: amazon.titan-embed-text-v1, cohere.embed-english-v3, cohere.embed-multilingual-v3 | | **region** | str | "us-east-1" | Optional name of the AWS Region in which the service should be called (e.g., "us-east-1"). | | **profile_name** | str | None | Optional name of the AWS profile to use for calling the Bedrock service. If not specified, the default profile will be used. | | **assumed_role** | str | None | Optional ARN of an AWS IAM role to assume for calling the Bedrock service. If not specified, the current active credentials will be used. | | **role_session_name** | str | "lancedb-embeddings" | Optional name of the AWS IAM role session to use for calling the Bedrock service. If not specified, a "lancedb-embeddings" name will be used. | | **runtime** | bool | True | Optional choice of getting different client to perform operations with the Amazon Bedrock service. | | **max_retries** | int | 7 | Optional number of retries to perform when a request fails. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector model = get_registry().get("bedrock-text").create() class TextModel(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hello world", "goodbye world"]}) db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "bedrock-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(df) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # Cohere Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/cohere Using cohere API requires cohere package, which can be installed using `pip install cohere`. Cohere embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `COHERE_API_KEY` environment variable to use the Cohere API. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export COHERE_API_KEY="your-api-key" ``` Supported models are: * embed-english-v3.0 * embed-multilingual-v3.0 * embed-english-light-v3.0 * embed-multilingual-light-v3.0 The v2.0 models (`embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`) were retired by Cohere on April 4, 2026. Python 0.41.0 defaults to `embed-multilingual-v2.0` (768 dimensions). Python 0.42.0b8 defaults to `embed-multilingual-v3.0` (1024 dimensions). Set `name="embed-multilingual-v3.0"` explicitly, as in the example below, rather than relying on the client default. Existing tables containing vectors from a v2.0 model must be re-embedded with an active model into a table whose vector column has the matching dimension. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | v2.0 in Python 0.41.0; v3.0 in Python 0.42.0b8 | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0 | | `source_input_type` | `str` | `"search_document"` | The type of input data to be used for the source column. | | `query_input_type` | `str` | `"search_query"` | The type of input data to be used for the query. | Cohere supports following input types: | Input type | Description | | - | - | | `search_document` | Used for embeddings stored in a vector database for search use cases. | | `search_query` | Used for embeddings of search queries run against a vector database. | | `semantic_similarity` | Specifies that the text will be used for semantic textual similarity (STS). | | `classification` | Used for embeddings passed through a text classifier. | | `clustering` | Used for embeddings run through a clustering algorithm. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector cohere = ( EmbeddingFunctionRegistry.get_instance() .get("cohere") .create(name="embed-multilingual-v3.0") ) class TextModel(LanceModel): text: str = cohere.SourceField() vector: Vector(cohere.ndims()) = cohere.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cohere-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` # ColPali Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/colpali We support [ColPali](https://github.com/illuin-tech/colpali) model embeddings for multimodal multi-vector retrieval. ColPali produces multiple embedding vectors per input (multi-vector), enabling more nuanced similarity matching between text queries and image documents. Using ColPali requires the colpali-engine package, which can be installed using `pip install colpali-engine`. > [!NOTE] > > ColPali produces **multi-vector** embeddings, meaning each input generates multiple embedding vectors rather than a single vector. Use `MultiVector(func.ndims())` instead of `Vector(func.ndims())` when defining your schema. Supported models are: * Metric-AI/ColQwen2.5-3b-multilingual-v1.0 (default) * vidore/colpali-v1.3 * vidore/colqwen2-v1.0 * vidore/colSmol-256M Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `model_name` | `str` | `"Metric-AI/ColQwen2.5-3b-multilingual-v1.0"` | The name of the model to use. | | `device` | `str` | `"auto"` | The device for inference. Can be `"auto"`, `"cpu"`, `"cuda"`, or `"mps"`. | | `dtype` | `str` | `"bfloat16"` | Data type for model weights (bfloat16, float16, float32, float64). | | `pooling_strategy` | `str` | `"hierarchical"` | Token pooling strategy: `"hierarchical"`, `"lambda"`, or `None`. | | `pool_factor` | `int` | `2` | Factor to reduce sequence length when pooling is enabled. | | `batch_size` | `int` | `2` | Batch size for processing inputs. | | `quantization_config` | `Optional[BitsAndBytesConfig]` | `None` | Quantization configuration for the model (requires bitsandbytes). | This embedding function supports ingesting images as both bytes and URLs. You can query them using text. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, MultiVector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "colpali-demo")) func = get_registry().get("colpali").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: MultiVector(func.ndims()) = func.VectorField() vec_from_bytes: MultiVector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "dog", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` Now we can search using text queries: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} actual = ( table.search("a furry pet", vector_column_name="vector") .limit(1) .to_pydantic(Images)[0] ) print(actual.label) ``` # Gemini Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/gemini With Google's Gemini, you can represent text (words, sentences, and blocks of text) in a vectorized form, making it easier to compare and contrast embeddings. For example, two texts that share a similar subject matter or sentiment should have similar embeddings, which can be identified through mathematical comparison techniques such as cosine similarity. For more on how and why you should use embeddings, refer to the Embeddings guide. The Gemini Embedding Model API supports various task types: | Task Type | Description | | - | - | | `retrieval_query` | Specifies the given text is a query in a search/retrieval setting. | | `retrieval_document` | Specifies the given text is a document in a search/retrieval setting. Using this task type requires a title but is automatically provided by Embeddings API | | `semantic_similarity` | Specifies the given text will be used for Semantic Textual Similarity (STS). | | `classification` | Specifies that the embeddings will be used for classification. | | `clustering` | Specifies that the embeddings will be used for clustering. | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector model = get_registry().get("gemini-text").create() class TextModel(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hello world", "goodbye world"]}) db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "gemini-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(df) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # HuggingFace Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/huggingface We offer support for all HuggingFace models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some HuggingFace models might require custom models defined on the HuggingFace Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Pin `revision` to a commit hash, and note that tables using such a model need it approved with `get_registry().allow_remote_code(...)` when opened in a new process. See [Trusting remote code and custom endpoints](/oss/v0-41-0/embedding#trusting-remote-code-and-custom-endpoints). Example usage: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "huggingface-demo")) model = get_registry().get("huggingface").create(name="facebook/bart-base") class Words(LanceModel): text: str = model.SourceField() vector: Vector(model.ndims()) = model.VectorField() df = pd.DataFrame({"text": ["hi hello sayonara", "goodbye world"]}) table = db.create_table("greets", schema=Words) table.add(df) query = "old greeting" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # IBM watsonx Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/ibm Generate text embeddings using IBM's watsonx.ai platform. ## Supported Models You can find a list of supported models at [IBM watsonx.ai Documentation](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx). The currently supported model names are: | Model ID | Dimensions | | - | - | | `ibm/granite-embedding-278m-multilingual` | 768 | | `ibm/slate-125m-english-rtrvr-v2` | 768 | | `ibm/slate-30m-english-rtrvr-v2` | 384 | | `intfloat/multilingual-e5-large` | 1024 | > [!NOTE] > > For new tables, pass `name="ibm/granite-embedding-278m-multilingual"`. The default `name` is still the legacy `ibm/slate-125m-english-rtrvr`, so tables created with it reload with the same model. Legacy and deprecated IDs (such as `ibm/slate-125m-english-rtrvr`, `sentence-transformers/all-minilm-l6-v2` and `sentence-transformers/all-minilm-l12-v2`) still work for tables whose stored metadata references them, but they aren't listed above for new use. ## Parameters The following parameters can be passed to the `create` method: | Parameter | Type | Default Value | Description | | - | - | - | - | | name | str | `"ibm/slate-125m-english-rtrvr"` | The model ID of the watsonx.ai model to use. Pass one of the current supported IDs above (e.g. `"ibm/granite-embedding-278m-multilingual"`) when creating new tables. | | api_key | str | None | Optional IBM Cloud API key (or set `WATSONX_API_KEY`) | | project_id | str | None | Optional watsonx project ID (or set `WATSONX_PROJECT_ID`). Mutually exclusive with `space_id`. | | space_id | str | None | Optional watsonx deployment space ID (or set `WATSONX_SPACE_ID`). Mutually exclusive with `project_id`. | | url | str | None | Optional custom URL for the watsonx.ai instance | | params | dict | None | Optional additional parameters for the embedding model (e.g. `{"truncate_input_tokens": 512}`) | > [!NOTE] > > You must supply exactly one of `project_id` or `space_id` (either as an argument or via its environment variable). Setting both, or neither, raises a `ValueError`. ## Usage Example First, the watsonx.ai library is an optional dependency, so must be installed separately: ``` pip install ibm-watsonx-ai ``` Optionally set environment variables (if not passing credentials to `create` directly): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export WATSONX_API_KEY="YOUR_WATSONX_API_KEY" # Provide exactly one of the following: export WATSONX_PROJECT_ID="YOUR_WATSONX_PROJECT_ID" # export WATSONX_SPACE_ID="YOUR_WATSONX_SPACE_ID" ``` Replace the credential placeholders with your provider credentials. The registry variable keeps the API key out of stored embedding configuration. In application code, load its value from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector registry = EmbeddingFunctionRegistry.get_instance() registry.set_var("watsonx-api-key", "your-api-key") watsonx_embed = registry.get("watsonx").create( name="ibm/slate-125m-english-rtrvr", api_key="$var:watsonx-api-key", project_id="your-project-id", ) class TextModel(LanceModel): text: str = watsonx_embed.SourceField() vector: Vector(watsonx_embed.ndims()) = watsonx_embed.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "watsonx-demo")) tbl = db.create_table("watsonx_test", schema=TextModel, mode="overwrite") tbl.add(data) rs = tbl.search("hello").limit(1).to_pandas() print(rs.head()) ``` # ImageBind Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/imagebind We have support for [imagebind](https://github.com/facebookresearch/ImageBind) model embeddings. You can download our version of the packaged model via - `pip install imagebind-packaged==0.1.2`. This function is registered as `imagebind` and supports Audio, Video and Text modalities(extending to Thermal,Depth,IMU data): | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"imagebind_huge"` | Name of the model. | | `device` | `str` | `"cpu"` | The device to run the model on. Can be `"cpu"` or `"gpu"`. | | `normalize` | `bool` | `False` | set to `True` to normalize your inputs before model ingestion. | Below is an example demonstrating how the API works: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect("/tmp/imagebind-db") func = get_registry().get("imagebind").create() class ImageBindModel(LanceModel): text: str image_uri: str = func.SourceField() audio_path: str vector: Vector(func.ndims()) = func.VectorField() text_list = ["A dog.", "A car", "A bird"] image_paths = [ "./assets/dog_image.jpg", "./assets/car_image.jpg", "./assets/bird_image.jpg", ] audio_paths = [ "./assets/dog_audio.wav", "./assets/car_audio.wav", "./assets/bird_audio.wav", ] inputs = [ {"text": a, "audio_path": b, "image_uri": c} for a, b, c in zip(text_list, audio_paths, image_paths) ] table = db.create_table("img_bind", schema=ImageBindModel) table.add(inputs) ``` Now, we can search using any modality: #### image search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_image = "./assets/dog_image2.jpg" actual = table.search(query_image).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "dog") ``` #### audio search ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query_audio = "./assets/car_audio2.wav" actual = table.search(query_audio).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "car") ``` #### Text search You can add any input query and fetch the result as follows: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} query = "an animal which flies and tweets" actual = table.search(query).limit(1).to_pydantic(ImageBindModel)[0] print(actual.text == "bird") ``` If you have any questions about the embeddings API, supported models, or see a relevant model missing, please raise an issue [on GitHub](https://github.com/lancedb/lancedb/issues). # Instructor Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/instructor [Instructor](https://instructor-embedding.github.io/) is an instruction-finetuned text embedding model that can generate text embeddings tailored to any task (e.g. classification, retrieval, clustering, text evaluation, etc.) and domains (e.g. science, finance, etc.) by simply providing the task instruction, without any finetuning. If you want to calculate customized embeddings for specific sentences, you can follow the unified template to write instructions. > [!NOTE] > > Represent the `domain` `text_type` for `task_objective`: > > * `domain` is optional, and it specifies the domain of the text, e.g. science, finance, medicine, etc. > * `text_type` is required, and it specifies the encoding unit, e.g. sentence, document, paragraph, etc. > * `task_objective` is optional, and it specifies the objective of embedding, e.g. retrieve a document, classify the sentence, etc. More information about the model can be found at the [source URL](https://github.com/xlang-ai/instructor-embedding). | Argument | Type | Default | Description | | - | - | - | - | | `name` | `str` | "hkunlp/instructor-base" | The name of the model to use | | `batch_size` | `int` | `32` | The batch size to use when generating embeddings | | `device` | `str` | `"cpu"` | The device to use when generating embeddings | | `show_progress_bar` | `bool` | `True` | Whether to show a progress bar when generating embeddings | | `normalize_embeddings` | `bool` | `True` | Whether to normalize the embeddings | | `quantize` | `bool` | `False` | Whether to quantize the model | | `source_instruction` | `str` | `"represent the document for retrieval"` | The instruction for the source column | | `query_instruction` | `str` | `"represent the document for retrieving the most similar documents"` | The instruction for the query | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector instructor = ( get_registry() .get("instructor") .create( source_instruction="represent the document for retrieval", query_instruction="represent the document for retrieving the most similar documents", ) ) class Schema(LanceModel): vector: Vector(instructor.ndims()) = instructor.VectorField() text: str = instructor.SourceField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "instructor-demo")) tbl = db.create_table("test", schema=Schema, mode="overwrite") texts = [ { "text": "Capitalism has been dominant in the Western world since the end of feudalism." }, { "text": "The disparate impact theory is especially controversial under the Fair Housing Act." }, { "text": "Disparate impact in United States labor law refers to practices in employment." }, ] tbl.add(texts) ``` # Jina Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/jina ## Text Embedding Models Jina embeddings are used to generate embeddings for text and image data. You also need to set the `JINA_API_KEY` environment variable to use the Jina API. You can find a list of supported models under [https://jina.ai/embeddings/](https://jina.ai/embeddings/) Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"jina-clip-v1"` | The model ID of the jina model to use | Usage Example: Replace `your-api-key` with your Jina API key. This provider reads it from `JINA_API_KEY`; the example sets it explicitly. In application code, supply it through your environment or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector os.environ["JINA_API_KEY"] = "your-api-key" jina_embed = ( EmbeddingFunctionRegistry.get_instance() .get("jina") .create(name="jina-embeddings-v2-base-en") ) class TextModel(LanceModel): text: str = jina_embed.SourceField() vector: Vector(jina_embed.ndims()) = jina_embed.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-text")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` ## Multimodal Embedding Models Jina embeddings can also be used to embed both text and image data, only some of the models support image data and you can check the list under [https://jina.ai/embeddings/](https://jina.ai/embeddings/) Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"jina-clip-v1"` | The model ID of the jina model to use | Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector os.environ["JINA_API_KEY"] = "your-api-key" db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-images")) func = get_registry().get("jina").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() vec_from_bytes: Vector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "cat", "dog", "dog", "horse", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", "http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` # NVIDIA Nemotron Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/nvidia Text embeddings with Nemotron 3.5 Embed 1B and 8B in the Python SDK. > [!NOTE] > > This integration uses Python 0.42.0b8 and is not available in Python 0.41.0. > Install the [documented preview client](/oss/v0-41-0/basics/sdk#enterprise-client-versions) > before following these examples, including the local Embedded example. The Python SDK registers `nvidia` for client-side text embedding with NVIDIA-hosted and self-hosted NIM endpoints. Documents use `input_type="passage"`; searches use `input_type="query"`. This provider supports text only, with floating-point output. Null and empty text values get a null vector without a request; pass `on_bad_vectors="null"` or `"drop"` to `add` to keep or skip those rows. Image and combined text/image inputs are not supported by this integration. Install the optional client and set your NVIDIA API key: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install openai export NVIDIA_API_KEY="your-api-key" ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector func = get_registry().get("nvidia").create( name="nvidia/nemotron-3.5-embed-1b", ) class Document(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() db = lancedb.connect("./nemotron-db") table = db.create_table("documents", schema=Document) table.add([{"text": "Paris is the capital of France."}]) results = table.search("What is the capital of France?").limit(3).to_list() ``` For a LanceDB Enterprise table, connect as usual, for example `lancedb.connect("db://my-database", api_key=..., region=...)`. The same schema, `add`, and `search` calls compute embeddings in the Python client. The NVIDIA key is separate from the LanceDB database key. Use a fresh table name when creating a table; reopening an existing table restores its embedding configuration. ## Models and configuration The hosted API documents these exact IDs and dimensions: | Model ID | Default dimensions | Supported `dim` | | - | -: | -: | | `nvidia/nemotron-3.5-embed-1b` | 2048 | 128–2048 | | `nvidia/nemotron-3.5-embed-8b` | 4096 | 1–4096 | | Parameter | Default | Description | | - | - | - | | `name` | `nvidia/nemotron-3.5-embed-1b` | Model ID sent to the endpoint. | | `dim` | Model default above | Output dimensions; required for other served model IDs. | | `base_url` | `https://integrate.api.nvidia.com/v1` | API base including `/v1`. | | `api_key` | `NVIDIA_API_KEY` for the hosted API | Alternatively, a registry reference such as `$var:nvidia-key`. | | `batch_size` | `32` | Maximum inputs per request. Reduce for your deployment's limits. | | `truncate` | `END` | Truncate overlong text at the end, or use `NONE` to reject it. | | `max_retries` | `7` | LanceDB's retry policy, applied to each request during automatic document/query embedding. | Requests specify `modality="text"` and `encoding_format="float"`. Returned vectors are checked for count, input indices, dimensions, and finite numeric values. The hosted input limit is 10,240 tokens per item; self-hosted limits depend on the served profile. This provider batches by item count, not token count. ## Self-hosted NIM Set `name` to the exact ID returned by your deployment's `GET /v1/models` and `dim` to an output dimension that deployment supports: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} func = get_registry().get("nvidia").create( name="nvidia/Nemotron-3.5-Embed-1B-BF16", base_url="http://localhost:8000/v1", dim=2048, ) ``` ### Authenticated endpoints Custom endpoints may run without a key. `NVIDIA_API_KEY` is only sent to the hosted API, so for authenticated endpoints use `get_registry().set_var("nvidia-key", key)` with `api_key="$var:nvidia-key"`. Registry references, rather than secret values, are stored in the schema. Restore registry variables in each process. Before using a custom endpoint restored from table metadata in a new process, call `get_registry().allow_endpoint("http://localhost:8000/v1")`. ### Output dimensions The NIM 2.4 support matrix lists `nvidia/Nemotron-3.5-Embed-8B-BF16` at 2048 dimensions, whereas the hosted 8B reference specifies 4096. For self-hosted model IDs, this provider requires an explicit `dim` and checks the response instead of assuming the hosted defaults. ## SDK support The NVIDIA provider is available in the Python SDK only. TypeScript, Rust and Java don't have an NVIDIA embedding provider. ## References NVIDIA documentation: [hosted 1B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-1b-infer), [hosted 8B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-8b-infer), [NIM request/response format](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/use-the-api-openai.html), [NIM support matrix](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/support-matrix.html). # Ollama Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/ollama Generate embeddings via the [ollama](https://github.com/ollama/ollama-python) python library. More details: * [Ollama docs on embeddings](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-embeddings) * [Ollama blog on embeddings](https://ollama.com/blog/embedding-models) For direct calls, `compute_source_embeddings` accepts a list of strings or a one-dimensional NumPy string array. Both inputs are sent to Ollama in one batch. | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `nomic-embed-text` | The name of the model. | | `host` | `str` | `http://localhost:11434` | The Ollama host to connect to. | | `options` | `ollama.Options` or `dict` | `None` | Additional model parameters listed in the documentation for the Modelfile such as `temperature`. | | `keep_alive` | `float` or `str` | `"5m"` | Controls how long the model will stay loaded into memory following the request. | | `ollama_client_kwargs` | `dict` | `{}` | kwargs that can be past to the `ollama.Client`. | ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "ollama-demo")) func = get_registry().get("ollama").create(name="nomic-embed-text") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add( [ {"text": "hello world"}, {"text": "goodbye world"}, ] ) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # OpenAI Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/openai LanceDB registers the OpenAI embeddings function in the registry by default, as `openai`. Below are the parameters that you can customize when creating the instances: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"text-embedding-ada-002"` | The name of the model. | | `dim` | `int` | Model default | Requested output dimensions for models that support shortening embeddings. Required for model names other than the OpenAI ones listed by `model_names()` (for example a model served behind an OpenAI-compatible `base_url`), where it is the model's embedding dimension. Use `func.ndims()` when defining the vector field. | | `use_azure` | bool | `False` | Set true to use Azure OpenAI SDK | Python 0.41.0 accepts only the model names returned by `model_names()`; setting `dim` does not enable an arbitrary model name in that version. Custom OpenAI-compatible model names with an explicit `dim` require the [0.42.0b8 client](/oss/v0-41-0/basics/sdk#enterprise-client-versions). Set your OpenAI API key before running the example: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export OPENAI_API_KEY="your-api-key" ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db_path = Path(tempfile.mkdtemp()) / "openai-embeddings" db = lancedb.connect(str(db_path)) func = get_registry().get("openai").create(name="text-embedding-ada-002") class Words(LanceModel): text: str = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() table = db.create_table("words", schema=Words, mode="overwrite") table.add( [ {"text": "hello world"}, {"text": "goodbye world"}, ] ) query = "greetings" actual = table.search(query).limit(1).to_pydantic(Words)[0] print(actual.text) ``` # OpenCLIP Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/openclip We support CLIP model embeddings using the open source alternative, [open-clip](https://github.com/mlfoundations/open_clip) which supports various customizations. It is registered as `open-clip` and supports the following customizations: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `"ViT-B-32"` | The name of the model. | | `pretrained` | `str` | `"laion2b_s34b_b79k"` | The name of the pretrained model to load. | | `device` | `str` | `"cpu"` | The device to run the model on. Can be `"cpu"` or `"gpu"`. | | `batch_size` | `int` | `64` | The number of images to process in a batch. | | `normalize` | `bool` | `True` | Whether to normalize the input images before feeding them to the model. | This embedding function supports ingesting images as both bytes and urls. You can query them using both text and other images. > [!NOTE] > > LanceDB supports ingesting images directly from accessible links. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb import pandas as pd import requests from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "openclip-demo")) func = get_registry().get("open-clip").create() class Images(LanceModel): label: str image_uri: str = func.SourceField() image_bytes: bytes = func.SourceField() vector: Vector(func.ndims()) = func.VectorField() vec_from_bytes: Vector(func.ndims()) = func.VectorField() table = db.create_table("images", schema=Images) labels = ["cat", "cat", "dog", "dog", "horse", "horse"] uris = [ "http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg", "http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg", "http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg", "http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg", "http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg", "http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg", ] image_bytes = [requests.get(uri).content for uri in uris] table.add( pd.DataFrame({"label": labels, "image_uri": uris, "image_bytes": image_bytes}) ) ``` Now we can search using text from both the default vector column and the custom vector column ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} actual = table.search("man's best friend").limit(1).to_pydantic(Images)[0] print(actual.label) frombytes = ( table.search("man's best friend", vector_column_name="vec_from_bytes") .limit(1) .to_pydantic(Images)[0] ) print(frombytes.label) ``` Because we're using a multimodal embedding function, we can also search using images ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import io from PIL import Image query_image_uri = "http://farm1.staticflickr.com/200/467715466_ed4a31801f_z.jpg" image_bytes = requests.get(query_image_uri).content query_image = Image.open(io.BytesIO(image_bytes)) actual = table.search(query_image).limit(1).to_pydantic(Images)[0] print(actual.label == "dog") other = ( table.search(query_image, vector_column_name="vec_from_bytes") .limit(1) .to_pydantic(Images)[0] ) print(other.label) ``` # Sentence Transformers Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/sentence-transformers Allows you to set parameters when registering a `sentence-transformers` object. > [!NOTE] > > Sentence transformer embeddings are normalized by default. It is recommended to use normalized embeddings for similarity search. > [!WARNING] > > Setting `trust_remote_code=True` allows the model to execute arbitrary code from its HuggingFace repository during loading. Only enable it for repositories you trust, and pin `revision` to a commit hash. When a table using such a model is opened in a new process, the model must be approved with `get_registry().allow_remote_code(...)`. See [Trusting remote code and custom endpoints](/oss/v0-41-0/embedding#trusting-remote-code-and-custom-endpoints). | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `all-MiniLM-L6-v2` | The name of the model | | `device` | `str` | `cpu` | The device to run the model on (can be `cpu` or `gpu`) | | `normalize` | `bool` | `True` | Whether to normalize the input text before feeding it to the model | | `trust_remote_code` | `bool` | `False` | Whether to trust and execute remote code from the model's HuggingFace repository | | `revision` | `str` | `None` | The model revision to load, such as a commit hash | **Check out available sentence-transformer models here!** ```markdown theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} - sentence-transformers/all-MiniLM-L12-v2 - sentence-transformers/paraphrase-mpnet-base-v2 - sentence-transformers/gtr-t5-base - sentence-transformers/LaBSE - sentence-transformers/all-MiniLM-L6-v2 - sentence-transformers/bert-base-nli-max-tokens - sentence-transformers/bert-base-nli-mean-tokens - sentence-transformers/bert-base-nli-stsb-mean-tokens - sentence-transformers/bert-base-wikipedia-sections-mean-tokens - sentence-transformers/bert-large-nli-cls-token - sentence-transformers/bert-large-nli-max-tokens - sentence-transformers/bert-large-nli-mean-tokens - sentence-transformers/bert-large-nli-stsb-mean-tokens - sentence-transformers/distilbert-base-nli-max-tokens - sentence-transformers/distilbert-base-nli-mean-tokens - sentence-transformers/distilbert-base-nli-stsb-mean-tokens - sentence-transformers/distilroberta-base-msmarco-v1 - sentence-transformers/distilroberta-base-msmarco-v2 - sentence-transformers/nli-bert-base-cls-pooling - sentence-transformers/nli-bert-base-max-pooling - sentence-transformers/nli-bert-base - sentence-transformers/nli-bert-large-cls-pooling - sentence-transformers/nli-bert-large-max-pooling - sentence-transformers/nli-bert-large - sentence-transformers/nli-distilbert-base-max-pooling - sentence-transformers/nli-distilbert-base - sentence-transformers/nli-roberta-base - sentence-transformers/nli-roberta-large - sentence-transformers/roberta-base-nli-mean-tokens - sentence-transformers/roberta-base-nli-stsb-mean-tokens - sentence-transformers/roberta-large-nli-mean-tokens - sentence-transformers/roberta-large-nli-stsb-mean-tokens - sentence-transformers/stsb-bert-base - sentence-transformers/stsb-bert-large - sentence-transformers/stsb-distilbert-base - sentence-transformers/stsb-roberta-base - sentence-transformers/stsb-roberta-large - sentence-transformers/xlm-r-100langs-bert-base-nli-mean-tokens - sentence-transformers/xlm-r-100langs-bert-base-nli-stsb-mean-tokens - sentence-transformers/xlm-r-base-en-ko-nli-ststb - sentence-transformers/xlm-r-bert-base-nli-mean-tokens - sentence-transformers/xlm-r-bert-base-nli-stsb-mean-tokens - sentence-transformers/xlm-r-large-en-ko-nli-ststb - sentence-transformers/bert-base-nli-cls-token - sentence-transformers/all-distilroberta-v1 - sentence-transformers/multi-qa-MiniLM-L6-dot-v1 - sentence-transformers/multi-qa-distilbert-cos-v1 - sentence-transformers/multi-qa-distilbert-dot-v1 - sentence-transformers/multi-qa-mpnet-base-cos-v1 - sentence-transformers/multi-qa-mpnet-base-dot-v1 - sentence-transformers/nli-distilroberta-base-v2 - sentence-transformers/all-MiniLM-L6-v1 - sentence-transformers/all-mpnet-base-v1 - sentence-transformers/all-mpnet-base-v2 - sentence-transformers/all-roberta-large-v1 - sentence-transformers/allenai-specter - sentence-transformers/average_word_embeddings_glove.6B.300d - sentence-transformers/average_word_embeddings_glove.840B.300d - sentence-transformers/average_word_embeddings_komninos - sentence-transformers/average_word_embeddings_levy_dependency - sentence-transformers/clip-ViT-B-32-multilingual-v1 - sentence-transformers/clip-ViT-B-32 - sentence-transformers/distilbert-base-nli-stsb-quora-ranking - sentence-transformers/distilbert-multilingual-nli-stsb-quora-ranking - sentence-transformers/distilroberta-base-paraphrase-v1 - sentence-transformers/distiluse-base-multilingual-cased-v1 - sentence-transformers/distiluse-base-multilingual-cased-v2 - sentence-transformers/distiluse-base-multilingual-cased - sentence-transformers/facebook-dpr-ctx_encoder-multiset-base - sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base - sentence-transformers/facebook-dpr-question_encoder-multiset-base - sentence-transformers/facebook-dpr-question_encoder-single-nq-base - sentence-transformers/gtr-t5-large - sentence-transformers/gtr-t5-xl - sentence-transformers/gtr-t5-xxl - sentence-transformers/msmarco-MiniLM-L-12-v3 - sentence-transformers/msmarco-MiniLM-L-6-v3 - sentence-transformers/msmarco-MiniLM-L12-cos-v5 - sentence-transformers/msmarco-MiniLM-L6-cos-v5 - sentence-transformers/msmarco-bert-base-dot-v5 - sentence-transformers/msmarco-bert-co-condensor - sentence-transformers/msmarco-distilbert-base-dot-prod-v3 - sentence-transformers/msmarco-distilbert-base-tas-b - sentence-transformers/msmarco-distilbert-base-v2 - sentence-transformers/msmarco-distilbert-base-v3 - sentence-transformers/msmarco-distilbert-base-v4 - sentence-transformers/msmarco-distilbert-cos-v5 - sentence-transformers/msmarco-distilbert-dot-v5 - sentence-transformers/msmarco-distilbert-multilingual-en-de-v2-tmp-lng-aligned - sentence-transformers/msmarco-distilbert-multilingual-en-de-v2-tmp-trained-scratch - sentence-transformers/msmarco-distilroberta-base-v2 - sentence-transformers/msmarco-roberta-base-ance-firstp - sentence-transformers/msmarco-roberta-base-v2 - sentence-transformers/msmarco-roberta-base-v3 - sentence-transformers/multi-qa-MiniLM-L6-cos-v1 - sentence-transformers/nli-mpnet-base-v2 - sentence-transformers/nli-roberta-base-v2 - sentence-transformers/nq-distilbert-base-v1 - sentence-transformers/paraphrase-MiniLM-L12-v2 - sentence-transformers/paraphrase-MiniLM-L3-v2 - sentence-transformers/paraphrase-MiniLM-L6-v2 - sentence-transformers/paraphrase-TinyBERT-L6-v2 - sentence-transformers/paraphrase-albert-base-v2 - sentence-transformers/paraphrase-albert-small-v2 - sentence-transformers/paraphrase-distilroberta-base-v1 - sentence-transformers/paraphrase-distilroberta-base-v2 - sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 - sentence-transformers/paraphrase-multilingual-mpnet-base-v2 - sentence-transformers/paraphrase-xlm-r-multilingual-v1 - sentence-transformers/quora-distilbert-base - sentence-transformers/quora-distilbert-multilingual - sentence-transformers/sentence-t5-base - sentence-transformers/sentence-t5-large - sentence-transformers/sentence-t5-xxl - sentence-transformers/sentence-t5-xl - sentence-transformers/stsb-distilroberta-base-v2 - sentence-transformers/stsb-mpnet-base-v2 - sentence-transformers/stsb-roberta-base-v2 - sentence-transformers/stsb-xlm-r-multilingual - sentence-transformers/xlm-r-distilroberta-base-paraphrase-v1 - sentence-transformers/clip-ViT-L-14 - sentence-transformers/clip-ViT-B-16 - sentence-transformers/use-cmlm-multilingual - sentence-transformers/all-MiniLM-L12-v1 ``` > [!NOTE] > > You can also load many other model architectures from the library. For example models from sources such as BAAI, Nomic, Salesforce Research, etc. See this HF hub page for all [supported models](https://huggingface.co/models?library=sentence-transformers). > [!NOTE] > > Here is an example that uses the BAAI embedding model from the HuggingFace Hub [supported models](https://huggingface.co/models?library=sentence-transformers). > > ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > import tempfile > from pathlib import Path > > import lancedb > from lancedb.embeddings import get_registry > from lancedb.pydantic import LanceModel, Vector > > db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "sentence-transformers")) > model = ( > get_registry() > .get("sentence-transformers") > .create(name="BAAI/bge-small-en-v1.5", device="cpu") > ) > > class Words(LanceModel): > text: str = model.SourceField() > vector: Vector(model.ndims()) = model.VectorField() > > table = db.create_table("words", schema=Words) > table.add( > [ > {"text": "hello world"}, > {"text": "goodbye world"}, > ] > ) > > query = "greetings" > actual = table.search(query).limit(1).to_pydantic(Words)[0] > print(actual.text) > ``` Visit the sentence-transformers [HuggingFace Hub](https://huggingface.co/sentence-transformers) page for more information on the available models. # Superlinked Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/superlinked [Superlinked](https://superlinked.com) is a self-hosted inference engine (SIE) for embedding, reranking, and extraction. The `sie-lancedb` package registers SIE as a first-class embedding function in LanceDB's embeddings registry, so embeddings are computed automatically on insert and search. You need a running SIE instance - see the [Superlinked quickstart](https://superlinked.com/docs) for deployment options. ## Installation ```bash Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install sie-lancedb ``` ```bash TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} npm install @superlinked/sie-lancedb @lancedb/lancedb ``` ## Registered functions Importing `sie_lancedb` registers two embedding functions in LanceDB's registry: | Name | Purpose | | - | - | | `"sie"` | Dense text embeddings | | `"sie-multivector"` | ColBERT-style late interaction with MaxSim scoring | Supported parameters on `.create()`: | Parameter | Type | Description | | - | - | - | | `model` | `str` | Any of 85+ SIE-supported models (e.g. `BAAI/bge-m3`, `NovaSearch/stella_en_400M_v5`, `jinaai/jina-colbert-v2`) | | `base_url` | `str` | URL of the SIE endpoint (e.g. `http://localhost:8080`) | ## Usage ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector import sie_lancedb # registers "sie" and "sie-multivector" sie = get_registry().get("sie").create( model="BAAI/bge-m3", base_url="http://localhost:8080", ) class Documents(LanceModel): id: int text: str = sie.SourceField() vector: Vector(sie.ndims()) = sie.VectorField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "superlinked-demo")) table = db.create_table("docs", schema=Documents) table.add([ {"id": 1, "text": "Machine learning is a subset of AI."}, {"id": 2, "text": "Neural networks use multiple layers."}, {"id": 3, "text": "Python is popular for ML development."}, ]) results = table.search("What is deep learning?").limit(3).to_list() ``` LanceDB handles embedding generation for both inserts and queries automatically, based on the `SourceField` / `VectorField` declarations on the schema. The `id` column gives each document a stable key, which [entity extraction](#entity-extraction) uses to merge its results back. ## Hybrid search with reranker `SIEReranker` plugs into LanceDB's hybrid search pipeline. It uses SIE's cross-encoder `score()` to rerank combined vector + full-text search results. You need a full-text search index on the column first: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from sie_lancedb import SIEReranker # Create FTS index for hybrid search table.create_fts_index("text", replace=True) results = ( table.search("What is deep learning?", query_type="hybrid") .rerank(SIEReranker(model="jinaai/jina-reranker-v2-base-multilingual")) .limit(5) .to_list() ) for r in results: print(f"{r['_relevance_score']:.3f} {r['text']}") ``` The reranker also works with pure vector or pure FTS search via `.rerank()`. ## ColBERT and multivector `SIEMultiVectorEmbeddingFunction` (registered as `"sie-multivector"`) works with LanceDB's native `MultiVector` type and MaxSim scoring for ColBERT and ColPali models. In LanceDB Python 0.40.0, a multivector that LanceDB generates on insert is stored as null unless the document's token count happens to equal the per-token dimension, so this example computes the document multivectors with `compute_source_embeddings()` and passes them in the `vector` column. LanceDB still generates the query multivector automatically: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.pydantic import MultiVector sie_colbert = get_registry().get("sie-multivector").create( model="jinaai/jina-colbert-v2", base_url="http://localhost:8080", ) class ColBERTDocs(LanceModel): text: str = sie_colbert.SourceField() vector: MultiVector(sie_colbert.ndims()) = sie_colbert.VectorField() table = db.create_table("colbert_docs", schema=ColBERTDocs) # Compute the document multivectors and store them with their text texts = ["Machine learning is a subset of AI."] vectors = sie_colbert.compute_source_embeddings(texts) table.add([{"text": text, "vector": vector} for text, vector in zip(texts, vectors)]) # MaxSim search - query and document multivectors compared token-by-token results = table.search("What is ML?").limit(5).to_list() ``` ## Entity extraction `SIEExtractor` adds entity extraction to LanceDB's data-enrichment workflows. Extract entities from a text column and merge the results back as a structured Arrow column - enabling filtered search on extracted entities. This example enriches the `docs` table from [Usage](#usage), matching rows on its `id` column: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from sie_lancedb import SIEExtractor extractor = SIEExtractor( base_url="http://localhost:8080", model="urchade/gliner_multi-v2.1", ) docs = db.open_table("docs") extractor.enrich_table( docs, source_column="text", target_column="entities", labels=["person", "technology", "organization"], id_column="id", ) ``` The `entities` column stores structured Arrow data (`list<struct<text, label, score, start, end, bbox>>`), so you can filter on extracted entities in queries. ## Links * [`sie-lancedb` on PyPI](https://pypi.org/project/sie-lancedb/) * [`@superlinked/sie-lancedb` on npm](https://www.npmjs.com/package/@superlinked/sie-lancedb) * [Superlinked on GitHub](https://github.com/superlinked/sie) * [Superlinked docs](https://superlinked.com/docs) # Voyage AI Source: https://docs.lancedb.com/oss/v0-41-0/integrations/embedding/voyageai Voyage AI provides cutting-edge embedding and rerankers. Using voyageai API requires voyageai package, which can be installed using `pip install voyageai`. Voyage AI embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `VOYAGE_API_KEY` environment variable to use the Voyage AI API. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export VOYAGE_API_KEY="your-api-key" ``` Supported models are: * voyage-4-large (best retrieval quality, 1024 default dimensions, supports 256/512/1024/2048) * voyage-4 (balanced general-purpose, 1024 default dimensions, supports 256/512/1024/2048) * voyage-4-lite (optimized for latency/cost, 1024 default dimensions, supports 256/512/1024/2048) * voyage-context-3 * voyage-3.5 * voyage-3.5-lite * voyage-3 * voyage-3-lite * voyage-finance-2 * voyage-multilingual-2 * voyage-law-2 * voyage-code-2 * voyage-multimodal-3.5 (multimodal - supports text, images, and video) > [!NOTE] > > **Multimodal Model:** `voyage-multimodal-3.5` supports text, images, and video inputs. It outputs 1024-dimensional embeddings by default, configurable via the `output_dimension` parameter (256, 512, 1024, 2048). See the [Voyage AI multimodal embeddings documentation](https://docs.voyageai.com/docs/multimodal-embeddings) for more details. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | | - | - | - | - | | `name` | `str` | `None` | The model ID of the model to use. Supported models: voyage-4-large, voyage-4, voyage-4-lite, voyage-3, voyage-3-lite, voyage-3.5, voyage-3.5-lite, voyage-context-3, voyage-finance-2, voyage-multilingual-2, voyage-law-2, voyage-code-2, voyage-multimodal-3.5 | | `input_type` | `str` | `None` | Type of the input text. Default to None. Other options: query, document. | | `truncation` | `bool` | `True` | Whether to truncate the input texts to fit within the context length. | | `output_dimension` | `int` | `None` | Output embedding dimension. Only supported by `voyage-multimodal-3.5`. Valid options: 256, 512, 1024 (default), 2048. | For text models, `compute_source_embeddings()` accepts a single string, a list of strings, a one-dimensional NumPy array, or a PyArrow `Array` or `ChunkedArray`. Batch inputs retain their order. Usage Example: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector voyageai = ( EmbeddingFunctionRegistry.get_instance().get("voyageai").create(name="voyage-3") ) class TextModel(LanceModel): text: str = voyageai.SourceField() vector: Vector(voyageai.ndims()) = voyageai.VectorField() data = [{"text": "hello world"}, {"text": "goodbye world"}] db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-demo")) tbl = db.create_table("test", schema=TextModel, mode="overwrite") tbl.add(data) ``` ### Multimodal Example The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, local `pathlib.Path` objects, raw image bytes, or PIL Image objects. For source embeddings, PIL images and images loaded from bytes or local paths are converted to RGB and encoded as JPEG. This supports RGBA, grayscale with alpha, and palette images; transparency is discarded. Composite transparent images onto your chosen background before embedding if the background color matters. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.pydantic import LanceModel, Vector # Create multimodal embedding function with custom dimension voyageai = ( EmbeddingFunctionRegistry.get_instance() .get("voyageai") .create(name="voyage-multimodal-3.5", output_dimension=512) ) class ImageModel(LanceModel): image_uri: str = voyageai.SourceField() vector: Vector(voyageai.ndims()) = voyageai.VectorField() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-multimodal")) tbl = db.create_table("images", schema=ImageModel, mode="overwrite") # Add images using URLs tbl.add( [ { "image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png" }, ] ) # Search with text query results = tbl.search("dice").limit(1).to_list() print(results) ``` # Integrations Source: https://docs.lancedb.com/oss/v0-41-0/integrations/index Connect LanceDB with popular AI providers, frameworks, and data platforms LanceDB seamlessly plugs into the rest of your AI and data engineering stack. Use the sections below to jump straight into the guides that matter for your workflow. | Group | Description | | :- | :- | | [Embedding models](/oss/v0-41-0/integrations/embedding/) | Connect with popular embedding model providers including OpenAI, Cohere, HuggingFace, and more | | [Reranking models](/oss/v0-41-0/integrations/reranking/) | Enhance search results with advanced reranking models and techniques | | [AI platforms & frameworks](/oss/v0-41-0/integrations/ai/) | Integrate with LangChain, LlamaIndex, Kiln, and other AI development frameworks | | [Data platforms & frameworks](/oss/v0-41-0/integrations/data/) | Integrate LanceDB with popular data tools and platforms like DuckDB, Pydantic and dlt | # LeRobotDataset Source: https://docs.lancedb.com/oss/v0-41-0/integrations/lerobotdataset Train LeRobot policies straight from object storage, and curate, search and visualize robotics datasets as Lance tables. [LeRobot](https://huggingface.co/docs/lerobot/index) is HuggingFace's open-source robotics stack. Since [lerobot#4363](https://github.com/huggingface/lerobot/pull/4363) it reads Lance datasets natively, and `lerobot-lancedb` wraps that into a ready-made dataset class for video features: same items, same training pipeline. Image-backed features are not supported -- re-encode them as video first. What you get: * **Train from object storage while keeping your GPUs fed.** Lance reads random frames straight from S3, GCS, the HF Hub or HF Storage Buckets, fetching only the bytes each batch needs, so every batch is a global shuffle: any frame, from anywhere in the dataset. In the table below (samples/s, 8 workers, batch 64), Lance and upstream local both draw every batch from the whole dataset. Upstream streaming does a reservoir shuffle, reading the dataset in order and drawing each batch from a pool of recently seen frames, so those two columns are not the same job: | dataset | window shuffle, Lance from object store | window shuffle, upstream streaming from the Hub | Lance (object store) vs upstream streaming | RAM, Lance | RAM, streaming | global shuffle, Lance from object store | global shuffle, upstream from local NVMe | Lance (object store) vs upstream (local NVMe) | | - | - | - | - | - | - | - | - | - | | DROID | 904 | 478 | 1.9x | 8 GB | 122 GB | 257 | 224 | 1.1x | | roboturk | 778 | 152 | 5.1x | 6 GB | 9 GB | 1,074 | 983 | 1.1x | | aloha_mobile_cabinet | 772 | 51 | 15.2x | 9 GB | 30 GB | 693 | 573 | 1.2x | | koch_pick_place_5_lego | 701 | 54 | 13.0x | 8 GB | 15 GB | 876 | 526 | 1.7x | | pusht | 5,340 | 648 | 8.2x | 3 GB | 7 GB | 5,508 | 4,224 | 1.3x | | aloha_static_cups_open | 597 | 45 | 13.2x | 10 GB | 38 GB | 575 | 483 | 1.2x | The shuffle window is 0.05% of the dataset, at least 5,000 frames: 5,000 on the small sets, 13,815 on DROID. Streaming DROID at that window in upstream default needs 122 GB, so those two runs used a 256 GB machine with the same decode speed. The DROID pair is noisy: Lance 684 and 1,124, streaming 303 and 653. Same batches: Lance from an object store is 1.9x faster than upstream streaming on DROID and 5x to 15x on the other datasets, with 8 GB of RAM against 122 GB on DROID. Global shuffle: Lance with nothing downloaded is 1.1x to 1.7x faster than upstream reading local NVMe after the download. berkeley_rpt, toto and soarm101 are left out because their metadata lists frames the videos do not have; `lerobot-lance-doctor` reports that before you train. * **Faster iteration, end to end.** 10,000 steps of SmolVLA on DROID, 8xH100, lerobot's default `num_workers=4`, same seed: | | Lance, S3, nothing downloaded | upstream, local NVMe after a 384 GB download | | - | - | - | | wall clock | **1 h 27 m** | 2 h 00 m | | steady rate | 495 samples/s | 361 samples/s | | of each step spent waiting on data | 1.7% | 37.4% | | final loss | 0.2380 | 0.2380 | Same model, same loss, 33 minutes sooner, and no 384 GB download first. The difference is time the GPUs spend waiting on data, so it grows with the run: at 100k steps it is over five hours, and every re-run and sweep point pays it again. * **The training table is also the index.** Parquet has no secondary indexes, so finding frames instead of scanning them usually means another system per question: a vector database for embeddings, a search service for instructions, a feature store for scores. With Lance those are columns and indexes on the same table the DataLoader reads. One query spans all of them, at a version the trainer can reopen. ## Install ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install "lerobot[lancedb]" # the reader, inside lerobot itself pip install lerobot-lancedb # the converter ``` ## Convert a dataset Any LeRobot v3.0 dataset, from the Hub or a local directory: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-lance-convert --repo-id lerobot/pusht --out ./pusht-lance ``` **Migration costs about as much as a file copy.** Videos are stored as blobs without re-encoding, so items are bit-identical to the source: 392,578 frames convert in 10 seconds, DROID's 27.6M in 34 minutes. Nothing about your recording or training code changes. The output keeps `meta/` as is and adds three Lance tables (`frames`, `videos`, `meta`). `lerobot-lance-doctor` audits the result and often finds problems in the source: DROID carries 44% orphaned rows, and three of eight public datasets we converted have frame-count defects that only random access exposes. Host the result anywhere: an HF dataset repo (`hf upload`, tag it `v3.0`), an HF Storage Bucket (`hf buckets sync`), or any object store (`aws s3 sync`). ## Load and train `lerobot-lancedb` provides one map-style dataset class for both image and video features, reading from a local path or an `s3://`, `gs://` or `hf://` URI with nothing downloaded up front. Pair it with `lance_mp_context()` so multi-worker `DataLoader`s share Lance's own multiprocessing context instead of the default one: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lerobot_lancedb import LanceDBDataset, lance_mp_context from torch.utils.data import DataLoader dataset = LanceDBDataset(root="hf://datasets/lance-format/pusht-lance") sample = dataset[0] print(sample["observation.state"].shape) print(sample["action"].shape) loader = DataLoader( dataset, batch_size=32, num_workers=8, multiprocessing_context=lance_mp_context(), ) ``` Items are bit-exact with `LeRobotDataset`, and `delta_timestamps` configures temporal windows the same way. Or from the CLI. Held-out evaluation on a remote dataset needs random access, so it only works on the Lance path: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-train \ --dataset.repo_id=my-org/my-bucket/pusht-lance \ --dataset.repo_type=bucket \ --dataset.eval_split=0.02 \ --policy.type=act ``` ## Visualize TB-scale datasets in Foxglove LeRobot's dataset viewer can serve an episode to [Foxglove](https://foxglove.dev) over its WebSocket protocol ([lerobot#4542](https://github.com/huggingface/lerobot/pull/4542)), and with a Lance dataset it works wherever the data lives: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lerobot-dataset-viz --repo-id lance-format/pusht-lance --episode-index 3 --display-mode foxglove ``` Open the Foxglove app, connect to `ws://localhost:8765`, and scrub. Cameras, joint state and actions show up as topics you can lay out however you like: ![Foxglove showing episode 7 of DROID served from S3: three camera panels and the joint state, scrubbed to 19.4 s](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/integrations/lerobot-foxglove-droid.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=4fc5a07ad42fc2009ecc4c74e19463eb) Frames are fetched as you scrub, so looking at one episode of the 373 GB DROID from S3 moves a few MB, not the dataset. No MCAP export, no download, and nothing new to install on the dataset side: this is the same reader the trainer uses. ## Query, curate, enrich The frames table is a LanceDB table like any other: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pusht-lance") frames = db.open_table("frames") videos = db.open_table("videos") print(len(frames), len(videos)) print(frames.schema) ``` Filter with SQL over any feature, using the indexes built at conversion: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} frame_rows = ( frames.search() .where("episode_index = 0 AND frame_index < 10", prefilter=True) .select(["episode_index", "frame_index", "timestamp", "action"]) .limit(10) .to_list() ) for row in frame_rows: print(row["episode_index"], row["frame_index"], row["timestamp"]) ``` From here it is standard LanceDB. The examples below are from our DROID walkthrough, all on the table the trainer reads. **Feature engineering costs nothing until you use it.** With [Geneva](/oss/v0-41-0/geneva/udfs/udfs), `add_columns` registers a `@udf` function and its input columns as a new column and computes nothing; `backfill` computes and stores the values later, in parallel. No copy of the dataset, and the videos are never touched: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.float32(), input_columns=["action_joint_velocity"]) def jerk_score(v): # per-frame motion roughness ... tbl.add_columns({"jerk_score": jerk_score}) # nothing computed yet tbl.backfill("jerk_score", concurrency=8) # 610,403 rows in 16.7 s ``` Embeddings work the same way, reading frames straight from the video blobs in the `videos` table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @udf(data_type=pa.list_(pa.float32(), 768), num_gpus=1, input_columns=["episode_index", "frame_index"]) class EmbedFromBlob: # SigLIP2 loads once per worker def __call__(self, episode_index, frame_index): blob = self.videos.fetch_blob_files("video_bytes", [video_row_id])[0] frame = VideoDecoder(blob).get_frames_at([pos]).data[0] ... ``` **Deduplication** removes near-static runs before they skew curation or training. A stopped gripper holding one pose for a few seconds produces many frames whose `emb_siglip2` vectors are nearly identical; LanceDB Enterprise's native [`dedupe`](/oss/v0-41-0/sql/dql/dedupe) collapses them into one representative per cluster, directly over the index, without a pairwise scan: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} db.execute_query(""" CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'emb_siglip2', distance_threshold => 0.01 ) """) ``` Every column survives the dedup unchanged -- `jerk_score`, the episode and camera metadata, the video blob reference -- since `dedupe` returns full rows, not just which ones matched. Wrap it in a materialized view, as above, to keep the deduplicated set current as new episodes land; see [Materialized views](/oss/v0-41-0/feature-engineering/materialized-views). **Search** is an index on those columns: a vector index over the embeddings built in 29.7 s across 27.6M rows, a full-text index over the instructions in 7.0 s, queries in 10 to 54 ms. **Curation** is one query across all of it. Semantic search with a predicate on the derived score, no join, no second system: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} results = ( tbl.search(vec("a gripper closing on an object"), vector_column_name="emb_siglip2") .where("jerk_score > 1.2875") # the roughest 1% of frames .limit(4) .to_arrow() ) ``` **Mining** is the same query pointed at the rare cases. `tbl.search().where("jerk_score > 1.2875 AND success = false")` pulls the rough, failed frames out of 27.6M rows in milliseconds, ready to become a fine-tuning set or a labeling queue. **EDA** is a scan of the tabular columns: a pass over all 27.6M rows reads 2.52 GB in 190 s and decodes no video. Then drop what you found from training with `episodes=[...]` instead of rewriting files. The reader ignores columns it does not know, and the table is versioned, so curation and training share one copy of the data at a version you can reopen. > [!NOTE] > > Lance datasets are read-only in LeRobot: record and edit in the default format, then convert. Public examples to try everything above: [`lance-format/pusht-lance`](https://huggingface.co/datasets/lance-format/pusht-lance) and friends under the [`lance-format`](https://huggingface.co/lance-format) org. # Answer.AI Rerankers Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/answerdotai Use AnswerDotAI's lightweight reranking library with LanceDB. Features unified API for common reranking models, configurable model selection, and comprehensive scoring options. # Answer.AI Rerankers This integration uses [AnswersDotAI's rerankers](https://github.com/AnswerDotAI/rerankers) to rerank the search results, providing a lightweight, low-dependency, unified API to use all common reranking and cross-encoder models. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import AnswerdotaiRerankers embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "answerdotai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = AnswerdotaiRerankers() # Run vector search with a reranker result = tbl.search("hello").rerank(reranker=reranker).to_list() # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() # Run hybrid search with a reranker result = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_type` | `str` | `"colbert"` | The type of model to use. Supported model types can be found here: [https://github.com/AnswerDotAI/rerankers](https://github.com/AnswerDotAI/rerankers). | | `model_name` | `str` | `"answerdotai/answerai-colbert-small-v1"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Cohere Reranker Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/cohere Integrate Cohere's powerful reranking API with LanceDB for enhanced search results. Supports English and multilingual models with configurable scoring options for vector, FTS, and hybrid search. # Cohere Reranker This reranker uses the [Cohere](https://cohere.ai/) API to rerank the search results. You can use this reranker by passing `CohereReranker()` to the `rerank()` method. Note that you'll either need to set the `COHERE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install cohere ``` Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import CohereReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "cohere-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = CohereReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"rerank-english-v2.0"` | The name of the reranker model to use. Available cohere models are: rerank-english-v2.0, rerank-multilingual-v2.0 | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Cohere API. If not provided, the `COHERE_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`) | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`) | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`) | # ColBERT Reranker Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/colbert Enhance search results with ColBERT's contextual reranking in LanceDB. Features efficient model deployment, device optimization, and flexible scoring options for vector, FTS, and hybrid search. # ColBERT Reranker This reranker uses ColBERT model to rerank the search results. You can use this reranker by passing `ColbertReranker()` to the `rerank()` method. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import ColbertReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "colbert-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = ColbertReranker() # Run vector search with a reranker result = tbl.search("hello").rerank(reranker=reranker).to_list() # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker result = tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() # Run hybrid search with a reranker result = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"colbert-ir/colbertv2.0"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `device` | `str` | `None` | The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu". | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Jina Reranker Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/jina Integrate Jina's multilingual reranking API with LanceDB for improved search results. Features model selection, API key management, and flexible scoring options for all search types. # Jina Reranker This reranker uses the [Jina](https://jina.ai/reranker/) API to rerank the search results. You can use this reranker by passing `JinaReranker()` to the `rerank()` method. Note that you'll either need to set the `JINA_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import os import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import JinaReranker os.environ["JINA_API_KEY"] = "your-api-key" embedder = get_registry().get("jina").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "jina-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = JinaReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"jina-reranker-v2-base-multilingual"` | The name of the reranker model to use. You can find the list of available models in [https://jina.ai/reranker](https://jina.ai/reranker). | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Jina API. If not provided, the `JINA_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # OpenAI Reranker (Experimental) Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/openai Explore experimental search reranking using OpenAI's GPT models in LanceDB. Features configurable model selection, API key management, and comprehensive scoring options for all search types. # OpenAI Reranker (Experimental) This reranker uses OpenAI chat model to rerank the search results. You can use this reranker by passing `OpenaiReranker()` to the `rerank()` method. > **Note:** Supported query types: Hybrid, Vector, and FTS. > **Warning:** This reranker is experimental. OpenAI does not have a dedicated reranking model, so it uses a chat model under the hood. Replace `your-api-key` with your provider API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import OpenaiReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "openai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = OpenaiReranker(api_key="your-api-key") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"gpt-5.6-sol"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | | `api_key` | `str` | `None` | The API key to use. If None, will use the OPENAI_API_KEY environment variable. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Voyage AI Reranker Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/voyageai Integrate Voyage AI's cutting-edge reranking models with LanceDB. Features model selection, API key management, and comprehensive scoring options for all search types. # Voyage AI Reranker Voyage AI provides cutting-edge embedding and rerankers. This reranker uses the [Voyage AI](https://docs.voyageai.com/docs/) API to rerank the search results. You can use this reranker by passing `VoyageAIReranker()` to the `rerank()` method. Note that you'll either need to set the `VOYAGE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. > **Note:** Supported query types: Hybrid, Vector, and FTS. Replace `your-api-key` with your provider API key. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import VoyageAIReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "voyageai-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) reranker = VoyageAIReranker(api_key="your-api-key", model_name="rerank-2") # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `None` | The name of the reranker model to use. Available models are: rerank-2, rerank-2-lite | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Voyage AI API. If not provided, the `VOYAGE_API_KEY` environment variable is used. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | | `truncation` | `bool` | `None` | Whether to truncate the input to satisfy the "context length limit" on the query and the documents. | ## Supported Scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ❌ Not Supported | Returns have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`) | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ✅ Supported | Returns have vector(`_distance`) along with Hybrid Search score(`_relevance_score`) | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Returns only have the `_relevance_score` column | | `all` | ✅ Supported | Returns have FTS(`score`) along with Hybrid Search score(`_relevance_score`) | # Watsonx Reranker Source: https://docs.lancedb.com/oss/v0-41-0/integrations/reranking/watsonx Rerank LanceDB search results with the IBM watsonx.ai text rerank API. Supports vector, FTS, and hybrid search with configurable models, projects, and spaces. # Watsonx Reranker This reranker uses the [IBM watsonx.ai](https://cloud.ibm.com/docs/apis/watsonx-ai#text-rerank) text rerank API to reorder search results. Pass `WatsonxReranker()` to the `rerank()` method on a query. Credentials come from the `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` (or `WATSONX_SPACE_ID`) environment variables, or can be passed explicitly as arguments. > **Note:** Supported query types: Hybrid, Vector, and FTS. ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install ibm-watsonx-ai ``` Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import tempfile from pathlib import Path import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector from lancedb.rerankers import WatsonxReranker embedder = get_registry().get("sentence-transformers").create() db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "watsonx-rerank")) class Schema(LanceModel): text: str = embedder.SourceField() vector: Vector(embedder.ndims()) = embedder.VectorField() data = [ {"text": "hello world"}, {"text": "goodbye world"}, ] tbl = db.create_table("test", schema=Schema) tbl.add(data) # Supply your API key and project ID (or use space_id instead of project_id). reranker = WatsonxReranker( api_key="your-api-key", project_id="your-project-id", ) # Run vector search with a reranker vector_results = tbl.search("hello").rerank(reranker=reranker).to_list() print(vector_results) # Build the full-text index before either FTS or hybrid search. tbl.create_fts_index("text", replace=True) # Run FTS search with a reranker fts_results = ( tbl.search("hello", query_type="fts").rerank(reranker=reranker).to_list() ) print(fts_results) # Run hybrid search with a reranker hybrid_results = ( tbl.search("hello", query_type="hybrid").rerank(reranker=reranker).to_list() ) print(hybrid_results) ``` ## Accepted Arguments | Argument | Type | Default | Description | | - | - | - | - | | `model_name` | `str` | `"cross-encoder/ms-marco-minilm-l-12-v2"` | The rerank model ID. See [supported rerank models](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx#rerank). | | `column` | `str` | `"text"` | The name of the table column to use as document input. | | `top_n` | `int` | `None` | The number of results to return. If `None`, all results are returned. | | `return_score` | `str` | `"relevance"` | Options are `"relevance"` or `"all"`. Controls which score columns are kept on the result. | | `api_key` | `str` | `None` | IBM Cloud API key. Falls back to the `WATSONX_API_KEY` environment variable. | | `project_id` | `str` | `None` | watsonx.ai project ID. Falls back to `WATSONX_PROJECT_ID`. Mutually exclusive with `space_id`. | | `space_id` | `str` | `None` | watsonx.ai deployment space ID. Falls back to `WATSONX_SPACE_ID`. Mutually exclusive with `project_id`. | | `url` | `str` | `"https://us-south.ml.cloud.ibm.com"` | watsonx.ai service URL. | | `truncate_input_tokens` | `int` | `None` | Truncate each document to this many tokens before scoring. | > [!NOTE] > > You must supply exactly one of `project_id` or `space_id` (either as an argument or via its environment variable). Setting both, or neither, raises a `ValueError`. ## Supported scores for each query type You can specify the type of scores you want the reranker to return. The following are the supported scores for each query type: ### Hybrid Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ❌ Not Supported | Results have vector(`_distance`) and FTS(`score`) along with Hybrid Search score(`_relevance_score`). | ### Vector Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have vector(`_distance`) along with Hybrid Search score(`_relevance_score`). | ### FTS Search | `return_score` | Status | Description | | - | - | - | | `relevance` | ✅ Supported | Results only have the `_relevance_score` column. | | `all` | ✅ Supported | Results have FTS(`score`) along with Hybrid Search score(`_relevance_score`). | # Stable World Model Source: https://docs.lancedb.com/oss/v0-41-0/integrations/stable-worldmodel Use Stable World Model with LanceDB-backed datasets for reproducible world model research, fast data loading, and compact storage. [Stable World Model](https://github.com/galilai-group/stable-worldmodel) is a research platform for collecting data, training world models, and evaluating policies with model-predictive control across standardized environments. The LanceDB integration is built into Stable World Model's data format registry. Lance is the default backend for collected datasets, so a path ending in `.lance` gives you an append-friendly LanceDB table with episode-contiguous rows and fast indexed reads. Random access speed is the bottleneck for world model training, since the loop repeatedly samples temporal windows from high-dimensional observations, actions, and rewards. The faster those windows arrive, the more GPU time goes into training rather than waiting on the data loader. ## Install ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} pip install stable-worldmodel ``` Datasets and checkpoints are stored under `$STABLEWM_HOME`, which defaults to `~/.stable_worldmodel/`. ## Collect data into Lance Stable World Model uses Lance by default when you collect to a `.lance` path. Replace `your_expert_policy` with the expert or scripted policy you use to collect demonstrations. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import stable_worldmodel as swm world = swm.World("swm/PushT-v1", num_envs=8) world.set_policy(your_expert_policy) world.collect("data/pusht_demo.lance", episodes=100, seed=0) ``` Every writer accepts a `mode` argument such as `append`, `overwrite`, or `error`. The default is append, so re-running collection extends the existing dataset. ## Load a Lance dataset for training The dataset loader autodetects the Lance format from the path. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} dataset = swm.data.load_dataset("data/pusht_demo.lance", num_steps=16) batch = dataset[0] print(batch.keys()) ``` Your model code stays focused on the world model objective while LanceDB handles the storage layout and read path. ## Evaluate with model-predictive control After training a world model on the Lance-backed dataset, Stable World Model can evaluate it with planning solvers such as CEM. Replace `world_model` with the trained model object from your training loop. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from stable_worldmodel.policy import PlanConfig, WorldModelPolicy from stable_worldmodel.solver import CEMSolver solver = CEMSolver(model=world_model, num_samples=300) policy = WorldModelPolicy(solver=solver, config=PlanConfig(horizon=10)) world.set_policy(policy) results = world.evaluate(episodes=50) print(f"Success Rate: {results['success_rate']:.1f}%") ``` ## Convert between formats Stable World Model can convert between registered dataset formats. A common workflow is to collect in Lance for fast training reads, then export to the video layout for compact inspection artifacts. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} swm.data.convert( "data/pusht_demo.lance", "data/pusht_video", dest_format="video", fps=30, ) ``` ## Throughput The Stable World Model README reports the following PushT benchmark results from `scripts/benchmark/compare_h5_lance.py`: | Format | Source | Cache | samples/s | ms/step | | :- | :- | :- | -: | -: | | HDF5 | local | no-cache | 1,416.1 | 45.2 | | HDF5 | local | cached | 1,474.0 | 43.4 | | LanceDB | local | no-cache | 4,814.8 | 13.3 | | LanceDB | local | cached | 4,431.3 | 14.4 | | Video | local | - | 1,330.6 | 48.1 | | LanceDB | s3 | no-cache | 3,183.7 | 20.1 | | LanceDB | s3 | cached | 3,253.2 | 19.7 | | HDF5 | s3 | no-cache | 9.1 | 7,032.5 | | HDF5 | s3 | cached | 756.5 | 84.6 | In that benchmark, local LanceDB reached about **3.4x** the no-cache throughput of local HDF5, while S3-backed LanceDB reached about **350x** the no-cache throughput of S3-backed HDF5. Even with cache enabled, S3-backed LanceDB was about **4.3x** faster than S3-backed HDF5. These numbers come from the Stable World Model project's own benchmark setup, so they're best read as a reproducible directional baseline that may shift across environments, models, and storage configurations. ## Storage The same README reports these local storage sizes for the benchmark dataset: | Format | Local size | | :- | -: | | HDF5 | 43.12 GB | | LanceDB | 13.31 GB | | Video | 496.29 MB | LanceDB used about **69% less local storage than HDF5** in the reported benchmark, while preserving a table interface built for fast training reads and append-heavy collection. ## More resources > [card] [Stable World Model README](https://github.com/galilai-group/stable-worldmodel/blob/main/README.md) > > Installation, quick start, supported formats, benchmarks, environments, solvers, and citation. > [card] [Stable World Model docs](https://galilai-group.github.io/stable-worldmodel/) > > Full upstream documentation with tutorials, API references, and guides. # REFRESH Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/refresh Filling computed columns and bringing materialized views up to date. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB extensions with no DataFusion equivalent. They are what makes [feature engineering](/oss/v0-41-0/feature-engineering) reachable from SQL: a column declared by [DDL](/oss/v0-41-0/sql/ddl/table#computed-column) starts empty, and a refresh fills it. ## REFRESH COLUMN ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN <column> ON [TABLE] <table> [WHERE <predicate>] [WITH (<option> = <value> [, ...])] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` Without `WHERE`, a refresh fills unassigned rows and recomputes values whose inputs changed, leaving other current values alone. A retry after a failure can still repeat work that was not committed. With `WHERE`, a refresh **recomputes every matching live row**, including rows that already have current values. Repeating the same predicate can repeat the Function calls and their cost. To fill only null outputs within a slice, add the output column to the predicate: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even if their inputs changed. It also selects outputs that were successfully computed as `NULL`; a null value does not necessarily mean the row has never been computed. Use an unfiltered refresh to let LanceDB track which outputs need updating. An initialized Function instance and its mutable state may survive across refresh jobs. Do not assume a new refresh resets instance state or calls `__init__` again. Instances are not shared across workers. Refresh computed columns in dependency order. A refresh fails before writing if the rows it would compute read another computed or Function column that has not been refreshed for its current inputs. Refresh that input first. A computed input that is current but evaluates to `NULL` is a valid value, not an unfilled placeholder. `WHERE` scopes the refresh, which is how you fill a slice and check it before committing to the whole table. It does not narrow the per-fragment input readiness checks: if a selected fragment contains unfilled computed input rows anywhere, refresh that input first and then rerun the filtered child. ### Previewing a refresh ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` `EXPLAIN` and `EXPLAIN VERBOSE` take the same options and validation as `REFRESH COLUMN` and return DataFusion's `plan_type`, `plan` rows: * `logical_plan`: the `RefreshColumn` statement. * `physical_plan`: a `RefreshJobExec` root carrying what the job runs with (the snapshot, worker count or Function resource budget, error policy, batch size, row timeout, how many fragments have work, which fragment is shown) over the plan each worker executes for one fragment: a `RefreshStageExec` stages the replacement file from the stored values and the rows `StaleRowsExec` selects, computed by a `ProjectionExec` for an expression column or a `PythonUdfExec` for a Function column. Nothing runs: the plan is built against a snapshot without submitting a job, starting a Function executor or taking a table lock. A refresh started later pins its own source version. Job metadata and the final result retain the original Job `source_version`. If a concurrent `UPDATE` or compaction invalidates staged fragments, a Function declaring `result_stability=input_and_context` and `side_effects=none` can re-plan the affected connected fragments for at most three job-wide rounds. Each successor request explicitly pins the newer snapshot it plans, executes, and finalizes against. These request-local snapshots do not replace the Job's original source pin. Unaffected staged results commit without rerunning, while effectful or per-call Functions fail with the named concurrent-write error. `EXPLAIN [VERBOSE] JOB '<job_id>'` renders the same tree for a submitted job, with the registry's view on the root: state, progress and the job's options. The tree is rebuilt from the job's spec against the table's current version on its branch (the root's `source=`), not the snapshot the job pinned when it started, so a representative fragment can differ from what a worker ran. A job whose work is not a plan, such as an index build or a compaction, renders its root alone. The predicate also accepts `_rowaddr` and `_rowid`. To retry specific rows reported by `table.function_errors()`, use each record's `row_id` with `_rowid` when it is present. This stable ID continues to identify the same logical row after compaction or another rewrite: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE _rowid IN (506, 507) ``` For records without `row_id`, combine `fragment_id` and `row_offset` as `(fragment_id << 32) | row_offset` and select those physical addresses before compaction or another rewrite moves the rows: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE _rowaddr IN (0, 4294967297) ``` Only matching live rows are recomputed. A successful Function refresh removes their earlier row errors from `function_errors()` and `SHOW ERRORS` when their physical locations have not changed; rows that fail again remain listed. After compaction or another rewrite moves a row, `_rowid` still selects it, but its earlier error may remain listed even when the retry succeeds. Error clearing currently matches physical locations, not stable row IDs. Older error records and tables without stable row IDs may omit `row_id`. Errors without an individual row location, including those whose per-row detail was capped, cannot all be selected individually. ### Options | Option | Meaning | | - | - | | `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | | `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | | `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | | `gpu_class` | operator-defined GPU pool, such as `'a10g'` or `'h100'` | | `gpu_count` | aggregate GPU ceiling across the refresh's Function workers | | `max_executor_processes_per_worker` | cap on executor processes per worker | | `batch_size` | hard maximum rows passed to one Function call; LanceDB normally chooses a smaller adaptive size | | `error_policy` | Function columns only: `'fail'` (default) stops after configured retries; `'skip'` writes null outputs and records row errors, subject to failure limits | | `retry_policy` | JSON policy for bounded retries of failed user-code calls; overrides the Function default | | `max_failed_fraction` | with `'skip'`, fail after more than this fraction of evaluated rows fail; between `0` and `1` | | `max_failed_rows` | with `'skip'`, fail after more than this many evaluated rows fail | | `row_timeout_seconds` | maximum time per Function call in seconds; overrides the Function's declared deadline and informs adaptive call sizing for this refresh | | `init_timeout_seconds` | maximum time for a Function `__init__` handshake in seconds; default `900`, separate from row execution and task preparation timeouts | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` `num_workers` sets a fixed worker count for expression-backed refreshes. Registered Function columns reject `num_workers`, even without a resource budget. Their worker count adapts within the aggregate resource ceiling. The example above allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the Function workers together. It does not reserve those resources for each worker or guarantee that all of them will be used. `gpu_count` may be set alone to use the deployment's default CPU and memory. When setting either `cpu_millis` or `memory_bytes`, provide all three budget fields. For a CPU-only Function, use `gpu_count = 0` in the complete budget: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN caption_length ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 0) ``` LanceDB adjusts the amount of work sent to each worker from observed execution time. `batch_size` limits rows in one Function call; it does not set the worker count or the size of a checkpoint. Small initial batches are expected while the refresh learns how long rows take. GPU class names are lowercase names of at most 63 letters, digits, or hyphens. The REST `backfill_column` body accepts `gpu_class`, `gpu_count`, and `init_timeout_seconds` as top-level options with the same validation and budget semantics as SQL. ### Retrying temporary Function errors Set `retry_policy` on a source Function at registration, or override it for one refresh. The same JSON object is accepted by `CREATE FUNCTION ... WITH (retry_policy = '...')` and by the registration and refresh REST APIs. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN caption ON videos WITH ( retry_policy = '{"max_attempts":3,"transient":true,"initial_backoff_seconds":0.2,"max_backoff_seconds":30}', error_policy = 'skip' ) ``` `max_attempts` includes the first call and accepts 1–100. An explicit `{"max_attempts":1}` disables user-code retries, including the built-in transient retry. Omitting the option preserves the Function default and existing behavior. Choose one or more matchers; matching any one allows retry: | Field | Matches | | - | - | | `exception_types` | Exception class names, preferably qualified, such as `["builtins.ConnectionError"]`; subclasses also match | | `message_pattern` | A regular expression in the rendered exception class and message | | `error_codes` | Structured provider codes or HTTP status codes, such as `["SlowDown", "503"]` | | `transient` | Built-in `ConnectionError`/`TimeoutError`, the Botocore transport exceptions listed below, HTTP 429/503, and provider codes `SlowDown`/`ServiceUnavailable` | The Botocore transport exceptions are `ReadTimeoutError`, `ConnectTimeoutError`, and `EndpointConnectionError` from `botocore.exceptions`. Requests and HTTPX transport exceptions require explicit `exception_types`, such as `["requests.exceptions.ConnectionError", "httpx.TransportError"]`. The runtime also checks wrapped causes. It does not infer a transient error from digits such as `429` appearing in an arbitrary message. An adapter may signal throttling with `status_code` or `code`, and `retry_after_seconds`. Message patterns must compile under both Rust's regex validator and the Function environment's Python `re` module. Retries use exponential backoff with full jitter. `initial_backoff_seconds` defaults to 0.2 and `max_backoff_seconds` to 30; both must be finite, between 0 and 3600, with the initial value no larger than the maximum. `honor_retry_after` defaults to `true` and honors HTTP `Retry-After` or the adapter's `retry_after_seconds`. A requested delay above the configured maximum ends retry instead of calling the provider early. Cancellation interrupts backoff. The retry unit is one row for a row Function and one whole call for a batch Function. Completed calls are not repeated. With an explicit policy, a failed batch is not bisected after retries: `skip` nulls every row in that failed call and records its error and `attempts`. Use a row Function when failures must be isolated to individual rows. Output conversion and partially consumed generator results are not retried. Invalid values in a returned batch are isolated from that existing result, without calling the Function again. Only opt in when repeating a partially failed call is safe. The runtime cannot undo effects a call performed before raising. Functions declaring external side effects are refused. User-code retries do not consume the worker's infrastructure attempt budget; initialization, worker loss and OOM recovery keep their own policy. After exhaustion, `fail` fails the job and `skip` records the last error and count in `SHOW ERRORS` and the table errors API, subject to the normal failure limits. A Function image created before retry support must be registered as a new version before a refresh can override its policy. ### Hugging Face model snapshots A Function can declare immutable Hugging Face repositories and revisions during registration. The worker prepares each declared snapshot before it creates the user Function instance: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb import HuggingFaceModel, udf MODEL = HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", ) @udf( name="embed_text", pip=["sentence-transformers==3.3.1"], models=[MODEL], ) class EmbedText: def __init__(self): from sentence_transformers import SentenceTransformer self.model = SentenceTransformer( "sentence-transformers/all-MiniLM-L6-v2", ) def __call__(self, text: str) -> list[float]: return self.model.encode(text).tolist() ``` Each repository may be declared once, and its revision must be the full 40-character commit hash. A completed snapshot stores that revision in `refs/main`, so the original no-revision `SentenceTransformer(repo)` call resolves without contacting the Hub. Model-declaring Functions run with a private `HF_HOME`, `HF_HUB_OFFLINE=1`, and `TRANSFORMERS_OFFLINE=1`; those environment variables cannot be overridden through the Function `env`. Before SQL execution or refresh worker admission, a shared preparation job imports the snapshot into database object storage. Concurrent consumers with the same database storage, pinned Secret scope, repository and revision reuse that attempt and its immutable snapshot. A code-only Function version can reuse the snapshot when these inputs are unchanged. Preparation failures are retained: waiting consumers do not automatically retry Hugging Face. An operator with System `Operate` privilege can retry the observed preparation job through `POST /v1/jobs/retry_model_preparation`, with `{"job_id":"<observed preparation attempt>"}`. After preparation succeeds, resubmit failed queries or refreshes; retrying the import does not restart them. Workers read prepared snapshots from database storage into a local model cache. With `computedRefresh.execution.imageCache.hostPath`, workers on one node share those local bytes. Without it, local materialization is private to the worker, while the shared snapshot still avoids repeated origin downloads. `computedRefresh.execution.modelCache.maxBytes` bounds local model bytes independently of the image cache, with a default of 32 GiB. A snapshot that does not fit is rejected before user code starts. For refreshes, `computedRefresh.execution.modelCache.preparationConcurrency` limits concurrent worker preparation requests to 16 by default. A request releases its slot when the snapshot is ready, without waiting for Python initialization. This per-refresh window does not impose a cluster-wide bandwidth quota. Without `models`, the existing behavior is unchanged: the Hub client may still request metadata or missing files, so a cached model and pinned revision alone do not guarantee offline execution. ### Discovering GPU classes ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW GPU CLASSES; ``` The result lists the legacy `default` class first, followed by named classes. Columns are `name`, `resource_name`, `gpu_model`, `gpu_memory_bytes`, `max_gpu_count_per_worker`, `cpu_millis`, `memory_bytes`, and `ephemeral_storage_bytes`. Optional values are `NULL` when the operator did not configure them. A non-NULL `max_gpu_count_per_worker` bounds adaptive growth for one worker; NULL leaves the refresh's aggregate GPU budget as the ceiling. The authenticated REST endpoint `GET /v1/gpu/classes` returns the same catalog as `gpu_classes`. It reports configured hardware, not current free capacity. ### Row errors Set `error_policy` on the refresh, not on the Function definition. With `skip`, inspect the recorded failures with `SHOW ERRORS` or `table.function_errors()` and retry the affected rows after fixing the cause. Skipping row errors does not suppress initialization, infrastructure, or publication failures. Under `error_policy = 'skip'`, a refresh defaults to failing when more than 50% of the first 1,000 evaluated rows in a fragment part fail. It also fails if the first 100 evaluated rows fail before any successful row. `max_failed_fraction` or `max_failed_rows` replaces that default fraction; when both are present, either limit can fail the Job. The counters are evaluated rows, not Function calls. Checks continue cumulatively after the 1,000-row sample and also run when a smaller part finishes. `batch_size` defines call boundaries: the worker checks the shared counts after every inner Function call, so a row-capped batch cannot continue past the ceiling. The part that crosses a limit is not published; fragments committed before it remain visible. LanceDB normally sizes calls from observed row latency and targets at most 25% of the row deadline. `batch_size` remains a hard upper bound, not a tuning requirement. For a Function whose image declares `result_stability=input_and_context` and `side_effects=none`, a timeout or resource failure can enter range recovery, which retries smaller physical-row ranges with a fresh executor. Under `error_policy = 'skip'`, a row timeout can enter range recovery when the Function declares `side_effects=none`, including when its result stability is undeclared or `per_call`. Ordinary vectorized batch exceptions already use the same best-effort bisection under skip. Because a failed batch has no row results to salvage, healthy calls in that batch run again and a per-call Function may return different values. A single row that still times out is written as null and recorded as one `RowTimeoutError`. Functions with declared effects are not replayed automatically. A quarantined terminal row is an exception to the per-part failure limits. Under `skip`, this applies to an OOM-poison row in a replay-safe Function, a typed `OversizedRows` failure for exactly one physical row after range recovery has reduced the unfinished work to that same row, and a non-interruptible row timeout in a `side_effects=none` Function. Oversized-row quarantine requires the executor evidence to name one physical row that matches the only unfinished row in the recovery range; multi-row or mismatched evidence does not become a skipped row. OOM and oversized-row quarantine require `result_stability=input_and_context` and `side_effects=none`; declared effects disable automatic replay. Under the default `fail`, a terminal oversized row fails the refresh without a skipped-row record. Quarantine writes one null row as a synthetic part, so applying the per-part fraction or initial-100-row guard there would reject every quarantine. Before bisecting, the supervisor retries the OOM-killed claim once by itself with one executor process on the largest eligible worker class; a row timeout reaches quarantine only after its execution range has been reduced to one row. The skipped row still counts toward the cumulative job-level failure limits, and the job fails if the quarantined rows cross either limit. ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip', max_failed_fraction = 0.05) ``` Per-row Function failures can include a Python traceback, bounded to a UTF-8 prefix or omitted when the reported errors exceed the byte limit. The compact error message and skipped-row count remain complete. The persisted error file can retain a prefix of records in row order while `rows_skipped` covers the full count. If the compact skipped-row reports alone exceed the event limit, the refresh fails before publication. Skipped-row tracebacks require a newly baked source image. ### Long-running Functions Source Functions default to a 300-second deadline per row. Set `row_timeout_seconds` high enough for the longest row, for example: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN analysis ON videos WITH (row_timeout_seconds = 3600) ``` The batch watchdog accommodates the row deadline and the number of input rows, so a row allowed an hour can run past 15 minutes. In vectorized mode, the row deadline applies to each vectorized call. Automatic sizing starts with a small probe and adjusts later calls; an explicit `batch_size` only lowers the ceiling. A source Function can call `heartbeat()` from the runtime-provided `lance_progress` module inside `__call__` to report liveness. Heartbeats do not extend the row deadline. `init_timeout_seconds` bounds only the interval from `Initialize` until the worker receives `Initialized`; image preparation, Secret resolution, and cleanup have their own bounded task handling. While a worker is waiting for `Initialized`, `SHOW JOBS` progress reports the `initializing` phase and initialized worker counts. It does not count endpoint readiness as initialization completion. If the budget expires, the refresh fails with an initialization-stage error and the bounded child stderr, even when `error_policy = 'skip'`. The row deadline does not extend the job's execution limit. On AWS deployments that vend temporary storage credentials, a Function refresh attempt is capped at **11 hours 40 minutes (42,000 seconds)**. A shorter deployment or job limit still applies; increasing the deployment timeout cannot lift this credential limit. Split longer work into disjoint filtered refreshes, keeping in mind that each predicate recomputes all matching rows. Other deployments use their configured job limit. Automatic column refreshes also have a 24-hour execution limit; an explicit refresh is still subject to the deployment and credential limits. > [!NOTE] > > `num_workers` is refused for a column filled by a registered > [function](/oss/v0-41-0/management/function); a Function refresh's worker count follows > its own resource budget instead. `error_policy` (and the other Function-only > options in the table above) is the reverse: it's refused for a plain > SQL-expression column, which has no per-row failures to skip, and accepted > only for a Function column. ### Automatic refresh timing Automatic column refresh requires a supporting server release and an enabled deployment. A column's `auto_refresh_interval_seconds` sets a minimum delay after its last successful refresh, not a completion deadline. The scheduler also waits for its computed inputs, available workers, and other refreshes. The deployment default allows one column refresh in flight per table. Failed automatic Function refreshes start with a 15-minute retry delay by default, then double it for consecutive failures: 15, 30, 60, 120 minutes, and so on. This is failure backoff, not a fixed refresh cadence. A manual refresh can run during that wait. Cancelling a Function refresh blocks automatic refresh for that binding on the same branch until a later explicit refresh completes or the binding is replaced. Check job history when automatic results stop appearing. ## REFRESH MATERIALIZED VIEW The syntax and options below apply to Enterprise deployments that support explicit `full = false` in SQL. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW <name> [WITH (full = <boolean>)] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks REFRESH MATERIALIZED VIEW chunks WITH (full = false) REFRESH MATERIALIZED VIEW chunks WITH (full = true) ``` A refresh updates the view's stored result. Refresh views in dependency order, starting with their source views. `CASCADE` is not supported. | Option | Meaning | | - | - | | `full = false` (default) | Refresh incrementally when supported, or rebuild when incremental refresh is unavailable. An eligible view whose sources are unchanged completes without rewriting data. | | `full = true` | Rebuild the complete stored result, even when the sources are unchanged. | > [!NOTE] > > Servers without SQL refresh option support require the basic statement without > `WITH`. Older servers may accept only `full = true`; some also accept `CASCADE`. > A local SDK's `refresh()` options do not determine which SQL options a server > accepts. ### Function row errors in materialized views Choose the policy when creating the view: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW captions WITH (error_policy = 'skip') AS SELECT id, caption(video) AS text FROM videos; ``` `error_policy = 'fail'` is the default, including for views created without this option. A Function failure aborts the refresh and preserves the previously published result. With `skip`, a failing scalar Function input produces NULL; a failing table Function input produces no output rows. Planning, storage, worker, and commit failures propagate to normal job failure and recovery handling; they are not converted into skipped inputs. Custom Function images must report a failure as attributable to the input before it can be skipped. Errors from older images that do not distinguish callable failures from worker failures stop the refresh. Use `SHOW ERRORS ON captions` or the SDK's `table.function_errors()` to inspect the diagnostics. `SHOW ERRORS` adds an `input` column containing JSON identifying the Function invocation and input offset. When a failed input can be traced to stored source rows, it also includes the source table, pinned version, and row address or stable row ID. Inputs computed by expressions or aggregations may have no single source row. Input offsets are not physical row offsets in the view. SDK error messages also include the source locator; use it instead of the view fragment fields for MV errors. Error records describe attempts and remain available after a later successful refresh. An incremental refresh over appended source rows leaves previously skipped inputs alone. When a change to existing source rows recomputes a block of the view, every input in that block runs again, skipped ones included. To retry them all, run: ```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW captions WITH (full = true); ``` A full refresh recomputes all inputs, including previously successful ones. The policy is fixed at creation; refresh does not accept a policy override. ### Interrupted materialized-view jobs LanceDB can replay `CREATE MATERIALIZED VIEW` and supported `REFRESH MATERIALIZED VIEW` operations, including `full = true`, after an infrastructure interruption. Other SQL statements remain non-replayable. A replacement worker keeps the same Job, job handle, and original deadline. A counted infrastructure disruption can use one replacement worker. User cancellation and permanent SQL or Function errors terminate the Job, and a terminal Job is not restarted. Recovery can run Function code again when the data commit has not completed, so external side effects from that attempt can repeat. After the data commit, receipt recovery finishes state and catalog publication without computing the committed rows again, and it does not need to plan the original source or Function. Cancellation does not guarantee that an in-flight storage write stops; a data or catalog request that was already issued or sent may still complete. Recovery therefore does not guarantee exactly-once execution of external side effects. ## Watching a refresh When a client requests an early job handle and the server can make the job registry available to it, the refresh returns a `job_id` with status `submitted`. The work then outlives the request. Track it with [`SHOW JOBS`](/oss/v0-41-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/oss/v0-41-0/sql/ddl/job#errors). The registry APIs require both `System Usage` and `System Operate`; refresh access scoped to a database or table is not enough. Submitting a Function refresh creates work; it does not reserve Function worker capacity or guarantee that a warm worker is available. A queued job reports a current admission observation when the dispatcher has one, but submission has no global queue position or start-time estimate. `CREATE MATERIALIZED VIEW` returns `(operation, name, status, job_id)`. The original three columns keep their positions; `job_id` is appended and is empty when the statement ran natively without a registry job. When the caller lacks both system privileges above, the server omits the early job-handle acknowledgement and the query continues through ordinary adaptive polling. Continue polling the returned descriptor until it completes, then read the result; the final refresh success or error is delivered through that path. When the bounded retained-run store is full, the server runs the refresh synchronously and reports its actual outcome without announcing a change of mode. A client must use the early acknowledgement and status `submitted`, rather than the presence of `job_id` alone, to decide that it received an early registry handle. Published view results remain visible whether the refresh was polled or run through the synchronous capacity fallback. Use `SHOW JOBS FOR JOB '<job_id>'` to discover a refresh's child jobs and inspect their phase, row progress, and attempt information. Pass a returned child ID to the same event command used for the parent: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOBS FOR TABLE frames; SHOW JOBS FOR JOB '<parent_job_id>'; SHOW JOB EVENTS '<child_job_id>' LIMIT 100; ``` Parent events do not include child events. Child diagnostics can expire at archival; the CLI reports unavailable history even when no rows remain. While a supervised refresh runs, `SHOW JOBS` includes a `progress` column containing a JSON sample: rows planned, computed, skipped and remaining, published and retained, failed rows, fragments planned and completed, active workers and active fragments, and the last row-progress timestamp when available. The same `progress` object is returned by `POST /v1/jobs/describe` and `POST /v1/jobs/list`. Samples update approximately every 30 seconds and after tracked progress changes. While at least one worker endpoint is ready and the latest sampled worker phase is `preparing`, `initializing`, or `initialized`, startup samples are published approximately every second so short initialization transitions are more likely to be observed. They are absent before the first sample and while the job is paused. Succeeded, failed, timed out, and canceled jobs retain the latest row progress and timing from the execution that ended, when a sample was recorded. Terminal jobs zero live worker, GPU, and active fragment counts and clear `resource_classes`, `warm_reused`, and wait reasons. `sample_at_millis` and `execution_epoch` identify that sample. A client may estimate remaining time from two observations only when the epoch and planned work are unchanged and accounted work advances; an estimate is unknown at startup, after a pause or epoch change, and when either sample is missing or stale. The Python SDK exposes a defensible estimate as `estimated_remaining_time_millis` and omits the field when the evidence is insufficient; the server does not persist or return a historical sampler. The optional `worker_fleet` object reports the Function-role worker cohorts from the supervisor's latest completed status observation. `desired` is the policy target for Function workers and can exceed the cohorts that have been created. `launched` counts surviving workers whose cohort launch was confirmed, `pending_workers` counts observed active workers not yet ready to accept dispatch, including workers still initializing. `ready` counts distinct endpoints in that launched set that can accept dispatch after status and worker announcements are merged. When an observation does not provide a usable pending count, readers may derive it from `active - ready`; this fallback only describes currently visible endpoint evidence and is not a guarantee about workers that have not yet become visible. `resource_classes` lists the observed class names. Draining, reaping, and dead workers are excluded consistently. `requested_gpus` totals the GPU devices requested by the observed Function cohorts; `ready_gpus` totals devices on dispatchable endpoints. Neither number is free cluster capacity or a queue position. `warm_reused` is `true` when at least one observed cohort was proven to come from a reusable pool. It is `false` only when every observed cohort was proven cold, and absent when no cohort was observed or the observations are incomplete. A `true` value does not guarantee that every worker in the fleet avoided a cold start. `worker_fleet` is absent until a coherent Function-worker observation exists. `first_launched_at_millis`, `first_ready_at_millis`, and `last_ready_at_millis` record milestones for the current supervisor run. Readiness means a dispatchable endpoint, not that Python initialization or the first function call has completed. When no dispatchable endpoint exists, `worker_fleet.wait_reason` may carry a fixed substrate-derived wait reason; it is cleared once an endpoint is ready or the job reaches a terminal state. The top-level `SHOW JOBS.phase` reports `queued`, `paused`, `starting`, `waiting_for_workers` (no Function workers have launched), and `starting_workers` (workers have launched but no endpoint is ready). Once an endpoint is ready, it mirrors the nested `progress.phase`, falling back to `running` until the first worker sample. The nested phase reports the observed worker phase: `preparing` before the initialization handshake, `initializing` while the worker is inside the `Initialize` handshake, `initialized` after a successful `Initialized` response, `running` while processing rows, `finalizing` while publishing, and `staged` after local output is staged. The top-level phase becomes `committing` once all planned rows are accounted for. Terminal jobs report `finished`, `failed`, or `cancelled` when the outcome is known. `workers_initializing` and `workers_initialized` count distinct live workers at those handshake boundaries; endpoint readiness alone does not increment either counter. These are sampled observations, so a short phase may be missed, and neither phase claims that every worker is in the same state. `queue_reason` is populated only from a current substrate observation; in particular, before a Function supervisor starts, the dispatcher may report that the job is waiting for executor capacity and include the worker slots requested and currently available. Those values are a point-in-time admission observation. A GPU-capacity reason requires PodScheduled=False evidence naming the requested GPU resource. CPU pressure, taints, and image-pull failures are not relabeled as GPU capacity waits. The object does not report global queue position or an ETA. `rows_computed` counts evaluated rows, including work later recomputed. `rows_published` counts evaluated rows backed by accepted publication receipts at the sample. `rows_retained` counts completed staged output that no accepted receipt has published yet; it is a sampled lower bound, not an exact final cancellation count. `rows_failed` is present only when a successful terminal result carries a typed failed-row count; it is not inferred from in-flight or non-successful job state. `active_workers` counts owners of execute claims, including workers that have not reported their first batch yet; it is separate from `worker_fleet.ready`. Job listings return the most recently created jobs first across tables. `SHOW JOB SPLITS '<job_id>'` returns completed splits and, while the refresh runs, the latest task for each split that has not completed. `state` preserves the worker's serialized phase, including phases introduced by a newer server; `queued`, `assigned`, `initializing`, `running`, `failed`, and `completed` do not share a closed mapping in older clients. Measurements that live evidence has not established are `NULL`, never a fabricated zero. `error_count` counts explicit failed execute completions for the current task identity in the current execution epoch, including failures that happened before a later retry or success. Expired leases are shown as `queued`; retries, expiry, success, replaced tasks, skipped rows, and row-level errors do not increment `error_count`, and they do not erase failures already recorded. Canceling a refresh leaves already published results visible. A later refresh of the same definition may reuse completed staged parts while its inputs and source provenance still match; parts affected by newer inputs or writes are recomputed or rejected under the concurrency rules above. Dropping a Function output column retires its binding and automatically cancels running and queued refreshes for that binding on the same table generation and branch. Failed drops and `IF EXISTS` drops that remove nothing leave refreshes running. Refreshes for other bindings are unaffected. `SHOW JOB SPLITS '<job_id>'` reports, per split: task, split and fragment identifiers, the worker that ran it, its row range, rows skipped, bytes read and staged, part and attempt counts, batch count, start and finish times, `state`, `error_count`, and the executor batch latency as p50/p95/p99/max in milliseconds. A split the supervisor recovered from a checkpoint rather than a worker report carries `recovered = true`. `POST /v1/jobs/query_splits` reports completed split records only -- not the live, not-yet-completed rows the SQL form returns while the refresh is still running -- and its records carry a different shape: no `state` or `error_count`, and a raw latency histogram in place of the SQL form's precomputed quantiles. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SHOW JOB SPLITS 'j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames'; ``` `DESCRIBE JOB '<job_id>'` -- also spelled `SHOW JOB SUMMARY '<job_id>'`, or abbreviated `DESC JOB` -- shows where a finished job spent its time, one line per row as `EXPLAIN` shows a plan: its totals, a timeline of its phases, and for a phase that runs on many workers at once, what their time went to. It works for any job; for a Function refresh the phases are queued, planning, starting workers, running splits and committing. A job still running returns no rows. `FORMAT TABLE` returns the same profile as typed rows, with `unit` saying whether `millis` is wall time or worker time, and `FORMAT JSON` as one JSON document. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} DESCRIBE JOB 'j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames'; ``` ``` j1-fr-0mvoq6qbb-3e172e8f1e334086979a5b2c0f1d5f7f-mydb:frames 18.7 s · 6 fragments · 300,000 rows · 102 splits · 6 workers Timeline at took queued +0.00 s 0.18 s planning +0.18 s 0.13 s starting workers +0.31 s 0.36 s launch 0.12 s, ready 0.01 s, dispatch 0.23 s running splits +0.67 s 16.45 s 88% committing +17.12 s 1.47 s publishing 1.40 s, final claim 0.06 s finishing +18.59 s 0.11 s Worker time, running splits (109 s) supervisor handoff 36% 39.6 s instance start 30% 33.0 s finalizing fragments 13% 14.6 s in the Function 10% 10.8 s idle 7% 7.5 s reading and writing 1% 1.6 s other 1% 1.5 s reporting, slot waits, uploads ``` Across refreshes, the `system.public.function_refresh_metering` view holds one row per succeeded refresh with the same summary, once the job events export has run. It needs system Usage and Select on the view. This grants access to refresh metering across all databases in the cluster; the connection's database does not filter the view. Only grant this access to users who may read cluster-wide usage. `SHOW JOBS` instead lists jobs in the connected database. Choosing a database in the SDK does not narrow an API key's permissions. For a database-specific report, filter `database_name` explicitly, as below. This query filter is not an access control boundary. Compare a Function's versions, or follow one over time: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT function_version, count(*) AS refreshes, avg(slot_occupancy) AS mean_occupancy, max(batch_latency_p95_millis) AS worst_p95_millis FROM system.public.function_refresh_metering WHERE database_name = 'my_database' AND function_id = 'embed' GROUP BY function_version; SELECT job_id, rows_assigned, splits, finished_at_millis - supervisor_started_at_millis AS millis FROM system.public.function_refresh_metering WHERE database_name = 'my_database' AND function_id = 'embed' AND ended_at_millis > 1793000000000 ORDER BY ended_at_millis DESC; ``` ## See also > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > The same operation from the SDKs, and what a refresh guarantees. > [card] [Table](/oss/v0-41-0/sql/ddl/table#alter) > > Declaring the columns this fills. # REFRESH COLUMN Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/refresh-column Fill computed outputs and select rows to recompute. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB extension with no DataFusion equivalent. It is what makes [feature engineering](/oss/v0-41-0/feature-engineering) reachable from SQL: a column declared by [DDL](/oss/v0-41-0/sql/ddl/table#computed-column) starts empty, and a refresh fills it. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN <column> ON [TABLE] <table> [WHERE <predicate>] [WITH (<option> = <value> [, ...])] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN doubled ON my_table REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` Without `WHERE`, a refresh fills unassigned rows and recomputes values whose inputs changed, leaving other current values alone. A retry after a failure can still repeat work that was not committed. With `WHERE`, a refresh **recomputes every matching live row**, including rows that already have current values. Repeating a predicate can repeat the Function calls and their cost. To select only null outputs within a slice: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` This skips non-null outputs even if their inputs changed. It also selects outputs that were successfully computed as `NULL`. Use an unfiltered refresh to let LanceDB track which outputs need updating. ## Options | Option | Meaning | | - | - | | `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | | `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | | `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | | `gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | | `gpu_class` | GPU class name for the refresh's workers. Function columns only | | `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | | `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` The example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the Function workers together. It does not reserve those resources per worker or guarantee a worker count. When setting CPU or memory, provide all three budget fields. A complete CPU-only budget uses `gpu_count = 0`. Set `error_policy` on the refresh, not on the Function definition. With `skip`, inspect failures with `SHOW ERRORS` or `table.function_errors()` and retry the affected rows after fixing the cause. Initialization, infrastructure, and publication failures can still fail the job. > [!NOTE] > > `num_workers` is refused for a column filled by a registered > [function](/oss/v0-41-0/management/function), which sizes its own workers from the CPU, > memory and GPU options instead. `error_policy` (and the Function-only options > above it in the table) is the reverse: it's refused for a plain SQL-expression > column, which has no per-row failures to skip -- it's accepted only for a > Function column. ## Watching a refresh A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/oss/v0-41-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/oss/v0-41-0/sql/ddl/job#errors). For per-split progress, worker fleet detail, and a `DESCRIBE JOB` example, see [Watching a refresh](/oss/v0-41-0/sql/dml/refresh#watching). ## See also > [card] [Refresh a computed column](/oss/v0-41-0/feature-engineering/refresh-column) > > The same operation from the SDKs, and what a refresh guarantees. > [card] [Table](/oss/v0-41-0/sql/ddl/table#alter) > > Declaring the columns this fills. > [card] [REFRESH MATERIALIZED VIEW](/oss/v0-41-0/sql/dml/refresh-materialized-view) > > Bringing a view's stored result up to date, instead of a column. # REFRESH MATERIALIZED VIEW Source: https://docs.lancedb.com/oss/v0-41-0/sql/dml/refresh-materialized-view Bringing a materialized view's stored result up to date. **Applies to:** Embedded ❌, Enterprise ✅ A LanceDB extension with no DataFusion equivalent. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW <name> [WITH (full = <boolean>)] ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} REFRESH MATERIALIZED VIEW chunks REFRESH MATERIALIZED VIEW chunks WITH (full = true) ``` A refresh updates the view's stored result. Refresh views in dependency order, starting with their source views. `full = true` forces a complete rebuild even when the sources are unchanged; the default, `false`, refreshes incrementally when supported and rebuilds otherwise. > [!NOTE] > > `CASCADE` is not accepted by the SQL implementation described here, > regardless of what a local SDK's `refresh()` method accepts -- do not > assume the two option sets match. ## Resource budgets Enterprise 1.12.0 supports only the `full` refresh option. It rejects CPU, memory and GPU budget options for materialized-view refreshes. ## Watching a refresh A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/oss/v0-41-0/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/oss/v0-41-0/sql/ddl/job#errors). For per-split progress, worker fleet detail, and a `DESCRIBE JOB` example, see [Watching a refresh](/oss/v0-41-0/sql/dml/refresh#watching). ## See also > [card] [Materialized View](/oss/v0-41-0/sql/ddl/materialized-view) > > Creating the view this refreshes. > [card] [Refresh a materialized view](/oss/v0-41-0/feature-engineering/refresh-materialized-view) > > The same operation from the SDKs, and automatic refresh. > [card] [REFRESH COLUMN](/oss/v0-41-0/sql/dml/refresh-column) > > Filling a computed column, instead of a view. # Aggregation Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/aggregation GROUP BY, HAVING, and the aggregate function set. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL aggregates to summarize records, either across a whole table or within groups. Common examples include counts by category, totals and averages. ## Grouping ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, count(*) AS n, avg(score) AS mean_score FROM documents GROUP BY category HAVING count(*) > 10 ORDER BY n DESC ``` `WHERE` filters rows before grouping; `HAVING` filters groups after. Use `WHERE` for row-level conditions and `HAVING` for conditions on aggregate results. The planner may push eligible predicates earlier in the query. Grouping by several expressions produces one row per distinct combination: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, source, count(*) FROM documents GROUP BY category, source ``` ## Aggregate without grouping Omitting `GROUP BY` aggregates the whole table into one row, which is the usual way to ask how big something is: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*), min(created_at), max(created_at) FROM documents ``` `count(*)` counts rows; `count(col)` counts non-null values, which is how you measure how populated a [computed column](/oss/v0-41-0/feature-engineering/add-computed-column) is before deciding to refresh it again. ## The function set Registered in DataFusion 54. Names below are what is actually available. **General** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} count sum min max avg median bit_and bit_or bit_xor bool_and bool_or first_value last_value nth_value grouping ``` **Statistical** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} stddev stddev_pop stddev_samp var var_pop var_samp corr covar_pop covar_samp regr_slope regr_intercept regr_count regr_r2 regr_avgx regr_avgy regr_sxx regr_syy regr_sxy ``` **Approximate** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} approx_distinct approx_median approx_percentile_cont approx_percentile_cont_with_weight percentile_cont ``` **Collecting** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} array_agg string_agg ``` The approximate functions are the ones worth reaching for on a large table. `approx_distinct` answers "roughly how many distinct values" for a fraction of what `count(DISTINCT ...)` costs, which can help with high-cardinality columns. Measure the accuracy and runtime for your workload. `DISTINCT` works inside an aggregate: `count(DISTINCT category)`. `FILTER` narrows one aggregate without narrowing the others: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT count(*) AS total, count(*) FILTER (WHERE score > 0.9) AS confident FROM documents ``` ## Aggregating a sample For an estimate over a very large table, aggregate a [sample](/oss/v0-41-0/sql/dql/sampling) rather than the whole thing: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT category, count(*) * 100 AS estimated FROM documents TABLESAMPLE (1) GROUP BY category ``` For a uniform percentage sample, counts and sums can be scaled by the inverse of the sample fraction to estimate whole-table values. Do not apply that scaling to averages, minima or maxima. Small samples can miss rare categories; consider the sampling method and uncertainty when interpreting the result. ## What aggregation does not do Aggregates run over rows the query already produced. Whether a statement can include [vector search](/oss/v0-41-0/search/vector-search) is described under [SQL vector search](/oss/v0-41-0/basics/sql#no-vector-sql). If your server does not support that query form, run the search in an SDK and aggregate its result, or materialize the search output first. # BLOB_DESCRIPTOR Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/blob-descriptor The blob_descriptor() scalar function: a BlobV2 column's payload location, without reading it. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, blob_descriptor(video) AS descriptor FROM videos ``` A [BlobV2](/oss/v0-41-0/management/table#managed-blobs) column's bytes are not fetched by a plain `SELECT`: that already returns `large_binary`, the same as any other binary column. `blob_descriptor` instead returns a small struct describing where the payload lives, without reading it. Pass one row's descriptor to the SDK's blob file reader to open that payload directly: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM videos").read_all().to_pylist() with table.open_blob_file(rows[0]["descriptor"]) as reader: payload = reader.read() ``` A descriptor is pinned to the table version it was read at: it keeps resolving correctly even after the table is appended to and checked out to a newer version. ## What to read next > [card] [Managed blobs](/oss/v0-41-0/management/table#managed-blobs) > > The BlobV2 column type this function describes. # Changes since a version Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/changes CHANGES: read the rows appended to a table since an earlier version. **Applies to:** Embedded ❌, Enterprise ✅ `CHANGES` reads the rows appended to a table since an earlier [version](/oss/v0-41-0/management/table#versioning), without rescanning rows that were already there: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) ``` This returns the rows appended after version 42, up to the table's current version at the time the query runs. ## Strictly append-only The clause is named for what it requires, not just what it does: every change to the table between the starting version and the current one must be an append. If any of them inserted with changes other than a pure append \-- an update, a delete, a merge -- the query is refused rather than silently returning an incomplete or wrong result. Re-run it with a later starting version that is itself after the non-append write, or read the table in full instead of incrementally. `INFORMATION => APPEND_ONLY` is the only supported value: it names what kind of history the clause is willing to read, not a choice among several. `AT (VERSION => ...)` takes a positive integer; there is no `AT (TIMESTAMP => ...)` form for this clause, unlike other version qualifiers. ## Where the clause can go It attaches to a table in `FROM`, including inside a subquery, a CTE, a join, a set operation, or `EXPLAIN`: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH recent AS ( SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) ) SELECT count(*) FROM recent SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 10) a JOIN events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 20) b ON a.id = b.id ``` Each occurrence of a table keeps its own starting version, even when the same table is referenced more than once in one statement. ## Unsupported forms | | | | - | - | | `CHANGES (INFORMATION => DEFAULT)` | only `APPEND_ONLY` is supported | | `AT (TIMESTAMP => ...)` | only `AT (VERSION => ...)` is supported | | `AT (VERSION => 0)` | the starting version must be positive | | `... END (VERSION => ...)` | not supported; the current version is always the end | | `CHANGES ... TABLESAMPLE (...)` | cannot be combined on the same table reference | ## What to read next > [card] [Table](/oss/v0-41-0/sql/ddl/table) > > CREATE, ALTER, CLONE and versioning basics. > [card] [Select](/oss/v0-41-0/sql/dql/select) > > The rest of the query grammar this clause attaches to. # CONTAINS_TOKENS Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/contains-tokens The contains_tokens() scalar function: an index-accelerated keyword predicate usable directly in WHERE. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM my_docs WHERE contains_tokens(text, 'fox jumps dog') ``` `contains_tokens(column, tokens)` is true when `column` contains **all** the tokens in `tokens`, split on whitespace and punctuation. It is equivalent to an [`fts()`](/oss/v0-41-0/sql/dql/fts) match query with fuzziness off, `AND` semantics and the simple tokenizer -- reach for it when you need a keyword test in a `WHERE` clause and have no use for a relevance score. **Index-accelerated.** When the column has a full-text index that suits the query, the planner uses it instead of scanning, which is the reason to prefer it over `LIKE` or `contains` for keyword tests. See [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain) to confirm the plan uses the index. ## What to read next > [card] [Full-Text Search](/oss/v0-41-0/sql/dql/fts) > > The `fts()` table function, for relevance-ranked results and fuzzy, > phrase, boolean, boost and multi-match queries. > [card] [FTS Index](/oss/v0-41-0/indexing/fts-index) > > Build the full-text index this predicate accelerates against. # DEDUPE Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/dedupe The dedupe() table function: one representative row per near-duplicate group, scanned over the index. **Applies to:** Embedded ❌, Enterprise ✅ `dedupe` scans a vector column's [index](/oss/v0-41-0/indexing/vector-index) partitions for rows closer than a distance threshold, resolves the overlapping pairs it finds into duplicate groups, and returns one representative row per group -- without a full pairwise scan or a shuffle. See [`duplicate_pairs`](/oss/v0-41-0/sql/dql/duplicate-pairs) to inspect the pairs themselves before committing to this resolution. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe( <table>, <vector_column>, distance_threshold => <float> [, resolution => 'connected_components' | 'direct_representative'] ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM dedupe( 'frames', 'vec', distance_threshold => 0.02 ) ``` > [!NOTE] > > Earlier releases spelled this `vector_dedup`; that name is rejected on > current deployments. ## Input | Argument | Type | Required | Meaning | | - | - | - | - | | table name | string literal | yes | the table to scan | | vector column | string literal | yes | the indexed vector column to compare | | `distance_threshold` | float | yes | maximum distance for a pair to count as close | | `resolution` | `'connected_components'` (default) \| `'direct_representative'` | no | how overlapping pairs group together -- see [Resolution](#resolution) | `dedupe` always scans every partition and returns original rows -- sampling a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/oss/v0-41-0/sql/dql/duplicate-pairs#input) but refused here. ## Output One row per duplicate group, **in the table's own schema** -- every column of `<table>`, including a BlobV2 column, comes through unchanged on the representative row Lance selected for that group. Unlike [`duplicate_pairs`](/oss/v0-41-0/sql/dql/duplicate-pairs#output), there is no fixed `dedupe`-specific schema to document: the output schema is the source table's schema. Because the result is already shaped like the table, it composes directly into a new table or a materialized view: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE MATERIALIZED VIEW frames_deduped AS SELECT * FROM dedupe( 'frames', 'vec', distance_threshold => 0.02 ) ``` ## Resolution `resolution` chooses how overlapping pairs group together: | `resolution` value | How pairs group | | - | - | | `connected_components` (default) | groups transitively: if a~~b and b~~c are both close, all three resolve together | | `direct_representative` | only pairs within the threshold of each other resolve together | ## Estimating on a sample first `dedupe` itself always scans every partition. To estimate a duplicate rate on a large table before committing to a full scan, sample partitions with [`duplicate_pairs`](/oss/v0-41-0/sql/dql/duplicate-pairs#sampling) instead, which accepts `selection`, `count` and `seed` for exactly this. ## What to read next > [card] [DUPLICATE_PAIRS](/oss/v0-41-0/sql/dql/duplicate-pairs) > > Inspect the close pairs themselves instead of the resolved groups. > [card] [Deduplicate near-duplicates](/oss/v0-41-0/curation/dedupe) > > When to reach for this instead of exact-key deduplication. # DUPLICATE_PAIRS Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/duplicate-pairs The duplicate_pairs() table function: every close pair in a vector column, scanned over the index. **Applies to:** Embedded ❌, Enterprise ✅ `duplicate_pairs` scans a vector column's [index](/oss/v0-41-0/indexing/vector-index) partitions for every pair of rows closer than a distance threshold, without a full pairwise scan or a shuffle. It returns one row per close pair, not one row per source row -- use it to inspect what would be collapsed before committing to [`dedupe`](/oss/v0-41-0/sql/dql/dedupe), which resolves these same pairs into groups. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( <table>, <vector_column>, distance_threshold => <float> [, id_column => <column>] [, selection => 'all' | 'first' | 'random', count => <int>, seed => <int>] ) ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02 ) ``` > [!NOTE] > > Earlier releases spelled this `vector_duplicate_pairs`; that name is rejected > on current deployments. ## Input | Argument | Type | Required | Meaning | | - | - | - | - | | table name | string literal | yes | the table to scan | | vector column | string literal | yes | the indexed vector column to compare | | `distance_threshold` | float | yes | maximum distance for a pair to count as close | | `id_column` | column name | no | project this column's value instead of the internal row ID -- see [Application-level identifiers](#id-column) | | `selection` | `'all'` (default) \| `'first'` \| `'random'` | no | which index partitions to scan | | `count` | int | no | number of partitions to sample when `selection => 'random'` | | `seed` | int | no | random seed when `selection => 'random'` | `resolution` is refused on `duplicate_pairs`: a pair has no notion of a group, only [`dedupe`](/oss/v0-41-0/sql/dql/dedupe#input) accepts it. ## Output One row per close pair found, in a fixed schema independent of the source table: | Column | Type | Meaning | | - | - | - | | `row_id_a` | uint64 | internal row ID of the first row in the pair, the same identifier as the [`_rowid`](/oss/v0-41-0/sql/data-types#pseudo-columns) pseudo-column | | `row_id_b` | uint64 | internal row ID of the second row in the pair | | `distance` | float32 | distance between the pair's vectors, at or below `distance_threshold`. For `l2`, this is the squared distance, not its square root | | `segment_id` | Utf8 | which index segment the pair was found in, a UUID | | `partition_id` | uint64 | which index partition the pair was found in | | `dataset_version` | uint64 | the dataset version the scan ran against | ### Application-level identifiers A row ID is internal and not stable across compaction. Pass `id_column`, a top-level scalar column such as a primary key, to also project its value: `id_a`/`id_b`, typed like `id_column`, are appended alongside `row_id_a`/`row_id_b`, which remain in the output. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02, id_column => 'frame_id' ) ``` ## Sampling partitions `selection` scopes the scan to a sample of partitions instead of all of them, the same `all` (default) / `first` / `random` choice as [`ivf_partition`](/oss/v0-41-0/sql/dql/ivf-partition). Use it to estimate a distance threshold or duplicate rate on a large table before scanning it in full: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM duplicate_pairs( 'frames', 'vec', distance_threshold => 0.02, selection => 'random', count => 100, seed => 42 ) ``` ## What to read next > [card] [DEDUPE](/oss/v0-41-0/sql/dql/dedupe) > > Resolve these same pairs into one representative row per group. > [card] [Deduplicate near-duplicates](/oss/v0-41-0/curation/dedupe) > > When to reach for this instead of exact-key deduplication. # Explain Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/explain EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE: reading and measuring a plan from SQL. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN SELECT * FROM documents WHERE identifier < 1000 EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` | Statement | What it returns | | - | - | | `EXPLAIN <query>` | Logical and physical plan, without executing the query. | | `EXPLAIN ANALYZE <query>` | Executes the query and annotates each operator with runtime metrics (rows, timing). | | `EXPLAIN VERBOSE <query>` | Adds intermediate optimizer plans on top of `EXPLAIN`. | The result is a small relation with `plan_type` and `plan` columns, read through the same client you use for regular queries. See [Connecting](/oss/v0-41-0/sql#connecting). SQL plans and the SDK's [`explain_plan` and `analyze_plan`](/oss/v0-41-0/basics/sql#query-plans) output share scan and index operators. Use the same approach to inspect index coverage and filter pushdown; SQL can also add joins, aggregates and other operators: > [card] [What it shows](/oss/v0-41-0/basics/sql#inspect-a-query-plan) > > Reading a plan: operators, pushdown, index usage. > [card] [What it measures](/oss/v0-41-0/basics/sql#analyze-a-query-plan) > > Reading the metrics, and a worked before/after. ## What to look for | Sign | Means | | - | - | | `ScalarIndexQuery` | the predicate used a scalar index | | `LanceScan` with high `bytes_read` | inspect the selected columns, filter pushdown and index use | | `FilterExec` above a search | the filter ran after search rather than pushing into it | | `ANNSubIndex` / `ANNIvfPartition` | the vector index was used | A `LanceScan` feeding a join is the common one worth acting on. See [Joins](/oss/v0-41-0/sql/dql/join#performance). For a table's columns and types without a plan, see [`DESCRIBE`](/oss/v0-41-0/sql/ddl/table#describe). # Full-Text Search Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/fts The fts() table function: match, fuzzy, phrase, boolean, boost and multi-match queries from SQL. **Applies to:** Embedded ❌, Enterprise ✅ Full-text search is a **table function**, `fts(table, query)`, rather than a predicate: it produces a relevance score alongside the matching rows, and a `WHERE` clause has nowhere to put one. The two string-literal arguments are the table name and a JSON-encoded query, built with the same query-builder classes used from the SDK and serialized with `.to_json()`. ## Setup Run these statements in order, sending one statement per SQL request. Semicolons separate the statements for clients that execute a script. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} CREATE TABLE my_docs (id INT, text STRING, category STRING, author STRING); INSERT INTO my_docs VALUES (1, 'The happy puppy runs merrily in the park', 'animals', 'Alice'), (2, 'A curious kitten jumps quickly over the fence', 'animals', 'Bob'), (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); CREATE INDEX ON my_docs USING fts (text); ``` > [!WARNING] > > Phrase queries need position information, which costs extra index size. > Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, > [phrase queries](#phrase) find nothing. See > [FTS parameters](/oss/v0-41-0/indexing/fts-index#fts-parameters). ## Basic search The query builder produces the JSON string used as the second SQL argument. The SQL examples below spell out the equivalent match object so they can be run directly after the setup above. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MatchQuery query = MatchQuery("puppy", "text") json_query = query.to_json() ``` ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, category FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) LIMIT 5 ``` By default the top 5 matches come back in **arbitrary order**. Select `_score` and order by it for relevance ranking: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, _score FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) ORDER BY _score DESC LIMIT 5 ``` `_score` is a pseudo-column carrying the query's BM25 relevance for the row; it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/oss/v0-41-0/sql/data-types#pseudo-columns). ## Fuzzy Tolerates typos, up to a character-edit budget: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} MatchQuery("pupy", "text", fuzziness=2) ``` ## Phrase Exact phrase, or with `slop` to allow words between terms: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import PhraseQuery PhraseQuery("happy puppy", "text") PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` ## Boolean Combine queries with `&` (AND) or `|` (OR): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} MatchQuery("puppy", "text") & MatchQuery("happy", "text") MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` ## Boost Weight a query up or down relative to another: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import BoostQuery BoostQuery( positive=MatchQuery("puppy", "text"), negative=MatchQuery("kitten", "text"), negative_boost=0.2, ) ``` ## Multi-match Search several columns at once, optionally weighting them differently: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.query import MultiMatchQuery MultiMatchQuery("puppy", ["text", "category"]) MultiMatchQuery("puppy", ["text", "category"], boosts=[2.0, 1.0]) # text weighted 2x ``` ## Combining with SQL `fts()` is a relation, so it composes with the rest of the SQL surface. Filter, join, or aggregate over it same as any table: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, text, category FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) WHERE category = 'animals' LIMIT 5 ``` ## What to read next > [card] [Full-Text Search](/oss/v0-41-0/search/full-text-search) > > The query-builder equivalent, and every query form in full. > [card] [FTS Index](/oss/v0-41-0/indexing/fts-index) > > Tokenizers, and the position information phrase queries need. # Functions Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/functions Where to find each kind of function, and the dialect version they come from. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB executes SQL with [Apache DataFusion](https://datafusion.apache.org), currently **version 54**. The function set is DataFusion's default registration plus what Lance adds. | | | | - | - | | [Scalar functions](/oss/v0-41-0/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct | | [Aggregate functions](/oss/v0-41-0/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | | [Window functions](/oss/v0-41-0/sql/dql/window#functions) | per window: ranking, offset, running aggregates | | [Table functions](#table-functions) | produce a relation rather than a value | > [!NOTE] > > Function availability is version-specific. DataFusion adds functions in most > releases, so one documented on `main` may not exist in 54. When a name is not > recognised, check it against the reference for that version before assuming a > bug. ## Table functions A table function appears in `FROM` and produces a relation, which is what lets it return columns a scalar function has nowhere to put. Each has its own reference page: | | | | - | - | | [`fts(table, query)`](/oss/v0-41-0/sql/dql/fts) | full-text search, with a relevance score alongside the matching rows | | [`dedupe(table, column, ...)`](/oss/v0-41-0/sql/dql/dedupe) | one representative row per near-duplicate group | | [`duplicate_pairs(table, column, ...)`](/oss/v0-41-0/sql/dql/duplicate-pairs) | every close pair, before resolving into groups | | [`generate_series(start, stop)`](/oss/v0-41-0/sql/dql/generate-series) | rows from a range | `_score`, the relevance pseudo-column `fts()` produces, is not a function; see [Data types](/oss/v0-41-0/sql/data-types#pseudo-columns). ## What Lance accelerates `contains_tokens` uses an index rather than scanning, which is the difference between a fast predicate and a slow one: | | Index used | | - | - | | [`contains_tokens`](/oss/v0-41-0/sql/dql/contains-tokens) | full-text index | Confirm with [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain): an accelerated predicate shows an index node rather than a `LanceScan` followed by a filter. # GENERATE_SERIES Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/generate-series The generate_series() table function: rows from a range. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM generate_series( 1, 10 ) ``` Rows from a range, useful for building a dense axis to left-join sparse data onto. ## What to read next > [card] [Functions](/oss/v0-41-0/sql/dql/functions#table-functions) > > The other table functions: `fts`, `dedupe`, and `duplicate_pairs`. # IVF_PARTITION Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/ivf-partition The ivf_partition() scalar function: assign each row to its trained IVF index partition. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT ivf_partition(embedding, selection => 'random', count => 100, seed => 42) AS partition, array_agg(id) AS ids FROM documents GROUP BY partition ``` `ivf_partition` reads an existing IVF-family vector index's trained partitions and assigns each row to the one its vector falls into. The column needs an up-to-date, single-segment index before the function runs -- the same requirement [`dedupe`](/oss/v0-41-0/curation/dedupe#example-data) has. Grouping by its result buckets rows by vector proximity without a full pairwise scan -- useful for blocking a large table into comparable chunks, such as before a pairwise similarity pass. ## Input `ivf_partition` takes exactly 1, 3, or 4 arguments -- the vector column alone (scans every partition), or the vector column plus `selection` and `count`, plus `seed` only when `selection` is `'random'`: | Argument | Type | Required | Meaning | | - | - | - | - | | vector column | column reference | yes | the indexed vector column to assign | | `selection` | `'first'` \| `'random'` | required with `count` | which partitions to sample -- there is no explicit `'all'`; omit `selection` and `count` entirely to scan every partition | | `count` | int, > 0 | required with `selection` | number of partitions to sample | | `seed` | int, >= 0 | required for `'random'`, refused for `'first'` | random seed | Arguments can be passed positionally, `ivf_partition(embedding, 'random', 100, 42)`, or named as shown above. `count` and `seed` are the same scan-scoping arguments [`duplicate_pairs`](/oss/v0-41-0/sql/dql/duplicate-pairs#sampling) accepts, so a sampled partition estimate carries over -- but not `dedupe`, which always scans every partition and refuses sampling arguments entirely. ## What to read next > [card] [Cluster records by index partition](/oss/v0-41-0/curation/clustering) > > Use this function to group and sample records by an existing index's partitions. > [card] [DEDUPE](/oss/v0-41-0/sql/dql/dedupe) > > The packaged table function for the deduplication use case, over the same index. # Joins Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/join Combining rows from more than one table, including across namespaces. **Applies to:** Embedded ❌, Enterprise ✅ Use SQL joins to combine rows from two or more tables. ## The join types ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT d.title, c.name FROM documents AS d JOIN categories AS c ON c.id = d.category_id ``` | | What it keeps | | - | - | | `[INNER] JOIN` | rows matching on both sides | | `LEFT [OUTER] JOIN` | every left row, nulls where the right has no match | | `RIGHT [OUTER] JOIN` | every right row | | `FULL [OUTER] JOIN` | every row from both | | `CROSS JOIN` | every combination (the product of the two) | `USING (col)` is shorthand for an equality join on a shared column name, and avoids repeating it in the select list. ## Across namespaces Tables in different [namespaces](/oss/v0-41-0/management/namespace) join like any other table, each addressed by its full `database.schema.table` identifier. The catalog is one catalog, so there is nothing to federate: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT c.id, u.email FROM prod.events.clicks AS c JOIN prod.reference.users AS u ON u.id = c.user_id ``` ## Joining a search result [`fts()`](/oss/v0-41-0/sql/dql/fts) is a table function, so its result is a relation and joins like any other. This example assumes `my_docs` has `text` and `category_id` columns, a full-text index on `text`, and a `categories` table with `id` and `name` columns: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT c.name, count(*) AS hits FROM fts( 'my_docs', '{"match":{"column":"text","terms":"puppy"}}' ) AS m JOIN categories AS c ON c.id = m.category_id GROUP BY c.name ORDER BY hits DESC ``` That composition is the reason full-text search is a relation rather than a predicate: a `WHERE` clause has nowhere to put the relevance score. ## Performance A [scalar index](/oss/v0-41-0/indexing/scalar-index) can accelerate supported filters on the input tables. An index on a join key does not by itself guarantee an index lookup join. Use SQL [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain) to inspect the scans, filters, and join chosen for the complete statement. > [!WARNING] > > Avoid selecting blob or vector columns you do not need on either side of a join. > The join multiplies rows before projection is applied in some plans, so a wide > column can be materialized many more times than the result has rows. ## Late materialization for wide columns The planner can avoid the multiplication above: when a join narrows down to a key column before a wide one is needed, it can defer reading a BlobV2 or vector column until after the join has already settled which rows survive. See [Blob Late Materialization](/oss/v0-41-0/curation/blob-late-materialization) for the eligibility conditions, the `RemoteTake` operator, and how to confirm a specific query got the deferred read with [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain). # Operators and literals Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/operators Comparison, logical and arithmetic operators, literals, and precedence. **Applies to:** Embedded ❌, Enterprise ✅ LanceDB uses DataFusion's SQL operators. This page describes comparison, logical and arithmetic operators, literal values, type conversions and operator precedence. ## Comparison | | | | - | - | | `=` `!=` `<>` `<` `<=` `>` `>=` | ordinary comparison | | `IS NULL` / `IS NOT NULL` | null test (`= NULL` is never true) | | `IS DISTINCT FROM` | comparison that treats null as a value | | `BETWEEN a AND b` | inclusive range | | `IN (...)` | set membership | | `LIKE` / `ILIKE` | pattern match, `%` and `_` | | `~` `~*` `!~` | regular expression match | > [!NOTE] > > For keyword matching on a text column, [`contains_tokens`](/oss/v0-41-0/sql/dql/contains-tokens) > is index-accelerated where `LIKE` is not. Reach for `LIKE` only when you need > its wildcard semantics. ## Logical `AND`, `OR`, `NOT`. Three-valued: a comparison against null is **unknown**, and `NOT unknown` is still unknown. A `WHERE` clause keeps only rows where the predicate is true, so unknown behaves like false there, but not inside `NOT IN`, which is the usual place this bites. See [Subqueries](/oss/v0-41-0/sql/dql/subqueries#in-exists). ## Arithmetic `+` `-` `*` `/` `%`, with the usual precedence. String concatenation is `||`. > [!WARNING] > > Arithmetic over a vector column is **list** arithmetic, not scalar arithmetic: > a vector is a `FixedSizeList<Float32>`. When the operation you want is a > similarity comparison, use [vector search](/oss/v0-41-0/search/vector-search); whether SQL > can express it [depends on the Enterprise server version](/oss/v0-41-0/basics/sql#no-vector-sql). ## Literals | | | | - | - | | String | `'text'`, with a doubled quote to escape: `'it''s'` | | Number | `42`, `3.14` | | Boolean | `TRUE`, `FALSE` | | Null | `NULL` | | Date / timestamp | `DATE '2026-01-01'`, `TIMESTAMP '2026-01-01 12:00:00'` | | Interval | `INTERVAL '7 days'` | | Array | `[1, 2, 3]` | Identifiers are quoted with double quotes when they need to be (a reserved word or a name with mixed case): `SELECT "order" FROM "MyTable"`. ## Casting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT CAST(identifier AS VARCHAR) AS with_cast, identifier::VARCHAR AS with_colons FROM documents ``` Both forms work. Give each its own alias when one projection uses both: they produce the same expression name, and a projection refuses two columns with one name. `TRY_CAST` returns null instead of erroring on a value that will not convert, which is the one to use over a column you do not control. ## Precedence Highest to lowest: `::` → unary `-` → `* / %` → `+ -` → `||` → comparison → `IS` → `NOT` → `AND` → `OR`. Parenthesize anything mixing `AND` and `OR`. `a OR b AND c` is `a OR (b AND c)`, which is rarely what was meant. # Random sampling Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/sampling TABLESAMPLE: draw a random subset of a table, by rows or by fragments. **Applies to:** Embedded ❌, Enterprise ✅ Use `TABLESAMPLE` to explore a subset of a table or estimate aggregate statistics. The sampling method determines how much data is read and whether the table's physical layout influences the sample. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE (10) -- 10 percent SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows ``` A bare number is a **percentage**. Add `ROWS` for a count instead. ## Rows or fragments The standard calls these two methods of one clause. They are different operations, and the difference matters on Lance: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE BERNOULLI (10) SELECT * FROM documents TABLESAMPLE SYSTEM (10) ``` | Method | Aliases | What it picks | | - | - | - | | `BERNOULLI` | `ROW` | rows, each considered independently | | `SYSTEM` | `BLOCK` | **Lance fragments**, and takes whatever rows they hold | `BERNOULLI` gives a genuinely uniform sample and reads across the whole table to get it. `SYSTEM` reads far less (it skips entire fragments), but the sample is only as uniform as the data's layout. If rows were written in an order that correlates with what you are measuring, a fragment sample inherits that correlation. Use `SYSTEM` for a quick look at the data and `BERNOULLI` when you need independent row sampling. Omitting the method gives `BERNOULLI`. ## Repeatability Without a seed, every execution resamples: running the same query twice gives different rows. `REPEATABLE` fixes the draw: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents TABLESAMPLE (10) REPEATABLE (42) ``` Use the same seed and table snapshot to reproduce a sampling run. For a fixed evaluation set, save the selected row IDs or materialize the sample and retain its version. A seed alone does not preserve membership after source changes or changes to the physical layout. ## Where the clause can go It attaches to a table in `FROM`, including inside a subquery, a CTE, or either side of a join: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d SELECT * FROM a TABLESAMPLE (5 ROWS) JOIN b ON a.id = b.id SELECT * FROM t a TABLESAMPLE (10) JOIN t b TABLESAMPLE (10) ON a.id = b.id ``` Each side of a join samples independently. Sampling both sides of a join shrinks the *result* far more than either fraction suggests, because a row only survives if both its sides were drawn. ## Unsupported sampling forms Sampling is semantics, not a hint. A clause that were read and then not applied would be a wrong answer rather than a missing feature, so anything that cannot be honoured exactly is an error: | | | | - | - | | `TABLESAMPLE (101)` | a percentage outside `0..=100` is refused, not clamped | | `TABLESAMPLE (1.5 ROWS)` | a row count must be whole | | `TABLESAMPLE (BUCKET 1 OUT OF 4)` | bucket sampling is not supported | | `(SELECT ...) d TABLESAMPLE (10)` | a subquery's result cannot be sampled; sample the table inside it | | the `SAMPLE` spelling | use `TABLESAMPLE` | | the `OFFSET` modifier | not supported | > [!NOTE] > > `TABLESAMPLE` is also refused on a WAL-backed table, where the rows a sample > would draw from are not all in the fragments yet. ## Sampling outside SQL For a training loop rather than a query, the SDKs read a table in a shuffled order without going through SQL at all. See [Training](/oss/v0-41-0/training/data-loading), where a permutation drives the data loader. # Scalar functions Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/scalar-functions The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds. **Applies to:** Embedded ❌, Enterprise ✅ Functions that take a value and return a value, one row at a time. The set is based on DataFusion's registration plus Lance and deployment-specific functions. The names below are selected examples, not an exhaustive catalog for every deployment. Availability depends on the deployed version and build. For per-group functions see [Aggregation](/oss/v0-41-0/sql/dql/aggregation); for per-window, [Window functions](/oss/v0-41-0/sql/dql/window). ## Math ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} abs ceil floor round trunc signum power sqrt cbrt exp ln log log2 log10 factorial gcd lcm pi random nanvl isnan iszero cot degrees radians to_degrees to_radians sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh ``` ## String ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} ascii bit_length btrim chr concat concat_ws contains ends_with starts_with levenshtein lower upper ltrim rtrim octet_length repeat replace split_part to_hex uuid ``` Unicode-aware variants: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} character_length find_in_set initcap left right lpad rpad reverse strpos substr substr_index substring translate ``` > [!NOTE] > > For keyword matching on a text column, [`contains_tokens`](/oss/v0-41-0/sql/dql/contains-tokens) > is index-accelerated where `contains` and `LIKE` are not. ## Regular expressions ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} regexp_count regexp_instr regexp_like regexp_match regexp_replace ``` ## Date and time ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} current_date current_time date_bin date_part date_trunc from_unixtime to_unixtime make_date make_time to_char to_date to_time to_local_time ``` `date_bin` is the one worth knowing for analytics: it buckets timestamps into fixed-width intervals, which is how you build a time series without a self-join. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT date_bin(INTERVAL '1 hour', created_at) AS hour, count(*) FROM events GROUP BY hour ORDER BY hour ``` ## Arrays and maps ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} make_array array_has array_filter array_transform array_any_match array_compact array_normalize array_slice arrays_zip cardinality flatten range generate_series ``` ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} map map_keys map_values map_entries map_extract ``` Distance functions over arrays: `cosine_distance`, `distance`, `exact_distance`, `inner_product`. Only `distance` and `exact_distance` take an options string, and only `distance` can plan as vector search; see [Vector distance functions](/oss/v0-41-0/sql/dql/vector-distance). ## Structs and fields ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} named_struct get_field coalesce nullif nvl nvl2 greatest least union_extract union_tag ``` ## Crypto and encoding ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} digest md5 sha224 sha256 sha384 sha512 encode decode ``` ## Type functions ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} arrow_cast arrow_try_cast arrow_typeof arrow_field arrow_metadata with_metadata version ``` Use `arrow_typeof` to inspect the Arrow data type of a column or expression: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT arrow_typeof(vector) FROM documents LIMIT 1 -- FixedSizeList(Field { name: "item", data_type: Float32, .. }, 1536) ``` `arrow_cast` casts to an Arrow type by name, reaching types SQL has no spelling for. See [Data types](/oss/v0-41-0/sql/data-types). ## What Lance adds These are registered by Lance on top of DataFusion's set, each with its own reference page: | | | | - | - | | [`contains_tokens`](/oss/v0-41-0/sql/dql/contains-tokens) | index-accelerated keyword predicate, usable in `WHERE` | | [`ivf_partition`](/oss/v0-41-0/sql/dql/ivf-partition) | assign each row to its trained IVF index partition | | [`blob_descriptor`](/oss/v0-41-0/sql/dql/blob-descriptor) | a BlobV2 column's payload location, without reading it | ## Additional scalar functions SQL queries can call functions registered with the server, including functions not listed on this page. Consult [DataFusion's scalar function reference](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) for version 54. Functions documented for a newer DataFusion release may not be available in your LanceDB Enterprise version. # SELECT Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/select Projection, filtering, ordering, and composing queries out of other queries. **Applies to:** Embedded ❌, Enterprise ✅ ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} [WITH cte AS (...)] SELECT [ALL | DISTINCT] select_expr [, ...] FROM from_item [[JOIN ...] ON ...] [WHERE predicate] [GROUP BY expr [, ...]] [HAVING predicate] [WINDOW name AS (...)] [ORDER BY expr [ASC | DESC] [NULLS FIRST | LAST] [, ...]] [LIMIT n] [OFFSET n] ``` ## Projection ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, title, identifier FROM documents ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search().select(["id", "title", "identifier"]).to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.query().select(["id", "title", "identifier"]).toArrow(); ``` Name the columns you need instead of using `SELECT *`, particularly for tables containing images, video or large vectors. Projection lets the engine avoid loading unnecessary columns, although columns used by filters, joins or other expressions may still need to be read. Row metadata is available as [pseudo-columns](/oss/v0-41-0/sql/data-types#pseudo-columns) (`_rowid`, `_rowaddr`, `_rowoffset`) but only when named, so they stay out of `SELECT *`. `DISTINCT` deduplicates the projected rows. ## Filtering ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM documents WHERE identifier > 0 AND identifier < 1000000 ``` ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl.search().where("identifier > 0 AND identifier < 1000000").to_arrow() ``` ```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} await tbl.query().where("identifier > 0 AND identifier < 1000000").toArrow(); ``` The SDK `where` takes the same expression language, so a predicate moves between them unchanged. A supported predicate can use a scalar index; confirm the chosen plan with [`explain_plan`](/oss/v0-41-0/basics/sql#query-plans). See [Filtering](/oss/v0-41-0/search/filtering) for the operators and their pushdown behaviour. ## Ordering and limiting ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id, title FROM documents ORDER BY created_at DESC NULLS LAST LIMIT 100 OFFSET 200 ``` `ORDER BY` on a large table is a sort over the whole result, so pair it with a `LIMIT` unless you genuinely need every row ordered. ## Set operations `UNION`, `UNION ALL`, `INTERSECT` and `EXCEPT` combine whole queries: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents WHERE category = 'film' UNION ALL SELECT id FROM archived_documents WHERE category = 'film' ``` `UNION` deduplicates and `UNION ALL` does not, which makes `UNION ALL` the cheaper one when you already know the inputs are disjoint. ## Common table expressions ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH recent AS ( SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ) SELECT category, count(*) FROM recent GROUP BY category ``` A CTE is scoped to the statement. One you want to keep is a [view](/oss/v0-41-0/management/view); one whose rows you want stored is a [materialized view](/oss/v0-41-0/management/materialized-view). ## Subqueries Subqueries are allowed anywhere an expression or a relation is (in `FROM`, in `WHERE` with `IN` or `EXISTS`, and as a scalar in the select list): ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) ``` ## Namespaced tables A table inside a [namespace](/oss/v0-41-0/management/namespace) is written with its schema -- the `$`-joined namespace path, not a dotted one -- before the table name; see [Schema](/oss/v0-41-0/basics/catalog#schema) for why: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM `prod$events`.clicks ``` ## Reading the plan `EXPLAIN` and `EXPLAIN ANALYZE` work as DataFusion defines them, and produce the same operators the SDK methods do: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` See [Explain](/oss/v0-41-0/basics/sql#inspect-a-query-plan) and [Explain Analyze](/oss/v0-41-0/basics/sql#analyze-a-query-plan). # Subqueries Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/subqueries Queries inside queries: scalar, IN, EXISTS, correlated, and derived tables. **Applies to:** Embedded ❌, Enterprise ✅ A subquery is allowed anywhere an expression or a relation is. ## As a relation ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM ( SELECT category, count(*) AS n FROM documents GROUP BY category ) AS counts WHERE n > 100 ``` A derived table needs an alias. Its result cannot be [sampled](/oss/v0-41-0/sql/dql/sampling); sample the table inside it instead: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d ``` ## As a scalar ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title, (SELECT count(*) FROM revisions r WHERE r.doc_id = d.id) AS revisions FROM documents AS d ``` A scalar subquery returns one column and at most one row. No rows produces `NULL`; more than one row is an error. ## IN and EXISTS ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) SELECT title FROM documents AS d WHERE EXISTS (SELECT 1 FROM revisions r WHERE r.doc_id = d.id) ``` Use `EXISTS` to test whether a matching row exists and `IN` to test membership in a set of values. The optimizer may rewrite either into a join; inspect `EXPLAIN` before choosing one for performance reasons. `NOT IN` and `NOT EXISTS` differ on nulls: `NOT IN` against a set containing a null yields no rows, because the comparison is unknown rather than false. Prefer `NOT EXISTS` unless you have ruled nulls out. ## Correlated subqueries A subquery referencing a column from the enclosing query, such as `d.id` above, is correlated, and is conceptually evaluated per outer row. The planner usually rewrites it into a join. > [!NOTE] > > Check with [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain) when a correlated subquery is slow. A plan > showing a join has been optimized; one showing a repeated scan has not, and > rewriting it as an explicit [join](/oss/v0-41-0/sql/dql/join) is the fix. ## CTEs as an alternative A [CTE](/oss/v0-41-0/sql/dql/select#ctes) is a named subquery, and is usually more readable when the same subquery appears twice or when nesting gets deep. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH active AS (SELECT id FROM categories WHERE active) SELECT title FROM documents WHERE category_id IN (SELECT id FROM active) ``` # Vector distance functions Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/vector-distance cosine_distance, distance, exact_distance and inner_product: per-row vector distance, and the ORDER BY rewrite into vector search. **Applies to:** Embedded ❌, Enterprise ✅ ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} cosine_distance distance exact_distance inner_product ``` > [!WARNING] > > Distance functions can evaluate arrays per row. Some deployment versions also > recognize `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan > and plan it as vector search, with indexed or flat search as appropriate. > Where available, `exact_distance` evaluates distance without that rewrite. > Confirm the functions supported by your deployment and inspect SQL > [`EXPLAIN`](/oss/v0-41-0/sql/dql/explain); the function name alone does not guarantee an > index-backed plan. See [SQL vector search](/oss/v0-41-0/basics/sql#no-vector-sql). A third, optional argument is a comma-separated options string, and only `distance` and `exact_distance` accept one; `cosine_distance` and `inner_product` are plain two-argument functions. `metric` selects `l2` (default, alias `euclidean`), `cosine`, or `dot`. `nprobes` and `use_index` only affect `distance`, since it's the only one of the two that the index-search rewrite applies to in the first place -- `exact_distance` is never rewritten into an index search, so passing it `use_index`/`nprobes` does nothing; use a plain `distance` call with `use_index=false` to force a flat scan instead: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT id FROM documents ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'metric=cosine,nprobes=20') LIMIT 10 -- Force a flat scan, bypassing the index: SELECT id FROM documents ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'use_index=false') LIMIT 10 ``` ## What to read next > [card] [SQL vector search](/oss/v0-41-0/basics/sql#no-vector-sql) > > Server-version requirements and the supported `ORDER BY` query forms. > [card] [EXPLAIN](/oss/v0-41-0/sql/dql/explain) > > Confirm whether a query planned as an index-backed vector search. # Window functions Source: https://docs.lancedb.com/oss/v0-41-0/sql/dql/window Compute over a set of rows related to the current one, without collapsing them. **Applies to:** Embedded ❌, Enterprise ✅ A window function computes across a set of rows related to the current one and returns a value **per row**. That is the difference from [aggregation](/oss/v0-41-0/sql/dql/aggregation), which collapses the rows it covers. ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT title, score, row_number() OVER (PARTITION BY category ORDER BY score DESC) AS rank FROM documents ``` Every row survives; each one gains its rank within its category. ## The window ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} OVER ( [PARTITION BY expr [, ...]] [ORDER BY expr [, ...]] [ROWS | RANGE BETWEEN frame_start AND frame_end] ) ``` `PARTITION BY` splits the rows into independent groups. `ORDER BY` orders them inside each partition. Supply an ordering for useful ranks, and a stable tie-breaker when selecting one row from several equal values. The frame clause narrows the window further, which is how running totals and moving averages are expressed: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT created_at, sum(amount) OVER (ORDER BY created_at ROWS UNBOUNDED PRECEDING) AS running_total, avg(amount) OVER (ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS trailing_7 FROM transactions ``` A `WINDOW` clause names a definition when several functions share one: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} SELECT row_number() OVER w, lag(score) OVER w FROM documents WINDOW w AS (PARTITION BY category ORDER BY score DESC) ``` ## The functions Registered in DataFusion 54. **Ranking** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} row_number rank dense_rank percent_rank cume_dist ntile ``` **Offset and positional** ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} lag lead first_value last_value nth_value ``` **Aggregates** Any [aggregate function](/oss/v0-41-0/sql/dql/aggregation#functions) used with `OVER` becomes a window function. This is how running totals and moving averages are written. ## Deduplicating with a window The common practical use: keep one row per key, chosen by some ordering. A window ranks, and an outer query filters: ```sql SQL icon="database" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} WITH ranked AS ( SELECT *, row_number() OVER (PARTITION BY doc_id ORDER BY version DESC) AS rn FROM revisions ) SELECT * FROM ranked WHERE rn = 1 ``` The outer query is needed because a window function cannot appear in `WHERE`: windows are computed after filtering, so the predicate would have nothing to read. > [!NOTE] > > Window functions sort within each partition, so on a large table they are among > the more expensive things you can ask for. Filter first, and check the cost with > [Explain Analyze](/oss/v0-41-0/basics/sql#analyze-a-query-plan). # Object Detection for AV Perception Source: https://docs.lancedb.com/oss/v0-41-0/training/object-detection End-to-end fine-tuning of a Faster R-CNN object detector on curated dashcam slices, using LanceDB as the data backbone from raw frames to checkpoints. This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) (riders, nighttime pedestrians, and distant pedestrians) using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/oss/v0-41-0/training/permutation) API, and pinning checkpoints to an exact data version. ## What you get Fine-tuning Faster R-CNN ResNet50 FPN v2 for 10 epochs on each curated slice (batch size 64, AMP, A100), starting from the same COCO-pretrained checkpoint and evaluating on the matching validation view: | Failure mode | Metric | Baseline (COCO) | Fine-tuned | Δ% | | - | - | - | - | - | | **Nighttime pedestrian** | mAP\@0.5 | 0.4025 | **0.5192** | **+29.0%** | | | Recall | 0.5923 | **0.7570** | **+27.8%** | | **Rider** | mAP\@0.5 | 0.5563 | **0.6676** | **+20.0%** | | | Recall | 0.6788 | **0.7847** | **+15.6%** | | **Distant pedestrian** | mAP\@0.5 | 0.4746 | **0.5788** | **+22.0%** | | | Recall | 0.6794 | **0.8024** | **+18.1%** | No external data added, only training-distribution correction via SQL filters over a single Lance table. Each panel below shows the same frame with three overlaid predictions: **green** = ground truth · **red** = pretrained COCO baseline · **blue** = fine-tuned model. ![Rider detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/t0AGunBr6LulGkIJ/oss/v0-41-0/static/assets/images/training/rider_04.jpg?fit=max\&auto=format\&n=t0AGunBr6LulGkIJ\&q=85\&s=d08683bdfbf4254a7d2a2d06e332362a) ![Nighttime pedestrian detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/training/nighttime_person_01.jpg?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=c84c1c502e03189e715e86c40a99961c) ![Distant pedestrian detection: ground truth vs baseline vs fine-tuned](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/training/distant_person_00.jpg?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=8e8826fce23c850550e38d5f89001f54) The rest of the page walks through the pipeline that produced these checkpoints. ## The failure modes A perception model fine-tuned on a generic dataset typically misses the long-tail scenarios that matter most in deployment. Three common failure modes drive this example: | Failure mode | Curation signal | | - | - | | **Riders** (person on bike/motorcycle) | `has_rider = true` | | **Nighttime pedestrians** | `timeofday = 'night' AND has_person = true` | | **Distant pedestrians** | `has_person = true AND person_bbox_area_pct < 30.0` | Each curated slice becomes a [Geneva materialized view](/oss/v0-41-0/geneva/jobs/materialized-views) (a named, refreshable SQL filter over the source table), and the training script loads it by name. New footage flows in through `add()` → `backfill()` → `refresh()`; no manifests, no exports, no reshuffling on disk. ## 1. Schema The source table holds raw image bytes alongside structured annotations. Bounding boxes are stored as a parallel list (one element per box) rather than a nested struct so they remain directly queryable with SQL. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa BDD_SCHEMA = pa.schema([ pa.field("image_id", pa.string()), pa.field("split", pa.string()), # "train" | "val" pa.field("image_bytes", pa.large_binary()), # raw JPEG pa.field("width", pa.int32()), pa.field("height", pa.int32()), # scene metadata pa.field("weather", pa.string()), pa.field("scene", pa.string()), pa.field("timeofday", pa.string()), # annotations — parallel lists, one element per box pa.field("ann_categories", pa.list_(pa.string())), pa.field("ann_bboxes", pa.list_(pa.list_(pa.float32()))), pa.field("ann_occluded", pa.list_(pa.bool_())), ]) ``` Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Lance table, with no intermediate preprocessing job. The table can live on local disk, S3, GCS, or Azure; everything downstream (backfills, views, the training loader) opens it in place via `lancedb.connect("s3://...")` with no local copy step. ## 2. Backfill curation features with Geneva Curation signals are added as columns on the same table using [Geneva backfilling](/oss/v0-41-0/geneva/jobs/backfilling). Backfills are incremental and checkpointed: re-running the command after new footage arrives only computes the new rows. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa from geneva.transformer import udf # Tier 1 — CPU, derived from annotations alone @udf(data_type=pa.bool_(), input_columns=["ann_categories"]) def has_rider(ann_categories: list[str]) -> bool: return "rider" in (ann_categories or []) # Tier 2 — GPU, runs a Faster R-CNN to find the largest detected person # as a percentage of frame area. <30% = a distant or small pedestrian, # the hard case we want to upweight in training. @udf(data_type=pa.float32(), input_columns=["image_bytes", "width", "height"], cuda=True, num_gpus=1) class PersonBboxAreaPct: def __init__(self): self._model = None def __call__(self, image_bytes, width, height): # lazy model load — runs once per Ray worker, then reused ... ``` Run the backfill against the live table: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva gconn = geneva.connect("data/bdd100k/lancedb") tbl = gconn.open_table("bdd100k") tbl.add_columns({"has_rider": has_rider}) tbl.add_columns({"person_bbox_area_pct": PersonBboxAreaPct()}) with gconn.local_ray_context(): tbl.backfill("has_rider") tbl.backfill("person_bbox_area_pct") ``` > [!NOTE] > > Because the curation features are flat scalar columns on the same table, all four retrieval modes (SQL, full-text search, vector search, and SQL-filtered vector search) work directly without joins or exports. See [Geneva backfilling](/oss/v0-41-0/geneva/jobs/backfilling) for how a backfill fills only the rows that lack values. ## 3. Define training splits as materialized views A training split is a named SQL filter, not a CSV manifest. Each view stays in sync with the source table and bumps its `version` on every refresh. That version is the link between a checkpoint and the exact data that produced it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import geneva gconn = geneva.connect("data/bdd100k/lancedb") gtbl = gconn.open_table("bdd100k") VIEWS = { "bdd100k_rider_train": "has_rider = true AND split = 'train'", "bdd100k_rider_val": "has_rider = true AND split = 'val'", "bdd100k_nighttime_person_train": "timeofday = 'night' AND has_person = true AND split = 'train'", "bdd100k_nighttime_person_val": "timeofday = 'night' AND has_person = true AND split = 'val'", "bdd100k_distant_person_train": "has_person = true AND person_bbox_area_pct < 30.0 AND split = 'train'", "bdd100k_distant_person_val": "has_person = true AND person_bbox_area_pct < 30.0 AND split = 'val'", } with gconn.local_ray_context(): for name, sql_filter in VIEWS.items(): query = gtbl.search().where(sql_filter) mv = gconn.create_materialized_view(name, query) mv.refresh() print(f"[{name}] {mv.count_rows()} rows (version {mv.version})") ``` ## 4. PyTorch DataLoader via the Permutation API The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/oss/v0-41-0/training/permutation) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import torch import torchvision.io as tio from lancedb.permutation import Permutation DETECTION_COLS = ["image_bytes", "ann_categories", "ann_bboxes"] class LanceDetectionDataset(torch.utils.data.Dataset): def __init__(self, uri: str, table_name: str): self.uri, self.table_name = uri, table_name self._perm = None self.length = len(lancedb.connect(uri).open_table(table_name)) def __len__(self): return self.length def __getstate__(self): # Permutation holds Rust async state — zero it so each worker reopens state = self.__dict__.copy() state["_perm"] = None return state def _ensure_open(self): if self._perm is None: tbl = lancedb.connect(self.uri).open_table(self.table_name) self._perm = ( Permutation.identity(tbl) .select_columns(DETECTION_COLS) .with_format("arrow") # zero-copy ) def __getitems__(self, indices: list[int]): self._ensure_open() return self._perm.__getitems__(indices) ``` The collate function decodes JPEG bytes and converts BDD category strings into COCO class IDs (so the comparison against the pretrained checkpoint is valid): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} BDD_LABEL_MAP = { "person": 1, "rider": 1, "bicycle": 2, "car": 3, "motorcycle": 4, "bus": 6, "train": 7, "truck": 8, "traffic light": 10, } def detection_collate(batch): images, targets = [], [] for raw, cats, bboxes in zip( batch.column("image_bytes").to_pylist(), batch.column("ann_categories").to_pylist(), batch.column("ann_bboxes").to_pylist(), ): buf = torch.frombuffer(bytearray(raw), dtype=torch.uint8) images.append(tio.decode_image(buf, tio.ImageReadMode.RGB).float() / 255.0) valid_boxes, valid_labels = [], [] for cat, box in zip(cats or [], bboxes or []): lid = BDD_LABEL_MAP.get(cat) if lid is None or box[2] <= box[0] or box[3] <= box[1]: continue valid_boxes.append(box) valid_labels.append(lid) targets.append({ "boxes": torch.tensor(valid_boxes or [], dtype=torch.float32).reshape(-1, 4), "labels": torch.tensor(valid_labels or [], dtype=torch.int64), }) return images, targets ``` Wire it into a standard `torch.utils.data.DataLoader`: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): dataset = LanceDetectionDataset(uri, table_name) sampler = torch.utils.data.RandomSampler(dataset) if shuffle else None return torch.utils.data.DataLoader( dataset, batch_size=batch_size, sampler=sampler, num_workers=num_workers, collate_fn=detection_collate, pin_memory=torch.cuda.is_available(), persistent_workers=(num_workers > 0), multiprocessing_context="spawn" if num_workers > 0 else None, ) ``` > [!NOTE] > > `with_format("arrow")` keeps batches as zero-copy `pa.RecordBatch`es: no per-row Python boxing, no pickling between worker and main. Each DataLoader worker reopens its own `Permutation` after fork (the Rust async handle is cleared in `__getstate__`), so reads scale with `num_workers` and stream straight from the underlying object store. JPEG decode overlaps with GPU compute via `pin_memory` + `prefetch_factor`, which is what keeps the loader from becoming the bottleneck on a fast GPU. ## 5. Fine-tune Faster R-CNN The training loop is plain PyTorch: the Lance integration ends at the loader. Mixed precision is enabled on CUDA for \~2× speedup on Ampere GPUs. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import time import torch from torchvision.models.detection import ( fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") use_amp = device.type == "cuda" # COCO pretrained weights — head left intact since BDD uses a subset of COCO IDs model = fasterrcnn_resnet50_fpn_v2( weights=FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1 ).to(device) train_loader = make_loader("data/bdd100k/lancedb", "bdd100k_rider_train", batch_size=64, num_workers=14, shuffle=True) val_loader = make_loader("data/bdd100k/lancedb", "bdd100k_rider_val", batch_size=64, num_workers=14) optimizer = torch.optim.SGD( [p for p in model.parameters() if p.requires_grad], lr=0.04, momentum=0.9, weight_decay=1e-4, ) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) scaler = torch.cuda.amp.GradScaler() if use_amp else None for epoch in range(1, 11): model.train() t0 = time.time() for images, targets in train_loader: images = [img.to(device) for img in images] targets = [{k: v.to(device) for k, v in t.items()} for t in targets] if all(t["labels"].numel() == 0 for t in targets): continue with torch.cuda.amp.autocast(enabled=use_amp): losses = sum(model(images, targets).values()) optimizer.zero_grad() if use_amp: scaler.scale(losses).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) scaler.step(optimizer) scaler.update() else: losses.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) optimizer.step() scheduler.step() print(f"epoch {epoch} ({time.time() - t0:.1f}s)") ``` ## 6. Pin the checkpoint to a data version Every Lance table, including a materialized view, exposes a monotonically increasing `version`. Logging it next to the weights gives a permanent, deterministic link between a checkpoint and the exact data snapshot that produced it. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import json from pathlib import Path train_tbl = lancedb.connect("data/bdd100k/lancedb").open_table("bdd100k_rider_train") out = Path("checkpoints/rider") out.mkdir(parents=True, exist_ok=True) torch.save(model.state_dict(), out / "fasterrcnn_bdd_finetuned.pt") with open(out / "metadata.json", "w") as f: json.dump({ "train_table": train_tbl.name, "table_version": train_tbl.version, "row_count": len(train_tbl), }, f, indent=2) ``` To reproduce a run, [time-travel](/oss/v0-41-0/management/table#versioning) the view to the recorded version before opening the loader: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl = lancedb.connect("data/bdd100k/lancedb").open_table("bdd100k_rider_train") tbl.checkout(version=7) # exact snapshot the checkpoint was trained on ``` ## 7. Continuous updates When new footage arrives, the same three calls update every downstream view (no view definitions change, no training-script edits required): ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1. ingest the new footage into the source table table.add(new_record_batches) # 2. backfill computes only the new rows (incremental, checkpointed) with gconn.local_ray_context(): tbl.backfill("has_rider") tbl.backfill("person_bbox_area_pct") # 3. refresh appends qualifying new rows to every materialized view for view_name in gconn.table_names(): if view_name == "bdd100k": continue mv = gconn.open_table(view_name) before = mv.count_rows() mv.refresh() print(f"[{view_name}] {before} → {mv.count_rows()} rows (version {mv.version})") ``` The next training run picks up the new data automatically and pins itself to the new `version`. ## Full source The complete code, including a synthetic-data mode for pipeline verification (`--synthetic 500`), GPU UDFs for CLIP embeddings and dHash deduplication, and the EDA notebook, is in this [GitHub repository](https://github.com/lancedb/training/tree/main/object-detection). # Fine-tuning a VLM on TextVQA Source: https://docs.lancedb.com/oss/v0-41-0/training/vlm-finetuning End-to-end fine-tuning of Qwen2.5-VL on a curated TextVQA slice, using LanceDB and Geneva to materialize expensive vision-language features once and train from cached columns. This example walks through a vision-language model (VLM) fine-tuning pipeline for [TextVQA](https://textvqa.org/), where the task is to answer questions that require reasoning over text *inside an image*. The base model is `Qwen2.5-VL-3B-Instruct`, fine-tuned with the [QLoRA](https://arxiv.org/abs/2305.14314) method. The data backbone is one Lance table that evolves from raw multimodal rows into training-ready features. The key idea is simple: in this QLoRA fine-tuning setup, we freeze the VLM's image encoder and train only a small adapter on the language-model side. We call that encoder the **vision tower** in this example: it is the part of the model that turns image pixels into visual hidden states before the language model reads them alongside the text prompt. Because the vision tower's weights do not change during fine-tuning, its output for a given image also does not change. That means the pipeline can compute those visual hidden states once, store them as a fixed-size Lance column, and reuse them in every epoch instead of recomputing them in every training step. This also helps the run fit comfortably on a small GPU, because the training job does not need to keep the vision encoder active or pay for its forward pass on every batch. > [card] [Open the Colab demo](https://colab.research.google.com/github/lancedb/training/blob/vlm-textvqa/examples/vlm-textvqa/notebooks/colab_textvqa_lance.ipynb) > > Run the Colab-sized workflow on a free T4: download the pre-baked Lance subset, explore it, benchmark Lance vs Parquet, fine-tune with QLoRA, and evaluate base vs tuned answers. > [card] [View the full demo source](https://github.com/lancedb/tmls-2026-demo) > > Full demo repository with the notebook, Geneva UDFs, direct backfill fallback, dataloader, training loop, and evaluation scripts. The Colab notebook uses a pre-baked subset of the TextVQA dataset: it downloads a curated Lance subset whose expensive feature columns have already been computed. This page explains the complete end-to-end pipeline that produced that subset, then shows how the notebook applies it to produce a fine-tuned model that improves performance on the TextVQA task. ## What you get On the curated `text_dense` TextVQA slice, the demo fine-tunes `Qwen2.5-VL-3B-Instruct` with QLoRA and evaluates on held-out images: | Setup | TextVQA accuracy | | - | - | | Base model | 0.799 | | LoRA-tuned model | **0.820** | | Lift | **+2.1 percentage points** | The larger point is not the absolute score, because you could just as well fine-tune a better base model on more data. The main takeaways are the workflow and quality-of-life improvements that you get when you combine LanceDB and Geneva: 1. **Add expensive features** as new columns without rewriting the raw dataset. 2. **Read fixed-size model features efficiently** for shuffled PyTorch batches. 3. **Iterate quickly** from feature idea to scalable CPU/GPU backfill, using Geneva UDFs. ## Why LanceDB fits this workflow VLM fine-tuning pipelines spend a lot of time between "I have an experiment idea" and "I trained the model." LanceDB shortens that loop in three places. > [card] Cheap feature evolution > > Lance can append derived columns such as `ocr_token_count`, `dhash`, `vision_tower_hiddens`, and tokenized SFT prompts without rewriting the existing image/question/answer columns or managing sidecar files. > [card] Efficient training reads > > Lance is optimized for scans and random access over fixed-size lists, which are common in model training: embeddings, hidden states, token IDs, masks, and labels. > [card] Fast experiment turnaround > > Geneva lets AI engineers express feature work as UDFs, run those UDFs across CPU or GPU workers, and materialize the results directly into the same Lance table. In this pipeline, those three properties combine into the core optimization: compute the VLM vision features once, store them cheaply, then train by reading only the cached columns the model needs. ## Pipeline overview The runnable demo uses the exact Colab subset hosted at [`lance-format/textvqa-lance-colab`](https://huggingface.co/datasets/lance-format/textvqa-lance-colab). It is derived from the Lance-formatted TextVQA corpus and stores inline JPEG bytes, questions, answers, OCR tokens, object classes, CLIP image/question embeddings, and the cached training features used by this example. The full demo pipeline adds three tiers of derived features on top. > [card] Tier 1: text features > > Cheap CPU columns such as `question_length`, `answer_length`, `question_type`, and `ocr_token_count`. > [card] Tier 2: light image features > > Image-derived columns such as `dhash`, computed by decoding the JPEG once and storing a perceptual hash. > [card] Tier 3: VLM training features > > GPU-heavy columns: `vision_tower_hiddens` plus SFT token fields (`input_ids`, `attention_mask`, `labels`). The Colab notebook's workflow starts after all three tiers have been computed. It downloads a small curated subset and runs the training/evaluation path without needing to run Geneva or the vision-tower backfill on the notebook GPU. ## 1. Start with a multimodal LanceDB table The base schema comes from the TextVQA Lance dataset. One row contains the image bytes, natural-language question, reference answers, OCR tokens, scene tags, and retrieval embeddings. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa BASE_SCHEMA = pa.schema([ pa.field("id", pa.int64()), pa.field("image", pa.large_binary()), pa.field("image_id", pa.string()), pa.field("question_id", pa.string()), pa.field("question", pa.string()), pa.field("answers", pa.list_(pa.string())), pa.field("answer", pa.string()), pa.field("image_emb", pa.list_(pa.float32(), 512)), pa.field("question_emb", pa.list_(pa.float32(), 512)), pa.field("ocr_tokens", pa.list_(pa.string())), pa.field("image_classes", pa.list_(pa.string())), pa.field("set_name", pa.string()), ]) ``` Because the raw image, text, OCR, and embedding features live together, the same table supports curation, retrieval, feature engineering, and training. For example, the notebook can run a text-to-image retrieval demo by searching `image_emb` with a question embedding that already exists in the row. ## 2. Add feature columns with Geneva Geneva turns feature engineering into UDF definitions plus backfills. The UDFs can be simple text functions, image-processing functions, or stateful GPU model calls. The Tier 1 features are ordinary CPU UDFs: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import re import pyarrow as pa from geneva.transformer import udf _QUESTION_TYPE_PATTERNS = [ ("how_many", re.compile(r"^\s*how\s+many\b", re.IGNORECASE)), ("what_brand", re.compile(r"^\s*what\s+(is\s+the\s+)?(brand|company|make)\b", re.IGNORECASE)), ("what", re.compile(r"^\s*what\b", re.IGNORECASE)), ] @udf(data_type=pa.string(), input_columns=["question"]) def question_type(question: str) -> str: for label, pattern in _QUESTION_TYPE_PATTERNS: if pattern.search(question or ""): return label return "other" @udf(data_type=pa.int32(), input_columns=["ocr_tokens"]) def ocr_token_count(ocr_tokens: list[str] | None) -> int: return len(ocr_tokens) if ocr_tokens else 0 ``` The Tier 3 feature is heavier: run Qwen2.5-VL's frozen vision tower once, then store the merged visual hidden states as a fixed-size fp16 list. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} IMAGE_PX = 560 LLM_TOKENS_PER_IMAGE = 400 VISION_HIDDEN = 2048 @udf( data_type=pa.list_(pa.float16(), LLM_TOKENS_PER_IMAGE * VISION_HIDDEN), input_columns=["image"], ) class VisionTowerEmbedder: def __init__(self): self._model = None self._processor = None def _lazy_load(self): if self._model is not None: return import torch from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration self._torch = torch self._model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-3B-Instruct", torch_dtype=torch.bfloat16, device_map="cuda:0", ).model.visual.eval() self._processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct") def __call__(self, image: bytes) -> list[float]: self._lazy_load() # Decode image, resize to IMAGE_PX, run the frozen vision tower, # and return fp16[400, 2048] flattened as one fixed-size list. ... ``` The fixed shape matters. With `IMAGE_PX = 560`, Qwen2.5-VL produces 400 merged visual tokens, each with hidden size 2048. That becomes one `fp16[400 * 2048]` column per row. Training can scan and randomly access that column without decoding images or running the vision tower in the hot loop, saving GPU compute at training time. Run the tiered backfill with Geneva: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -m vlm.backfill_geneva --tier 1 # CPU text columns python -m vlm.backfill_geneva --tier 2 # image decode + dhash python -m vlm.backfill_geneva --tier 3 # vision tower + SFT tokens ``` > [!TIP] > > The same Tier 3 work can be done manually by creating PyArrow batches and calling Lance's column-evolution APIs directly. The demo repo includes [`backfill_direct.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_direct.py) for that path. Geneva is the preferred abstraction when you want to scale the same feature code across CPU or GPU workers and keep backfills incremental. See the full UDF registry in [`vlm/geneva_udfs.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/geneva_udfs.py) and the backfill driver in [`vlm/backfill_geneva.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_geneva.py). ## 3. Curate a training slice The demo uses a `text_dense` slice: TextVQA examples whose images contain many OCR tokens. The slice was chosen empirically because it gave the clearest LoRA lift over the already-strong base model. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} TEXT_DENSE_OCR_THRESHOLD = 16 def matches_text_dense(row: dict) -> bool: return len(row.get("ocr_tokens") or []) >= TEXT_DENSE_OCR_THRESHOLD ``` The Colab-ready bake ingests a small train split, backfills Tier 3 on that train table, ingests a held-out validation split, and optionally pushes the result to HuggingFace: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -m vlm.colab_prepare \ --out data/colab \ --slice text_dense \ --train-rows 600 \ --val-rows 400 \ --hf-repo lance-format/textvqa-lance-colab \ --push ``` The train table contains cached Tier 3 columns because training reads them directly. The validation table keeps raw images because evaluation should run the full VLM on unseen images. ## 4. Explore the prepared table Before training, it helps to look at the actual task. Each row pairs an image with a question whose answer is often visible as text in the image: a product label, phone screen, sign, book spine, or package. > [card] Q: what is the name of the airline on the sugar packet? > > **A:** TWA > > **OCR:** 7h the Finest... 74 1E TWA 8 SALT REESE PEPPER > [card] Q: what time is displayed? > > **A:** 12:39 am > > **OCR:** AT\&T 12:39 AM TV CS WATCH P PANDORA YouTube Ustream > [card] Q: what brand of building block is this? > > **A:** lego > > **OCR:** LEGO CITY Ages/edades 5-12 POLICE B-403 4473 112 112 pcs > [card] Q: what is printed in red? > > **A:** warning > > **OCR:** WARNING Controlled Area Itis unlawf enter thisre without permission nstallation The notebook downloads the public pre-baked subset: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from huggingface_hub import snapshot_download import os local = snapshot_download( repo_id="lance-format/textvqa-lance-colab", repo_type="dataset", local_dir="data/colab", ) def open_tbl(path: str): name = os.path.basename(path).removesuffix(".lance") return lancedb.connect(os.path.dirname(path)).open_table(name) train_tbl = open_tbl(f"{local}/textvqa_colab_train.lance") val_tbl = open_tbl(f"{local}/textvqa_colab_val.lance") ``` Because the table also ships CLIP embeddings, you can run cross-modal retrieval without loading a model: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import numpy as np seed = ( train_tbl.search() .select(["question", "question_emb"]) .limit(40) .to_arrow() .to_pylist()[11] ) hits = ( train_tbl.search( np.asarray(seed["question_emb"], dtype=np.float32), vector_column_name="image_emb", ) .select(["image", "question", "answer", "_distance"]) .limit(5) .to_arrow() .to_pylist() ) ``` This is the same table that later feeds training. There is no separate feature store, image directory, Parquet export, or manifest to keep synchronized. ## 5. Benchmark Lance vs Parquet-style reads Many training pipelines start with Parquet. Parquet is excellent for columnar analytics, but training commonly needs shuffled batches and fixed-size tensor columns. The notebook compares Lance and Parquet on two access patterns: | Column group | Why it matters | | - | - | | `image`, `question`, `answer` | Raw multimodal rows: the baseline "decode and tokenize during training" path. | | `vision_tower_hiddens` | Cached fixed-size fp16 VLM features: the optimized training path. | The notebook mirrors those column groups to uncompressed Parquet, then measures sequential scans and shuffled random batches: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} RAW = ["image", "question", "answer"] VEC = ["vision_tower_hiddens"] BATCH = 8 lance_ds = train_tbl.to_lance() n = train_tbl.count_rows() def seq(ds, cols): t0 = time.time() for _ in ds.to_batches(columns=cols, batch_size=BATCH): pass return n / (time.time() - t0) def shuf(ds, cols, num_batches=20): batches = [ sorted(rng.choice(n, BATCH, replace=False).tolist()) for _ in range(num_batches) ] t0 = time.time() for idx in batches: ds.take(idx, columns=cols) return (num_batches * BATCH) / (time.time() - t0) ``` One Colab run produced the following throughput: | Throughput, rows/s | LanceDB | Parquet | | - | -: | -: | | `image` + `question` + `answer`, sequential | 2,603 | 8,311 | | `image` + `question` + `answer`, shuffled | 2,613 | 352 | | `vision_tower_hiddens` fp16, sequential | 1,452 | 90 | | `vision_tower_hiddens` fp16, shuffled | 2,149 | -- | The takeaways are workload-specific: * For a traditional sequential scan over raw image/question/answer columns, Parquet is faster in this run: 8,311 rows/s vs 2,603 rows/s. * For shuffled raw multimodal batches, Lance is faster because training reads scattered rows repeatedly instead of streaming the file once. * For cached fp16 fixed-size arrays, Lance is about 16x faster than Parquet on the sequential scan. This is the training-relevant path in this example: the model reads `vision_tower_hiddens`, token IDs, masks, and labels as fixed-size columns. * The benchmark intentionally skips the Parquet fp16 shuffled case. Parquet would re-decode whole row groups for each random batch, which is slow enough to distract from the real use case. The sequential fp16 row already shows the layout gap, while Lance shuffled reads remain fast. The numbers shown above are central to the example. The Tier 3 feature is only useful if the storage format can read it efficiently in the way a trainer actually needs: projected columns, repeated scans, and shuffled batches. **Lance specializes in exactly that access pattern**, including fixed-size list columns stored on disk. ## 6. Load cached columns with the Permutation API The training DataLoader projects only the columns needed by the cached training loop: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from lancedb.permutation import Permutation CACHED_COLS = [ "vision_tower_hiddens", "input_ids", "attention_mask", "labels", ] class LancePermutationDataset(torch.utils.data.Dataset): def __init__(self, uri: str, table_name: str): self.uri = uri self.table_name = table_name self._perm = None self.length = len(lancedb.connect(uri).open_table(table_name)) def __len__(self): return self.length def __getstate__(self): state = self.__dict__.copy() state["_perm"] = None return state def _ensure_open(self): if self._perm is None: tbl = lancedb.connect(self.uri).open_table(self.table_name) self._perm = ( Permutation.identity(tbl) .select_columns(CACHED_COLS) .with_format("arrow") ) def __getitems__(self, indices: list[int]): self._ensure_open() return self._perm.__getitems__(indices) ``` Each worker opens its own `Permutation`, reads Arrow batches directly from Lance, and avoids per-row Python object conversion until the collate function converts arrays into tensors. The training batch contains: | Field | Shape | | - | - | | `vision_hiddens` | `fp16[B, 400, 2048]` | | `input_ids` | `int64[B, 512]` | | `attention_mask` | `int64[B, 512]` | | `labels` | `int64[B, 512]` | ## 7. Fine-tune without loading the vision tower The training process loads the language-model side of Qwen2.5-VL in 4-bit, deletes the vision tower, and wraps the LLM projections with LoRA adapters. During the forward pass, the model embeds the token IDs, finds the `<|image_pad|>` positions, and inserts the cached visual hidden states into those positions: ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} def forward_cached(model, batch, image_pad_id: int): base = model.get_base_model() if hasattr(model, "get_base_model") else model inner = base.model inputs_embeds = inner.get_input_embeddings()(batch.input_ids) _, _, hidden_dim = inputs_embeds.shape mask = ( (batch.input_ids == image_pad_id) .unsqueeze(-1) .expand_as(inputs_embeds) ) vision_flat = batch.vision_hiddens.to(inputs_embeds.dtype).reshape(-1, hidden_dim) inputs_embeds = inputs_embeds.masked_scatter(mask, vision_flat) return model( inputs_embeds=inputs_embeds, attention_mask=batch.attention_mask, labels=batch.labels, ).loss ``` At this point, the LanceDB integration is done. The rest is plain PyTorch: optimizer, gradient accumulation, checkpointing, and saving the LoRA adapter. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} loader = make_cached_loader( "data/colab/textvqa_colab_train.lance", batch_size=2, shuffle=True, ) for batch in loader: batch = batch.to(device) loss = forward_cached(model, batch, image_pad_id) (loss / grad_accum).backward() ... ``` This produces a training log like the following. The loss falls as the adapter learns from the cached features, and peak VRAM stays at 5.3 GB because QLoRA trains without keeping the vision tower active: ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} step 10/300 loss=2.6694 5.9 samples/s step 20/300 loss=2.3133 6.1 samples/s . . . step 290/300 loss=0.0359 6.3 samples/s step 300/300 loss=0.4750 6.3 samples/s saved adapter to runs/colab_lora/lora | peak VRAM 5.3 GB ``` The training loop pays zero per-step cost for image decode, vision-tower forward, or prompt tokenization. Those costs were moved into feature engineering, where LanceDB and Geneva make them durable, incremental, and reusable. ## 8. Evaluate on held-out images Evaluation uses the held-out validation table and loads the full VLM, including the vision tower. That is intentional: inference should see raw unseen images, not the cached train features. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} rows = ( val_tbl.search() .select(["image", "question", "answer", "answers"]) .limit(256) .to_arrow() .to_pylist() ) base_model, processor = load_model(adapter_dir=None, load_4bit=True) tuned_model, processor = load_model(adapter_dir="runs/colab_lora/lora", load_4bit=True) base_score = score_textvqa(base_model, processor, rows) tuned_score = score_textvqa(tuned_model, processor, rows) ``` In this end-to-end example, the held-out curated validation split produced: | Model | TextVQA accuracy | | - | -: | | Base `Qwen2.5-VL-3B-Instruct` | 0.799 | | QLoRA-tuned adapter | **0.820** | | Lift | **+2.1 percentage points** | The tuned adapter is not meant to be a state-of-the-art TextVQA checkpoint. It is the proof point for the pipeline: the same Lance table supports curation, feature engineering, efficient training reads, and evaluation on held-out raw images. The notebook renders side-by-side examples: image, question, base answer, tuned answer, and ground truth. This closes the loop from feature idea to trained model while keeping the source data, derived features, training batches, and evaluation split in Lance. ## Full source The complete demo implementation with helper scripts and usage instructions is in [this repo](https://github.com/lancedb/tmls-2026-demo). > [card] [Notebook](https://github.com/lancedb/training/blob/vlm-textvqa/examples/vlm-textvqa/notebooks/colab_textvqa_lance.ipynb) > > The runnable Colab workflow: download, explore, benchmark, train, and evaluate. > [card] [UDF registry](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/geneva_udfs.py) > > Tier 1, Tier 2, and Tier 3 feature definitions. > [card] [Backfill driver](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_geneva.py) > > Feature materialization for the tiers above. > [card] [Training loop](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/train_qwen25vl_lora.py) > > QLoRA training from cached Lance columns. # Agentic RAG Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/agentic-rag Several agents collaborating to retrieve and answer. Builds a RAG system where multiple agents collaborate (retrieving information, checking it, and generating answers) rather than a single retrieve-then-generate pass. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Agentic_RAG/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/Agentic_RAG) > > Read the source. # Contextual RAG Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/contextual-rag Prepend LLM-generated context to each chunk before embedding it. Addresses the "lost in the middle" problem in retrieval. An LLM generates a succinct piece of context for each document chunk, which is prepended to the chunk before embedding, so a chunk carries enough surrounding meaning to be retrieved for the right queries. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Contextual-RAG/Anthropic_Contextual_RAG.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Contextual-RAG) > > Read the source. # HyDE: hypothetical document embeddings Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/hyde Generate a hypothetical answer, then retrieve documents similar to it. An LLM writes a hypothetical document answering the query, and that document, not the query, is embedded and used for retrieval. It works because a plausible answer sits nearer the real answers in embedding space than a question does. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Advance-RAG-with-HyDE/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Advance-RAG-with-HyDE) > > Read the source. # Late chunking Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/late-chunking Retrieve whole documents first, chunk them afterwards. Inverts the usual order: documents are retrieved first and chunked just before synthesis. Chunking late preserves context that pre-chunking discards, since a chunk is cut with knowledge of the query it is answering. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Advanced_RAG_Late_Chunking/Late_Chunking_\(Chunked_Pooling\).ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Advanced_RAG_Late_Chunking) > > Read the source. # Matryoshka embeddings Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/matryoshka-embeddings Nested, variable-size embeddings with LanceDB and LlamaIndex. A RAG pipeline built on Matryoshka embeddings with LlamaIndex. The embeddings nest, so one model serves several dimensionalities: store the full vector and retrieve with a truncated one when the cheaper comparison is good enough. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/RAG-with_MatryoshkaEmbed-Llamaindex/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/RAG-with_MatryoshkaEmbed-Llamaindex) > > Read the source. # Multimodal Agent Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/multimodal-agent/index Build an AI agent that understands both text and images to help users find recipes using LanceDB and PydanticAI [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) Ever wanted to combine the power of text and images in a single AI agent? In this tutorial, you'll build an agent that can understand both text and images to help users discover recipes that are relevant to them. The approach shown combines LanceDB's multimodal capabilities with [Pydantic AI](https://ai.pydantic.dev/) for the agentic workflow. ## Key Technologies * **LanceDB**: Embedded retrieval library and multimodal lakehouse for efficient storage and retrieval * **PydanticAI**: Modern AI agent framework with type safety * **Sentence Transformers**: Text embeddings for semantic search * **CLIP**: Vision-language model for image understanding * **Streamlit**: Interactive web application framework ## Tutorial Overview ### Option 1: Notebook The notebook shows how to work through the steps and prepare a small sample recipe dataset, generate both text and image embeddings, store everything efficiently in LanceDB, and then build a PydanticAI agent with custom tools to query it. You'll finish by testing the agent against a few example questions to see the full multimodal flow end to end. > [card] [Notebook](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) > > This simple tutorial provides a step-by-step workflow with a small demo dataset of 4 examples. > No local setup required - just click and start learning about multimodal agents. > [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1pxavAGoXa-KSh_4HxNpvP2AjHPcIRpbq?usp=sharing) ### Option 2: Demo Application (Local Setup) The demo application is the full codebase: you'll download and process a real recipe dataset with thousands of items, run a Streamlit chat interface that supports image upload, and follow a structure that includes production-minded touches like error handling, logging, and monitoring. Everything you need to deploy is included. > [card] [Download Tutorial Files](https://github.com/lancedb/vectordb-recipes/tree/main/applications/multimodal-recipe-agent) > > Download the files for the full demo application here. ### Dataset Information * **Source**: [Kaggle Recipe Dataset](https://www.kaggle.com/datasets/pes12017000148/food-ingredients-and-recipe-dataset-with-images) * **Size**: Thousands of recipes with images * **Format**: CSV file with recipe data and image references ### Setup ```bash bash icon="code" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # 1. Extract the downloaded files to a folder # 2. Navigate to the folder in terminal cd multimodal-recipe-agent # 3. Install dependencies with uv uv sync # 4. Download the Kaggle dataset # Visit: https://www.kaggle.com/datasets/pes12017000148/food-ingredients-and-recipe-dataset-with-images # Extract recipes.csv to the data/ folder # 5. Import the dataset uv run python import.py # 6. Run the complete Streamlit chat application uv run streamlit run app.py ``` # NVIDIA RAG Blueprint with LanceDB Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/nvidia-rag-blueprint/index Use LanceDB as the retrieval layer for NVIDIA RAG Blueprint with a Docker-first, retrieval-only reference integration. ## What this tutorial shows If you are using [NVIDIA RAG Blueprints](https://build.nvidia.com/blueprints) and want to evaluate LanceDB in that stack, this tutorial gives you a concrete starting point. It shows how to use LanceDB as the retrieval layer for a Docker-based NVIDIA RAG deployment with a small, script-driven reference integration where LanceDB Embedded runs directly in the NVIDIA containers, the collection is prepared ahead of time, and the RAG server retrieves from it for search and generation. The example is intentionally retrieval-only, but it also includes hybrid search and reranker selection so you can see how LanceDB fits into a realistic NVIDIA retrieval workflow. > [!TIP] > > The runnable example for this tutorial lives in the > [VectorDB recipes repository](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb). ## How NVIDIA organizes vector databases NVIDIA's [RAG Blueprint documentation](https://docs.nvidia.com/rag/latest/readme.html) effectively describes three different patterns for vector database support. 1. There are built-in backends such as Milvus, where NVIDIA already owns both ingestion and retrieval. 2. There are built-in alternatives such as Elasticsearch, where NVIDIA still owns the end-to-end flow but switches the backend through configuration. 3. Then, there is the custom vector database path, where you implement a `VDBRag` backend yourself and register it in NVIDIA's factory. The LanceDB example shown below fits into the third category. More specifically, it follows NVIDIA's **retrieval-only** custom backend path: the data is prepared in LanceDB ahead of time, and NVIDIA RAG Blueprint is then pointed at that existing collection for search and generation. It does not yet teach NVIDIA's ingestor how to write new documents into LanceDB automatically. ## Deployment model This reference integration uses **LanceDB Embedded as an embedded retrieval library**, not as a separate database service. In practice, `APP_VECTORSTORE_NAME` is set to `lancedb`, `APP_VECTORSTORE_URL` points to a local filesystem path inside the NVIDIA containers, the LanceDB collection is prepared ahead of time, and the NVIDIA RAG server loads the LanceDB adapter to retrieve directly from that local dataset. ## What the recipe contains The recipe at [`examples/nvidia-rag-blueprint-lancedb`](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb) is organized around a small number of practical pieces. The data-prep script builds a demo LanceDB collection from scratch, generates embeddings through the LanceDB embedding registry, and creates a full-text index so hybrid retrieval works immediately. The adapter file shows the retrieval-only integration point for NVIDIA RAG Blueprint, while the Docker override and NVIDIA change guide show the minimal configuration and source changes needed to run the example against NVIDIA's containers. ## End-to-end flow ### 1. Prepare the LanceDB collection From the [recipe directory](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb): ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} uv sync uv run prepare_lancedb.py --embedder demo-keyword --reranker mrr ``` That script creates: * a local LanceDB dataset under `data/` * a collection named `nvidia_blueprint_demo` * automatic embeddings generated at ingest time * an FTS index for hybrid search The default embedder is an offline demo embedder so the example stays easy to run. If you want a more realistic setup, the same script can switch to a sentence-transformers embedder. ### 2. Patch the NVIDIA blueprint Follow the instructions in the recipe's [`nvidia_blueprint_changes.md`](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb/nvidia_blueprint_changes.md). The essential changes are: * add LanceDB dependencies to the NVIDIA environment * copy `lancedb_vdb.py` into the NVIDIA source tree * register the `lancedb` branch in NVIDIA's VDB factory NVIDIA's [RAG blueprint documentation](https://docs.nvidia.com/rag/latest/readme.html) and custom-VDB guide provide useful background if you want more context before applying the LanceDB-specific changes. ### 3. Start the Docker deployment Set the absolute path to the recipe directory: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_RECIPE_DIR=/absolute/path/to/vectordb-recipes/examples/nvidia-rag-blueprint-lancedb ``` Then from the NVIDIA repo root: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} docker compose \ -f deploy/compose/docker-compose-rag-server.yaml \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ up -d --build docker compose \ -f deploy/compose/docker-compose-ingestor-server.yaml \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ up -d --build ``` The key environment values are: * `APP_VECTORSTORE_NAME=lancedb` * `APP_VECTORSTORE_URL=/opt/lancedb-recipe/data` * `COLLECTION_NAME=nvidia_blueprint_demo` * `APP_VECTORSTORE_SEARCHTYPE=hybrid` * `LANCEDB_RERANKER=mrr` ## Verifying the integration ### Search ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X POST http://localhost:8081/v1/search \ -H 'Content-Type: application/json' \ -d '{ "query": "How do I replace Milvus in the NVIDIA RAG blueprint with LanceDB?", "use_knowledge_base": true, "collection_names": ["nvidia_blueprint_demo"], "vdb_top_k": 3, "reranker_top_k": 0 }' ``` ### Generate ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -N -X POST http://localhost:8081/v1/generate \ -H 'Content-Type: application/json' \ -d '{ "messages": [{"role":"user","content":"Summarize the LanceDB integration approach."}], "use_knowledge_base": true, "collection_names": ["nvidia_blueprint_demo"], "vdb_top_k": 3, "reranker_top_k": 0 }' ``` ## Hybrid retrieval and rerankers This example is meant to prove more than a trivial vector lookup. * LanceDB hybrid retrieval combines vector search with full-text search * the recipe creates the FTS index as part of dataset prep * the adapter supports `RRFReranker`, `MRRReranker`, and `CrossEncoderReranker` * the default example uses `MRRReranker`, not a plain weighted linear combination Hybrid retrieval is important for NVIDIA partner workloads because product names, storage platforms, and technical jargon often need exact lexical matching as well as semantic retrieval. ## How this can be extended The current example follows NVIDIA's **custom retrieval-only backend** path. In practice, that means the LanceDB collection is created ahead of time and NVIDIA RAG Blueprint is then pointed at that existing collection for search and generation. The sample data in `prepare_lancedb.py` exists only to make that flow runnable end to end: it creates a small local collection, inserts a few documents, generates embeddings, and builds an FTS index so the NVIDIA side has something real to query. A fuller integration is possible. NVIDIA's custom `VDBRag` interface also supports the pattern used by built-in backends such as Milvus and Elasticsearch, where NVIDIA owns both ingestion and retrieval. To make LanceDB work that way, a complete LanceDB backend would need to implement the ingestion methods NVIDIA documents, especially `create_collection` and `write_to_index`, along with the retrieval and collection-management methods expected by the rest of the stack. The open work is in defining how NVIDIA's ingestor should write records into LanceDB, how that storage is shared between the ingestor and the RAG server, and how document and collection metadata should be exposed so the broader NVIDIA APIs behave correctly. Until those pieces exist, this example should be read as: prepare LanceDB first, then let NVIDIA retrieve from it. # Time-Travel RAG with versioned data Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/agents/time-travel-rag/index Build a RAG example that retrieves documents from a selected table version. > [!TIP] > > All the scripts and code for this tutorial are available in the > [vectorDB recipes](https://github.com/lancedb/vectordb-recipes/tree/main/examples/time-travel-rag) repository. ## Use case: Financial services regulatory knowledge base Imagine you're a major investment bank. Your team is tasked with building a critical Retrieval-Augmented Generation (RAG) system. This system must provide instant, accurate answers to compliance officers about ever-changing financial regulations. A wrong or out-of-date answer isn't just an inconvenience: it could lead to multi-million dollar fines, reputational damage, and regulatory audits. Your knowledge base is a living entity, constantly evolving with: * Daily regulatory updates from government bodies. * New internal policy documents and interpretations. * A/B testing of different embedding models and text chunking strategies to improve accuracy. This dynamic environment creates a series of high-stakes challenges that traditional vector databases are ill-equipped to handle. ## Pain points solved by LanceDB 1. "Our RAG gave different answers yesterday versus today. Which version was used in the official compliance report?" Without versioning, you can't prove what the AI knew at a specific point in time, making audits impossible. 2. "The new embedding model we deployed corrupted half the vectors. Can we instantly roll back our 10TB dataset?" With traditional systems, a rollback means a painful, hours-long (or days-long) process of re-indexing from a backup, leading to significant downtime. 3. "Regulators want to audit an AI-assisted decision from three months ago. How can we prove what data the model had access to at that exact moment?" Reproducibility is key for compliance. You must be able to reconstruct the exact state of the knowledge base for any historical query. 4. "We need to A/B test a new chunking strategy, but we can't disrupt the production system or duplicate the entire dataset." Experimentation is vital for improvement, but it can't come at the cost of production stability or a massive infrastructure bill. LanceDB's [column-based data evolution](/oss/v0-41-0/management/table#schema) and [time-travel capabilities](/oss/v0-41-0/management/table#versioning) help preserve the dataset used for a particular answer. This tutorial demonstrates versioned retrieval; production auditing also needs application logs, retention policies and access controls. ## Dataset: The U.S. Federal Register To make this use case realistic, we'll use a perfect real-world dataset: The U.S. Federal Register, the official daily journal of the United States Government. It contains all new rules, proposed rules, and notices from federal agencies. It is the canonical source for regulatory changes, and it's updated every business day. It even has a public API, allowing us to simulate the real-time ingestion of new documents. An example output of the workflow defined in main.py is shown below. ```bash main.py expandable icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} --- Initializing Database Environment --- Removed old database at ./lancedb Loading embedding model: all-MiniLM-L6-v2... --- STEP 1: Initial Data Ingestion --- Fetching 500 documents for publication date: 2024-08-19... Successfully fetched 86 documents. Embedding 86 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 7.12it/s] Successfully embedded 86 documents. Creating table 'federal_register'... ✅ Table 'federal_register' created. Version: 1, Rows: 86 --- STEP 2: Simulating Sequential Daily Updates --- Fetching 500 documents for publication date: 2024-08-20... Successfully fetched 102 documents. Embedding 102 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 10.66it/s] Successfully embedded 102 documents. ✅ Data added to 'federal_register'. New Version: 2, Total Rows: 188 Fetching 500 documents for publication date: 2024-08-21... Successfully fetched 114 documents. Embedding 114 documents... Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 10.19it/s] Successfully embedded 114 documents. ✅ Data added to 'federal_register'. New Version: 3, Total Rows: 302 ======================================================== = PART 1: AUDITING KNOWLEDGE BASE ACROSS TIME = ======================================================== Running audit for query: 'cybersecurity reporting requirements for public companies' Attempting to open 'federal_register' and checkout version 1... ✅ Successfully checked out Version 1 of 'federal_register'. Total rows: 86 Querying table 'federal_register' (Version 1)... --- Top Result for Version: V1 (all-MiniLM-L6-v2) --- 📄 Title: Public Company Accounting Oversight Board; Extension of Approval Periods for Proposed Rules on a Firm's System of Quality Control and Related Amendments to PCAOB Standards, Proposed Rules on Amendments Related to Aspects of Designing and Performing Audit Procedures That Involve Technology-Assisted Analysis of Information in Electronic Form, and Proposed Rules on Amendment to PCAOB Rule 3502 Governing Contributory Liability 🗓️ Date: 2024-08-19 📏 Distance: 1.1667 📝 Abstract: [No abstract available for this document] -------------------------------------- Attempting to open 'federal_register' and checkout version 2... ✅ Successfully checked out Version 2 of 'federal_register'. Total rows: 188 Querying table 'federal_register' (Version 2)... --- Top Result for Version: V2 (all-MiniLM-L6-v2) --- 📄 Title: Information Collection Being Reviewed by the Federal Communications Commission Under Delegated Authority 🗓️ Date: 2024-08-20 📏 Distance: 1.1436 📝 Abstract: As part of its continuing effort to reduce paperwork burdens, and as required by the Paperwork Reduction Act (PRA) of 1995, the Federal Communications Commission (FCC or the Commission) invites the general public and other Federal agencies to take this opportunity to comment on the following information collection. Comments are requested concerning: whether the proposed collection of information is necessary for the proper performance of the functions of the Commission, including whether the information shall have practical utility; the accuracy of the Commission's burden estimate; ways to enhance the quality, utility, and clarity of the information collected; ways to minimize the burden of the collection of information on the respondents, including the use of automated collection techniques or other forms of information technology; and ways to further reduce the information collection burden on small business concerns with fewer than 25 employees. The FCC may not conduct or sponsor a collection of information unless it displays a currently valid control number. No person shall be subject to any penalty for failing to comply with a collection of information subject to the PRA that does not display a valid Office of Management and Budget (OMB) control number. -------------------------------------- Attempting to open 'federal_register' and checkout version 3... ✅ Successfully checked out Version 3 of 'federal_register'. Total rows: 302 Querying table 'federal_register' (Version 3)... --- Top Result for Version: V3 (all-MiniLM-L6-v2) --- 📄 Title: Equipment, Systems, and Network Information Security Protection 🗓️ Date: 2024-08-21 📏 Distance: 1.0942 📝 Abstract: This proposed rulemaking would impose new design standards to address cybersecurity threats for transport category airplanes, engines, and propellers. The intended effect of this proposed action is to standardize the FAA's criteria for addressing cybersecurity threats, reducing certification costs and time while maintaining the same level of safety provided by current special conditions. -------------------------------------- ✅ Date-based audit complete. Results show how knowledge evolves over time. This demonstrates LanceDB's powerful [versioning capabilities](/tutorials/tables/consistency#versioning) for maintaining audit trails. ============================================================= = PART 2: A/B TESTING DIFFERENT EMBEDDING MODELS = ============================================================= Loading embedding model: all-mpnet-base-v2... Embedding 302 documents... Batches: 100%|█████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:03<00:00, 2.55it/s] Successfully embedded 302 documents. Creating table 'federal_register_experimental'... ✅ Table 'federal_register_experimental' created. Version: 1, Rows: 302 Comparing search results for the same data with different models: Querying table 'federal_register' (Version 3)... --- Top Result for Version: Latest Prod V3 (all-MiniLM-L6-v2) --- 📄 Title: Equipment, Systems, and Network Information Security Protection 🗓️ Date: 2024-08-21 📏 Distance: 1.0942 📝 Abstract: This proposed rulemaking would impose new design standards to address cybersecurity threats for transport category airplanes, engines, and propellers. The intended effect of this proposed action is to standardize the FAA's criteria for addressing cybersecurity threats, reducing certification costs and time while maintaining the same level of safety provided by current special conditions. -------------------------------------- Querying table 'federal_register_experimental' (Version 1)... --- Top Result for Version: Experimental (all-mpnet-base-v2) --- 📄 Title: Commission Information Collection Activities (FERC-725B); Comment Request; Extension 🗓️ Date: 2024-08-20 📏 Distance: 1.0827 📝 Abstract: In compliance with the requirements of the Paperwork Reduction Act of 1995, the Federal Energy Regulatory Commission (Commission or FERC) is soliciting public comment on the currently approved information collection, FERC-725B, Mandatory Reliability Standards, Critical Infrastructure Protection (CIP) (Update for CIP-012-1 to version CIP-012-02) Cyber Security--Communications between Control Centers. The 60-day notice comment period ended on July 23, 2024, with no comments received. -------------------------------------- ✅ A/B test complete. Notice the difference in relevance (distance score) between models. This showcases how LanceDB enables [experimentation with different embedding models](/docs/embeddings/) without disrupting production systems. ``` # Feature engineering 101 Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/feature-engineering/feature-engineering-101 Add derived feature columns to an existing table. Adds new derived features to a table, the pattern documented under [computed columns](/oss/v0-41-0/feature-engineering/add-computed-column). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/feature-engineering/feature-engineering-101.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/feature-engineering/feature-engineering-101.ipynb) > > Read the source. # Materialized views Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/feature-engineering/materialized-views Persist query results as physical tables and keep them current. Creates [materialized views](/oss/v0-41-0/management/materialized-view): query results persisted as physical tables, brought up to date by a [refresh](/oss/v0-41-0/feature-engineering/refresh-materialized-view). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/feature-engineering/materialized-views.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/feature-engineering/materialized-views.ipynb) > > Read the source. # Tutorials Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/index Worked examples of building with LanceDB, grouped by what they build. Every tutorial is one page in the sidebar, grouped by what it builds. The documentation explains how a feature works; these show it doing something. Examples marked as notebooks live in the [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository and are runnable in Colab; the rest are written up here. ## Where to start > [card] [Search](/oss/v0-41-0/tutorials/search/hybrid-search-beir) > > Vector, multi-vector, hybrid and full-text retrieval. > [card] [RAG](/oss/v0-41-0/tutorials/agents/contextual-rag) > > Retrieval-augmented generation and agent applications. > [card] [Feature engineering](/oss/v0-41-0/tutorials/feature-engineering/feature-engineering-101) > > Deriving columns and materialized views. > [card] [Training](/oss/v0-41-0/training/object-detection) > > Curating data and training models directly on a table. ## The features these use | Feature | What it covers | | :- | :- | | [Vector search](/oss/v0-41-0/search/vector-search) | Similarity search, distance metrics, and tuning it. | | [Full-text search](/oss/v0-41-0/search/full-text-search) | Keyword search over text columns. | | [Hybrid search](/oss/v0-41-0/search/hybrid-search) | Keyword and vector search combined. | | [Multi-vector search](/oss/v0-41-0/search/vector-search) | Several embeddings per document. | | [Reranking](/oss/v0-41-0/reranking) | Reordering results to improve the top-k. | | [Feature engineering](/oss/v0-41-0/feature-engineering) | Deriving columns and tables from data already stored. | | [Materialized views](/oss/v0-41-0/management/materialized-view) | A table defined by a query, brought up to date by each refresh. | | [Training](/oss/v0-41-0/training/data-loading) | Reading a table into a data loader. | # Hybrid search and reranking on BEIR Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/hybrid-search-beir Combine semantic and keyword search on the BEIR benchmark, then rerank the results. Uses LanceDB's built-in [hybrid search](/oss/v0-41-0/search/hybrid-search), which combines the strengths of semantic and full-text search. Working against the BEIR dataset, it shows how searching for both the meaning of a query and the specific keywords in it produces more relevant results than either alone, and how a [reranker](/oss/v0-41-0/reranking) refines what comes back. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Inbuilt-Hybrid-Search/Inbuilt_Hybrid_Search_with_LanceDB.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Inbuilt-Hybrid-Search) > > Read the source. # Finding the Needle in a Haystack: Comparing Multi-vector Search Strategies Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/multivector-needle-in-a-haystack Tutorial on token-level retrieval with LanceDB multivector search. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-1.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=4649d48f421bfc299bb67c67f5d65f5d) In the development of advanced search and retrieval systems, moving from keyword matching to semantic understanding is a critical step. However, a key distinction exists between finding a relevant document and locating a specific piece of information within that document with precision. While there are techniques that perform well for retrieving documents, most of them work by extracting summarized semantic meaning of the document. This can be seen as these models trying to understand the "gist" of the documents. Both single-vector search and late-interaction approaches work well for these conditions with various tradeoffs involved. But there's another type of problem where the goal is not just to understand the overall topic of a document in general, but to also specifically account for the requested detail within the document. This "needle in a haystack" problem is a significant challenge, and addressing it is essential for building high-precision retrieval systems. This guide provides a technical analysis of multivector search for high-precision information retrieval. We will examine various optimization strategies and analyze their performance. This guide should be seen as complementary to resources like [this blog post by Answer.AI](https://www.answer.ai/posts/colbert-pooling.html) on ColBERT pooling, which explains how pooling strategies can be effective for document-level retrieval. Here, we will demonstrate why those same techniques can be counterproductive when precision at an intra-document, token level is the primary objective. To reproduce the work below, see the code [here](https://github.com/lancedb/research/tree/main/multivector-needle-haystack-bench). ## The Dataset This task is different from benchmarks like BEIR, which focus on text-based doc retrieval, finding the most relevant documents from a large collection. Here, we want *intra-document localization*, where the goal is to find a precise piece of information within a single, dense document, in a multimodal setting. ### The Task: The Document Haystack Dataset Our benchmark is built on the **[AmazonScience/document-haystack](https://huggingface.co/datasets/AmazonScience/document-haystack)** dataset, which contains 25 visually complex source documents (e.g., financial reports, academic papers). To create a rigorous test, our evaluation follows a per-document methodology: * We process each of the 25 source documents independently. * **Table Creation:** For a single source document (e.g., "AIG"), we ingest all pages from all of its page-length variants (from 5 to 200 pages long). This creates a temporary LanceDB table containing approximately 1,230 pages. * **The Task:** We then query this table using a set of "needle" questions, where the goal is to retrieve the **exact page number** containing the answer. A successful retrieval means the correct page number is within the top K results. * **Target metric:** We measure both retrieval accuracy (Hit\@K) and the average search latency for each query against this table. **Dataset example** The documents contain "text needles" like these ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-2.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=7b591c1a386e23f6e758355ba63c483b) ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-3.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=a117439a903041f58dd35f61c0c65ca3) During evaluation, the queries processed are somewhat like this: ``` What is the secret currency in the document? What is the secret object #3 in the document? ``` The intention of this task is to find the page which has the text needle that answers this questions ## Models and Architectures Our testbed includes a baseline single-vector model and a family of advanced multivector models. ### Single-Vector (Bi-Encoder) Baseline: CLIP ViT-Base-Patch32 A bi-encoder maps an entire piece of content (a query, a document page) to a *single* vector. The search process is simple: pre-compute one vector for every page, and at query time, find the page vector closest to the query vector. * **Strength:** Speed and simplicity. * **Weakness:** This creates an **information bottleneck**. All the nuanced details, keywords, and semantic relationships on a page must be compressed into a single, fixed-size vector. For finding a needle, this is like trying to describe a specific person's face using only one word. ### Multi-vector (Late-Interaction) Models Multi-vector models, pioneered by ColBERT, take a different approach. Instead of one vector per page, they generate a *set of vectors* for each page: one for every token (or image patch). * **Mechanism (MaxSim):** The search process is more sophisticated. For each token in the query, the system finds the most similar token on the page. These maximum similarity scores are then summed up to get the final relevance score. This "late-interaction" preserves fine-grained, token-level details. * **The Models:** We used several vision-language models adapted for this architecture, including `ColPali`, `ColQwen2`, and `ColSmol`. While their underlying transformer backbones differ, they all share the ColBERT philosophy of representing documents as a bag of contextualized token embeddings. ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-4.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=92ff6e6e9994104e386dba5e20c0c33c) ## Different Retrieval Strategies Used A full multivector search is powerful but computationally intensive. Here are five strategies for managing it, complete with LanceDB implementation details. ### 1. `base`: The Gold Standard (Full Multi-vector Search) This is the pure, baseline late-interaction search. It offers the highest potential for accuracy by considering every token. **LanceDB also integrates with ConteXtualized Token Retriever (XTR)** , an advanced retrieval model that prioritizes the most semantically important document tokens during search. This integration enhances the quality of search results by focusing on the most relevant token matches. **LanceDB Implementation:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa # Schema for multivector data # Assumes embeddings are 128-dimensional schema = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.list_(pa.float32(), 128))) ]) db = lancedb.connect("./lancedb") tbl = db.create_table("document_pages_base", schema=schema) # Ingesting multi-token embeddings for a page # multi_token_embeddings is a NumPy array of shape (num_tokens, 128) tbl.add([{"page_num": 1, "vector": multi_token_embeddings.tolist()}]) # Searching with a multi-token query # query_multi_vector is also shape (num_query_tokens, 128) results = tbl.search(query_multi_vector).limit(5).to_list() ``` ### 2. `flatten`: Mean Pooling This strategy "flattens" the set of token vectors into a single vector by averaging them. This transforms the search into a standard, fast approximate nearest neighbor (ANN) search. **LanceDB Implementation:** ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema for single-vector data schema_flat = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.float32(), 128)) ]) tbl_flat = db.create_table("document_pages_flat", schema=schema_flat) # Ingesting the mean-pooled vector mean_vector = multi_token_embeddings.mean(axis=0) tbl_flat.add([{"page_num": 1, "vector": mean_vector.tolist()}]) # Searching with a single averaged query vector query_mean_vector = query_multi_vector.mean(axis=0) results = tbl_flat.search(query_mean_vector).limit(5).to_list() ``` ### 3. Max pooling This is a variation of `flatten`. `max_pooling` takes the element-wise max across all token vectors instead of the mean. The implementation is identical to `flatten`, just with a different aggregation method (`.max(axis=0)`). ### 4. `flatten and multivector rerank`: The Hybrid Optimization This two-stage strategy aims for the best of both worlds. First, use a fast, pooled-vector search to find a set of promising candidates. Then, run the full, accurate multivector search on *only* those candidates. **LanceDB Implementation:** This requires a table with two vector columns. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} # Schema with both flat and multivector columns schema_rerank = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector_flat", pa.list_(pa.float32(), 128)), pa.field("vector_multi", pa.list_(pa.list_(pa.float32(), 128))) ]) tbl_rerank = db.create_table("document_pages_rerank", schema=schema_rerank) # Ingest both vectors tbl_rerank.add([ { "page_num": 1, "vector_flat": multi_token_embeddings.mean(axis=0).tolist(), "vector_multi": multi_token_embeddings.tolist() } ]) # --- Two-Stage Search --- # Stage 1: Fast search on the flat vector query_flat = query_multi_vector.mean(axis=0) candidates = tbl_rerank.search(query_flat, vector_column_name="vector_flat") \ .limit(100) \ .with_row_id(True) \ .to_pandas() # Stage 2: Precise multivector search on candidates candidate_ids = tuple(candidates["_rowid"].to_list()) final_results = tbl_rerank.search(query_multi_vector, vector_column_name="vector_multi") \ .where(f"_rowid IN {candidate_ids}") \ .limit(5) \ .to_list() ``` ### 5. `hierarchical token pooling`: Compressing the Haystack This is an indexing-time strategy that aims to reduce the storage footprint and computational cost of multivector search by reducing the number of vectors per document. Instead of using every token vector, it clusters semantically similar tokens together and replaces them with a single, averaged vector. * **Mechanism:** For each document, it computes the similarity between all token vectors, performs hierarchical clustering to group them, and then mean-pools the vectors within each cluster. This results in a smaller, more compact set of token vectors representing the document. * **Goal:** To reduce memory and disk usage while attempting to preserve the most important semantic information, potentially offering a middle ground between the high accuracy of `base` search and the speed of pooled methods. **LanceDB Implementation:** The schema is identical to the `base` multivector search, but the data is pre-processed before ingestion. ```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} from utils import pool_embeddings_hierarchical import numpy as np # Schema is the same as the base multivector schema schema = pa.schema([ pa.field("page_num", pa.int32()), pa.field("vector", pa.list_(pa.list_(pa.float32(), 128))) ]) tbl_hierarchical = db.create_table("document_pages_hierarchical", schema=schema) # Pool the embeddings before ingestion # multi_token_embeddings is a NumPy array of shape (num_tokens, 128) pooled_embeddings = pool_embeddings_hierarchical( multi_token_embeddings, pool_factor=4 # Reduce vector count by a factor of 4 ) # Ingest the smaller set of multi-token embeddings # pooled_embeddings is now shape (approx. num_tokens / 4, 128) tbl_hierarchical.add([{"page_num": 1, "vector": pooled_embeddings.tolist()}]) # Search is identical to the base multivector search results = tbl_hierarchical.search(query_multi_vector).limit(5).to_list() ``` ## The Results For a "needle in a haystack" task, retrieval accuracy is the primary metric of success. The benchmark results reveal a significant performance gap between the full multivector search strategy and common optimization techniques. ### Baseline Performance: Single-Vector Bi-Encoder First, we establish a baseline using a standard single-vector bi-encoder model, `openai/clip-vit-base-patch32`. This represents a common approach to semantic search but, as the data shows, is ill-suited for this task's precision requirements. | Model | Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | :- | | `openai/clip-vit-base-patch32` | `base` | 1.6% | 4.7% | 11.8% | **0.008 s** | With a Hit\@20 rate of just under 12%, the baseline model struggles to reliably locate the correct page. This performance level is insufficient for applications requiring high precision. ### Multi-vector Model Performance We now examine the performance of multivector models using different strategies. The following table compares the `base` (full multivector), `flatten` (mean pooling), and `rerank` (hybrid) strategies across several late-interaction models. | Model | Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | :- | | `vidore/colqwen2-v1.0` | `flatten` | 1.9% | 5.5% | 11.9% | 0.010 s | | `vidore/colqwen2-v1.0` | `flatten and multivector rerank` | 0.3% | 1.5% | 7.3% | 0.692 s | | **`vidore/colqwen2-v1.0`** | **`hierarchical token pooling`** | **13.7%** | **60.5%** | **91.6%** | **0.144 s** | | **`vidore/colqwen2-v1.0`** | **`base`** | **14.0%** | **65.4%** | **95.5%** | 0.668 s | | `vidore/colpali-v1.3` | `flatten` | 1.7% | 4.5% | 9.3% | 0.008 s | | `vidore/colpali-v1.3` | `flatten and multivector rerank` | 0.6% | 2.3% | 6.9% | 0.949 s | | **`vidore/colpali-v1.3`** | **`hierarchical token pooling`** | **10.8%** | **41.7%** | **64.8%** | **0.189 s** | | **`vidore/colpali-v1.3`** | **`base`** | **11.3%** | **42.3%** | **65.6%** | 0.936 s | | `vidore/colSmol-256M` | `flatten` | 1.6% | 4.7% | 10.5% | 0.008 s | | `vidore/colSmol-256M` | `flatten and multivector rerank` | 0.3% | 1.6% | 7.0% | 0.853 s | | **`vidore/colSmol-256M`** | **`base`** | **14.4%** | **64.0%** | **91.7%** | 0.848 s | The data shows a consistent pattern: the `base` strategy outperforms all other techniques. The flattned pooling and reranking strategies perform no better than the single-vector baseline. However, hierarchical token pooling seems like a decent alternative to base considering speed vs accuracy tradeoff. Let's look at the numbers in detail. ### In-Depth Analysis of Pooling Strategies To further understand the failure of optimization techniques, we compared different methods for pooling token vectors into a single vector: `mean` (`flatten`), `max`. | Model & Pooling Strategy | Hit\@1 | Hit\@5 | Hit\@20 | Avg. Latency (s) | | :- | :- | :- | :- | :- | | `vidore/colqwen2-v1.0` (`mean_pooling`) | 1.9% | 5.5% | 11.9% | 0.010 s | | `vidore/colqwen2-v1.0` (`max_pooling`) | 1.4% | 4.2% | 11.2% | 0.011 s | | **`vidore/colqwen2-v1.0` (`base`)** | **14.0%** | **65.4%** | **95.5%** | 0.668 s | All flattened pooling methods perform poorly, confirming that the aggregation of token vectors into a single representation loses the fine-grained detail required for this task. **Finding the Right Trade-Off** ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-5.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=f4d9588d50bdb0bb8e2830e56cc7be57) 1. **The Failure of Simple Pooling:** The `flatten` (mean pooling) and `max_pooling` strategies fail to improve upon the baseline. This is because their aggressive compression **destroys the essential localization signal**. The resulting single vector represents the *topic* of the page, not the *specific needle* on it. 2. **The Failure of `flatten and multivector rerank`:** This hybrid strategy is the *worst-performing* of all. The reason is a fundamental flaw in its design for this task: the first stage uses a simple pooled vector to retrieve candidates. Since this pooling eliminates the localization signal, the initial candidate set is effectively random. 3. **`hierarchical token pooling`:** By clustering and pooling tokens at indexing time, it reduces the number of vectors per page (in our case, by a factor of 4). This intelligently compresses the data, while preserving enough token-level detail in multivector setting. It achieves a **Hit\@20 of 91.6%**, only slightly behind the `base` strategy's 95.5%, but is significantly faster. 4. **`base` multivector Search:** The vanilla, un-optimized `base` multivector search remains the most accurate strategy. Preserving every token vector provides the highest guarantee of finding the needle, but this comes at the highest computational cost. ### Latency: ![](https://mintcdn.com/lancedb-bcbb4faf/06qyYZ1Az1OmWUp2/oss/v0-41-0/static/assets/images/search/multivector/multivector-6.png?fit=max\&auto=format\&n=06qyYZ1Az1OmWUp2\&q=85\&s=5e03779805d21a8a26d94db5be99756d) The "optimizations" are not all created equal. While simple pooling is fast, its inaccuracy makes it unusable. Hierarchical pooling, however, offers a compelling balance of speed and accuracy. | Strategy (on `vidore/colqwen2-v1.0`) | Avg. Search Latency (s) | Hit\@20 Accuracy | | :- | :- | :- | | `flatten` (Fast but Ineffective) | **0.010 s** | 11.9% | | `flatten and multivector rerank` (Slower and Ineffective) | 0.692 s | 7.3% | | **`hierarchical token pooling` (Accurate & Fast)** | **0.144 s** | **91.6%** | | `base` (Most Accurate) | 0.668 s | **95.5%** | | *Latency reported is as seen on NVIDIA H100 GPUs* | | | ## Practical Considerations The accuracy of `base` multivector search is impressive, but its computational intensity has historically limited its use. `hierarchical token pooling` as a viable strategy creates a new, practical sweet spot on the accuracy-latency curve, making high-precision search accessible for a wider range of applications. ### Search Latency and Computational Complexity As the benchmark data shows, the search latency for `base` multivector search is orders of magnitude higher than for single-vector (or pooled-vector) search. It's important to note that the reported \~670ms latency is an average from per-document evaluations. In this benchmark, each of the 25 documents is processed independently. All pages from a single document's variants (ranging from 5 to 200 pages) are ingested into a temporary table, resulting in a table size of approximately **1,230 rows (pages)** per evaluation. The search is performed on this table, and then the table is discarded. This highlights a significant performance cost even on a relatively small, per-document scale. This stems from a fundamental difference in computational complexity: * **Modern ANN Search (for single vectors):** Algorithms like HNSW (Hierarchical Navigable Small World) provide sub-linear search times, often close to `O(log N)`, where `N` is the number of items in the index. This allows them to scale to billions of vectors with millisecond-level latency. * **Late-Interaction Search (Multi-vector):** The search process is far more intensive. For each query, it must compute similarity scores between query tokens and the tokens of many candidate documents. The complexity is closer to `O(M * Q * D)`, where `M` is the number of candidate documents to score, `Q` is the number of query tokens, and `D` is the average number of tokens per document. `Hierarchical token pooling` directly attacks this problem by reducing `D`, leading to a significant reduction in search latency. ### When to Use Multi-Vector Search Given these constraints, the choice of strategy depends on the specific requirements of the application. * **For Maximum Precision (`base`):** In domains where the cost of missing the needle is extremely high, the full `base` search is the most reliable option. * **For a Balance of Precision and Performance (`hierarchical token pooling`):** This is the ideal choice for many applications. It makes high-precision search practical for larger datasets and more interactive use cases where the sub-second latency of the `base` search may be too high. It significantly lowers the barrier to entry for adopting multivector search. It should still not be seen as a drop-in replacement for ANN, as it still requires more computational resources than single-vector search. * **For General-Purpose Document Retrieval (`flatten` / single-vector):** For large-scale retrieval where understanding the "gist" is sufficient or where in cases where large-context text-based models suffice, single-vector search remains the most practical and scalable solution. ## Appendix: Full Benchmark Results The full benchmark results are shown below. ```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} | name | _runtime | _step | _timestamp | _wandb | avg_inference_latency | avg_search_latency | hit_rates | model_name | strategy | |:--------------------------------------------|-----------:|--------:|--------------:|:-------------------|------------------------:|---------------------:|:------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------|:---------------------| | vidore/colqwen2-v0.1_base | 13410 | 0 | 1.75873e+09 | {'runtime': 13410} | 0.0418646 | 0.751151 | {'1': 0.1355151515151515, '10': 0.888, '20': 0.9597575757575758, '3': 0.3936969696969697, '5': 0.6349090909090909} | vidore/colqwen2-v0.1 | base | | vidore/colqwen2-v1.0_rerank | 13008 | 0 | 1.75873e+09 | {'runtime': 13008} | 0.0426252 | 0.692482 | {'1': 0.003393939393939394, '10': 0.03296969696969697, '20': 0.07296969696969698, '3': 0.010666666666666666, '5': 0.015272727272727271} | vidore/colqwen2-v1.0 | rerank | | vidore/colpali-v1.3_flatten | 2998 | 0 | 1.75872e+09 | {'runtime': 2998} | 0.0296511 | 0.00833224 | {'1': 0.017454545454545455, '10': 0.06448484848484848, '20': 0.09333333333333334, '3': 0.034666666666666665, '5': 0.04509090909090909} | vidore/colpali-v1.3 | flatten | | vidore/colqwen2-v0.1_rerank | 13512 | 0 | 1.75873e+09 | {'runtime': 13512} | 0.0418855 | 0.662372 | {'1': 0.002909090909090909, '10': 0.026424242424242423, '20': 0.05987878787878788, '3': 0.0075151515151515155, '5': 0.014545454545454544} | vidore/colqwen2-v0.1 | rerank | | vidore/colqwen2-v1.0_base | 12933 | 0 | 1.75873e+09 | {'runtime': 12933} | 0.0416839 | 0.667898 | {'1': 0.14012121212121212, '10': 0.8846060606060606, '20': 0.9553939393939394, '3': 0.4111515151515152, '5': 0.6538181818181819} | vidore/colqwen2-v1.0 | base | | vidore/colpali-v1.3_rerank | 12090 | 0 | 1.75873e+09 | {'runtime': 12090} | 0.0310783 | 0.949047 | {'1': 0.006060606060606061, '10': 0.03878787878787879, '20': 0.06933333333333333, '3': 0.014545454545454544, '5': 0.022787878787878788} | vidore/colpali-v1.3 | rerank | | vidore/colqwen2-v1.0_flatten | 4846 | 0 | 1.75874e+09 | {'runtime': 4846} | 0.0504031 | 0.010443 | {'1': 0.018666666666666668, '10': 0.07854545454545454, '20': 0.11903030303030304, '3': 0.041212121212121214, '5': 0.055030303030303034} | vidore/colqwen2-v1.0 | flatten | | vidore/colqwen2-v0.1_base | 10838 | 0 | 1.75874e+09 | {'runtime': 10838} | 0.04627 | 0.692836 | {'1': 0.13575757575757577, '10': 0.8870303030303031, '20': 0.96, '3': 0.3941818181818182, '5': 0.6351515151515151} | vidore/colqwen2-v0.1 | base | | vidore/colqwen2-v0.1_flatten | 4828 | 0 | 1.75874e+09 | {'runtime': 4828} | 0.0486335 | 0.0103028 | {'1': 0.018424242424242423, '10': 0.07224242424242425, '20': 0.10521212121212122, '3': 0.03903030303030303, '5': 0.05212121212121213} | vidore/colqwen2-v0.1 | flatten | | vidore/colpali-v1.3_base | 10253 | 0 | 1.75874e+09 | {'runtime': 10253} | 0.0312334 | 0.93611 | {'1': 0.11272727272727272, '10': 0.551030303030303, '20': 0.6555151515151515, '3': 0.29987878787878786, '5': 0.4232727272727273} | vidore/colpali-v1.3 | base | | vidore/colqwen2-v0.1_flatten | 4745 | 0 | 1.75874e+09 | {'runtime': 4745} | 0.0472825 | 0.00990508 | {'1': 0.018424242424242423, '10': 0.07296969696969698, '20': 0.10496969696969696, '3': 0.03951515151515152, '5': 0.05236363636363636} | vidore/colqwen2-v0.1 | flatten | | vidore/colqwen2.5-v0.2_base | 17218 | 0 | 1.75875e+09 | {'runtime': 17218} | 0.0540356 | 0.694855 | {'1': 0.11903030303030304, '10': 0.7127272727272728, '20': 0.8366060606060606, '3': 0.336, '5': 0.5258181818181819} | vidore/colqwen2.5-v0.2 | base | | vidore/colqwen2.5-v0.2_rerank | 16859 | 0 | 1.75875e+09 | {'runtime': 16859} | 0.0518383 | 0.71693 | {'1': 0.0026666666666666666, '10': 0.025212121212121213, '20': 0.060848484848484846, '3': 0.006787878787878788, '5': 0.01187878787878788} | vidore/colqwen2.5-v0.2 | rerank | | vidore/colqwen2-v0.1_rerank | 9484 | 0 | 1.75875e+09 | {'runtime': 9484} | 0.0445599 | 0.691609 | {'1': 0.005333333333333333, '10': 0.030545454545454542, '20': 0.064, '3': 0.010666666666666666, '5': 0.017696969696969697} | vidore/colqwen2-v0.1 | rerank | | vidore/colSmol-256M_flatten | 6822 | 0 | 1.75875e+09 | {'runtime': 6822} | 0.0404544 | 0.00822329 | {'1': 0.01575757575757576, '10': 0.06836363636363636, '20': 0.10496969696969696, '3': 0.03442424242424243, '5': 0.04678787878787879} | vidore/colSmol-256M | flatten | | vidore/colSmol-500M_base | 12681 | 0 | 1.75875e+09 | {'runtime': 12681} | 0.0408026 | 0.850902 | {'1': 0.136, '10': 0.8029090909090909, '20': 0.8993939393939394, '3': 0.3806060606060606, '5': 0.5975757575757575} | vidore/colSmol-500M | base | | vidore/colSmol-500M_rerank | 13066 | 0 | 1.75876e+09 | {'runtime': 13066} | 0.0440974 | 0.927632 | {'1': 0.003636363636363637, '10': 0.028606060606060607, '20': 0.07054545454545455, '3': 0.00896969696969697, '5': 0.015030303030303033} | vidore/colSmol-500M | rerank | | vidore/colSmol-256M_rerank | 12646 | 0 | 1.75876e+09 | {'runtime': 12646} | 0.0391553 | 0.853279 | {'1': 0.003393939393939394, '10': 0.02909090909090909, '20': 0.07006060606060606, '3': 0.008727272727272728, '5': 0.015515151515151517} | vidore/colSmol-256M | rerank | | vidore/colqwen2.5-v0.2_flatten | 6348 | 0 | 1.75876e+09 | {'runtime': 6348} | 0.0509971 | 0.00772653 | {'1': 0.017696969696969697, '10': 0.06545454545454546, '20': 0.09284848484848485, '3': 0.03515151515151515, '5': 0.045575757575757575} | vidore/colqwen2.5-v0.2 | flatten | | vidore/colSmol-256M_base | 11554 | 0 | 1.75876e+09 | {'runtime': 11554} | 0.0366467 | 0.848463 | {'1': 0.1435151515151515, '10': 0.8426666666666667, '20': 0.9173333333333332, '3': 0.40824242424242424, '5': 0.6404848484848484} | vidore/colSmol-256M | base | | vidore/colSmol-500M_flatten | 6395 | 0 | 1.75876e+09 | {'runtime': 6395} | 0.0384664 | 0.00716238 | {'1': 0.018424242424242423, '10': 0.07345454545454545, '20': 0.11393939393939394, '3': 0.03903030303030303, '5': 0.05090909090909091} | vidore/colSmol-500M | flatten | | openai/clip-vit-base-patch32_base | 815 | 0 | 1.75876e+09 | {'runtime': 815} | 0.00533487 | 0.00794629 | {'1': 0.016, '10': 0.07636363636363637, '20': 0.11757575757575756, '3': 0.03296969696969697, '5': 0.04703030303030303} | openai/clip-vit-base-patch32 | base | | vidore/colqwen2-v0.1_max_pooling | 8758 | 0 | 1.7595e+09 | {'runtime': 8758} | 0.0985753 | 0.0106716 | {'1': 0.015515151515151517, '10': 0.07296969696969698, '20': 0.11248484848484848, '3': 0.032484848484848484, '5': 0.04703030303030303} | vidore/colqwen2-v0.1 | max_pooling | | vidore/colpali-v1.3_max_pooling | 4728 | 0 | 1.75949e+09 | {'runtime': 4728} | 0.0718573 | 0.0103053 | {'1': 0.011393939393939394, '10': 0.05672727272727273, '20': 0.08872727272727272, '3': 0.02666666666666667, '5': 0.03709090909090909} | vidore/colpali-v1.3 | max_pooling | | vidore/colqwen2-v1.0_max_pooling | 8760 | 0 | 1.7595e+09 | {'runtime': 8760} | 0.0981102 | 0.0106316 | {'1': 0.013575757575757576, '10': 0.06933333333333333, '20': 0.112, '3': 0.02812121212121212, '5': 0.041939393939393936} | vidore/colqwen2-v1.0 | max_pooling | | vidore/colqwen2-v0.1_max_pooling | 7696 | 0 | 1.7595e+09 | {'runtime': 7696} | 0.105203 | 0.011907 | {'1': 0.016242424242424242, '10': 0.07321212121212121, '20': 0.1132121212121212, '3': 0.03442424242424243, '5': 0.04945454545454545} | vidore/colqwen2-v0.1 | max_pooling | | vidore/colSmol-256M_max_pooling | 13982 | 0 | 1.75951e+09 | {'runtime': 13982} | 0.0999708 | 0.0121211 | {'1': 0.00993939393939394, '10': 0.05818181818181818, '20': 0.09187878787878788, '3': 0.025212121212121213, '5': 0.037575757575757575} | vidore/colSmol-256M | max_pooling | | vidore/colSmol-500M_max_pooling | 14191 | 0 | 1.75951e+09 | {'runtime': 14191} | 0.111858 | 0.0121703 | {'1': 0.012363636363636365, '10': 0.07539393939393939, '20': 0.13187878787878787, '3': 0.02787878787878788, '5': 0.0416969696969697} | vidore/colSmol-500M | max_pooling | | vidore/colqwen2-v0.1_hierarchical_pooling | 4507 | 0 | 1.7599e+09 | {'runtime': 4507} | 0.0320023 | 0.133653 | {'1': 0.1296969696969697, '10': 0.8504242424242424, '20': 0.9343030303030304, '3': 0.37527272727272726, '5': 0.6041212121212122} | vidore/colqwen2-v0.1 | hierarchical_pooling | | vidore/colpali-v1.3_hierarchical_pooling | 5816 | 0 | 1.7599e+09 | {'runtime': 5816} | 0.0217625 | 0.188727 | {'1': 0.10763636363636364, '10': 0.5372121212121213, '20': 0.6482424242424243, '3': 0.29333333333333333, '5': 0.4167272727272727} | vidore/colpali-v1.3 | hierarchical_pooling | | vidore/colqwen2.5-v0.2_hierarchical_pooling | 8430 | 0 | 1.75991e+09 | {'runtime': 8430} | 0.043073 | 0.141276 | {'1': 0.11103030303030303, '10': 0.6892121212121212, '20': 0.8203636363636364, '3': 0.3185454545454545, '5': 0.4989090909090909} | vidore/colqwen2.5-v0.2 | hierarchical_pooling | | vidore/colqwen2-v1.0_hierarchical_pooling | 5685 | 0 | 1.75991e+09 | {'runtime': 5685} | 0.0343824 | 0.144062 | {'1': 0.13745454545454547, '10': 0.822060606060606, '20': 0.9156363636363636, '3': 0.3856969696969697, '5': 0.6050909090909091} | vidore/colqwen2-v1.0 | hierarchical_pooling | ``` # Multi-vector search with XTR Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/multivector-xtr Represent a document with many vectors, and speed retrieval with ConteXtualized Token Retrieval. Covers [multi-vector search](/oss/v0-41-0/search/vector-search) enhanced by XTR (ConteXtualized Token Retriever): representing complex data with several vectors for more nuanced meaning, and using XTR to speed retrieval by prioritizing the most important tokens. For a comparison of retrieval strategies on a token-level benchmark, see [Needle in a haystack](/oss/v0-41-0/tutorials/search/multivector-needle-in-a-haystack). > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/multivector_xtr/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/multivector_xtr) > > Read the source. # NER-powered vector search Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/ner-search Extract named entities and embed them to sharpen retrieval. Uses Named Entity Recognition to power vector search. Extracting entities (people, places, organizations) and embedding them alongside the text improves accuracy when queries are about specific things rather than general topics. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/NER-powered-Semantic-Search/NER_powered_Semantic_Search_with_LanceDB.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/tutorials/NER-powered-Semantic-Search) > > Read the source. # Reddit concept summarizer Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/reddit-summarizer An end-to-end pipeline from Reddit text to embeddings to summarization and search. A complete pipeline: acquire text from Reddit, turn it into embeddings, store and manage those vectors in LanceDB, then build summarization and semantic search on top. Useful as a shape for any ingest-embed-serve workflow. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Reddit-summarization-and-search/subreddit_summarization_querying.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Reddit-summarization-and-search) > > Read the source. # Semantic result merging Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/vector-arithmetic Add and subtract embeddings to steer a query toward or away from a concept. Explores vector arithmetic: manipulating embeddings to capture relationships a single query vector cannot. Adding or subtracting the vector representation of a concept shifts the query, which makes searches more nuanced than a literal similarity lookup. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/Vector-Arithmetic-with-LanceDB/main.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/Vector-Arithmetic-with-LanceDB) > > Read the source. # Semantic search across videos Source: https://docs.lancedb.com/oss/v0-41-0/tutorials/search/video-search Embed video with V-JEPA and search it by similarity. Builds a video search application on V-JEPA (Video Joint Embedding Predictive Architecture). Generates vector embeddings for video content and uses [vector search](/oss/v0-41-0/search/vector-search) to find visually similar clips: a multimodal case where the searchable column is not text. > [!NOTE] > > This example is a runnable notebook in the > [vectordb-recipes](https://github.com/lancedb/vectordb-recipes) repository rather than a page here. > [card] [Open in Colab](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/examples/v-jepa-video-search/intra-video.ipynb) > > Run it end to end in the browser. > [card] [View on GitHub](https://github.com/lancedb/vectordb-recipes/tree/main/examples/v-jepa-video-search) > > Read the source. # REST API Reference Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/index API reference for LanceDB [Lance REST Namespace](https://lance.org/format/namespace/) spec is an OpenAPI protocol that enables reading, writing and managing Lance tables by connecting those metadata services or building a custom metadata server in a standardized way. LanceDB Embedded allows you to interface with Lance tables via the REST Namespace. LanceDB Enterprise provides an extended REST API with additional endpoints for managing tables and data. If you have specific needs or questions about the Enterprise REST API Namespace, please [contact us](mailto:support@lancedb.com). ## Authentication Enterprise All HTTP requests to LanceDB APIs must contain an x-api-key header that specifies a valid API key and must be encoded as JSON or Arrow RPC. To authenticate to the Enterprise REST API, you need the endpoint for your deployment and a valid API key for that deployment. ### Get your Enterprise credentials 1. Obtain the following values from your LanceDB administrator or the LanceDB team that provisioned your Enterprise deployment: * an API key * your Enterprise REST endpoint * your database name, if your deployment uses a private endpoint or `host_override` 2. Export those values in your terminal: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} export LANCEDB_API_KEY="<your-api-key>" export LANCEDB_HOST_OVERRIDE="https://your-enterprise-endpoint.com" export LANCEDB_DATABASE="your-database-name" ``` `LANCEDB_HOST_OVERRIDE` is the endpoint the SDKs take as `host_override`; the database name is the part of its `db://` URI after `db://`. 3. If your Enterprise deployment is private, connect through the private network endpoint provided for your deployment. For example, Azure Private Link deployments commonly use a private IP or an internal DNS name as the endpoint. ### Verify authentication 4. Check that you can reach the deployment and list tables: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X GET "$LANCEDB_HOST_OVERRIDE/v1/table/" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" ``` The response lists one page of table names, with a token for the next page when there are more. If your deployment endpoint already includes the database host name, you can omit the `x-lancedb-database` header. 5. Create a table to confirm write access. Let's call it `words`. A table is created from an Arrow IPC stream, which this writes with PyArrow: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} python -c "import pyarrow as pa, sys; t = pa.table({'word': ['hello', 'world']}); w = pa.ipc.new_stream(sys.stdout.buffer, t.schema); w.write_table(t); w.close()" > words.arrow curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \ -H "Content-Type: application/vnd.apache.arrow.stream" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ --data-binary @words.arrow ``` 6. Check that the table has been created: ```bash Bash icon="terminal" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/describe" \ -H "Content-Type: application/json" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ -d '{}' ``` That's it. You're connected! Now, you can start adding data and querying it. You can visit the tutorial section to build your own applications with LanceDB. > [card] [Tutorials](/oss/v0-41-0/tutorials/) > > Check out our tutorials on building various applications with LanceDB. # Create a materialized view Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/materializedview/create-a-materialized-view /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/materialized_view/{id}/create Create a materialized view at identifier `id`. The view may be query-backed, UDTF-backed, or chunker-backed, controlled by the `kind` discriminator. # Trigger an async materialized view refresh Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/materializedview/trigger-an-async-materialized-view-refresh /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/materialized_view/{id}/refresh Trigger an asynchronous refresh job for materialized view `id`. Returns a job ID for tracking. # Check if a namespace exists Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/check-if-a-namespace-exists /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/exists Check if namespace `id` exists. This operation must behave exactly like the DescribeNamespace API, except it does not contain a response body. REST NAMESPACE ONLY REST namespace conveys the result through the HTTP status code with no response body. The REST response maps to the `NamespaceExistsResponse` model as follows: - a `200` response means the namespace exists; a `404` response means it does not - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Create a new namespace Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/create-a-new-namespace /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/create Create new namespace `id`. During the creation process, the implementation may modify user-provided `properties`, such as adding additional properties like `created_at` to user-provided properties, omitting any specific property, or performing actions based on any property value. # Describe a namespace Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/describe-a-namespace /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/describe Describe the detailed information for namespace `id`. # Drop a namespace Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/drop-a-namespace /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/namespace/{id}/drop Drop namespace `id` from its parent namespace. # List namespaces Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/list-namespaces /oss/v0-41-0/api-reference/rest/openapi.yaml get /v1/namespace/{id}/list List all child namespace names of the parent namespace `id`. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListNamespacesRequest` information in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List tables in a namespace Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/namespace/list-tables-in-a-namespace /oss/v0-41-0/api-reference/rest/openapi.yaml get /v1/namespace/{id}/table/list List all child table names of the parent namespace `id`. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListTablesRequest` information in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `include_declared`: pass through query parameter of the same name # Add new columns to table schema Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/add-new-columns-to-table-schema /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/add_columns Add new columns to table `id` using SQL expressions or default values. # Analyze query execution plan Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/analyze-query-execution-plan /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/analyze_plan Analyze the query execution plan for a query against table `id`. Returns detailed statistics and analysis of the query execution plan. REST NAMESPACE ONLY REST namespace returns the response as a plain string instead of the `AnalyzeTableQueryPlanResponse` JSON object. # Atomically commit a batch of mixed table operations Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/atomically-commit-a-batch-of-mixed-table-operations /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/batch-commit Atomically commit a batch of table operations. This is a generalized version of `BatchCreateTableVersions` that supports mixed operation types within a single atomic transaction at the metadata layer. Supported operation types: - `DeclareTable`: Declare (reserve) a new table - `CreateTableVersion`: Create a new version entry for a table - `DeleteTableVersions`: Delete version ranges from a table - `DeregisterTable`: Deregister (soft-delete) a table All operations are committed atomically: either all succeed or none are applied. # Atomically create versions for multiple tables Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/atomically-create-versions-for-multiple-tables /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/version/batch-create Atomically create new version entries for multiple tables. This operation is atomic: either all table versions are created successfully, or none are created. If any version creation fails (e.g., due to conflict), the entire batch operation fails. Each entry in the request specifies the table identifier and version details. This supports `put_if_not_exists` semantics for each version entry. # Check if a table exists Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/check-if-a-table-exists /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/exists Check if table `id` exists. This operation should behave exactly like DescribeTable, except it does not contain a response body. REST NAMESPACE ONLY REST namespace conveys the result through the HTTP status code with no response body. The REST response maps to the `TableExistsResponse` model as follows: - a `200` response means the table exists; a `404` response means it does not - response headers map to `context` via the `header.` prefix (see the `Context` schema) For DirectoryNamespace implementation, a table exists if either: - The table has Lance data versions (regular table created with CreateTable) - A `.lance-reserved` file exists in the table directory (declared table created with DeclareTable) # Count rows in a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/count-rows-in-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/count_rows Count the number of rows in table `id` REST NAMESPACE ONLY REST namespace returns the response as a plain integer instead of the `CountTableRowsResponse` JSON object. The REST response maps to the `CountTableRowsResponse` model as follows: - the integer response body maps to `count` - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Create a new branch Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-a-new-branch /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/create Create a new branch for table `id` starting from a source ref (another branch and/or version), defaulting to the latest version of the main branch. # Create a new table version Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-a-new-table-version /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/create Create a new version entry for table `id`. This operation supports `put_if_not_exists` semantics. The operation will fail with 409 Conflict if the version already exists. # Create a new tag Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-a-new-tag /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/create Create a new tag for table `id` that points to a specific version. # Create a scalar index on a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-a-scalar-index-on-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create_scalar_index Create a scalar index on a table field for faster filtering operations. Supports scalar indexes (BTREE, BITMAP, LABEL_LIST, FTS, etc.). This is an alias for CreateTableIndex specifically for scalar indexes. Index creation is handled asynchronously. Use the `ListTableIndices` and `DescribeTableIndexStats` operations to monitor index creation progress. # Create a table with the given name Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-a-table-with-the-given-name /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create Create table `id` in the namespace with the given data in Arrow IPC stream. The schema of the Arrow IPC stream is used as the table schema. If the stream is empty, the API creates a new empty table. REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `CreateTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `mode`: pass through query parameter of the same name - `properties`: serialize as a single JSON-encoded query parameter such as `properties={"user":"alice","team":"eng"}`; these are business logic properties managed by the namespace implementation outside Lance context - `storage_options`: serialize as a single JSON-encoded query parameter such as `storage_options={"aws_region":"us-east-1","timeout":"30s"}`; these configure write-time overrides for data and metadata written during table creation # Create an index on a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/create-an-index-on-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/create_index Create an index on a table field for faster search operations. Supports vector indexes (IVF_FLAT, IVF_HNSW_SQ, IVF_PQ, etc.) and scalar indexes (BTREE, BITMAP, FTS, etc.). Index creation is handled asynchronously. Use the `ListTableIndices` and `DescribeTableIndexStats` operations to monitor index creation progress. # Declare a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/declare-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/declare Declare a table with the given name without touching storage. This is a metadata-only operation that records the table existence and sets up aspects like access control. For DirectoryNamespace implementation, this creates a `.lance-reserved` file in the table directory to mark the table's existence without creating actual Lance data files. # Delete a branch Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/delete-a-branch /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/delete Delete an existing branch from table `id`. # Delete a tag Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/delete-a-tag /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/delete Delete an existing tag from table `id`. # Delete rows from a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/delete-rows-from-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/delete Delete rows from table `id`. # Delete table version records Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/delete-table-version-records /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/delete Delete version metadata records for table `id`. This operation deletes version tracking records, NOT the actual table data. It supports deleting ranges of versions for efficient bulk cleanup. Special range values: - `start_version: 0` with `end_version: -1` means delete ALL version records # Deregister a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/deregister-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/deregister Deregister table `id` from its namespace. # Describe a specific table version Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/describe-a-specific-table-version /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/describe Describe the detailed information for a specific version of table `id`. Returns the manifest path and metadata for the specified version. # Describe information of a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/describe-information-of-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/describe Describe the detailed information for table `id`. REST NAMESPACE ONLY REST namespace passes `with_table_uri`, `load_detailed_metadata`, and `check_declared` as query parameters instead of in the request body. # Drop a specific index Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/drop-a-specific-index /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/{index_name}/drop Drop the specified index from table `id`. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `DropTableIndexRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `index_name`: pass through path parameter of the same name # Drop a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/drop-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/drop Drop table `id` and delete its data. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `DropTableRequest` information is passed in the following way: - `id`: pass through path parameter of the same name # Get query execution plan explanation Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/get-query-execution-plan-explanation /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/explain_plan Get the query execution plan for a query against table `id`. Returns a human-readable explanation of how the query will be executed. REST NAMESPACE ONLY REST namespace returns the response as a plain string instead of the `ExplainTableQueryPlanResponse` JSON object. # Get table index statistics Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/get-table-index-statistics /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/{index_name}/stats Get statistics for a specific index on a table. Returns information about the index type, distance type (for vector indices), and row counts. # Get table statistics Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/get-table-statistics /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/stats Get statistics for table `id`, including row counts, data sizes, and column statistics. # Get version for a specific tag Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/get-version-for-a-specific-tag /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/version Get the version number that a specific tag points to for table `id`. # Insert records into a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/insert-records-into-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/insert Insert new records into table `id`. For tables that have been declared but not yet created on storage (is_only_declared=true), this operation will create the table with the provided data. REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `InsertIntoTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `mode`: pass through query parameter of the same name # List all branches for a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/list-all-branches-for-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/branches/list List all branches that have been created for table `id`. Returns a map of branch names to their contents. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableBranchesRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List all tables Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/list-all-tables /oss/v0-41-0/api-reference/rest/openapi.yaml get /v1/table List all tables across all namespaces. REST NAMESPACE ONLY REST namespace uses GET to perform this operation without a request body. It passes in the `ListAllTablesRequest` information in the following way: - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `delimiter`: pass through query parameter of the same name - `include_declared`: pass through query parameter of the same name # List all tags for a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/list-all-tags-for-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/list List all tags that have been created for table `id`. Returns a map of tag names to their corresponding version numbers and metadata. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableTagsRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name # List all versions of a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/list-all-versions-of-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/version/list List all versions (commits) of table `id` with their metadata. Use `descending=true` to guarantee versions are returned in descending order (latest to oldest). Otherwise, the ordering is implementation-defined. REST NAMESPACE ONLY REST namespace does not use a request body for this operation. The `ListTableVersionsRequest` information is passed in the following way: - `id`: pass through path parameter of the same name - `page_token`: pass through query parameter of the same name - `limit`: pass through query parameter of the same name - `descending`: pass through query parameter of the same name # List indexes on a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/list-indexes-on-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/index/list List all indices created on a table. Returns information about each index including name, columns, status, and UUID. # Merge insert (upsert) records into a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/merge-insert-upsert-records-into-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/merge_insert Performs a merge insert (upsert) operation on table `id`. This operation updates existing rows based on one or more matching columns and inserts new rows that don't match. It returns the number of rows inserted and updated. For tables that have been declared but not yet created on storage (is_only_declared=true), this operation will create the table with the provided data (since there are no existing rows to merge with). REST NAMESPACE ONLY REST namespace uses Arrow IPC stream as the request body. It passes in the `MergeInsertIntoTableRequest` information in the following way: - `id`: pass through path parameter of the same name - `on`: pass through query parameter of the same name, repeated once per field path - `when_matched_update_all`: pass through query parameter of the same name - `when_matched_update_all_filt`: pass through query parameter of the same name - `when_not_matched_insert_all`: pass through query parameter of the same name - `when_not_matched_by_source_delete`: pass through query parameter of the same name - `when_not_matched_by_source_delete_filt`: pass through query parameter of the same name # Modify existing columns Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/modify-existing-columns /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/alter_columns Modify existing columns in table `id`, such as renaming or changing data types. # Query a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/query-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/query Query table `id` with vector search, full text search and optional SQL filtering. Returns results in Arrow IPC file or stream format. REST NAMESPACE ONLY REST namespace returns the response as Arrow IPC file binary data instead of the `QueryTableResponse` JSON object. The REST response maps to the `QueryTableResponse` model as follows: - the Arrow IPC file binary body maps to `data` - response headers map to `context` via the `header.` prefix (see the `Context` schema) # Register a table to a namespace Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/register-a-table-to-a-namespace /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/register Register an existing table at a given storage location as `id`. # Remove columns from table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/remove-columns-from-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/drop_columns Remove specified columns from table `id`. # Rename a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/rename-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/rename Rename table `id` to a new name. # Restore table to a specific version Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/restore-table-to-a-specific-version /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/restore Restore table `id` to a specific version. # Trigger an async column backfill job Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/trigger-an-async-column-backfill-job /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/backfill_column Trigger an asynchronous backfill job for a computed column on table `id`. The column must be a virtual (UDF-backed) column or a computed column declared with an expression binding. Returns a job ID for tracking. # Update a tag to point to a different version Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/update-a-tag-to-point-to-a-different-version /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/tags/update Update an existing tag for table `id` to point to a different version. # Update per-field metadata Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/update-per-field-metadata /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/update_field_metadata Update the Arrow field (column) metadata for table `id`. Each entry targets a field by `path` and merges the provided key-value pairs into that field's existing metadata, or replaces it when `replace` is true. A null metadata value deletes that key. # Update rows in a table Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/update-rows-in-a-table /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/update Update existing rows in table `id`. # Update table schema metadata Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/table/update-table-schema-metadata /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/table/{id}/schema_metadata/update Replace the schema metadata for table `id` with the provided key-value pairs. REST NAMESPACE ONLY REST namespace uses a direct object (map of string to string) as both request and response body instead of the wrapped `UpdateTableSchemaMetadataRequest` and `UpdateTableSchemaMetadataResponse`. # Alter information of a transaction. Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/transaction/alter-information-of-a-transaction /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/transaction/{id}/alter Alter a transaction with a list of actions such as setting status or properties. The server should either succeed and apply all actions, or fail and apply no action. # Describe information about a transaction Source: https://docs.lancedb.com/oss/v0-41-0/api-reference/rest/transaction/describe-information-about-a-transaction /oss/v0-41-0/api-reference/rest/openapi.yaml post /v1/transaction/{id}/describe Return a detailed information for a given transaction # ADE20K Source: https://docs.lancedb.com/oss/v0-41-0/datasets/ade20k A Lance-formatted version of the full ADE20K scene parsing benchmark, sourced from 1aurent/ADE20K. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/ade20k-lance) > > Source dataset card and downloadable files for `lance-format/ade20k-lance`. Each row is one scene image with its inline JPEG bytes, a per-pixel semantic segmentation map encoded as PNG bytes, an optional instance map, scene class labels, the full per-polygon object-name list, an OpenCLIP image embedding, and pre-built indices — all available directly from the Hub at `hf://datasets/lance-format/ade20k-lance/data`. ## Key features * **Inline image and segmentation bytes** — both the JPEG image and the RGB-encoded PNG segmentation map ride on the same row, so an annotated example is a single row read with no sidecar files. * **Per-polygon object metadata** — `object_names` keeps the full list (one entry per annotated polygon), `objects_present` is the deduped set used for class-presence filters, and `num_objects` is precomputed. * **CLIP image embeddings** (`image_emb`, OpenCLIP ViT-B/32, 512-d, cosine-normalized) for visual retrieval over scenes. * **Indices shipped on disk** — `IVF_PQ` on `image_emb`, `BTREE` on `num_objects`, and `LABEL_LIST` on `objects_present` for fast `array_has_any` / `array_has_all` predicates. ## Splits | Split | Rows | | - | - | | `train.lance` | 25,574 | | `validation.lance` | 2,000 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `segmentation` | `large_binary` | Inline PNG bytes — semantic segmentation map (RGB encoding per ADE20K spec) | | `instance` | `large_binary?` | Inline PNG bytes — instance map; null if not provided | | `filename` | `string` | ADE20K relative filename | | `scene` | `list<string>` | Scene class labels (e.g. `["bathroom"]`) | | `object_names` | `list<string>` | Per-polygon object names (one entry per polygon, not deduped) | | `objects_present` | `list<string>` | Deduped object names — feeds the `LABEL_LIST` index | | `num_objects` | `int32` | Number of annotated objects | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP ViT-B/32 image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `num_objects` — fast range filters on scene complexity * `LABEL_LIST` on `objects_present` — supports `array_has_any` / `array_has_all` for class-presence filtering ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/ade20k-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["filename"], row["scene"], row["num_objects"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and any mutation are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/ade20k-lance --repo-type dataset --local-dir ./ade20k-lance > ``` > > Then point LanceDB at `./ade20k-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor scene retrieval a single call. In production you would encode a query image through the same OpenCLIP ViT-B/32 model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored on row 42 as a runnable stand-in, so the snippet works without loading any model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "filename", "scene"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["filename", "scene", "objects_present"]) .limit(10) .to_list() ) print("query scene:", seed["scene"]) for r in hits: print(f" {r['filename']} scene={r['scene']} objs={r['objects_present'][:5]}") ``` Because the embeddings are cosine-normalized, the first hit will typically be the source image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate Curation for a semantic-segmentation workflow usually means picking scenes that contain specific classes, possibly bounded by complexity. The `LABEL_LIST` index on `objects_present` makes class-presence predicates trivial, and Lance evaluates them inside the same scan as a structural filter on `num_objects`. The bounded `.limit(500)` keeps the result small and inspectable, and the `segmentation` blob is left out of the projection so the candidate scan is dominated by metadata, not PNG bytes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "array_has_all(objects_present, ['bed', 'window']) AND num_objects >= 8", prefilter=True, ) .select(["id", "filename", "scene", "objects_present", "num_objects"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first scene: {candidates[0]['scene']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. Swapping `array_has_all` for `array_has_any` widens the recall; replacing the structural predicate with `num_objects BETWEEN 3 AND 6` selects simpler scenes for an ablation slice. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `has_person` flag and a `scene_label` string pulled out of the `scene` list, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./ade20k-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "has_person": "array_has_any(objects_present, ['person'])", "scene_label": "element_at(scene, 1)", "complexity_bucket": "CASE WHEN num_objects < 5 THEN 'sparse' " "WHEN num_objects < 15 THEN 'medium' ELSE 'dense' END", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline panoptic ids, predictions from a baseline segmenter, a second-pass embedding), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "baseline_miou": pa.array([0.41, 0.55, 0.62]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., re-running a segmentation model over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a semantic-segmentation run, project the JPEG bytes and the segmentation PNG bytes; both are decoded inside the training step. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "segmentation"]) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) for batch in loader: # batch carries only the JPEG and PNG byte columns; decode both, # remap the ADE20K RGB-encoded mask to class ids, forward, loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "objects_present"]` to `select_columns(...)` on the next run skips JPEG and PNG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight scene classifier or a class-presence probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./ade20k-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("segmenter-baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="segmenter-baseline-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A serving pipeline locked to `segmenter-baseline-v1` keeps reading the exact same segmentation maps and class lists while the dataset evolves in parallel; newly merged predictions or evolved columns do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, so changes in mIoU reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/ade20k-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(objects_present, ['bed', 'sofa', 'chair']) AND num_objects >= 5") .select(["id", "image", "segmentation", "filename", "scene", "objects_present", "num_objects", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./ade20k-indoor-subset") local_db.create_table("train", batches) ``` The resulting `./ade20k-indoor-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/ade20k-lance/data` for `./ade20k-indoor-subset`. ## Source & license Converted from [`1aurent/ADE20K`](https://huggingface.co/datasets/1aurent/ADE20K). Review the MIT CSAIL [ADE20K Terms of Use](https://ade20k.csail.mit.edu/terms/): images are available for non-commercial research and educational use, while the software and annotations are covered by the BSD 3-Clause license. ## Citation ``` @inproceedings{zhou2017scene, title={Scene Parsing through ADE20K Dataset}, author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio}, booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2017} } ``` # ChartQA Source: https://docs.lancedb.com/oss/v0-41-0/datasets/chartqa A Lance-formatted version of ChartQA, a benchmark for question answering over scientific and business charts that demands a mix of logical and visual reasoning, redistributed via lmms-lab/ChartQA. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/chartqa-lance) > > Source dataset card and downloadable files for `lance-format/chartqa-lance`. Each row carries the chart image as inline JPEG bytes, the natural-language question and reference answer(s), a question-type tag (`human` vs `augmented`), and paired CLIP embeddings for the image and the question — all available directly from the Hub at `hf://datasets/lance-format/chartqa-lance/data`. ## Key features * **Inline chart image bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (ViT-B/32, 512-dim, cosine-normalized) — so visual and textual retrieval are one indexed lookup. * **All reference answers preserved in `answers`** alongside a canonical `answer` string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the question and answer strings, and the `type` tag. ## Splits | Split | Rows | Notes | | - | - | - | | `test.lance` | 2,500 | Public test slice from `lmms-lab/ChartQA` | > The `lmms-lab/ChartQA` redistribution exposes the test split only. Train and validation live in the original ChartQA release; extend `chartqa/dataprep.py` with additional sources to add them. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string?` | Source does not assign explicit ids — null | | `question_id` | `string?` | Source does not assign explicit ids — null | | `question` | `string` | Natural-language question | | `answers` | `list<string>` | Reference answer(s), typically a single string | | `answer` | `string` | First reference answer — canonical, used for FTS | | `type` | `string?` | Question type (`human` vs `augmented`) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BITMAP` on `type` — fast filtering by question type ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/chartqa-lance", split="test", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/chartqa-lance --repo-type dataset --local-dir ./chartqa-lance > ``` > > Then point LanceDB at `./chartqa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes question-to-question retrieval a single call: encode a query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question", "answer", "type"]) .limit(10) .to_list() ) print("query:", seed["question"]) for r in hits: print(f" [{r['type']}] {r['question'][:70]} -> {r['answer']}") ``` Swap `vector_column_name="question_emb"` for `image_emb` to do question-to-chart retrieval against the visual embedding instead — useful for finding charts whose layout is similar to a given prompt encoding. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "percentage" or "highest bar" must literally appear in the question but you still want CLIP to do the heavy lifting on semantic similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="question_emb") .vector(seed["question_emb"]) .text("percentage") .select(["question", "answer", "type"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" [{r['type']}] {r['question'][:70]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass combines a content predicate on the question text with a structural predicate on the question-type tag. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. The example below collects human-authored questions that mention a percentage, which is a common slice for evaluating numeric-reasoning behaviour. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") candidates = ( tbl.search("percentage OR percent") .where("type = 'human'", prefilter=True) .select(["id", "question", "answer", "type"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question and answer text rather than chart JPEGs. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `answer_length`, an `is_yes_no` flag, and an `is_numeric` flag, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./chartqa-lance/data") # local copy required for writes tbl = db.open_table("test") tbl.add_columns({ "answer_length": "length(answer)", "is_yes_no": "lower(answer) IN ('yes', 'no')", "is_numeric": "regexp_match(answer, '^-?[0-9]+(\\.[0-9]+)?%?$') IS NOT NULL", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (model predictions on the test set, reasoning-chain annotations, a difficulty score), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2]), "pred_answer": pa.array(["12%", "Yes", "34"]), "is_correct": pa.array([True, True, False]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a chart-OCR model over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For fine-tuning a VLM on chart QA, project the chart bytes plus the question and answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question/answer pair, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight answer-classifier or a linear probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") tbl = db.open_table("test") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./chartqa-lance/data") local_tbl = local_db.open_table("test") local_tbl.tags.create("eval-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("test", version="eval-v1") tbl_v5 = db.open_table("test", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `eval-v1` keeps producing comparable scores while the dataset evolves in parallel — newly added prediction columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same charts and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/chartqa-lance/data") remote_tbl = remote_db.open_table("test") batches = ( remote_tbl.search("percentage OR percent") .where("type = 'human'") .select(["id", "image", "question", "answer", "type", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./chartqa-human-subset") local_db.create_table("test", batches) ``` The resulting `./chartqa-human-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/chartqa-lance/data` for `./chartqa-human-subset`. ## Source & license Converted from [`lmms-lab/ChartQA`](https://huggingface.co/datasets/lmms-lab/ChartQA). The original ChartQA dataset is released under the GNU GPL-3.0 license by Masry et al. ## Citation ``` @inproceedings{masry2022chartqa, title={ChartQA: A Benchmark for Question Answering about Charts with Visual and Logical Reasoning}, author={Masry, Ahmed and Long, Do Xuan and Tan, Jia Qing and Joty, Shafiq and Hoque, Enamul}, booktitle={Findings of the Association for Computational Linguistics: ACL 2022}, year={2022} } ``` # COCO Captions 2017 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/coco-captions-2017 A Lance-formatted version of the COCO Captions 2017 corpus, redistributed via lmms-lab/COCO-Caption2017. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/coco-captions-2017-lance) > > Source dataset card and downloadable files for `lance-format/coco-captions-2017-lance`. Each row is one image with **5–7 human-written captions**, a cosine-normalized CLIP image embedding, and a cosine-normalized CLIP text embedding of the canonical caption — all stored inline and available directly from the Hub at `hf://datasets/lance-format/coco-captions-2017-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `text_emb` (ViT-B/32, 512-dim, cosine-normalized) — so cross-modal retrieval is one indexed lookup. * **All 5–7 raw captions kept in `captions`** alongside a `caption` canonical string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the canonical caption, and `image_id`. ## Splits | Split | Rows | Notes | | - | - | - | | `val.lance` | 5,000 | Canonical COCO 2017 val set | | `test.lance` | 40,700 | Public test slice from `lmms-lab/COCO-Caption2017` | > The 2017 train split (118 k images, \~18 GB of source JPEGs) is intentionally not bundled here because the `lmms-lab/COCO-Caption2017` redistribution does not include it. To extend with train, run `coco_captions_2017/dataprep.py` against your local COCO 2017 train mirror. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string` | COCO image id | | `filename` | `string` | Original filename (e.g. `000000179765.jpg`) | | `captions` | `list<string>` | All 5–7 captions for the image | | `caption` | `string` | First caption — canonical text used for FTS | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `text_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `caption` — keyword and hybrid search * `BTREE` on `image_id` — fast lookup by COCO image id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/coco-captions-2017-lance", split="val", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/coco-captions-2017-lance --repo-type dataset --local-dir ./coco-captions-2017-lance > ``` > > Then point LanceDB at `./coco-captions-2017-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a text query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `text_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a caption", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") seed = ( tbl.search() .select(["text_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "caption"]) .limit(10) .to_list() ) print("query caption:", seed["caption"]) for r in hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Because OpenAI-style CLIP embeddings are normalized, cosine is the right metric and the first hit will typically be the source image itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `text_emb` to do text→text retrieval against the canonical captions instead. Because the dataset also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "yellow taxi" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["text_emb"]) .text("a man riding a surfboard") .select(["image_id", "caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a captioning or contrastive-training workflow combines a content filter on the captions with a structural filter on the image. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") candidates = ( tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) >= 5", prefilter=True) .select(["image_id", "caption", "captions"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first caption: {candidates[0]['caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by caption text rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `num_captions` and a `long_caption` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./coco-captions-2017-lance/data") # local copy required for writes tbl = db.open_table("val") tbl.add_columns({ "num_captions": "array_length(captions)", "long_caption": "length(caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, a second-pass caption from a different model), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "image_id": pa.array(["179765", "000139"]), "scene_label": pa.array(["beach", "kitchen"]), }) tbl.add_columns([f for f in labels.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second CLIP variant over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a CLIP-style contrastive run, project the JPEG bytes and a sampled caption; for a reranker or probe on top of frozen features, project the precomputed embeddings instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the captions, encode, contrastive loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "text_emb"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") tbl = db.open_table("val") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./coco-captions-2017-lance/data") local_tbl = local_db.open_table("val") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("val", version="clip-vitb32-v1") tbl_v5 = db.open_table("val", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and captions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/coco-captions-2017-lance/data") remote_tbl = remote_db.open_table("test") batches = ( remote_tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) >= 5") .select(["image_id", "image", "caption", "captions", "image_emb", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./coco-surf-subset") local_db.create_table("train", batches) ``` The resulting `./coco-surf-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/coco-captions-2017-lance/data` for `./coco-surf-subset`. ## Source & license Converted from [`lmms-lab/COCO-Caption2017`](https://huggingface.co/datasets/lmms-lab/COCO-Caption2017). Original COCO 2017 annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the underlying images are subject to Flickr terms of service. Please review the [COCO Terms of Use](https://cocodataset.org/#termsofuse) before redistribution. ## Citation ``` @inproceedings{lin2014microsoft, title={Microsoft COCO: Common objects in context}, author={Lin, Tsung-Yi and Maire, Michael and Belongie, Serge and Hays, James and Perona, Pietro and Ramanan, Deva and Doll{\'a}r, Piotr and Zitnick, C Lawrence}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # COCO 2017 Detection Source: https://docs.lancedb.com/oss/v0-41-0/datasets/coco-detection-2017 A Lance-formatted version of the COCO 2017 object detection benchmark, sourced from detection-datasets/coco. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/coco-detection-2017-lance) > > Source dataset card and downloadable files for `lance-format/coco-detection-2017-lance`. Each row is one image with its inline JPEG bytes, the full per-image list of bounding boxes, COCO 80-class category ids and names, per-object areas, an OpenCLIP image embedding, and pre-built indices — all available directly from the Hub at `hf://datasets/lance-format/coco-detection-2017-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Per-object annotations as parallel list columns** — `bboxes`, `categories`, `category_names`, and `areas` are aligned position-for-position, so iterating boxes alongside their labels is a single row read. * **Pre-aggregated annotation summaries** — `num_objects` (int) and `categories_present` (deduped string list) precompute the predicates curation queries hit most. * **CLIP image embeddings** (`image_emb`, OpenCLIP ViT-B/32, 512-d, cosine-normalized) with a bundled `IVF_PQ` index for visual retrieval. ## Splits | Split | Rows | | - | - | | `train.lance` | 117,000+ | | `val.lance` | 4,950+ | Total annotated boxes: \~860k train / \~37k val. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `int64` | COCO image id (natural join key) | | `width`, `height` | `int32` | Image dimensions in pixels | | `bboxes` | `list<list<float32, 4>>` | Each box is `[x_min, y_min, x_max, y_max]` in absolute pixel coordinates | | `categories` | `list<int32>` | COCO 80-class id (0–79), aligned with `bboxes` | | `category_names` | `list<string>` | Human-readable class name per object (e.g. `person`, `dog`) | | `areas` | `list<float32>` | Bounding-box area in pixels², aligned with `bboxes` | | `num_objects` | `int32` | Number of annotated objects in the image | | `categories_present` | `list<string>` | Deduped class names — feeds the `LABEL_LIST` index | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP ViT-B/32 image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `image_id` — fast lookup by COCO image id * `BTREE` on `num_objects` — range filters on image complexity * `LABEL_LIST` on `categories_present` — supports `array_has_any` / `array_has_all` for class-presence filtering ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/coco-detection-2017-lance", split="val", streaming=True) for row in hf_ds.take(3): print(row["image_id"], row["num_objects"], row["categories_present"][:5]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and any mutation are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/coco-detection-2017-lance --repo-type dataset --local-dir ./coco-detection-2017-lance > ``` > > Then point LanceDB at `./coco-detection-2017-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor visual retrieval a single call. In production you would encode a query image through the same OpenCLIP ViT-B/32 model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored on row 42 as a runnable stand-in, so the snippet works without loading any model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") seed = ( tbl.search() .select(["image_emb", "image_id", "categories_present"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["image_id", "categories_present", "num_objects"]) .limit(10) .to_list() ) print("query categories:", seed["categories_present"]) for r in hits: print(f" image_id={r['image_id']:>10} n={r['num_objects']:>3} cats={r['categories_present'][:5]}") ``` Because the embeddings are cosine-normalized, the first hit will typically be the source image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate Curation for a detection workflow usually means picking images that contain a specific class combination, possibly bounded by scene complexity. The `LABEL_LIST` index on `categories_present` makes class-presence predicates trivial, and Lance evaluates them inside the same scan as range filters on `num_objects` or `width`/`height`. The bounded `.limit(500)` keeps the result small and inspectable, and the `image` column is left out of the projection so the candidate scan is dominated by annotation metadata, not JPEG bytes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") candidates = ( tbl.search() .where( "array_has_all(categories_present, ['person', 'frisbee']) " "AND num_objects BETWEEN 3 AND 12", prefilter=True, ) .select(["image_id", "categories_present", "num_objects", "width", "height"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first image_id: {candidates[0]['image_id']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. Swapping `array_has_all` for `array_has_any` widens recall to images containing any of the listed classes; replacing the structural predicate with `num_objects >= 10` selects busy scenes for crowd-detection ablations. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `has_person` flag, an `aspect_ratio`, and a `max_box_area` that surfaces the largest annotated object area per image — all of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./coco-detection-2017-lance/data") # local copy required for writes tbl = db.open_table("val") tbl.add_columns({ "has_person": "array_has_any(categories_present, ['person'])", "aspect_ratio": "CAST(width AS DOUBLE) / CAST(height AS DOUBLE)", "max_box_area": "array_max(areas)", "crowded": "num_objects >= 10", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline predictions from a baseline detector, per-image difficulty scores, or a second-pass embedding), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "image_id": pa.array([397133, 37777, 252219], type=pa.int64()), "baseline_map": pa.array([0.31, 0.48, 0.22]), }) tbl.add_columns([f for f in predictions.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second detector over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a detector training run, project the JPEG bytes alongside the parallel annotation columns the loss consumes — boxes, category ids, and (optionally) areas. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["image", "bboxes", "categories", "areas"] ) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4, collate_fn=lambda b: b) # detection targets are ragged for batch in loader: # batch is a list of dicts: decode each JPEG, stack the bboxes / categories # into the target dictionary your detector expects, forward, loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "categories_present"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight multi-label classifier or a class-presence probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") tbl = db.open_table("val") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./coco-detection-2017-lance/data") local_tbl = local_db.open_table("val") local_tbl.tags.create("detector-baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("val", version="detector-baseline-v1") tbl_v5 = db.open_table("val", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `detector-baseline-v1` keeps scoring against the exact same boxes and category ids while the dataset evolves in parallel; newly merged predictions or evolved columns do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and annotations, so changes in mAP reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/coco-detection-2017-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(categories_present, ['dog', 'cat']) AND num_objects >= 2") .select(["image_id", "image", "bboxes", "categories", "category_names", "areas", "num_objects", "categories_present", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./coco-pets-subset") local_db.create_table("train", batches) ``` The resulting `./coco-pets-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/coco-detection-2017-lance/data` for `./coco-pets-subset`. ## Source & license Converted from [`detection-datasets/coco`](https://huggingface.co/datasets/detection-datasets/coco). COCO annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the underlying images are subject to Flickr terms of service. See the [COCO Terms of Use](https://cocodataset.org/#termsofuse) before redistribution. ## Citation ``` @inproceedings{lin2014microsoft, title={Microsoft COCO: Common objects in context}, author={Lin, Tsung-Yi and Maire, Michael and Belongie, Serge and Hays, James and Perona, Pietro and Ramanan, Deva and Doll{\'a}r, Piotr and Zitnick, C Lawrence}, booktitle={European Conference on Computer Vision (ECCV)}, year={2014} } ``` # DocVQA Source: https://docs.lancedb.com/oss/v0-41-0/datasets/docvqa A Lance-formatted version of DocVQA, a benchmark for visual question answering over document images such as industry and government scans, multi-page reports, forms, and receipts, redistributed via lmms-lab/DocVQA (DocVQA config). > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/docvqa-lance) > > Source dataset card and downloadable files for `lance-format/docvqa-lance`. Each row carries the page image as inline JPEG bytes, the question and reference answer span(s), the original DocVQA question-type tags, UCSF Industry Documents Library provenance, and paired CLIP embeddings for the image and the question — all available directly from the Hub at `hf://datasets/lance-format/docvqa-lance/data`. ## Key features * **Inline page image bytes** in the `image` column — no sidecar files, no document folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (ViT-B/32, 512-dim, cosine-normalized) — so visual and textual retrieval are one indexed lookup. * **All reference answer spans preserved in `answers`** alongside a canonical `answer` string used for full-text search. * **Pre-built ANN, FTS, scalar, and label-list indices** covering both embedding columns, the question and answer text, the document ids, and the `question_types` tag list. ## Splits | Split | Rows | Notes | | - | - | - | | `validation.lance` | 5,349 | Canonical DocVQA validation set | | `test.lance` | 5,188 | Public test slice from `lmms-lab/DocVQA` | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes (page image) | | `image_id` | `string?` | DocVQA `docId` (alias of `doc_id`) | | `question_id` | `string?` | DocVQA `questionId` | | `question` | `string` | Natural-language question | | `answers` | `list<string>` | Reference answer span(s) | | `answer` | `string` | First reference answer — canonical, used for FTS | | `doc_id` | `string?` | DocVQA document id | | `ucsf_document_id` | `string?` | UCSF Industry Documents Library id | | `ucsf_document_page_no` | `string?` | Page number within the source document | | `data_split` | `string?` | Original split label from the source | | `question_types` | `list<string>` | DocVQA question-type tags (`form`, `figure`, `table`, …) | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BTREE` on `image_id`, `question_id`, `doc_id` — fast lookup by document or question id * `LABEL_LIST` on `question_types` — set-membership filtering over question-type tags ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/docvqa-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/docvqa-lance --repo-type dataset --local-dir ./docvqa-lance > ``` > > Then point LanceDB at `./docvqa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes question-to-question retrieval a single call: encode a query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question_id", "question", "answer", "question_types"]) .limit(10) .to_list() ) print("query:", seed["question"]) for r in hits: print(f" {r['question_id']:>8} {r['question'][:60]} -> {r['answer']}") ``` Swap `vector_column_name="question_emb"` for `image_emb` to retrieve pages whose visual layout is similar to a given embedding — useful when you want to find other forms or invoices that look like a seed page. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "invoice total" or "date of birth" must literally appear in the question but you still want CLIP to do the heavy lifting on semantic similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="question_emb") .vector(seed["question_emb"]) .text("invoice total") .select(["question_id", "question", "answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['question_id']:>8} {r['question'][:60]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a document-VQA workflow combines a content filter on the question with a structural filter on the question-type tags. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. The example below collects form-style questions that mention a date, which is a common slice for evaluating form-understanding behaviour. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search("date") .where("array_has_any(question_types, ['form'])", prefilter=True) .select(["question_id", "doc_id", "question", "answer", "question_types"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question and answer text rather than page JPEGs. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `answer_length`, an `is_form_question` flag, and a `has_table` flag, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./docvqa-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "answer_length": "length(answer)", "is_form_question": "array_has_any(question_types, ['form'])", "has_table": "array_has_any(question_types, ['table/list'])", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (OCR-extracted page text, model predictions, layout-detector outputs), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["49153", "49154", "49155"]), "pred_answer": pa.array(["$1,234.56", "John Doe", "2018-04-12"]), "is_correct": pa.array([True, True, False]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running OCR or a layout model over the page bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For fine-tuning a document-VLM, project the page bytes plus the question and answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question/answer pair, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight answer-classifier or a linear probe on top of frozen features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./docvqa-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("eval-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="eval-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `eval-v1` keeps producing comparable scores while the dataset evolves in parallel — newly added prediction columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same pages and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/docvqa-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search("date") .where("array_has_any(question_types, ['form'])") .select(["id", "image", "question_id", "doc_id", "question", "answer", "question_types", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./docvqa-forms-subset") local_db.create_table("validation", batches) ``` The resulting `./docvqa-forms-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/docvqa-lance/data` for `./docvqa-forms-subset`. ## Source & license Converted from [`lmms-lab/DocVQA`](https://huggingface.co/datasets/lmms-lab/DocVQA). DocVQA is released under the MIT license; the underlying documents come from the [UCSF Industry Documents Library](https://www.industrydocuments.ucsf.edu/) — review their access conditions before redistribution. ## Citation ``` @inproceedings{mathew2021docvqa, title={DocVQA: A Dataset for VQA on Document Images}, author={Mathew, Minesh and Karatzas, Dimosthenis and Jawahar, CV}, booktitle={Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV)}, year={2021} } ``` # EuroSAT Source: https://docs.lancedb.com/oss/v0-41-0/datasets/eurosat A Lance-formatted version of EuroSAT, the canonical Sentinel-2 RGB land-cover benchmark, sourced from blanchon/EuroSAT_RGB. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/eurosat-lance) > > Source dataset card and downloadable files for `lance-format/eurosat-lance`. Each row is a single 64×64 RGB tile with its integer class id, the human-readable class name, and a cosine-normalized OpenCLIP image embedding — all stored inline and available directly from the Hub at `hf://datasets/lance-format/eurosat-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar TIF folders, no per-class subdirectories. * **Pre-computed OpenCLIP image embeddings** (`image_emb`, ViT-B/32, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both label representations** — integer `label` (0-9) and string `label_name` — with scalar indices on both for fast class filters. * **One columnar dataset** — scan labels and embeddings cheaply, fetch tile bytes only for the rows you actually need. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 16,200 | Training split | | `validation.lance` | 5,400 | Validation split | | `test.lance` | 5,400 | Held-out test split | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes (64×64 RGB Sentinel-2 tile) | | `label` | `int32` | Class id (0-9) | | `label_name` | `string` | One of `Annual_Crop`, `Forest`, `Herbaceous_Vegetation`, `Highway`, `Industrial_Buildings`, `Pasture`, `Permanent_Crop`, `Residential_Buildings`, `River`, `SeaLake` | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BTREE` on `label` — fast equality / range filters by class id * `BITMAP` on `label_name` — fast set-membership filters by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/eurosat-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/eurosat-lance --repo-type dataset --local-dir ./eurosat-lance > ``` > > Then point LanceDB at `./eurosat-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visually-similar-tile retrieval a single call. In production you would encode a query tile through the same OpenCLIP `ViT-B-32` model used at ingest (cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print(f"reference tile class: {seed['label_name']}") for r in hits: print(f" id={r['id']:>6} {r['label_name']}") ``` Because the embeddings are cosine-normalized at ingest, `metric="cosine")` is the right choice and the first hit will typically be the seed tile itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a land-cover classification or retrieval study narrows the dataset to a single class and then retrieves the visually closest tiles to a seed. Lance evaluates the vector search and the metadata filter inside a single query, so the candidate set comes back already filtered. The example below pulls the 500 forest tiles most similar to a chosen seed; the bounded `.limit(500)` keeps the output small enough to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(0) .to_list()[0] ) candidates = ( tbl.search(seed["image_emb"]) .where("label_name = 'Forest'", prefilter=True) .select(["id", "label", "label_name"]) .limit(500) .to_list() ) print(f"{len(candidates)} Forest candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by the small metadata payload rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse `is_urban` flag that captures whether a tile belongs to one of the built-environment classes, useful as a direct predicate in later `where` clauses without re-evaluating the class set on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./eurosat-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "is_urban": "label_name IN ('Highway', 'Industrial_Buildings', 'Residential_Buildings')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a coarse climate label per class, an external aesthetic score, model predictions from a separate eval), add the new fields and update matching rows by `label_name`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa climate = pa.table({ "label_name": pa.array(["Forest", "Pasture", "SeaLake", "River"]), "climate_zone": pa.array(["temperate", "temperate", "marine", "freshwater"]), }) tbl.add_columns([f for f in climate.schema if f.name != "label_name"]) tbl.merge_insert("label_name").when_matched_update_all().execute(climate) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative remote-sensing model over the tile bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward through a CNN or ViT, cross-entropy loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight classifier head on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./eurosat-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same tiles, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/eurosat-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("label_name IN ('Forest', 'River', 'SeaLake')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./eurosat-natural-subset") local_db.create_table("train", batches) ``` The resulting `./eurosat-natural-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/eurosat-lance/data` for `./eurosat-natural-subset`. ## Source & license Converted from [`blanchon/EuroSAT_RGB`](https://huggingface.co/datasets/blanchon/EuroSAT_RGB). EuroSAT is released under the MIT license by Helber et al. The underlying Sentinel-2 imagery is © European Space Agency, made available under the [Copernicus open data policy](https://www.copernicus.eu/en/access-data/copyright-and-licences). ## Citation ``` @inproceedings{helber2019eurosat, title={EuroSAT: A novel dataset and deep learning benchmark for land use and land cover classification}, author={Helber, Patrick and Bischke, Benjamin and Dengel, Andreas and Borth, Damian}, journal={IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing}, year={2019} } ``` # FineWeb-Edu Source: https://docs.lancedb.com/oss/v0-41-0/datasets/fineweb-edu A Lance-formatted version of FineWeb-Edu — over 1.5 billion educational web passages with cleaned text, source metadata, language detection signals, and 384-dim text embeddings — available directly from the Hub at hf://datasets/lance-format/fineweb-edu/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/fineweb-edu) > > Source dataset card and downloadable files for `lance-format/fineweb-edu`. ## Key features * **Cleaned passage text** in the `text` column with the source `url` and `title` carried alongside. * **Language detection signals** (`language`, `language_probability`) for filtered subsets. * **Pre-computed 384-dim text embeddings** in `text_embedding`, ready for ANN search once an index is built locally. * **One columnar dataset** — scan metadata cheaply, project just the columns each query needs, defer the heavy `text` and `text_embedding` reads to the rows that matter. > **No pre-built indices on the Hub copy yet.** At 1.5 B+ rows the on-disk indices are too large to ship comfortably alongside the data on the Hub. The Search, Curate, Evolve, and Train sections below describe the same APIs you'd use against a fully indexed dataset, but vector and full-text examples assume a local copy with `IVF_PQ` and `INVERTED` indices built once after download. See the Materialize-a-subset section at the end for a focused-subset workflow that makes indexing tractable. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `text` | `string` | Cleaned passage body | | `title` | `string` | Page or article title when available | | `url` | `string` | Canonical source URL | | `language` | `string` | Detected language code (e.g., `en`) | | `language_probability` | `float32` | Confidence of the language detector | | `text_embedding` | `fixed_size_list<float32, 384>` | Passage embedding for retrieval | | *FineWeb-Edu quality metadata* | — | Heuristic scores and length statistics carried over from the upstream corpus | ## Pre-built indices None bundled at present. Build the recommended indices on a local copy: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") tbl = db.open_table("train") tbl.create_index( metric="cosine", vector_column_name="text_embedding", index_type="IVF_PQ", num_partitions=2048, num_sub_vectors=96, ) tbl.create_fts_index("text", replace=True) ``` Both indices live next to the data, so subsequent queries against the same local path pick them up automatically. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/fineweb-edu", split="train", streaming=True) for row in hf_ds.take(3): print(row["title"] or row["url"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but at 1.5 B+ rows random access and any kind of search are dramatically faster against a local copy, and ANN / FTS require local indices anyway: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/fineweb-edu --repo-type dataset --local-dir ./fineweb-edu > ``` > > Then point LanceDB at `./fineweb-edu/data`. For most workflows, the Materialize-a-subset section is a better starting point than downloading the full 1.5 B-row corpus. ## Search Once an `IVF_PQ` index exists on `text_embedding`, dense retrieval is a single call. In production you would encode a query string through the same 384-dim text encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") # local copy with the indices from the section above tbl = db.open_table("train") seed = ( tbl.search() .select(["text_embedding", "url"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_embedding"]) .metric("cosine") .where("language = 'en' AND language_probability > 0.9", prefilter=True) .select(["title", "url", "text"]) .limit(10) .to_list() ) for r in hits: print(f"{r['url']}\n {(r['title'] or '')[:80]}") ``` The result set carries only the projected columns. The `text_embedding` vector is never read on the result side, and the `text` body is fetched only for the ten passages that actually came back, keeping the working set small even though the corpus is enormous. Because the recommended setup also builds an `INVERTED` index on `text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase must literally appear in the passage but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["text_embedding"]) .text("quantum computing") .where("language = 'en'", prefilter=True) .select(["title", "url", "text"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['url']}\n {(r['title'] or '')[:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass over a web corpus starts with a metadata filter — pick high-confidence English, drop short or low-quality fragments, restrict to a domain — before any text gets read. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "language = 'en' " "AND language_probability > 0.95 " "AND length(text) >= 1000", prefilter=True, ) .select(["url", "title", "language_probability"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first url: {candidates[0]['url']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of URLs, or hand to the Materialize-a-subset section below for export to a writable local copy. Neither the `text` body nor the `text_embedding` vector is read by this scan, so a 1000-row curation pass against the Hub moves only kilobytes of metadata even though the underlying table is in the billions. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `text_length` and a `long_passage` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull a larger slice first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./fineweb-edu/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "text_length": "length(text)", "long_passage": "length(text) >= 1000", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, topic classifications, alternate embeddings from a stronger model), add the new fields and update matching rows by `url`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "url": pa.array(["https://example.com/a", "https://example.com/b"]), "topic": pa.array(["math", "history"]), }) tbl.add_columns([f for f in labels.schema if f.name != "url"]) tbl.merge_insert("url").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For language-model pretraining the natural projection is just the `text` column; for a retrieval probe or a reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./fineweb-edu/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["text"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=8) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["text_embedding"]` to `select_columns(...)` on the next run reads only the 384-d vectors and skips the text body entirely, which is the right shape for training a lightweight retrieval head on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./fineweb-edu/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("english-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="english-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `english-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same passages, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset At 1.5 B+ rows, very few workflows want the full corpus on local disk. The practical entry point is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. The result is a writable LanceDB database scoped to the rows that actually matter for the downstream task, sized to index and iterate cheaply. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/fineweb-edu/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "language = 'en' " "AND language_probability > 0.95 " "AND length(text) >= 1000" ) .select(["url", "title", "text", "language", "language_probability", "text_embedding"]) .to_batches() ) local_db = lancedb.connect("./fineweb-edu-en") local_db.create_table("train", batches) ``` The resulting `./fineweb-edu-en` is a first-class LanceDB database. Build the recommended indices on it once (the same `create_index` / `create_fts_index` calls shown in the Pre-built indices section, pointed at the local path), and every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/fineweb-edu/data` for `./fineweb-edu-en`. ## Source & license Converted from [`HuggingFaceFW/fineweb-edu`](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu). FineWeb-Edu is distributed under [ODC-BY 1.0](https://opendatacommons.org/licenses/by/1-0/); individual document content remains subject to the rights of the original publishers. Review the [upstream dataset card](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) before downstream use. ## Citation ``` @misc{lozhkov2024finewebedu, title = {FineWeb-Edu: the Finest Collection of Educational Content the Web Has to Offer}, author = {Lozhkov, Anton and Ben Allal, Loubna and von Werra, Leandro and Wolf, Thomas}, year = {2024}, url = {https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu} } ``` # Flickr30k Source: https://docs.lancedb.com/oss/v0-41-0/datasets/flickr30k A Lance-formatted version of Flickr30k, redistributed via lmms-lab/flickr30k. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/flickr30k-lance) > > Source dataset card and downloadable files for `lance-format/flickr30k-lance`. Each row is one image with **5 human-written captions**, a cosine-normalized CLIP image embedding, and a cosine-normalized CLIP text embedding of the canonical caption — all stored inline and available directly from the Hub at `hf://datasets/lance-format/flickr30k-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `text_emb` (ViT-B/32, 512-dim, cosine-normalized) — so cross-modal retrieval is one indexed lookup. * **All 5 raw captions kept in `captions`** alongside a `caption` canonical string used for full-text search. * **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the canonical caption, and `image_id`. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 31,783 | All Flickr30k images; the `lmms-lab/flickr30k` redistribution merges the original train/val/test labels into a single split | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string` | Original Flickr image id | | `filename` | `string?` | Original filename (e.g. `1000092795.jpg`) | | `captions` | `list<string>` | All 5 captions for the image | | `caption` | `string` | First caption — canonical text used for FTS | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `text_emb` — text-side vector search (cosine) * `INVERTED` (FTS) on `caption` — keyword and hybrid search * `BTREE` on `image_id` — fast lookup by Flickr image id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/flickr30k-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/flickr30k-lance --repo-type dataset --local-dir ./flickr30k-lance > ``` > > Then point LanceDB at `./flickr30k-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a text query with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `text_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a caption", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["text_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "caption"]) .limit(10) .to_list() ) print("query caption:", seed["caption"]) for r in hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Because OpenAI-style CLIP embeddings are normalized, cosine is the right metric and the first hit will typically be the source image itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `text_emb` to do text→text retrieval against the canonical captions instead. Because the dataset also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "dog playing in the snow" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["text_emb"]) .text("dog playing in the snow") .select(["image_id", "caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['caption'][:70]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a captioning or contrastive-training workflow combines a content filter on the captions with a structural filter on the row. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") candidates = ( tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) = 5", prefilter=True) .select(["image_id", "caption", "captions"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first caption: {candidates[0]['caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by caption text rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds `num_captions` and a `long_caption` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./flickr30k-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "num_captions": "array_length(captions)", "long_caption": "length(caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, an aesthetic or NSFW score, a second-pass caption from a different model), add the new fields and update matching rows by `image_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "image_id": pa.array(["1000092795", "10002456"]), "scene_label": pa.array(["outdoor", "indoor"]), }) tbl.add_columns([f for f in labels.schema if f.name != "image_id"]) tbl.merge_insert("image_id").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second CLIP variant over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a CLIP-style contrastive run, project the JPEG bytes and a sampled caption; for a reranker or probe on top of frozen features, project the precomputed embeddings instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the captions, encode, contrastive loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "text_emb"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./flickr30k-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and captions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search("surfer OR surfboard OR wave") .where("array_length(captions) = 5") .select(["image_id", "image", "caption", "captions", "image_emb", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./flickr30k-surf-subset") local_db.create_table("train", batches) ``` The resulting `./flickr30k-surf-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/flickr30k-lance/data` for `./flickr30k-surf-subset`. ## Source & license Converted from [`lmms-lab/flickr30k`](https://huggingface.co/datasets/lmms-lab/flickr30k), which is itself a parquet redistribution of the [original Flickr30k corpus](https://shannon.cs.illinois.edu/DenotationGraph/). Original images come from Flickr; review the Flickr30k licensing terms before redistribution. ## Citation ``` @article{young2014image, title={From image descriptions to visual denotations: New similarity metrics for semantic inference over event descriptions}, author={Young, Peter and Lai, Alice and Hodosh, Micah and Hockenmaier, Julia}, journal={Transactions of the Association for Computational Linguistics}, volume={2}, pages={67--78}, year={2014} } ``` # GQA testdev-balanced Source: https://docs.lancedb.com/oss/v0-41-0/datasets/gqa-testdev-balanced A Lance-formatted version of the canonical GQA testdev_balanced slice — 12,578 compositional VQA questions joined against the matching 398 images — sourced from lmms-lab/GQA. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/gqa-testdev-balanced-lance) > > Source dataset card and downloadable files for `lance-format/gqa-testdev-balanced-lance`. The original redistribution ships instructions and images as separate parquet configs; here they are pre-joined on `image_id`, so each row carries the question text, the short answer, the GQA reasoning-program tags, paired CLIP image and question embeddings, and the inline JPEG bytes — all available directly from the Hub at `hf://datasets/lance-format/gqa-testdev-balanced-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column, duplicated across rows that share an `image_id` so each Q/A row is self-contained. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (512-dim, cosine-normalized) — for cross-modal retrieval as one indexed lookup. * **Compositional reasoning metadata** — `structural`, `semantic`, and `detailed` question-type tags plus the `semantic_str` reasoning program. * **Pre-built ANN, FTS, scalar, and bitmap indices** covering both embeddings, the question and short answer, the reasoning-type tags, and the image/question ids. ## Splits | Split | Rows | Distinct images | | - | - | - | | `testdev.lance` | 12,578 | 398 | The train_balanced (\~943 k Q's × 72 k images) and val_balanced splits are not bundled by default; pass `--instr-config` / `--images-config` to `gqa/dataprep.py` to extend. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes (duplicated across rows that share an `image_id`) | | `image_id` | `string` | GQA scene-graph image id | | `question_id` | `string` | GQA question id | | `question` | `string` | Compositional natural-language question | | `answers` | `list<string>` | One-element list (the GQA short answer) | | `answer` | `string` | Canonical short answer (used for FTS) | | `full_answer` | `string?` | Full-sentence answer | | `structural` | `string?` | One of `verify`, `query`, `compare`, `choose`, `logical` | | `semantic` | `string?` | One of `attr`, `cat`, `global`, `obj`, `rel` | | `detailed` | `string?` | Fine-grained type (e.g. `weatherVerifyC`) | | `is_balanced` | `bool` | GQA balanced subset flag | | `group_global`, `group_local` | `string?` | GQA reasoning-group ids | | `semantic_str` | `string?` | Compact description of the reasoning program | | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BITMAP` on `structural`, `semantic`, `detailed` — fast categorical filters on the reasoning program * `BTREE` on `image_id`, `question_id` — fast lookup by GQA id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/gqa-testdev-balanced-lance", split="testdev", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/gqa-testdev-balanced-lance --repo-type dataset --local-dir ./gqa-testdev-balanced-lance > ``` > > Then point LanceDB at `./gqa-testdev-balanced-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") seed = ( tbl.search() .select(["question_emb", "question", "answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "answer", "structural"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["answer"]) for r in hits: print(f" {r['image_id']:>12} [{r['structural']}] {r['question'][:70]}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased or topically related questions instead. The dataset also ships an `INVERTED` index on `question` and `answer`, so the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is useful when a noun like "umbrella" must appear in the question text but you still want CLIP to handle visual similarity over the candidate set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("umbrella") .select(["image_id", "question", "answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['question'][:70]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for a compositional-reasoning study combines a predicate on the question text (or the GQA short answer) with a structural filter on the reasoning program, so the candidate set is both topically and structurally consistent. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") candidates = ( tbl.search() .where( "structural = 'verify' AND answer IN ('yes', 'no') AND question LIKE 'Is %'", prefilter=True, ) .select(["question_id", "image_id", "question", "answer", "semantic"]) .limit(500) .to_list() ) print(f"{len(candidates)} verify-style yes/no candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by the question and answer strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_binary_answer` flag and a `question_length` integer, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./gqa-testdev-balanced-lance/data") # local copy required for writes tbl = db.open_table("testdev") tbl.add_columns({ "is_binary_answer": "answer IN ('yes', 'no')", "question_length": "length(question)", "answer_length": "length(answer)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, scene-graph features, or per-question predictions from an external model), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["20240268", "20240269"]), "model_answer": pa.array(["yes", "left"]), "model_confidence": pa.array([0.91, 0.62]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation, Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a VQA fine-tune, project the JPEG bytes, the question, and the short answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question, forward through the VLM, compute the loss... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for a lightweight reasoning probe over frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") tbl = db.open_table("testdev") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./gqa-testdev-balanced-lance/data") local_tbl = local_db.open_table("testdev") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("testdev", version="clip-vitb32-v1") tbl_v5 = db.open_table("testdev", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added model predictions or reasoning annotations do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data") remote_tbl = remote_db.open_table("testdev") batches = ( remote_tbl.search() .where("structural = 'verify' AND answer IN ('yes', 'no')") .select(["question_id", "image_id", "image", "question", "answer", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./gqa-yesno-subset") local_db.create_table("testdev", batches) ``` The resulting `./gqa-yesno-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/gqa-testdev-balanced-lance/data` for `./gqa-yesno-subset`. ## Source & license Converted from [`lmms-lab/GQA`](https://huggingface.co/datasets/lmms-lab/GQA). GQA is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) by Hudson and Manning (Stanford NLP). ## Citation ``` @inproceedings{hudson2019gqa, title={GQA: A New Dataset for Real-World Visual Reasoning and Compositional Question Answering}, author={Hudson, Drew A. and Manning, Christopher D.}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2019} } ``` # Handwriting OCR Source: https://docs.lancedb.com/oss/v0-41-0/datasets/handwriting-ocr This Lance-formatted version of the Doctor's Handwritten Prescription BD dataset contains 4,680 cropped PNG images of handwritten medicine names from Bangladesh. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/handwriting-ocr) > > Source dataset card and downloadable files for `lance-format/handwriting-ocr`. Each row keeps the original image bytes with the medicine and generic-name labels, plus deterministic search metadata derived from those labels. The dataset contains three source-preserved splits: train, validation, and test. > [!NOTE] > > **Training note:** The same samples appear repeatedly because a model (during training) should learn from multiple *different handwritten crops* of the same medicine, because they capture different writers, pen strokes, sizes, and image quality. The dataset would need to be shuffled and sampled appropriately before running downstream training tasks ## Key features * **Original inline PNG bytes** in `image`, with no image folders or sidecar files required. * **Three preserved splits**: 3,120 training, 780 validation, and 780 test examples. * **Medicine annotations**: 78 medicine names mapped to 15 generic names. * **Built-in text retrieval** over `searchable_summary`, with scalar indices matching the companion OCR retrieval project. ## Splits | Split | Rows | Source directory | | - | -: | - | | `train` | 3,120 | `Training` | | `validation` | 780 | `Validation` | | `test` | 780 | `Testing` | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | Stable split-qualified row identifier | | `image` | `large_binary` | Original inline PNG bytes | | `medicine_name` | `string` | Source medicine-name label | | `generic_name` | `string` | Source generic-name label | | `normalized_text` | `string` | Deterministic normalization of `medicine_name` | | `category` | `string` | `medication` for every source row | | `is_medical` | `bool` | `true` for every source row | | `needs_human_review` | `bool` | `false`; this conversion does not run OCR confidence assessment | | `searchable_summary` | `string` | Label-derived text: `Medication mention: <medicine> (<generic>)` | | `source_dataset` | `string` | Upstream Kaggle dataset identifier | | `split` | `string` | Original source split name: `Training`, `Validation`, or `Testing` | | `image_filename` | `string` | Original PNG filename within the source split | `normalized_text`, `category`, `is_medical`, `needs_human_review`, and `searchable_summary` are deterministic conversion metadata. They are not OCR or clinical-model predictions. ## Pre-built indices * `INVERTED` (FTS) on `searchable_summary` * `BTREE` on `id` * `BITMAP` on `category` * `BITMAP` on `needs_human_review` ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets through the standard Hugging Face `datasets` interface when you want a streaming sample or your pipeline already uses `Dataset` / `IterableDataset`. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset( "lance-format/handwriting-ocr", split="train", streaming=True, ) for row in hf_ds.take(3): print(row["medicine_name"], row["generic_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the downloaded dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, and Versioning examples below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip - for production use, download locally first.** Streaming from the Hub works for exploration, but repeated random access and training are faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/handwriting-ocr --repo-type dataset --local-dir ./handwriting-ocr > ``` > > Then run the examples below from `./handwriting-ocr`, where `./data` contains the downloaded Lance splits. ## Search The bundled full-text index makes medicine and generic-name lookups efficient without an embedding model. `searchable_summary` combines the two labels, so a text query can return the matching word image and its annotations in one bounded result set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") hits = ( tbl.search("Paracetamol") .select(["id", "medicine_name", "generic_name", "searchable_summary"]) .limit(10) .to_list() ) for row in hits: print(row["medicine_name"], "-", row["generic_name"]) ``` The FTS index operates on label-derived text, not a transcription produced from the image. It is useful for inspecting the handwritten examples associated with known medicine or generic names. ## Curate Filters produce small, explicit candidate sets for experiments. The example selects a bounded set of Paracetamol examples while avoiding image bytes until a later step needs them. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") candidates = ( tbl.search() .where("generic_name = 'Paracetamol'") .select(["id", "image_filename", "medicine_name", "generic_name"]) .limit(100) .to_list() ) ``` This list can be reviewed directly, saved as an experiment manifest, or used as the input to an annotation or training workflow. ## Evolve Lance can append new columns without rewriting the original images or annotations. For example, a local copy can add a flag for a specific generic name using a SQL expression, then merge independently produced labels by `id`. > **Note**: Mutations require a local copy. The examples in this card assume the dataset was downloaded into the current directory, as shown above. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb import pyarrow as pa db = lancedb.connect("./data") tbl = db.open_table("train") # SQL-derived columns append a column file without rewriting existing columns or indices tbl.add_columns({"is_paracetamol": "generic_name = 'Paracetamol'"}) review_labels = pa.table({ "id": ["train_00000"], "review_status": ["reviewed"], }) tbl.add_columns([pa.field("review_status", pa.string())]) tbl.merge_insert("id").when_matched_update_all().execute(review_labels) ``` Matched rows receive the new labels while unmatched rows stay `null`, and each mutation becomes visible to queries as soon as its new table version commits. ## Train Projection lets a training loop read only the columns it needs. The image bytes and medicine label below are projected through a standard PyTorch `DataLoader`; fields added later do not add read cost unless selected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "medicine_name"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # Decode PNG bytes and train an OCR or classification model. ... ``` This keeps the original image representation available for training while avoiding unrelated columns on each epoch. ## Versioning Every Lance mutation creates a version, so the table history can identify the exact split and annotation state used by a retrieval service or experiment. The downloaded dataset can list its history and create tags for reproducible local workflows. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) tbl.tags.create("labels-v1", tbl.version) ``` A pinned version or tag keeps retrieval and training tied to a known dataset state even as review labels or derived columns are added later. ## Materialize a subset Use a filtered query to materialize a compact local LanceDB table for writes or intensive training. The query streams matching rows and projected columns without materializing the full result set in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb source_db = lancedb.connect("./data") source_tbl = source_db.open_table("train") batches = ( source_tbl.search() .where("generic_name = 'Paracetamol'") .select(["id", "image", "medicine_name", "generic_name", "searchable_summary"]) .to_batches() ) local_db = lancedb.connect("./paracetamol-subset") local_db.create_table("train", batches) ``` The resulting local table can replace `./data` in the Evolve, Train, and Versioning examples when a compact writable subset is sufficient. ## Citation Please cite both the upstream dataset and the associated research paper: ```bibtex theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} @inproceedings{mia2024deep, title={A Deep Neural Network Approach with Pioneering Local Dataset to Recognize Doctor's Handwritten Prescription in Bangladesh}, author={Mia, Abdur Rahim and Chowdhury, Mohammad Abdullah-Al-Sajid and Mamun, Abdullah Al and Ruddra, Aurunave Mollik and Tanny, Nawshin Tabassum}, booktitle={2024 International Conference on Advances in Computing, Communication, Electrical, and Smart Systems}, pages={1--6}, year={2024}, publisher={IEEE}, doi={10.1109/iCACCESS61735.2024.10499631} } ``` Source dataset: [Mamun1113, Doctor's Handwritten Prescription BD dataset](https://www.kaggle.com/datasets/mamun1113/doctors-handwritten-prescription-bd-dataset). Associated paper: [IEEE Xplore](https://ieeexplore.ieee.org/document/10499631). ## License The upstream Kaggle metadata identifies the database license as [Open Database License (ODbL) v1.0](https://opendatacommons.org/licenses/odbl/1.0/) and states that the contents are copyright the original authors. The upstream page also describes the dataset as free for educational and research use. Downstream users should review the upstream dataset page and publication, satisfy the ODbL obligations, and obtain any additional permissions needed for their intended use. # HotpotQA distractor Source: https://docs.lancedb.com/oss/v0-41-0/datasets/hotpotqa-distractor A Lance-formatted version of HotpotQA using the distractor config — multi-hop reading-comprehension questions where each answer requires combining facts from two Wikipedia paragraphs, with 10 candidate paragraphs per question (gold + 8 distractors). > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/hotpotqa-distractor-lance) > > Source dataset card and downloadable files for `lance-format/hotpotqa-distractor-lance`. The dataset ships with MiniLM question embeddings, flattened context text for full-text search, and pre-built ANN/FTS indices, available directly from the Hub at `hf://datasets/lance-format/hotpotqa-distractor-lance/data`. ## Key features * **Multi-hop questions with gold supporting facts** — each row carries the question, the canonical short answer, and the `(title, sent_id)` pointers into the paragraphs that justify it. * **Ten candidate paragraphs per question** in the parallel `context_titles` / `context_sentences` columns, plus a flattened `context_text` field that feeds the FTS index. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question lookup. * **One columnar dataset** — scan metadata cheaply, then read the heavy context text only for the rows you actually want. ## Splits | Split | Rows | | - | - | | `train.lance` | 90,447 | | `validation.lance` | 7,405 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | HotpotQA question id | | `question` | `string` | The question | | `answer` | `string` | Reference short answer (`yes` / `no` / span) | | `type` | `string?` | `bridge` or `comparison` | | `level` | `string?` | `easy` / `medium` / `hard` | | `supporting_titles` | `list<string>` | Wikipedia titles that contain the gold facts | | `supporting_sent_ids` | `list<int32>` | Sentence indices into those titles | | `context_titles` | `list<string>` | All 10 paragraph titles (gold + distractors) | | `context_sentences` | `list<list<string>>` | Sentences per paragraph | | `context_text` | `string` | Flattened paragraphs — feeds the FTS index | | `num_supporting_facts` | `int32` | Number of gold supporting facts | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM question embedding | ## Pre-built indices * `IVF_PQ` on `question_emb` — semantic question lookup (cosine) * `INVERTED` (FTS) on `question` and `context_text` — keyword and hybrid search * `BTREE` on `id`, `answer` — stable lookup by identifier * `BITMAP` on `type`, `level` — cheap predicate evaluation for question class ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/hotpotqa-distractor-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`train`, `validation`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/hotpotqa-distractor-lance --repo-type dataset --local-dir ./hotpotqa-distractor-lance > ``` > > Then point LanceDB at `./hotpotqa-distractor-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes nearest-neighbour question lookup a single call. In production you would encode an incoming user question through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("level = 'hard'", prefilter=True) .select(["question", "answer", "supporting_titles", "type"]) .limit(10) .to_list() ) for r in hits: print(f"[{r['type']}] {r['question']} -> {r['answer']}") ``` The result set carries only the projected columns; the 384-d `question_emb` is never read on the result side, and the long `context_text` body is left untouched, keeping the working set small even when the underlying scan touches every row of the train split. Because the dataset also ships an `INVERTED` index on both `question` and `context_text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the full paragraph text. LanceDB merges the two result lists and reranks them in a single call, which is useful when a named entity must literally appear in one of the supporting paragraphs but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("inception dunkirk") .select(["question", "answer", "supporting_titles"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["question"], "->", r["answer"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate Building a focused evaluation slice usually means stacking predicates over the question metadata before any context text gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(2000)` keeps the output small enough to inspect. The example below assembles a set of hard, multi-hop comparison questions for which the gold answer is a real span rather than `yes`/`no`. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "type = 'comparison' " "AND level = 'hard' " "AND num_supporting_facts >= 2 " "AND answer NOT IN ('yes', 'no') " "AND length(question) >= 40", prefilter=True, ) .select(["id", "question", "answer", "supporting_titles"]) .limit(2000) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Evolve and Train sections below. Neither `context_text` nor `context_sentences` is read by this scan, so a 2000-row curation pass against the Hub moves only kilobytes of metadata. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length` column and a `is_multi_hop` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./hotpotqa-distractor-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "is_multi_hop": "num_supporting_facts >= 2", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline retriever scores, reranker logits, alternate embeddings from a stronger model), add the new fields and update matching rows by question `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa retriever_scores = pa.table({ "id": pa.array(["5a8b57f25542995d1e6f1371", "5a8c7595554299585d9e36b6"]), "bm25_top1_score": pa.array([12.7, 9.4]), }) tbl.add_columns([f for f in retriever_scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(retriever_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different encoder over the question text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a multi-hop QA model the natural projection is the question plus the flattened context and the gold answer; for a question-encoder retraining loop the precomputed embedding is enough on its own. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["question", "context_text", "answer"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "answer"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the short answer string, which is the right shape for fine-tuning a retrieval head on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./hotpotqa-distractor-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("hard-multihop-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="hard-multihop-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A QA system locked to `hard-multihop-v1` keeps returning stable supporting facts while the dataset evolves in parallel — newly added retriever scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and contexts, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/hotpotqa-distractor-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "type = 'comparison' " "AND level = 'hard' " "AND num_supporting_facts >= 2" ) .select(["id", "question", "answer", "supporting_titles", "context_text", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./hotpotqa-hard-comparison") local_db.create_table("train", batches) ``` The resulting `./hotpotqa-hard-comparison` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/hotpotqa-distractor-lance/data` for `./hotpotqa-hard-comparison`. ## Source & license Converted from [`hotpot_qa`](https://huggingface.co/datasets/hotpot_qa) (`distractor` config). HotpotQA is released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @inproceedings{yang2018hotpotqa, title={HotpotQA: A Dataset for Diverse, Explainable Multi-hop Question Answering}, author={Yang, Zhilin and Qi, Peng and Zhang, Saizheng and Bengio, Yoshua and Cohen, William W. and Salakhutdinov, Ruslan and Manning, Christopher D.}, booktitle={Empirical Methods in Natural Language Processing (EMNLP)}, year={2018} } ``` # ImageNet-1k Validation Source: https://docs.lancedb.com/oss/v0-41-0/datasets/imagenet-1k-val A Lance-formatted version of the canonical 50,000-image ImageNet-1k (ILSVRC2012) validation split, sourced from benjamin-paine/imagenet-1k. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/imagenet-1k-val-lance) > > Source dataset card and downloadable files for `lance-format/imagenet-1k-val-lance`. Each row is one image with its integer class id, a string class name, and a cosine-normalized OpenCLIP image embedding — all stored inline and available directly from the Hub at `hf://datasets/lance-format/imagenet-1k-val-lance/data`. The 1.28 M ImageNet-1k train split (\~155 GB) is intentionally out of scope for this redistribution; the val split is the canonical evaluation slice for classification benchmarks and is small enough (\~7 GB Lance) to ride entirely in inline storage alongside its embeddings. ## Key features * **Inline JPEG bytes** in the `image` column — no per-class folders, no sidecar files. * **Pre-computed OpenCLIP image embeddings** (`image_emb`, ViT-B/32 trained on `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both label representations** — integer `label` (0-999) and string `label_name` (first synonym of the WordNet synset, e.g. `golden_retriever`) — with scalar indices on both for fast class filters. * **One columnar dataset** — scan labels and embeddings cheaply, fetch image bytes only for the rows you actually need. ## Splits A single split, shipped as `validation.lance` (50,000 rows). ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split, 0-49,999 (natural join key) | | `image` | `large_binary` | Inline JPEG bytes | | `label` | `int32` | Class id (0-999) | | `label_name` | `string` | First synonym of the synset, underscore-spaced (e.g. `golden_retriever`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k` image embedding (cosine-normalized) | The full comma-separated WordNet synset descriptions for each class are stored in the dataset metadata under `lance:class_names`. ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine, `num_partitions=64`) * `BTREE` on `label` — fast equality / range filters by class id * `BITMAP` on `label_name` — fast set-membership filters by class name ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/imagenet-1k-val-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["label_name"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/imagenet-1k-val-lance --repo-type dataset --local-dir ./imagenet-1k-val-lance > ``` > > Then point LanceDB at `./imagenet-1k-val-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes nearest-neighbor retrieval over the validation set a single call. In production you would encode a query image through the same OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k` model used at ingest (cosine-normalized) and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in, so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["image_emb", "label_name"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name"]) .limit(10) .to_list() ) print(f"reference class: {seed['label_name']}") for r in hits: print(f" id={r['id']:>6} {r['label_name']}") ``` Because the embeddings are cosine-normalized at ingest, `metric="cosine"` is the right choice and the first hit will typically be the seed image itself — a useful sanity check. Tune `nprobes` and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for an ImageNet-style classification or robustness study narrows the validation set to a single class (or a synset prefix) and then materializes a small candidate set for inspection. Stacking the filter and the projection inside a single scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where("label_name = 'golden_retriever'") .select(["id", "label", "label_name"]) .limit(200) .to_list() ) print(f"{len(candidates)} golden_retriever validation rows") ``` The `BITMAP` index on `label_name` resolves the predicate without scanning, and the `image` column is never read, so the network traffic for the candidate scan is dominated by the small metadata payload rather than JPEG bytes. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row ids, or feed into the Evolve and Train workflows below. To grab a family of related classes, replace the equality with a `LIKE` predicate such as `label_name LIKE 'tabby%'` or an `IN` set over a curated synset list. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a coarse `is_dog` flag over a curated set of canine synsets, which can then be used directly in later `where` clauses without re-listing the class set on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./imagenet-1k-val-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_dog": "label_name IN ('golden_retriever', 'Labrador_retriever', 'beagle', 'pug', 'poodle')", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table — per-class hypernyms from WordNet, ImageNet-A / ImageNet-R membership flags, model-prediction logs from an external eval run — add the new fields and update matching rows by `label_name`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa hypernyms = pa.table({ "label_name": pa.array(["golden_retriever", "tabby", "espresso"]), "hypernym": pa.array(["dog", "cat", "beverage"]), }) tbl.add_columns([f for f in hypernyms.schema if f.name != "label_name"]) tbl.merge_insert("label_name").when_matched_update_all().execute(hypernyms) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative vision backbone over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop — or, more commonly for this split, an evaluation loop — read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") eval_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(eval_ds, batch_size=128, shuffle=False, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, forward through your classifier, accumulate top-1 / top-5... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight classifier head on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./imagenet-1k-val-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("clip-vitb32-laion2b-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="clip-vitb32-laion2b-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. An evaluation harness locked to `clip-vitb32-laion2b-v1` keeps reporting numbers against a fixed snapshot of labels and embeddings even as the dataset evolves in parallel; newly added columns or relabelings do not change what the tag resolves to. A research experiment pinned to the same tag can be rerun later against the exact same images, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training or evaluation loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/imagenet-1k-val-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where("label_name IN ('golden_retriever', 'Labrador_retriever', 'beagle', 'pug', 'poodle')") .select(["id", "image", "label", "label_name", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./imagenet-dogs-subset") local_db.create_table("validation", batches) ``` The resulting `./imagenet-dogs-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/imagenet-1k-val-lance/data` for `./imagenet-dogs-subset`. ## Source & license Converted from [`benjamin-paine/imagenet-1k`](https://huggingface.co/datasets/benjamin-paine/imagenet-1k), itself a redistribution of the [ILSVRC2012 ImageNet-1k validation split](https://image-net.org/challenges/LSVRC/2012/). All use is subject to the [ImageNet terms of access](https://image-net.org/download.php) — **for research use only**. ## Citation ``` @inproceedings{deng2009imagenet, title={ImageNet: A Large-Scale Hierarchical Image Database}, author={Deng, Jia and Dong, Wei and Socher, Richard and Li, Li-Jia and Li, Kai and Fei-Fei, Li}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2009} } ``` # KITTI 2D Detection Source: https://docs.lancedb.com/oss/v0-41-0/datasets/kitti-2d-detection A Lance-formatted version of the KITTI 2D Object Detection benchmark, sourced from nateraw/kitti so no manual signup or download from cvlibs.net is required. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/kitti-2d-detection-lance) > > Source dataset card and downloadable files for `lance-format/kitti-2d-detection-lance`. Each row is a single driving frame with inline JPEG bytes, the full set of 2D and 3D object annotations stored as parallel per-object lists, plus a cosine-normalized OpenCLIP `ViT-B-32` image embedding — all available directly from the Hub at `hf://datasets/lance-format/kitti-2d-detection-lance/data`. KITTI is the canonical autonomous-driving detection benchmark with 8 object classes drawn from real street scenes around Karlsruhe. It is widely used for AV perception research and serves as a small-scale companion to nuScenes and Waymo. ## Key features * **Inline JPEG bytes** in the `image` column — no parallel `image_2/` and `label_2/` folders to keep in sync. * **Per-object 2D and 3D annotations on the same row** — bounding boxes, observation angles, 3D dimensions, locations, yaw, occlusion and truncation flags travel as parallel list columns of equal length. * **Pre-computed CLIP image embeddings** (`image_emb`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for visual similarity over driving scenes. * **Scalar and label-list indices** on `num_objects` and `types_present` make per-class and crowdedness filters cheap on the Hub copy and locally. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 7,481 | Official KITTI training set with labels | The KITTI `test` split has no public labels and is intentionally not bundled. Add it via `--splits train test` in `kitti/dataprep.py` if you want the unlabeled images for inference. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (re-encoded from the source PNG) | | `bboxes` | `list<list<float32, 4>>` | 2D box per object — `[left, top, right, bottom]` in pixel coords | | `alphas` | `list<float32>` | Observation angle per object (radians, KITTI convention) | | `dimensions` | `list<list<float32, 3>>` | 3D box `(h, w, l)` per object, in metres | | `locations` | `list<list<float32, 3>>` | 3D centre `(x, y, z)` per object in camera coords, in metres | | `rotation_y` | `list<float32>` | Yaw per object in camera coords (radians) | | `occluded` | `list<int8>` | KITTI occlusion flag (0=visible, 1=partly, 2=largely, 3=unknown) | | `truncated` | `list<float32>` | Truncation fraction per object (0.0-1.0) | | `types` | `list<string>` | Class name per object (`Car`, `Van`, `Truck`, `Pedestrian`, `Person_sitting`, `Cyclist`, `Tram`, `Misc`, `DontCare`) | | `num_objects` | `int32` | Number of annotated objects in the frame | | `types_present` | `list<string>` | Deduped class names — feeds the LABEL_LIST index | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | All `list<...>` annotation columns on the same row are aligned — index `i` across `bboxes`, `alphas`, `dimensions`, `locations`, `rotation_y`, `occluded`, `truncated`, and `types` describes the same physical object. ## Pre-built indices * `IVF_PQ` on `image_emb` — `metric=cosine` * `BTREE` on `num_objects` * `LABEL_LIST` on `types_present` ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/kitti-2d-detection-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["id"], row["num_objects"], row["types_present"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/kitti-2d-detection-lance --repo-type dataset --local-dir ./kitti-2d-detection-lance > ``` > > Then point LanceDB at `./kitti-2d-detection-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visual nearest-neighbour search over driving scenes a single call. In production you would encode a query frame (or a scene prototype) through OpenCLIP `ViT-B-32` at runtime and pass the resulting 512-d cosine-normalized vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "types_present"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "num_objects", "types_present"]) .limit(10) .to_list() ) print("query scene types:", seed["types_present"]) for r in hits: print(f" id={r['id']:>5} n={r['num_objects']:>2} {r['types_present']}") ``` Because the embeddings are cosine-normalized, `metric="cosine"` is the natural choice and the first hit is typically the seed row itself. Visual neighbours tend to share scene-level structure (highway vs. urban intersection vs. parked-cars row) before they share class composition, which is what makes the cross between `image_emb` and the `types_present` / `num_objects` indices useful for the curation patterns below. ## Curate KITTI's parallel per-object list columns make composition-based filters natural: pick scenes by which classes are present, by how many objects are in them, or by the occlusion profile of those objects. Lance evaluates these predicates inside a single filtered scan, and the bounded `.limit(...)` keeps the candidate set small and explicit. The first snippet below finds crowded scenes that contain at least one cyclist and one pedestrian — a useful slice for vulnerable-road-user studies. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") vru = ( tbl.search() .where( "array_has_all(types_present, ['Cyclist', 'Pedestrian']) AND num_objects >= 8", prefilter=True, ) .select(["id", "num_objects", "types_present"]) .limit(200) .to_list() ) print(f"{len(vru)} VRU-rich frames") ``` A second pass can combine a structural filter with visual similarity: take a crowded urban seed frame and look for visually similar frames whose object lists also contain cars. This is a one-shot retrieval against the `IVF_PQ` index, joined with the `LABEL_LIST` index on `types_present` inside a single query. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} seed = ( tbl.search() .where("num_objects >= 10 AND array_contains(types_present, 'Car')", prefilter=True) .select(["image_emb"]) .limit(1) .to_list()[0] ) similar_crowded = ( tbl.search(seed["image_emb"]) .metric("cosine") .where("array_contains(types_present, 'Car')", prefilter=True) .select(["id", "num_objects", "types_present"]) .limit(50) .to_list() ) ``` The results are plain lists of dictionaries, ready to inspect, persist as manifests of `id`s, or feed into the Evolve and Train workflows below. The annotation list columns and `image_emb` are read; the JPEG bytes are not touched until you ask for them. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds per-frame counts for the two most safety-relevant classes plus a `has_vru` flag, all of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./kitti-2d-detection-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "num_cars": "array_length(array_filter(types, x -> x = 'Car'))", "num_pedestrians": "array_length(array_filter(types, x -> x = 'Pedestrian'))", "has_vru": "array_has_any(types_present, ['Pedestrian', 'Cyclist'])", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table — detector predictions on the same frames, LIDAR-derived per-frame features, or human re-annotation — add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "pred_num_cars": pa.array([3, 5, 0], type=pa.int32()), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (running a fresh detector over the JPEG bytes, deriving alternative embeddings), Lance also provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a 2D detector, project the JPEG bytes together with the per-object `bboxes` and `types` lists; everything else (3D annotations, CLIP embeddings) stays on disk until you opt in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") train_ds = ( Permutation.identity(tbl) .select_columns(["image", "bboxes", "types"]) ) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; 3D fields and image_emb stay on disk. # decode the JPEGs, drop DontCare boxes, build target tensors, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "types_present"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors plus the deduped class list, which is the right shape for training a lightweight scene classifier or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges predictions, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./kitti-2d-detection-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("kitti-clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="kitti-clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A perception service locked to `kitti-clip-vitb32-v1` keeps returning stable retrieval results while the dataset evolves in parallel — newly added detector predictions or alternative embeddings do not change what the tag resolves to. A detection-training experiment pinned to the same tag can be rerun later against the exact same frames and annotations, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. The filter below carves out a vulnerable-road-user training set — frames that contain at least one pedestrian or cyclist — and writes them to a local LanceDB database. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/kitti-2d-detection-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_has_any(types_present, ['Pedestrian', 'Cyclist'])") .select(["id", "image", "bboxes", "types", "num_objects", "types_present", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./kitti-vru-subset") local_db.create_table("train", batches) ``` The resulting `./kitti-vru-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/kitti-2d-detection-lance/data` for `./kitti-vru-subset`. ## Source & license Converted from [`nateraw/kitti`](https://huggingface.co/datasets/nateraw/kitti). KITTI is released under the [CC BY-NC-SA 3.0 license](https://creativecommons.org/licenses/by-nc-sa/3.0/) by Karlsruhe Institute of Technology and Toyota Technological Institute at Chicago — **non-commercial research use only**. See the [KITTI license page](https://www.cvlibs.net/datasets/kitti/) for details. ## Citation ``` @inproceedings{geiger2012are, title={Are we ready for autonomous driving? The KITTI vision benchmark suite}, author={Geiger, Andreas and Lenz, Philip and Urtasun, Raquel}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2012} } ``` # LAION-1M Source: https://docs.lancedb.com/oss/v0-41-0/datasets/laion-1m A Lance-formatted slice of the LAION image-text corpus (~1M rows) with inline JPEG bytes, CLIP image embeddings (img_emb), full metadata, and a pre-built ANN index — all available directly from the Hub at hf://datasets/lance-format/laion-1m/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/laion-1m) > > Source dataset card and downloadable files for `lance-format/laion-1m`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`img_emb`, 768-dim) with a bundled `IVF_PQ` index for similarity search. * **Full LAION metadata** — captions, URLs, NSFW flags, EXIF, dimensions, similarity scores. * **One columnar dataset** — scan metadata cheaply, then fetch image bytes only for the rows you want. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `key` | `int64` | Row key (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes | | `image_path` | `string` | Original filename | | `caption` | `string` | Image caption | | `url` | `string` | Source URL | | `NSFW` | `int64` | 0 = safe, 1 = NSFW | | `LICENSE` | `string` | Per-row license tag | | `similarity` | `float64` | CLIP image–text cosine similarity | | `width`, `height` | `int64` | Image dimensions | | `original_width`, `original_height` | `int64` | Original dimensions before resize | | `exif`, `md5`, `status`, `error_message` | `string` | Provenance / metadata | | `img_emb` | `fixed_size_list<float32, 768>` | CLIP image embedding | ## Pre-built indices * `IVF_PQ` on `img_emb` — vector similarity search (L2) ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/laion-1m", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, and Versioning examples below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/laion-1m --repo-type dataset --local-dir ./laion-1m > ``` > > Then point LanceDB at `./laion-1m/data`. ## Search The bundled `IVF_PQ` index on `img_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a user prompt or query image through CLIP at runtime and pass the resulting 768-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") query = ( tbl.search() .select(["img_emb"]) .limit(1) .offset(42) .to_list()[0]["img_emb"] ) hits = ( tbl.search(query) .metric("L2") .select(["caption", "url", "similarity"]) .limit(10) .to_list() ) for r in hits: print(f"{r['similarity']:.3f} | {r['caption'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate Building a focused subset usually means combining similarity with metadata filters. Lance evaluates both inside a single query, so the candidate set comes back already filtered. The example below finds images visually similar to a seed row and restricts the result to safe-rated, high-resolution rows in one call. The bounded `.limit(500)` keeps the output small enough to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["img_emb", "caption"]) .limit(1) .offset(42) .to_list()[0] ) candidates = ( tbl.search(seed["img_emb"]) .where('"NSFW" = 0 AND similarity > 0.3 AND width >= 512', prefilter=True) .select(["key", "url", "caption", "similarity"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates around: {seed['caption'][:60]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of row keys, or feed into the Evolve and Train workflows below. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a precomputed `aspect_ratio` and an `is_high_res` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note**: Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./laion-1m/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "aspect_ratio": "CAST(width AS DOUBLE) / CAST(height AS DOUBLE)", "is_high_res": "width >= 512 AND height >= 512", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, aesthetic scores), add the new fields and update matching rows by `key`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "key": pa.array([0, 1, 2]), "aesthetic_score": pa.array([7.1, 6.4, 8.9]), }) tbl.add_columns([f for f in labels.schema if f.name != "key"]) tbl.merge_insert("key").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an embedding model over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "caption"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; img_emb / img_emb_dinov3 stay on disk. # decode the JPEG bytes, tokenize the captions, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["img_emb_dinov3", "caption"]` to `select_columns(...)` on the next run reads only those columns, with no data movement or shard reorganization. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./laion-1m/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("aesthetic-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="aesthetic-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `aesthetic-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same data, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where('"NSFW" = 0 AND similarity > 0.35 AND width >= 512') .select(["key", "image", "caption", "url", "img_emb"]) .to_batches() ) local_db = lancedb.connect("./laion-subset") local_db.create_table("train", batches) ``` The resulting `./laion-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/laion-1m/data` for `./laion-subset`. ## Citation ``` @article{schuhmann2022laion5b, title={LAION-5B: An open large-scale dataset for training next generation image-text models}, author={Schuhmann, Christoph and others}, journal={NeurIPS Datasets and Benchmarks Track}, year={2022} } ``` ## License Content inherits LAION's original licensing and safety guidelines. Review [LAION policy](https://laion.ai/blog/laion-5b/) before downstream use. # LibriSpeech clean Source: https://docs.lancedb.com/oss/v0-41-0/datasets/librispeech-clean A Lance-formatted version of the LibriSpeech ASR clean configuration, sourced from openslr/librispeech_asr. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/librispeech-clean-lance) > > Source dataset card and downloadable files for `lance-format/librispeech-clean-lance`. Each row is one utterance with inline FLAC audio bytes, the reference transcript, a sentence-transformers embedding of that transcript, and speaker/chapter metadata — all available directly from the Hub at `hf://datasets/lance-format/librispeech-clean-lance/data`. ## Key features * **Inline FLAC bytes** in the `audio` column at 16 kHz mono, with no re-encoding from the upstream parquet. * **Sentence-transformers embedding of the transcript** in `text_emb` (`all-MiniLM-L6-v2`, 384-dim, cosine-normalized) with a bundled `IVF_PQ` index for semantic transcript search. * **Pre-built `INVERTED` FTS index on `text`** and `BTREE` indices on `id`, `speaker_id`, and `chapter_id` for keyword search and stable lookup by identifier. * **Per-utterance metadata** — `speaker_id`, `chapter_id`, `num_chars`, `sampling_rate` — that downstream filters can stack on. ## Splits | Split | Source config | Rows | Description | | - | - | - | - | | `dev_clean.lance` | `dev.clean` | 2,703 | Standard ASR validation set | | `test_clean.lance` | `test.clean` | 2,620 | Standard ASR test set | | `train_clean_100.lance` | `train.clean.100` | 28,539 | 100-hour clean training subset | > The 360-hour and 500-hour LibriSpeech subsets (`train.360`, `train.other.500`) are not bundled here. To extend, point `librispeech/dataprep.py` at additional splits. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | Utterance id (e.g. `1272-128104-0000`) | | `audio` | `large_binary` | Inline FLAC bytes (16 kHz mono) | | `sampling_rate` | `int32` | Always 16,000 | | `text` | `string` | Reference transcript | | `speaker_id` | `int64` | LibriVox speaker id | | `chapter_id` | `int64` | LibriVox chapter id | | `num_chars` | `int32` | Length of `text` in characters | | `text_emb` | `fixed_size_list<float32, 384>` | sentence-transformers `all-MiniLM-L6-v2` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `text_emb` — semantic transcript search (cosine) * `INVERTED` (FTS) on `text` — keyword and hybrid search * `BTREE` on `id`, `speaker_id`, `chapter_id` — fast lookup by identifier ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/librispeech-clean-lance", split="test_clean", streaming=True) for row in hf_ds.take(3): print(row["id"], row["text"][:80]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`dev_clean`, `test_clean`, `train_clean_100`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and audio decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/librispeech-clean-lance --repo-type dataset --local-dir ./librispeech-clean > ``` > > Then point LanceDB at `./librispeech-clean/data`. ## Search The bundled `IVF_PQ` index on `text_emb` makes semantic transcript retrieval a single call. In production you would encode a query string through the same sentence-transformers model used at ingest (`all-MiniLM-L6-v2`, cosine-normalized), then pass the resulting 384-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") seed = ( tbl.search() .select(["text_emb", "text"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["text_emb"], vector_column_name="text_emb") .metric("cosine") .select(["id", "speaker_id", "text"]) .limit(10) .to_list() ) print("query transcript:", seed["text"][:80]) for r in hits: print(f" {r['id']} spk={r['speaker_id']} {r['text'][:80]}") ``` The `audio` blob is never touched. A top-10 semantic search moves a few kilobytes of transcript text rather than the FLAC bytes for every candidate. Because the dataset also ships an `INVERTED` index on `text`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query — useful when a name or domain term must literally appear in the transcript but you still want the semantic side to rank the rest. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="text_emb") .vector(seed["text_emb"]) .text("astronomy") .select(["id", "speaker_id", "text"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['id']} spk={r['speaker_id']} {r['text'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Building a focused subset of utterances usually means combining content with structure — pick utterances by a single speaker, or above a minimum transcript length, or matching a topic. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") candidates = ( tbl.search() .where("speaker_id = 1272 AND num_chars >= 60", prefilter=True) .select(["id", "chapter_id", "num_chars", "text"]) .limit(500) .with_row_id(True) .to_list() ) print(f"{len(candidates)} utterances; first: {candidates[0]['text'][:80]}") ``` The scan never reads the `audio` column. Lance stores binary columns independently, so a metadata-only curation pass moves only the transcript text and scalar fields across the wire — even though the underlying table includes hours of inline FLAC audio. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `is_long_utterance` flag and a coarse `length_bucket`, either of which can then be used directly in `where` clauses without re-evaluating the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./librispeech-clean/data") # local copy required for writes tbl = db.open_table("train_clean_100") tbl.add_columns({ "is_long_utterance": "num_chars >= 200", "length_bucket": ( "CASE WHEN num_chars < 80 THEN 'short' " "WHEN num_chars < 200 THEN 'medium' ELSE 'long' END" ), }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (alternate transcripts, speaker embeddings, model predictions), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "id": pa.array(["1272-128104-0000", "1272-128104-0001"]), "wer": pa.array([0.04, 0.12]), }) tbl.add_columns([f for f in predictions.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a speaker embedding model over the FLAC bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for audio training is to pre-extract decoded features once into a derived LanceDB table — one row per training-ready window of log-mel frames or raw PCM samples — and train against that table with the regular projection-based dataloader. `fetch_blob_files` (in `lancedb >= 0.41.0`) is the mechanism that makes the extraction step tractable: each utterance's FLAC bytes are randomly addressable, so the pass can subset audio on demand and write decoded windows into a fresh table without an external file store. Other workflows project `audio` directly through `select_columns(...)` and decode at the batch boundary, or skip audio entirely and train on the cached transcript embeddings — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. Against a pre-extracted features table: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./librispeech-features") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["log_mel", "text", "speaker_id"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) ``` Against the cached transcript embeddings on the source table (no audio decode): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader src_db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") src_tbl = src_db.open_table("train_clean_100") train_ds = Permutation.identity(src_tbl).select_columns(["text_emb", "speaker_id"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` The inline `audio` storage and `fetch_blob_files` still earn their place around the training process — listening back to an utterance in a notebook, sampling for human review, one-off evaluation against a held-out set, and the pre-extraction pass itself. Each of those reads a small, explicit set of blobs once. What the Train section above keeps off the per-batch hot path is exactly that raw-audio decode: paying it every step is what the pre-extracted features are designed to avoid. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") tbl = db.open_table("train_clean_100") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./librispeech-clean/data") local_tbl = local_db.open_table("train_clean_100") local_tbl.tags.create("minilm-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train_clean_100", version="minilm-v1") tbl_v5 = db.open_table("train_clean_100", version=5) ``` Pinning supports two workflows. A retrieval system locked to `minilm-v1` keeps returning stable results while the dataset evolves in parallel. A training experiment pinned to the same tag can be rerun later against the exact same utterances, so changes in metrics reflect model changes rather than data drift. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training pipeline benefits from a local copy with fast random access to the FLAC bytes. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the `audio` column, which streams through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/librispeech-clean-lance/data") remote_tbl = remote_db.open_table("train_clean_100") batches = ( remote_tbl.search() .where("speaker_id = 1272") .select(["id", "audio", "sampling_rate", "text", "speaker_id", "chapter_id", "text_emb"]) .to_batches() ) local_db = lancedb.connect("./librispeech-speaker-1272") local_db.create_table("train", batches) ``` The resulting `./librispeech-speaker-1272` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/librispeech-clean-lance/data` for `./librispeech-speaker-1272`. ## Source & license Converted from [`openslr/librispeech_asr`](https://huggingface.co/datasets/openslr/librispeech_asr). LibriSpeech is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) and is built from the public-domain LibriVox audiobook corpus. ## Citation ``` @inproceedings{panayotov2015librispeech, title={LibriSpeech: An ASR corpus based on public domain audiobooks}, author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev}, booktitle={IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP)}, year={2015} } ``` # MS MARCO v2.1 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/ms-marco-v2 A Lance-formatted version of MS MARCO v2.1 — Microsoft's machine-reading-comprehension benchmark built from anonymized Bing query logs. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/ms-marco-v2.1-lance) > > Source dataset card and downloadable files for `lance-format/ms-marco-v2.1-lance`. Each row is one user query, the up-to-10 candidate passages Bing retrieved for it with relevance flags, and the human-written reference answers, with MiniLM query embeddings stored inline and pre-built ANN/FTS indices, available directly from the Hub at `hf://datasets/lance-format/ms-marco-v2.1-lance/data`. ## Key features * **Self-contained passage-ranking rows** — each query carries up to 10 candidate passages in parallel `passage_text` / `passage_url` / `passage_is_selected` columns, alongside the human-written `answers` and `well_formed_answers`. * **First relevant passage promoted to its own field** in `selected_passage`, so RAG / answer-evaluation workflows can read the gold context without indexing into the parallel passage lists. * **Pre-computed 384-dim query embeddings** (`query_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic query lookup. * **One columnar dataset** — scan query metadata cheaply, defer the heavy passage text reads to the rows that matter. ## Splits | Split | Rows | | - | - | | `train.lance` | 808,731 | | `validation.lance` | 101,093 | ## Schema | Column | Type | Notes | | - | - | - | | `query_id` | `int64` | MS MARCO query id | | `query` | `string` | The user's natural-language query | | `query_type` | `string` | One of `DESCRIPTION`, `NUMERIC`, `ENTITY`, `LOCATION`, `PERSON` | | `answers` | `list<string>` | Human-written reference answers | | `well_formed_answers` | `list<string>` | Reference answers re-written as full sentences | | `passage_text` | `list<string>` | Up to 10 candidate passages | | `passage_url` | `list<string>` | Source URLs for each candidate | | `passage_is_selected` | `list<int8>` | `1` if Bing labelled the passage relevant | | `selected_passage` | `string?` | First relevant passage (null if none) | | `query_emb` | `fixed_size_list<float32, 384>` | MiniLM query embedding | ## Pre-built indices * `IVF_PQ` on `query_emb` — semantic query lookup (cosine) * `INVERTED` (FTS) on `query` and `selected_passage` — keyword and hybrid search * `BTREE` on `query_id` — stable lookup by identifier * `BITMAP` on `query_type` — cheap predicate evaluation for query class ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/ms-marco-v2.1-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["query"], "->", row["answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. Each `.lance` file in `data/` is a table — open by name (`train`, `validation`). The same handle is used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/ms-marco-v2.1-lance --repo-type dataset --local-dir ./ms-marco-v2.1-lance > ``` > > Then point LanceDB at `./ms-marco-v2.1-lance/data`. ## Search The bundled `IVF_PQ` index on `query_emb` makes nearest-neighbour query lookup a single call. In production you would encode an incoming user query through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["query_emb", "query"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["query_emb"], vector_column_name="query_emb") .metric("cosine") .where("query_type = 'NUMERIC'", prefilter=True) .select(["query_id", "query", "selected_passage", "answers"]) .limit(10) .to_list() ) for r in hits: print(r["query"], "->", (r["selected_passage"] or "")[:120]) ``` The result set carries only the projected columns; the 384-d `query_emb` is never read on the result side, and the full `passage_text` list is left untouched, keeping the working set small even when the underlying scan touches every row of the validation split. Because the dataset also ships an `INVERTED` index on both `query` and `selected_passage`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the gold passage. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase must literally appear in the relevant passage but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["query_emb"]) .text("determinant matrix") .select(["query", "selected_passage", "answers"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["query"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate A typical curation pass over MS MARCO starts by combining metadata filters with structural predicates over the parallel passage lists before any heavy text gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(1000)` keeps the output small enough to inspect. The example below assembles a set of numeric questions for which Bing labelled at least one passage relevant and the annotators produced a well-formed reference answer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "query_type = 'NUMERIC' " "AND selected_passage IS NOT NULL " "AND array_length(well_formed_answers) > 0 " "AND length(query) >= 30", prefilter=True, ) .select(["query_id", "query", "answers", "well_formed_answers"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['query']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `query_id`s, or hand to the Evolve and Train sections below. Neither `passage_text` nor `query_emb` is read by this scan, so a 1000-row curation pass against the Hub moves only kilobytes of metadata. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `query_length` column and a `num_selected` count over the parallel `passage_is_selected` list, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./ms-marco-v2.1-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "query_length": "length(query)", "num_selected": "array_length(passage_is_selected)", "has_well_formed": "array_length(well_formed_answers) > 0", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (cross-encoder reranker scores, generated-answer judgments, alternate embeddings from a stronger model), add the new fields and update matching rows by `query_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa reranker_scores = pa.table({ "query_id": pa.array([1185869, 9083, 524332], type=pa.int64()), "reranker_top1_score": pa.array([0.91, 0.47, 0.83]), }) tbl.add_columns([f for f in reranker_scores.schema if f.name != "query_id"]) tbl.merge_insert("query_id").when_matched_update_all().execute(reranker_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different encoder over the query text), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a reader-style QA model the natural projection is the query plus the gold passage and the answer; for a query-encoder retraining loop the precomputed embedding is enough on its own. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["query", "selected_passage", "answers"]) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["query_emb", "passage_text", "passage_is_selected"]` to `select_columns(...)` on the next run reads only those columns, which is the right shape for training a passage reranker on cached query embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./ms-marco-v2.1-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("numeric-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="numeric-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `numeric-v1` keeps returning stable passages while the dataset evolves in parallel — newly added reranker scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same queries and passages, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/ms-marco-v2.1-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where( "query_type = 'NUMERIC' " "AND selected_passage IS NOT NULL " "AND array_length(well_formed_answers) > 0" ) .select(["query_id", "query", "query_type", "answers", "well_formed_answers", "selected_passage", "query_emb"]) .to_batches() ) local_db = lancedb.connect("./ms-marco-numeric") local_db.create_table("train", batches) ``` The resulting `./ms-marco-numeric` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/ms-marco-v2.1-lance/data` for `./ms-marco-numeric`. ## Source & license Converted from [`microsoft/ms_marco`](https://huggingface.co/datasets/microsoft/ms_marco) (`v2.1`). MS MARCO is released under the MIT license. ## Citation ``` @article{nguyen2016ms, title={MS MARCO: A Human Generated MAchine Reading COmprehension Dataset}, author={Nguyen, Tri and Rosenberg, Mir and Song, Xia and Gao, Jianfeng and Tiwary, Saurabh and Majumder, Rangan and Deng, Li}, journal={arXiv preprint arXiv:1611.09268}, year={2016} } ``` # Natural Questions Validation Source: https://docs.lancedb.com/oss/v0-41-0/datasets/natural-questions-val A Lance-formatted version of the Natural Questions validation split — 7,830 real Google search queries paired with the full Wikipedia article a human used to answer them, plus 1–5 annotator labels per question. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/natural-questions-val-lance) > > Source dataset card and downloadable files for `lance-format/natural-questions-val-lance`. MiniLM question embeddings are stored inline and the dataset ships with pre-built ANN/FTS indices, all available directly from the Hub at `hf://datasets/lance-format/natural-questions-val-lance/data`. Sourced from [`google-research-datasets/natural_questions`](https://huggingface.co/datasets/google-research-datasets/natural_questions). > The NQ **train** split is 143 GB (307,373 rows); it is intentionally not bundled here. Add it via `natural_questions/dataprep.py --splits train` once disk and bandwidth allow. ## Key features * **Real Google search queries** with the full Wikipedia article that answers each one — `document_html` carries the inline UTF-8 HTML, so no sidecar files or external lookups are needed at query time. * **Annotator answer summaries** — `short_answers` aggregates and dedupes spans across all annotators, `yes_no_answer` carries the majority vote, and the `has_short_answer` / `has_long_answer` flags make annotation-coverage filters a single predicate. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question lookup. * **One columnar dataset** — scan question metadata cheaply, then read the heavy `document_html` only for the rows you actually want. ## Splits | Split | Rows | | - | - | | `validation.lance` | 7,830 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | NQ example id | | `question` | `string` | Original Google search query | | `document_title` | `string` | Wikipedia article title | | `document_url` | `string` | Wikipedia article URL | | `document_html` | `large_binary` | Full HTML of the article (inline; UTF-8 bytes) | | `short_answers` | `list<string>` | Deduped short-answer spans across all annotators | | `num_short_answers` | `int32` | Total annotator spans (incl. duplicates) | | `has_short_answer` | `bool` | At least one annotator provided a short-answer span | | `has_long_answer` | `bool` | At least one annotator selected a long-answer candidate | | `yes_no_answer` | `string` | `YES` / `NO` / `NONE` — majority vote across annotators | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM question embedding | ## Pre-built indices * `IVF_PQ` on `question_emb` — semantic question lookup (cosine) * `INVERTED` (FTS) on `question` — keyword and hybrid search * `BTREE` on `id`, `document_title` — stable lookup by identifier * `BITMAP` on `yes_no_answer`, `has_short_answer`, `has_long_answer` — cheap predicate evaluation for annotation coverage ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/natural-questions-val-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["short_answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and HTML decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/natural-questions-val-lance --repo-type dataset --local-dir ./natural-questions-val-lance > ``` > > Then point LanceDB at `./natural-questions-val-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` makes nearest-neighbour question lookup a single call. In production you would encode an incoming user query through the same 384-dim MiniLM encoder used at ingest and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in so the snippet works without loading a model. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("has_short_answer = TRUE", prefilter=True) .select(["question", "short_answers", "document_title"]) .limit(10) .to_list() ) for r in hits: print(r["question"], "->", r["short_answers"]) ``` The result set carries only the projected columns; the 384-d `question_emb` is never read on the result side, and the heavy `document_html` is left untouched, keeping the working set small even though each row carries a full Wikipedia article inline. Because the dataset also ships an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query against the question text. LanceDB merges the two result lists and reranks them in a single call, which is useful when a named entity must literally appear in the query but the dense side still does most of the ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("declaration of independence") .select(["question", "short_answers", "document_title"]) .limit(10) .to_list() ) for r in hybrid_hits: print(r["question"]) ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency for your workload. ## Curate A typical curation pass over NQ starts with annotation-coverage filters before any HTML gets read. Lance evaluates the filter inside a single scan, so the candidate set comes back already filtered, and the bounded `.limit(500)` keeps the output small enough to inspect. The example below assembles a set of factoid questions with at least one short-answer span and a non-yes/no resolution. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "has_short_answer = TRUE " "AND yes_no_answer = 'NONE' " "AND array_length(short_answers) >= 1 " "AND length(question) >= 30", prefilter=True, ) .select(["id", "question", "short_answers", "document_title", "document_url"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of NQ example ids, or hand to the Evolve and Train sections below. The large `document_html` column is not read by this scan, so a 500-row curation pass against the Hub moves only kilobytes of metadata even though each row holds an entire Wikipedia article. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length` column, a `first_short_answer_length` derived from the deduped span list, and an `is_factoid` flag that combines the annotation flags, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./natural-questions-val-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "question_length": "length(question)", "first_short_answer_length": "length(short_answers[1])", "is_factoid": "has_short_answer = TRUE AND yes_no_answer = 'NONE'", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline retriever scores, generated-answer judgments, alternate embeddings from a stronger model), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa retriever_scores = pa.table({ "id": pa.array(["797803103333068850", "5225754983651766092"]), "bm25_top1_score": pa.array([14.2, 8.7]), }) tbl.add_columns([f for f in retriever_scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(retriever_scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., extracting the long-answer paragraph from `document_html`), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For an open-domain QA reader the natural projection is the question plus the full document HTML and the answer spans; for a question-encoder retraining loop the precomputed embedding is enough on its own, and skipping `document_html` keeps each batch small. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["question", "document_html", "short_answers"]) loader = DataLoader(train_ds, batch_size=4, shuffle=True, num_workers=2) for batch in loader: # batch carries only the projected columns; tokenize, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "short_answers"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the answer spans, which is the right shape for fine-tuning a retrieval head on cached embeddings without paying for the multi-megabyte `document_html` per row. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./natural-questions-val-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("factoid-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="factoid-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A QA system locked to `factoid-v1` keeps returning stable answer spans while the dataset evolves in parallel — newly added retriever scores or labels do not change what the tag resolves to. An evaluation experiment pinned to the same tag can be rerun later against the exact same questions and articles, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/natural-questions-val-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where( "has_short_answer = TRUE " "AND yes_no_answer = 'NONE' " "AND array_length(short_answers) >= 1" ) .select(["id", "question", "document_title", "document_url", "short_answers", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./nq-factoid") local_db.create_table("validation", batches) ``` The resulting `./nq-factoid` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/natural-questions-val-lance/data` for `./nq-factoid`. Note that this projection deliberately omits `document_html`; include it in the `.select(...)` list when the downstream task needs the article body. ## Source & license Converted from [`google-research-datasets/natural_questions`](https://huggingface.co/datasets/google-research-datasets/natural_questions). NQ is released under [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) (matching the Wikipedia source). ## Citation ``` @article{kwiatkowski2019natural, title={Natural Questions: A Benchmark for Question Answering Research}, author={Kwiatkowski, Tom and Palomaki, Jennimaria and Redfield, Olivia and Collins, Michael and Parikh, Ankur and Alberti, Chris and Epstein, Danielle and Polosukhin, Illia and Devlin, Jacob and Lee, Kenton and Toutanova, Kristina and Jones, Llion and Kelcey, Matthew and Chang, Ming-Wei and Dai, Andrew M. and Uszkoreit, Jakob and Le, Quoc and Petrov, Slav}, journal={Transactions of the Association for Computational Linguistics}, year={2019} } ``` # OpenVid-1M Source: https://docs.lancedb.com/oss/v0-41-0/datasets/openvid A Lance-formatted version of the OpenVid-1M corpus — 937,957 high-quality clips with inline MP4 bytes, 1024-dim video embeddings, captions, and rich per-clip quality signals — available directly from the Hub at hf://datasets/lance-format/openvid-lance/data/train.lance. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/openvid-lance) > > Source dataset card and downloadable files for `lance-format/openvid-lance`. ![](https://huggingface.co/datasets/nkp37/OpenVid-1M/resolve/main/OpenVid-1M.png) ## Key features * **Inline MP4 bytes** in the `video_blob` column, stored in a side blob file and surfaced as lazy `BlobFile` handles via `tbl.fetch_blob_files` — metadata scans, search, and filtering never read a single byte of video data. * **Pre-computed 1024-dim video embeddings** in `embedding` with a bundled `IVF_PQ` ANN index. * **Pre-built `INVERTED` (FTS) index on `caption`** for keyword and hybrid search. * **Rich quality signals** — `aesthetic_score`, `motion_score`, `temporal_consistency_score`, `camera_motion`, `fps`, `seconds` — that downstream filters can stack on. ## Splits `train.lance` ## Schema | Column | Type | Notes | | - | - | - | | `video_blob` | `large_binary` (blob-encoded) | Inline MP4 bytes; stored in a separate blob file and read lazily through `tbl.fetch_blob_files` | | `video_path` | `string` | Original file path / object key | | `caption` | `string` | Text description of the clip | | `embedding` | `fixed_size_list<float32, 1024>` | Video embedding | | `aesthetic_score` | `float64` | Visual quality, roughly 0–6 | | `motion_score` | `float64` | Amount of motion, 0–1 | | `temporal_consistency_score` | `float64` | Frame-to-frame stability, 0–1 | | `camera_motion` | `string` | `pan`, `zoom`, `static`, etc. | | `fps` | `float64` | Frames per second | | `seconds` | `float64` | Clip duration | | `frame` | `int64` | Total frame count | ## Pre-built indices * `IVF_PQ` on `embedding` — video similarity (L2) * `INVERTED` (FTS) on `caption` — keyword and hybrid search ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you just want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/openvid-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access, ANN search, and video decoding are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/openvid-lance --repo-type dataset --local-dir ./openvid > ``` > > Then point LanceDB at `./openvid/data`. ## Search The bundled `IVF_PQ` index on `embedding` makes approximate-nearest-neighbor search a single call. In production you would encode a text prompt through a text-to-video model or a reference clip through the same video encoder used at ingest, and pass the resulting 1024-d vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["embedding", "caption"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["embedding"]) .metric("L2") .select(["caption", "aesthetic_score", "camera_motion", "seconds"]) .limit(10) .to_list() ) for r in hits: print(f"{r['aesthetic_score']:.2f} | {r['camera_motion']:>8} | {r['caption'][:60]}") ``` The result set carries only the projected columns. The `video_blob` column is never read, so the network traffic for a top-10 search is dominated by a few kilobytes of caption text, not by megabytes of MP4. The lazy blob fetch comes later — see Curate below. Because OpenVid also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["embedding"]) .text("sunset over the ocean") .select(["caption", "aesthetic_score", "seconds"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['aesthetic_score']:.2f} | {r['seconds']:.1f}s | {r['caption'][:60]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Curation for a video workflow almost always starts as a metadata filter — pick the dynamic, high-aesthetic, well-stabilized clips first, then decide what to do with the video bytes. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "aesthetic_score >= 4.5 " "AND motion_score >= 0.3 " "AND temporal_consistency_score >= 0.9", prefilter=True, ) .select(["caption", "camera_motion", "aesthetic_score", "fps", "seconds"]) .limit(200) .with_row_id(True) .to_list() ) print(f"{len(candidates)} clips selected") ``` The scan above never reads the `video_blob` column. Lance stores blobs in a separate side file referenced by the dataset, so column-projected reads skip them entirely until they are explicitly requested. That is what makes "find me the right clips" a metadata-only operation against a million-row video corpus. Once the candidate set is fixed, open lazy video handles with `tbl.fetch_blob_files` (requires `lancedb >= 0.41.0` for legacy blob-encoded columns). It returns one `BlobFile` per row — a seekable file-like handle that streams from inline blob storage on demand rather than reading the full clip into Python memory up front. For video specifically, this is the operation that matters: a video model trainer or a dataloader inspecting a few seconds of each clip should never have to materialize entire MP4s in memory just to inspect or decode part of them. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} row_ids = [r["_rowid"] for r in candidates[:10]] blob_files = tbl.fetch_blob_files("video_blob", row_ids) ``` Each `BlobFile` implements the file protocol, so it can be passed straight to a decoder like PyAV without first being copied through a `bytes` object. The decoder seeks and reads against the underlying handle, which means a 2-second sample from a 30-second clip moves only the bytes the decoder actually touches — not the whole MP4. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import av with av.open(blob_files[0]) as container: stream = container.streams.video[0] for seconds in (0.0, 1.0, 2.5): target = int(seconds / stream.time_base) container.seek(target, stream=stream) frame = next( (f for f in container.decode(stream) if f.time is not None and f.time >= seconds), None, ) if frame is not None: print(f" seek {seconds:.1f}s -> {frame.width}x{frame.height} @ {frame.time:.2f}s") ``` If you only need the raw bytes (e.g., to persist a hand-picked subset to disk), call `.read()` on each handle. The lazy semantics are the same; `read()` simply materializes the full blob for that one row. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} for r_id, blob in zip(row_ids, blob_files): blob.seek(0) with open(f"clip_{r_id}.mp4", "wb") as f: f.write(blob.read()) ``` ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data — including the video blobs, which stay exactly where they are. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `duration_bucket` and a `is_high_quality` flag, either of which can then be used directly in `where` clauses without re-evaluating the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./openvid/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "duration_bucket": ( "CASE WHEN seconds < 5 THEN 'short' " "WHEN seconds < 15 THEN 'medium' ELSE 'long' END" ), "is_high_quality": ( "aesthetic_score >= 4.5 AND temporal_consistency_score >= 0.9" ), }) ``` The original columns and the `video_blob` side file are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, safety classifications, a second embedding from a different encoder), add the new fields and update matching rows by `video_path`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa labels = pa.table({ "video_path": pa.array(["s3://openvid/clips/00001.mp4", "s3://openvid/clips/00002.mp4"]), "scene_label": pa.array(["beach", "city"]), }) tbl.add_columns([f for f in labels.schema if f.name != "video_path"]) tbl.merge_insert("video_path").when_matched_update_all().execute(labels) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternative video encoder over the inline bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train A common pattern for video training is to pre-extract decoded frames once into a derived LanceDB table, and train against that table with the regular projection-based dataloader. `tbl.fetch_blob_files` is the mechanism that makes the extraction step tractable: each clip's MP4 is randomly addressable, so the pass can subset bytes on demand and write decoded windows into a fresh table without an external file store. Other workflows project `video_blob` directly through `select_columns(...)` and decode at the batch boundary, or skip pixels entirely and train on the cached embeddings — the right shape is workload-specific. The actual training loop is the same `Permutation.identity(tbl).select_columns(...)` snippet in every case; only the source table and the column list change. Against a pre-extracted frames table: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("./openvid-frames") # local table produced by the one-time extraction tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["frames", "caption", "aesthetic_score"]) loader = DataLoader(train_ds, batch_size=8, shuffle=True, num_workers=4) ``` Against the cached embeddings on the source table (no pre-extraction): ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader src_db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") src_tbl = src_db.open_table("train") train_ds = Permutation.identity(src_tbl).select_columns(["embedding", "caption"]) loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4) ``` The inline `video_blob` storage and `tbl.fetch_blob_files` still earn their place outside of the training loop — random-access inspection of a clip in a notebook, sampling for human review, one-off evaluation against a held-out set, and the pre-extraction step itself — but they are not the dataloader. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk, with the same blob handles still valid. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./openvid/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("quality-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="quality-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `quality-v1` keeps returning stable results while the dataset evolves in parallel — newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same clips, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access into the blob file. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory — including the `video_blob` column, which streams through Arrow record batches rather than being assembled in a single buffer. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/openvid-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("aesthetic_score >= 4.5 AND motion_score >= 0.3") .select(["caption", "embedding", "video_blob", "aesthetic_score", "camera_motion"]) .to_batches() ) local_db = lancedb.connect("./openvid-subset") local_db.create_table("train", batches) ``` The resulting `./openvid-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/openvid-lance/data` for `./openvid-subset`. The same `fetch_blob_files` pattern from Curate also works against the local copy — and runs faster, because the blob side file is now on local disk. ## Citation ``` @article{nan2024openvid, title={OpenVid-1M: A Large-Scale High-Quality Dataset for Text-to-video Generation}, author={Nan, Kepan and Xie, Rui and Zhou, Penghao and Fan, Tiehan and Yang, Zhenheng and Chen, Zhijie and Li, Xiang and Yang, Jian and Tai, Ying}, journal={arXiv preprint arXiv:2407.02371}, year={2024} } ``` ## License Content inherits the original OpenVid-1M dataset license. Review the [upstream dataset card](https://huggingface.co/datasets/nkp37/OpenVid-1M) before downstream use. # Oxford-IIIT Pet Source: https://docs.lancedb.com/oss/v0-41-0/datasets/oxford-pets A Lance-formatted version of the Oxford-IIIT Pet dataset — 7,390 cat and dog photos across 37 breeds — sourced from pcuenq/oxford-pets. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/oxford-pets-lance) > > Source dataset card and downloadable files for `lance-format/oxford-pets-lance`. Each row carries the inline JPEG bytes, the breed name, a species flag distinguishing cats from dogs, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/oxford-pets-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **Both breed and species labels** (`label_name`, `is_dog`) so a query can target a specific breed, all dogs, or all cats by stacking simple predicates. * **Bitmap indices on both label columns** make species- and breed-based curation a cheap predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 7,390 | The `pcuenq/oxford-pets` source mirror ships a single split; the canonical Oxford-IIIT trainval/test partition is not pre-applied here. | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (quality 92) | | `label_name` | `string` | One of 37 breeds, underscore-spaced (`british_shorthair`, `golden_retriever`, …) | | `is_dog` | `bool` | `true` for dog breeds, `false` for cat breeds | | `path` | `string?` | Original filename from the source dataset | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `BITMAP` on `label_name` — fast lookup by breed * `BITMAP` on `is_dog` — fast species filter ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/oxford-pets-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label_name"], row["is_dog"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/oxford-pets-lance --repo-type dataset --local-dir ./oxford-pets-lance > ``` > > Then point LanceDB at `./oxford-pets-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without a model loaded; on a clean run the first hit is expected to be the seed image itself, which is a useful sanity check on the index. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "label_name", "is_dog"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label_name", "is_dog"]) .limit(10) .to_list() ) print(f"seed: {seed['label_name']} (is_dog={seed['is_dog']})") for r in hits: print(f" {r['id']:>5} {r['label_name']:<22} is_dog={r['is_dog']}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. ## Curate A typical curation pass for a fine-grained pet classifier stacks the species predicate and a breed predicate inside a single filtered scan. With bitmap indices on both `label_name` and `is_dog`, the result comes back in milliseconds, and the bounded `.limit(200)` keeps it small enough to inspect or hand off to a training run. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where("is_dog = true AND label_name IN ('golden_retriever', 'beagle', 'pug')") .select(["id", "label_name", "is_dog", "path"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['label_name']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read by this query, so the network traffic is dominated by the small label fields rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below derives a `species` string from the `is_dog` boolean and adds a coarse breed-group flag for terriers, either of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./oxford-pets-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "species": "CASE WHEN is_dog THEN 'dog' ELSE 'cat' END", "is_terrier": "label_name LIKE '%terrier%'", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, an integer class id), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_ids = pa.table({ "id": pa.array([0, 1, 2]), "label_int": pa.array([0, 0, 17]), }) tbl.add_columns([f for f in class_ids.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_ids) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second embedding model over the JPEG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch breed classifier, project the JPEG bytes and the string breed label; for a linear probe on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label_name"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEG bytes, map label_name -> int via a class list, forward, cross-entropy... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label_name"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe or a lightweight reranker. Projecting `["image", "is_dog"]` reduces the task to binary species classification on the same data. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./oxford-pets-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/oxford-pets-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("is_dog = true") .select(["id", "image", "label_name", "is_dog", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./oxford-pets-dogs-subset") local_db.create_table("train", batches) ``` The resulting `./oxford-pets-dogs-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/oxford-pets-lance/data` for `./oxford-pets-dogs-subset`. ## Source & license Converted from [`pcuenq/oxford-pets`](https://huggingface.co/datasets/pcuenq/oxford-pets). Released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @inproceedings{parkhi2012cats, title={Cats and Dogs}, author={Parkhi, Omkar M. and Vedaldi, Andrea and Zisserman, Andrew and Jawahar, C. V.}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2012} } ``` # Pascal VOC 2012 Segmentation Source: https://docs.lancedb.com/oss/v0-41-0/datasets/pascal-voc-2012-segmentation A Lance-formatted version of the Pascal VOC 2012 semantic segmentation split, sourced from nateraw/pascal-voc-2012. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/pascal-voc-2012-segmentation-lance) > > Source dataset card and downloadable files for `lance-format/pascal-voc-2012-segmentation-lance`. Each row pairs an inline JPEG image with the per-pixel PNG segmentation mask and a cosine-normalized OpenCLIP `ViT-B-32` image embedding, so a single columnar table carries both annotation modalities and the features needed to retrieve, curate, and train against them — all available directly from the Hub at `hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data`. ## Key features * **Inline JPEG bytes and inline PNG mask bytes in the same row** — image and per-pixel segmentation travel together with no sidecar folders or mask lookups. * **Pre-computed CLIP image embeddings** (`image_emb`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for visual similarity search. * **Standard VOC class encoding** — mask pixel values are class ids in `0..20` plus `255` for void, identical to the official VOC palette. * **One columnar dataset** — scan image-level metadata cheaply, then fetch image or mask bytes only for the rows you actually want. The 20 Pascal VOC foreground classes are: `aeroplane`, `bicycle`, `bird`, `boat`, `bottle`, `bus`, `car`, `cat`, `chair`, `cow`, `diningtable`, `dog`, `horse`, `motorbike`, `person`, `pottedplant`, `sheep`, `sofa`, `train`, `tvmonitor`. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 1,464 | Official VOC 2012 segmentation train | | `validation.lance` | 1,449 | Official VOC 2012 segmentation val | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within the split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes | | `mask` | `large_binary` | Inline PNG bytes — class id per pixel (0=background, 1-20=VOC classes, 255=void) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — `metric=cosine` > Note: the small split sizes (≤1,464 rows) sit below Lance's default partition count, so the helper falls back to a smaller `num_partitions` automatically. For higher recall, rebuild the index with `num_partitions=16` against a local copy. ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/pascal-voc-2012-segmentation-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["id"], len(row["image"]), len(row["mask"])) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/pascal-voc-2012-segmentation-lance --repo-type dataset --local-dir ./pascal-voc-2012-segmentation-lance > ``` > > Then point LanceDB at `./pascal-voc-2012-segmentation-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes visual nearest-neighbour search a single call. In production you would encode a query image (or a class prototype) through OpenCLIP `ViT-B-32` at runtime and pass the resulting 512-d cosine-normalized vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id"]) .limit(10) .to_list() ) for r in hits: print(r["id"]) ``` Because the embeddings are cosine-normalized, `metric="cosine"` is the natural choice and the first hit is typically the seed row itself — a useful sanity check before tuning `nprobes` and `refine_factor` for recall. ## Curate A typical curation pass for a segmentation workflow combines visual similarity with a structural filter on the row. Stacking both inside a single filtered scan keeps the candidate set small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing to anything downstream. The snippet below seeds from row 42 and restricts the candidates to rows whose mask payload is non-trivially sized — a cheap proxy for masks that actually carry foreground annotation. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb"]) .limit(1) .offset(42) .to_list()[0] ) candidates = ( tbl.search(seed["image_emb"]) .metric("cosine") .where("octet_length(mask) > 2000", prefilter=True) .select(["id"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `mask` columns are never read in the candidate scan, so the network traffic stays dominated by the embedding vectors rather than image or mask bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `image_bytes` size and a `has_mask` flag, both of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./pascal-voc-2012-segmentation-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "image_bytes": "octet_length(image)", "has_mask": "octet_length(mask) > 1024", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. For class-level statistics — for example, a per-row list of class ids present in the mask, or a per-class pixel count — the values cannot be derived in SQL because they require decoding the PNG. Compute them once in an external table and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_stats = pa.table({ "id": pa.array([0, 1, 2], type=pa.int64()), "classes_present": pa.array([[15], [7, 15], [9]], type=pa.list_(pa.int8())), }) tbl.add_columns([f for f in class_stats.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_stats) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require running a model over the image bytes (a second-pass embedding, an instance segmentation, a depth prediction), Lance also provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a segmentation run, project the JPEG bytes and the PNG mask bytes together; everything else, including the CLIP embeddings, stays on disk until you opt in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "mask"]) loader = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb stays on disk. # decode the JPEGs and PNGs, build (image, label) tensors, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["image_emb"]` to `select_columns(...)` on the next run skips JPEG and PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight linear probe over frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges class statistics, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./pascal-voc-2012-segmentation-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("voc2012-clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="voc2012-clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `voc2012-clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added class statistics or alternative embeddings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same image/mask pairs, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("octet_length(mask) > 2000") .select(["id", "image", "mask", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./voc-subset") local_db.create_table("train", batches) ``` The resulting `./voc-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/pascal-voc-2012-segmentation-lance/data` for `./voc-subset`. ## Source & license Converted from [`nateraw/pascal-voc-2012`](https://huggingface.co/datasets/nateraw/pascal-voc-2012). The Pascal VOC dataset is released under [its own custom license](http://host.robots.ox.ac.uk/pascal/VOC/) — please review before redistribution. ## Citation ``` @misc{everingham2012pascal, title={The Pascal Visual Object Classes Challenge: A Retrospective}, author={Everingham, Mark and Eslami, S. M. Ali and Van Gool, Luc and Williams, Christopher K. I. and Winn, John and Zisserman, Andrew}, journal={International Journal of Computer Vision}, year={2015} } ``` # SQuAD v2 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/squad-v2 A Lance-formatted version of SQuAD v2 — the Stanford Question Answering Dataset with both answerable and deliberately unanswerable questions over Wikipedia passages — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/squad-v2-lance/data. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/squad-v2-lance) > > Source dataset card and downloadable files for `lance-format/squad-v2-lance`. ## Key features * **Span-extraction QA over Wikipedia** with 130k+ training questions and an `is_impossible` flag that cleanly separates answerable from unanswerable items. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question retrieval. * **Full-text inverted indices** on both `question` and `context` for keyword search alongside dense retrieval. * **One columnar dataset** carrying questions, contexts, answer spans, and embeddings together — project only the columns each query needs. ## Splits | Split | Rows | | - | - | | `train.lance` | 130,319 | | `validation.lance` | 11,873 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `string` | SQuAD question id (natural join key for merges) | | `title` | `string` | Wikipedia article title | | `context` | `string` | Paragraph the question was generated from | | `question` | `string` | The question text | | `answers` | `list<string>` | Accepted answer spans (empty for impossible questions) | | `answer_starts` | `list<int32>` | Character offsets of each answer within `context` | | `is_impossible` | `bool` | `true` for SQuAD 2.0 unanswerable questions | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM embedding of `question` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `question_emb` — `metric=cosine`, vector similarity search * `INVERTED` on `question` and `context` — full-text search * `BTREE` on `id` and `title` — point lookups and prefix scans * `BITMAP` on `is_impossible` — fast filtering between answerable and unanswerable ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/squad-v2-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answers"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/squad-v2-lance --repo-type dataset --local-dir ./squad-v2-lance > ``` > > Then point LanceDB at `./squad-v2-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` turns semantic question retrieval into a single call. In production you would encode an incoming question through the same MiniLM encoder used at ingest and pass the resulting 384-dim vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in, then restricts the result to answerable items so the response always carries a usable span. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .where("is_impossible = false", prefilter=True) .select(["id", "title", "question", "answers"]) .limit(10) .to_list() ) for r in hits: print(f"{r['title']:30s} | {r['question'][:80]}") ``` Because the recommended setup also builds an `INVERTED` index on both `question` and `context`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges and reranks the two result lists in a single call, which is useful when a literal phrase must appear in the passage but the dense side should still drive ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("eiffel tower") .where("is_impossible = false", prefilter=True) .select(["id", "title", "question", "context", "answers"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['title']:30s} | {r['question'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate SQuAD v2 has a natural split between answerable and unanswerable questions, and the `is_impossible` boolean — backed by a `BITMAP` index — makes either subset cheap to extract. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it easy to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") impossible = ( tbl.search() .where("is_impossible = true AND length(question) >= 40", prefilter=True) .select(["id", "title", "question", "context"]) .limit(1000) .to_list() ) print(f"{len(impossible)} hard unanswerable questions; first title: {impossible[0]['title']}") ``` The mirror query — long, well-grounded answerable questions — looks identical with the boolean flipped, and the `question_emb` vector is never read by either scan. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Materialize-a-subset section below for export to a writable local copy. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length`, a `num_answers` count, and a `has_answer` flag — any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./squad-v2-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "num_answers": "array_length(answers)", "has_answer": "NOT is_impossible", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reader-model predictions, alternate embeddings, span-level labels), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa scores = pa.table({ "id": pa.array(["56be4db0acb8001400a502ec", "56be4db0acb8001400a502ed"]), "reader_score": pa.array([0.91, 0.42]), }) tbl.add_columns([f for f in scores.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the questions), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a reading-comprehension model the natural projection is the question, the context, and the answer spans together; for a retriever or reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["question", "context", "answers", "answer_starts", "is_impossible"] ) loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; question_emb stays on disk. # tokenize question+context, build span labels from answer_starts, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb"]` (optionally with `["answers"]` for hard-negative mining) to `select_columns(...)` on the next run reads only the 384-d vectors and skips the bulky `context` strings entirely, which is the right shape for training a retrieval head or reranker on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./squad-v2-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="baseline-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `baseline-v1` keeps returning stable results while the dataset evolves in parallel — newly added reader scores or labels do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and contexts, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("is_impossible = false AND length(question) >= 30") .select(["id", "title", "context", "question", "answers", "answer_starts", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./squad-v2-answerable") local_db.create_table("train", batches) ``` The resulting `./squad-v2-answerable` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/squad-v2-lance/data` for `./squad-v2-answerable`. ## Source & license Converted from [`rajpurkar/squad_v2`](https://huggingface.co/datasets/rajpurkar/squad_v2). SQuAD v2 is distributed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). ## Citation ``` @article{rajpurkar2018know, title={Know What You Don't Know: Unanswerable Questions for SQuAD}, author={Rajpurkar, Pranav and Jia, Robin and Liang, Percy}, journal={Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Short Papers)}, year={2018} } ``` # Stanford Cars Source: https://docs.lancedb.com/oss/v0-41-0/datasets/stanford-cars A Lance-formatted version of the Stanford Cars fine-grained benchmark — 8,144 photographs across 196 make/model/year classes — sourced from Multimodal-Fatima/StanfordCars_train. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/stanford-cars-lance) > > Source dataset card and downloadable files for `lance-format/stanford-cars-lance`. Each row carries the inline JPEG bytes, the integer class id, a BLIP-generated caption inherited from the source mirror, and a cosine-normalized CLIP image embedding, all available directly from the Hub at `hf://datasets/lance-format/stanford-cars-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files, no image folders. * **Pre-computed CLIP image embeddings** (`image_emb`, OpenCLIP `ViT-B-32`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index for similarity search. * **BLIP captions in `blip_caption`** with a full-text index, so keyword search on visual descriptions composes with vector search in a single query. * **A bundled scalar index on `label`** makes class-based curation a cheap predicate rather than a full scan. ## Splits | Split | Rows | Notes | | - | - | - | | `train.lance` | 8,144 | The source mirror redistributes a single split; the original Stanford Cars test split is not included here. | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split (natural join key for merges) | | `image` | `large_binary` | Inline JPEG bytes (quality 92) | | `label` | `int32` | Class id (0–195), one per Make Model Year combination | | `blip_caption` | `string?` | BLIP-generated caption (beam=5) carried through from the source mirror | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP `ViT-B-32` image embedding (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `image_emb` — vector similarity search (cosine) * `INVERTED` (FTS) on `blip_caption` — keyword and hybrid search * `BTREE` on `label` — fast lookup by class id ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/stanford-cars-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["label"], row["blip_caption"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Train, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/stanford-cars-lance --repo-type dataset --local-dir ./stanford-cars-lance > ``` > > Then point LanceDB at `./stanford-cars-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes approximate-nearest-neighbor search a single call. In production you would encode a query photo through the same OpenCLIP `ViT-B-32` model used at ingest and pass the resulting 512-d vector to `tbl.search(...)`. The example below uses the embedding stored in row 0 as a runnable stand-in so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["image_emb", "blip_caption"]) .limit(1) .to_list()[0] ) hits = ( tbl.search(seed["image_emb"]) .metric("cosine") .select(["id", "label", "blip_caption"]) .limit(10) .to_list() ) print("seed caption:", seed["blip_caption"]) for r in hits: print(f" {r['id']:>6} label={r['label']:>3} {r['blip_caption'][:60]}") ``` Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency for your workload. Because the dataset also ships an `INVERTED` index on `blip_caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "red convertible" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["image_emb"]) .text("red convertible") .select(["id", "label", "blip_caption"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['id']:>6} label={r['label']:>3} {r['blip_caption'][:60]}") ``` ## Curate A typical curation pass for a fine-grained classifier combines a class-based filter with a content filter on the caption. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(200)` makes it cheap to inspect before committing the subset to anything downstream. The `BTREE` on `label` and the `INVERTED` index on `blip_caption` make both predicates effectively free. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") candidates = ( tbl.search("convertible OR coupe") .where("label IN (12, 47, 89)", prefilter=True) .select(["id", "label", "blip_caption"]) .limit(200) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['blip_caption'][:80]}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 200-row candidate scan is dominated by the small caption strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. Stanford Cars class strings often encode the model year as a trailing four-digit token in the caption; the example below uses a SQL regex to lift that year into its own column, and adds a flag for vintage cars. Either can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./stanford-cars-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "caption_year": "CAST(regexp_extract(blip_caption, '(\\d{4})', 1) AS INTEGER)", "is_long_caption": "length(blip_caption) >= 80", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline labels, classifier predictions, the Make Model Year strings from the original Stanford metadata), add the new fields and update matching rows by `id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa class_strings = pa.table({ "id": pa.array([0, 1, 2]), "class_name": pa.array([ "AM General Hummer SUV 2000", "Acura RL Sedan 2012", "Acura TL Sedan 2012", ]), }) tbl.add_columns([f for f in class_strings.schema if f.name != "id"]) tbl.merge_insert("id").when_matched_update_all().execute(class_strings) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a second captioner over the image bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern. ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetch, shuffling, and batching behave as in any PyTorch pipeline. For a from-scratch fine-grained classifier, project the JPEG bytes and the integer label; for a linear probe on top of frozen CLIP features, swap the projection to the embedding column and skip JPEG decoding entirely. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "label"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; image_emb and blip_caption stay on disk. # decode the JPEG bytes, forward, cross-entropy against `label`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run reads only the cached 512-d vectors and the label, which is the right shape for a linear probe or a lightweight reranker. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./stanford-cars-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("clip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="clip-vitb32-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added columns or captions do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/stanford-cars-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search("convertible OR coupe") .select(["id", "image", "label", "blip_caption", "image_emb"]) .to_batches() ) local_db = lancedb.connect("./stanford-cars-sports-subset") local_db.create_table("train", batches) ``` The resulting `./stanford-cars-sports-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/stanford-cars-lance/data` for `./stanford-cars-sports-subset`. ## Source & license Converted from [`Multimodal-Fatima/StanfordCars_train`](https://huggingface.co/datasets/Multimodal-Fatima/StanfordCars_train), itself a redistribution of the Stanford Cars dataset. The original dataset is for non-commercial research use; review the [archived Stanford Cars usage FAQ](https://web.archive.org/web/20210219110131/https://ai.stanford.edu/~jkrause/cars/car_dataset.html) before redistribution. ## Citation ``` @inproceedings{krause2013collecting, title={Collecting a large-scale dataset of fine-grained cars}, author={Krause, Jonathan and Stark, Michael and Deng, Jia and Fei-Fei, Li}, booktitle={Workshop on Fine-Grained Visual Categorization (CVPR)}, year={2013} } ``` # TextVQA Source: https://docs.lancedb.com/oss/v0-41-0/datasets/textvqa A Lance-formatted version of TextVQA — visual question answering where the question requires reading text in the image (street signs, product labels, screen captures) — sourced from lmms-lab/textvqa. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/textvqa-lance) > > Source dataset card and downloadable files for `lance-format/textvqa-lance`. Each row carries the image bytes, the question, the 10 reference annotator answers, the OCR tokens detected by the source pre-processing, OpenImages-style scene tags, and paired CLIP image and question embeddings — all available directly from the Hub at `hf://datasets/lance-format/textvqa-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files or image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (OpenCLIP ViT-B/32, 512-dim, cosine-normalized) — so cross-modal text→image retrieval is one indexed lookup. * **OCR tokens travel with the row** in `ocr_tokens`, which makes OCR-aware filtering and reranking a single SQL predicate alongside the visual and textual features. * **Pre-built ANN, FTS, and scalar indices** covering both embeddings, the question and canonical answer, and the source partition. ## Splits | Split | Rows | | - | - | | `validation.lance` | 5,000 | | `train.lance` | 34,602 | ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `string?` | TextVQA image id | | `question_id` | `string?` | TextVQA question id | | `question` | `string` | The question text | | `answers` | `list<string>` | 10 annotator answers | | `answer` | `string` | First annotator answer (used as canonical / FTS target) | | `ocr_tokens` | `list<string>` | OCR tokens detected on the image | | `image_classes` | `list<string>` | OpenImages-style scene tags from the source | | `set_name` | `string?` | Source partition (`train`, `val`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | OpenCLIP text embedding of the question | ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search * `BTREE` on `image_id`, `question_id`, `set_name` — fast lookup by id and partition ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/textvqa-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/textvqa-lance --repo-type dataset --local-dir ./textvqa-lance > ``` > > Then point LanceDB at `./textvqa-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same OpenCLIP model used at ingest (ViT-B/32 `laion2b_s34b_b79k`, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question", "answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "answer", "ocr_tokens"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["answer"]) for r in hits: print(f" {r['image_id']:>14} {r['question'][:60]} ocr={r['ocr_tokens'][:5]}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased questions instead of visually similar images. Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is particularly useful for TextVQA, where a brand name or sign content like "stop" must literally appear in the question (or eventually, the answer) while CLIP handles the visual side. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("brand name") .select(["image_id", "question", "answer", "ocr_tokens"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>14} {r['question'][:60]} -> {r['answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate Curation passes for TextVQA usually combine an OCR-driven structural filter (does this image actually contain a meaningful amount of detected text?) with a content predicate on the question or the canonical answer, so the candidate set is both visually interesting and topically focused. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "array_length(ocr_tokens) >= 5 AND question LIKE '%brand%' AND length(answer) > 0", prefilter=True, ) .select(["question_id", "image_id", "question", "answer", "ocr_tokens"]) .limit(500) .to_list() ) print(f"{len(candidates)} candidates; first: {candidates[0]['question']} -> {candidates[0]['answer']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by question, answer, and OCR-token strings rather than JPEG bytes. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `ocr_token_count`, an `is_yes_no_question` flag, and an `answer_length` integer, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./textvqa-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "ocr_token_count": "array_length(ocr_tokens)", "is_yes_no_question": "lower(answer) IN ('yes', 'no')", "answer_length": "length(answer)", "question_length": "length(question)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a stronger OCR system's tokens, a model's predicted answer, an annotator-disagreement score), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array(["34602", "34603"]), "model_answer": pa.array(["pepsi", "exit"]), "model_confidence": pa.array([0.88, 0.72]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternate OCR engine over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a TextVQA fine-tune that needs OCR conditioning, project the JPEG bytes, the question, the OCR tokens, and the canonical answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "ocr_tokens", "answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question and OCR tokens, forward through the VLM, # compute the loss against `answer`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./textvqa-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("openclip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="openclip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `openclip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added OCR systems or model predictions do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, questions, and OCR tokens, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("array_length(ocr_tokens) >= 5") .select(["question_id", "image_id", "image", "question", "answer", "ocr_tokens", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./textvqa-ocr-rich") local_db.create_table("train", batches) ``` The resulting `./textvqa-ocr-rich` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/textvqa-lance/data` for `./textvqa-ocr-rich`. ## Source & license Converted from [`lmms-lab/textvqa`](https://huggingface.co/datasets/lmms-lab/textvqa). TextVQA is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) by Singh et al. (Facebook AI Research). ## Citation ``` @inproceedings{singh2019towards, title={Towards VQA models that can read}, author={Singh, Amanpreet and Natarajan, Vivek and Shah, Meet and Jiang, Yu and Chen, Xinlei and Batra, Dhruv and Parikh, Devi and Rohrbach, Marcus}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2019} } ``` # TriviaQA Source: https://docs.lancedb.com/oss/v0-41-0/datasets/trivia-qa A Lance-formatted version of TriviaQA (rc.nocontext config) — a large reading-comprehension dataset of trivia questions paired with a canonical answer, accepted aliases, and entity-type metadata — with MiniLM question embeddings stored inline and ready for retrieval at hf://datasets/lance-format/trivia-qa-lance/data. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/trivia-qa-lance) > > Source dataset card and downloadable files for `lance-format/trivia-qa-lance`. The `rc.nocontext` slice is the standard reading-comprehension form without the multi-gigabyte `entity_pages` / `search_results` payloads, which keeps the dataset compact while preserving everything needed for closed-book QA, retrieval research, and as a search target. ## Key features * **138k+ trivia questions** with a canonical `answer_value`, normalized form for exact-match scoring, and a list of accepted `answer_aliases`. * **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question retrieval. * **Full-text inverted index** on `question` for keyword search and hybrid retrieval. * **One columnar dataset** carrying questions, canonical answers, aliases, types, and embeddings together — project only the columns each query needs. ## Splits | Split | Rows | | - | - | | `train.lance` | 138,384 | | `validation.lance` | 17,944 | ## Schema | Column | Type | Notes | | - | - | - | | `question_id` | `string` | TriviaQA question id (e.g. `tc_1`); natural join key for merges | | `question` | `string` | The trivia question | | `question_source` | `string` | URL or source the question came from | | `answer_value` | `string` | Canonical answer | | `answer_aliases` | `list<string>` | Other accepted phrasings (e.g. `["Sinclair Lewis", "Harry Sinclair Lewis"]`) | | `normalized_answer` | `string` | Lowercased / normalized form for exact-match scoring | | `answer_type` | `string` | TriviaQA entity type (e.g. `WikipediaEntity`, `FreebaseEntity`) | | `question_emb` | `fixed_size_list<float32, 384>` | MiniLM embedding of `question` (cosine-normalized) | ## Pre-built indices * `IVF_PQ` on `question_emb` — `metric=cosine`, vector similarity search * `INVERTED` on `question` — full-text search * `BTREE` on `question_id` and `answer_value` — point lookups and prefix scans * `BITMAP` on `answer_type` — fast filtering by entity type ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/trivia-qa-lance", split="train", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["answer_value"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/trivia-qa-lance --repo-type dataset --local-dir ./trivia-qa-lance > ``` > > Then point LanceDB at `./trivia-qa-lance/data`. ## Search The bundled `IVF_PQ` index on `question_emb` turns semantic retrieval over trivia questions into a single call. In production you would encode an incoming question through the same MiniLM encoder used at ingest and pass the resulting 384-dim vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") seed = ( tbl.search() .select(["question_emb", "question"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="question_emb") .metric("cosine") .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(10) .to_list() ) for r in hits: print(f"{r['answer_value']:30s} | {r['question'][:80]}") ``` Because the recommended setup also builds an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges and reranks the two result lists in a single call, which is useful when a specific named entity must literally appear in the question but the dense side should still drive ranking. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid") .vector(seed["question_emb"]) .text("sistine chapel") .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f"{r['answer_value']:30s} | {r['question'][:80]}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate TriviaQA's `answer_type` column — backed by a `BITMAP` index — makes it cheap to slice the dataset by entity category, and the question text itself is a useful predicate for filtering out very short or unusually long items. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it easy to inspect or hand off. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") candidates = ( tbl.search() .where( "answer_type = 'WikipediaEntity' " "AND length(question) BETWEEN 60 AND 300", prefilter=True, ) .select(["question_id", "question", "answer_value", "answer_aliases"]) .limit(1000) .to_list() ) print(f"{len(candidates)} candidates; first answer: {candidates[0]['answer_value']}") ``` Neither the `question_emb` vector nor the unused alias fields drive this scan, so a 1000-row curation pass against the Hub moves only the projected text columns. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Materialize-a-subset section below for export to a writable local copy. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds a `question_length`, a `num_aliases` count, and a `has_aliases` flag — any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full corpus. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./trivia-qa-lance/data") # local copy required for writes tbl = db.open_table("train") tbl.add_columns({ "question_length": "length(question)", "num_aliases": "array_length(answer_aliases)", "has_aliases": "array_length(answer_aliases) > 0", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (offline reader-model predictions, alternate embeddings, retrieval scores from a different system), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa scores = pa.table({ "question_id": pa.array(["tc_1", "tc_2"]), "retriever_score": pa.array([0.88, 0.31]), }) tbl.add_columns([f for f in scores.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(scores) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running a different embedding model over the questions), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a closed-book QA model the natural projection is the question, the canonical answer, and the alias list (the aliases serve as additional supervision targets during loss computation or evaluation); for a retriever or reranker on top of frozen features, project the precomputed embedding instead. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") train_ds = Permutation.identity(tbl).select_columns( ["question", "answer_value", "answer_aliases"] ) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; question_emb stays on disk. # tokenize question and answer, forward, backward... ... ``` Switching feature sets is a configuration change: passing `["question_emb", "answer_value"]` to `select_columns(...)` on the next run reads only the 384-d vectors and the canonical answer string, which is the right shape for training a retrieval head or reranker on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") tbl = db.open_table("train") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./trivia-qa-lance/data") local_tbl = local_db.open_table("train") local_tbl.tags.create("baseline-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("train", version="baseline-v1") tbl_v5 = db.open_table("train", version=5) ``` Pinning supports two workflows. A retrieval system locked to `baseline-v1` keeps returning stable results while the dataset evolves in parallel — newly added scores or alternate embeddings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same questions and answers, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full corpus. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/trivia-qa-lance/data") remote_tbl = remote_db.open_table("train") batches = ( remote_tbl.search() .where("answer_type = 'WikipediaEntity' AND length(question) >= 60") .select( ["question_id", "question", "answer_value", "answer_aliases", "normalized_answer", "answer_type", "question_emb"] ) .to_batches() ) local_db = lancedb.connect("./trivia-qa-wiki") local_db.create_table("train", batches) ``` The resulting `./trivia-qa-wiki` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/trivia-qa-lance/data` for `./trivia-qa-wiki`. ## Source & license Converted from [`mandarjoshi/trivia_qa`](https://huggingface.co/datasets/mandarjoshi/trivia_qa) (`rc.nocontext` config). TriviaQA is released under the Apache 2.0 license. ## Citation ``` @article{joshi2017triviaqa, title={TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension}, author={Joshi, Mandar and Choi, Eunsol and Weld, Daniel S and Zettlemoyer, Luke}, journal={arXiv preprint arXiv:1705.03551}, year={2017} } ``` # VQAv2 Source: https://docs.lancedb.com/oss/v0-41-0/datasets/vqav2 A Lance-formatted version of VQAv2 — open-ended visual question answering on COCO images — sourced from lmms-lab/VQAv2. > [card] [View on Hugging Face](https://huggingface.co/datasets/lance-format/vqav2-lance) > > Source dataset card and downloadable files for `lance-format/vqav2-lance`. Each row is one `(image, question, 10 annotator answers)` triple with paired CLIP image and question embeddings drawn from the same shared space, plus the VQAv2 `question_type` / `answer_type` taxonomy and the consensus `multiple_choice_answer` — all available directly from the Hub at `hf://datasets/lance-format/vqav2-lance/data`. ## Key features * **Inline JPEG bytes** in the `image` column — no sidecar files or image folders. * **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (OpenCLIP ViT-B/32, 512-dim, cosine-normalized) — so cross-modal text→image retrieval and question-similarity retrieval both work as a single indexed lookup. * **Both raw and consensus answers** — the 10 annotator answers in `answers` alongside the canonical `multiple_choice_answer`, with parallel `answer_confidences`. * **Pre-built ANN, FTS, scalar, and bitmap indices** covering both embeddings, the question text, the answer taxonomy, and the COCO and VQAv2 ids. ## Splits | Split | Rows | | - | - | | `validation.lance` | 214,354 | The `lmms-lab/VQAv2` redistribution declares only the eval splits in its `dataset_info`, so the train shards (\~444 k rows) are not bundled here today; they can be enabled by reading `data/train-*.parquet` directly with PyArrow or by switching to `Multimodal-Fatima/VQAv2_train`. Track progress in `TRACKED_DATASETS.md`. ## Schema | Column | Type | Notes | | - | - | - | | `id` | `int64` | Row index within split | | `image` | `large_binary` | Inline JPEG bytes | | `image_id` | `int64` | COCO image id | | `question_id` | `int64` | VQAv2 question id | | `question` | `string` | Natural-language question | | `question_type` | `string` | First few tokens of the question (e.g. `what is`, `is the`) | | `answer_type` | `string` | One of `yes/no`, `number`, `other` | | `multiple_choice_answer` | `string` | Canonical (most-common) answer | | `answers` | `list<string>` | 10 annotator answers | | `answer_confidences` | `list<string>` | Parallel confidence list (`yes` / `maybe` / `no`) | | `image_emb` | `fixed_size_list<float32, 512>` | OpenCLIP image embedding (cosine-normalized) | | `question_emb` | `fixed_size_list<float32, 512>` | OpenCLIP text embedding of the question (cosine-normalized) | Because both embeddings come from the same CLIP model, they share an embedding space and cross-modal retrieval (image→question or question→image) works without any additional alignment. ## Pre-built indices * `IVF_PQ` on `image_emb` — image-side vector search (cosine) * `IVF_PQ` on `question_emb` — question-side vector search (cosine) * `INVERTED` (FTS) on `question` — keyword and hybrid search * `BITMAP` on `question_type`, `answer_type` — fast categorical filters over the VQAv2 taxonomy * `BTREE` on `image_id`, `question_id`, `multiple_choice_answer` — fast lookup by id and canonical answer ## Why Lance? 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation. 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search. 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them. 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time. 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes. 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history. ## Load with `datasets.load_dataset` You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import datasets hf_ds = datasets.load_dataset("lance-format/vqav2-lance", split="validation", streaming=True) for row in hf_ds.take(3): print(row["question"], "->", row["multiple_choice_answer"]) ``` ## Load with LanceDB LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") print(len(tbl)) ``` > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy: > > ```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} > hf download lance-format/vqav2-lance --repo-type dataset --local-dir ./vqav2-lance > ``` > > Then point LanceDB at `./vqav2-lance/data`. ## Search The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same OpenCLIP model used at ingest (ViT-B/32 `laion2b_s34b_b79k`, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") seed = ( tbl.search() .select(["question_emb", "question", "multiple_choice_answer"]) .limit(1) .offset(42) .to_list()[0] ) hits = ( tbl.search(seed["question_emb"], vector_column_name="image_emb") .metric("cosine") .select(["image_id", "question", "multiple_choice_answer", "answer_type"]) .limit(10) .to_list() ) print("query question:", seed["question"], "->", seed["multiple_choice_answer"]) for r in hits: print(f" {r['image_id']:>12} [{r['answer_type']}] {r['question'][:60]} -> {r['multiple_choice_answer']}") ``` Because the CLIP embeddings are cosine-normalized, cosine is the right metric. Swap `vector_column_name="image_emb"` for `question_emb` to do question→question retrieval against the validation set instead, which is useful for clustering paraphrases or spotting near-duplicate questions across COCO images. Because the dataset also ships an `INVERTED` index on `question`, the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is useful when a noun like "dog" must appear in the question text but you still want CLIP to handle visual similarity over the candidate set. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} hybrid_hits = ( tbl.search(query_type="hybrid", vector_column_name="image_emb") .vector(seed["question_emb"]) .text("dog") .select(["image_id", "question", "multiple_choice_answer"]) .limit(10) .to_list() ) for r in hybrid_hits: print(f" {r['image_id']:>12} {r['question'][:60]} -> {r['multiple_choice_answer']}") ``` Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency. ## Curate A typical curation pass for VQAv2 combines a structural filter on the answer taxonomy (e.g. only yes/no questions, or only counting questions) with a content predicate on the question text or the consensus answer, so the candidate set is both categorically uniform and topically focused. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") candidates = ( tbl.search() .where( "answer_type = 'yes/no' AND question_type = 'is the' AND multiple_choice_answer IN ('yes', 'no')", prefilter=True, ) .select(["question_id", "image_id", "question", "multiple_choice_answer"]) .limit(500) .to_list() ) print(f"{len(candidates)} 'is the' yes/no candidates; first: {candidates[0]['question']} -> {candidates[0]['multiple_choice_answer']}") ``` The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` and embedding columns are never read, so the network traffic for a 500-row candidate scan is dominated by question and answer strings rather than JPEG bytes or vectors. ## Evolve Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_binary_answer` flag, a `num_answer_tokens` count, and a `question_length` integer, any of which can then be used directly in `where` clauses without recomputing the predicate on every query. > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("./vqav2-lance/data") # local copy required for writes tbl = db.open_table("validation") tbl.add_columns({ "is_binary_answer": "multiple_choice_answer IN ('yes', 'no')", "question_length": "length(question)", "answer_length": "length(multiple_choice_answer)", "num_unique_answers": "array_length(answers)", }) ``` The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. If the values you want to attach already live in another table (a model's predicted answer, an annotator-agreement score, or a difficulty rating), add the new fields and update matching rows by `question_id`: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import pyarrow as pa predictions = pa.table({ "question_id": pa.array([262148000, 262148001], type=pa.int64()), "model_answer": pa.array(["yes", "2"]), "model_confidence": pa.array([0.87, 0.64]), }) tbl.add_columns([f for f in predictions.schema if f.name != "question_id"]) tbl.merge_insert("question_id").when_matched_update_all().execute(predictions) ``` Matched rows receive the new values while unmatched rows stay `null`, and the update commits as a new table version. For column values that require a Python computation (e.g., running an alternate VLM over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/). ## Train Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a VQA fine-tune, project the JPEG bytes, the question, and the consensus answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb from lancedb.permutation import Permutation from torch.utils.data import DataLoader db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") train_ds = Permutation.identity(tbl).select_columns(["image", "question", "multiple_choice_answer"]) loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4) for batch in loader: # batch carries only the projected columns; decode the JPEG bytes, # tokenize the question, forward through the VLM, compute the loss # against `multiple_choice_answer`... ... ``` Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "multiple_choice_answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a lightweight reranker or a linear probe on top of frozen CLIP features. ## Versioning Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") tbl = db.open_table("validation") print("Current version:", tbl.version) print("History:", tbl.list_versions()) print("Tags:", tbl.tags.list()) ``` Once you have a local copy, tag a version for reproducibility: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} local_db = lancedb.connect("./vqav2-lance/data") local_tbl = local_db.open_table("validation") local_tbl.tags.create("openclip-vitb32-v1", local_tbl.version) ``` A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one: ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} tbl_v1 = db.open_table("validation", version="openclip-vitb32-v1") tbl_v5 = db.open_table("validation", version=5) ``` Pinning supports two workflows. A retrieval system locked to `openclip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added model predictions or alternative annotations do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images, questions, and consensus answers, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking. ## Materialize a subset Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory. ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}} import lancedb remote_db = lancedb.connect("hf://datasets/lance-format/vqav2-lance/data") remote_tbl = remote_db.open_table("validation") batches = ( remote_tbl.search() .where("answer_type = 'number'") .select(["question_id", "image_id", "image", "question", "multiple_choice_answer", "answers", "image_emb", "question_emb"]) .to_batches() ) local_db = lancedb.connect("./vqav2-counting-subset") local_db.create_table("validation", batches) ``` The resulting `./vqav2-counting-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/vqav2-lance/data` for `./vqav2-counting-subset`. ## Source & license Converted from [`lmms-lab/VQAv2`](https://huggingface.co/datasets/lmms-lab/VQAv2). VQAv2 questions and annotations are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The underlying images come from COCO and are subject to Flickr terms of service. See the [VQAv2 download page](https://visualqa.org/download.html) for details. ## Citation ``` @inproceedings{goyal2017making, title={Making the V in VQA Matter: Elevating the Role of Image Understanding in Visual Question Answering}, author={Goyal, Yash and Khot, Tejas and Summers-Stay, Douglas and Batra, Dhruv and Parikh, Devi}, booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2017} } ```