mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Part of #4554. Supersedes #4555. This exposes Lance's R-tree index in the Python and TypeScript SDKs. Python gets a `lancedb.index.RTree` config with an optional `page_size`, accepted by `create_index(config=...)` on local, async and remote tables. TypeScript gets `Index.rtree({ pageSize })` and `RTreeOptions`. Both map to the Rust crate's existing `Index::RTree`, so remote tables send `index_type: "RTREE"`. The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` filters between a GeoArrow column and a constant geometry, in either argument order, including as a prefilter on vector search. The scalar index docs page gets an R-tree section. `geo` is now a default feature of the Python and Node packages. Without it, a local table can neither build the index nor evaluate `ST_*` filters, and because wheels and npm packages are prebuilt, an opt-in Cargo feature would not reach users. pylance already ships with `geo` on. It adds pure-Rust crates under licenses that `deny.toml` already allows. `Cargo.lock` doesn't change, and the third-party license notices are regenerated. The cost is size: the macOS arm64 release wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%). The tests pin the constant-first predicate bug that held up #4555, which lance-format/lance#10080 fixed, in queries, `delete()` and `update()`, with and without the index. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
442 lines
17 KiB
Plaintext
442 lines
17 KiB
Plaintext
---
|
|
title: "Scalar Indexing"
|
|
sidebarTitle: "Scalar Indexing"
|
|
description: "Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization."
|
|
icon: "tree"
|
|
availability:
|
|
embedded: available
|
|
enterprise: available
|
|
---
|
|
|
|
import {
|
|
PyScalarIndexBuild as ScalarIndexBuild,
|
|
PyScalarIndexWait as ScalarIndexWait,
|
|
PyScalarIndexOptimize as ScalarIndexOptimize,
|
|
PyScalarIndexFilter as ScalarIndexFilter,
|
|
PyScalarIndexPrefilter as ScalarIndexPrefilter,
|
|
PyScalarIndexUuidType as ScalarIndexUuidType,
|
|
PyScalarIndexUuidData as ScalarIndexUuidData,
|
|
PyScalarIndexUuidTable as ScalarIndexUuidTable,
|
|
PyScalarIndexUuidWait as ScalarIndexUuidWait,
|
|
PyScalarIndexUuidUpsert as ScalarIndexUuidUpsert,
|
|
PyScalarIndexNestedFields as ScalarIndexNestedFields,
|
|
PyScalarIndexRtreeData as ScalarIndexRtreeData,
|
|
PyScalarIndexRtreeCreate as ScalarIndexRtreeCreate,
|
|
PyScalarIndexRtreeFilter as ScalarIndexRtreeFilter,
|
|
PyScalarIndexRtreeVector as ScalarIndexRtreeVector,
|
|
PyScalarIndexRtreeExplain as ScalarIndexRtreeExplain,
|
|
} from '/snippets/indexing.mdx';
|
|
|
|
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 these scalar index types, among others:
|
|
|
|
- `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.
|
|
- `RTREE`: R-tree over GeoArrow geometry columns that accelerates spatial filters such as `ST_Intersects` and `ST_Within`.
|
|
|
|
<Tip title="Working with scalar indices">
|
|
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)
|
|
</Tip>
|
|
|
|
## 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` |
|
|
| GeoArrow geometry (`geoarrow.point`, `geoarrow.polygon`, `geoarrow.wkb`, ...) | `ST_Intersects`, `ST_Within`, `ST_Contains` and other spatial relationships, `is null` | `RTREE` |
|
|
|
|
## 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`
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexBuild}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
<Note title="LanceDB Enterprise">
|
|
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.
|
|
</Note>
|
|
|
|
### 2\. Check Index Status
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexWait}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
`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.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexOptimize}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
<Note title="LanceDB Enterprise">
|
|
New data added after creating the scalar index remains searchable through a
|
|
slower flat scan of the unindexed rows. LanceDB Enterprise adds new rows to
|
|
`BTREE`, `BITMAP`, and `LABEL_LIST` indexes in the background once enough have
|
|
accumulated. It does not update `FM` indexes automatically. The Enterprise
|
|
[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction)
|
|
submits compaction only and does not trigger this index maintenance.
|
|
</Note>
|
|
|
|
### 4\. Run Indexed Searches
|
|
|
|
The following scan will be faster if the column `book_id` has a scalar index:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexFilter}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
Scalar indexes can also speed up scans containing a vector search or full text search, and a prefilter:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexPrefilter}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
## 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](/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.
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
from lancedb.index import Fm
|
|
|
|
await tbl.create_index("text", config=Fm())
|
|
```
|
|
|
|
```typescript TypeScript icon="square-js"
|
|
import * as lancedb from "@lancedb/lancedb";
|
|
import { Index } from "@lancedb/lancedb";
|
|
|
|
await tbl.createIndex("text", { config: Index.fm() });
|
|
```
|
|
|
|
```rust Rust icon="rust"
|
|
use lancedb::index::Index;
|
|
use lancedb::index::scalar::FmIndexBuilder;
|
|
|
|
tbl.create_index(&["text"], Index::Fm(FmIndexBuilder::default()))
|
|
.execute()
|
|
.await?;
|
|
```
|
|
</CodeGroup>
|
|
|
|
After the index is built, substring filters use it automatically:
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
table.search().where("contains(text, 'needle')").limit(10).to_pandas()
|
|
```
|
|
</CodeGroup>
|
|
|
|
`list_indices()` reports the index type as `"Fm"`.
|
|
|
|
## NGram index for substring search
|
|
|
|
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())`.
|
|
|
|
<CodeGroup>
|
|
```python Python icon="python"
|
|
from lancedb.index import NGram
|
|
|
|
await tbl.create_index("text", config=NGram())
|
|
```
|
|
|
|
```rust Rust icon="rust"
|
|
use lancedb::index::Index;
|
|
use lancedb::index::scalar::NGramIndexBuilder;
|
|
|
|
tbl.create_index(&["text"], Index::NGram(NGramIndexBuilder::default()))
|
|
.execute()
|
|
.await?;
|
|
```
|
|
</CodeGroup>
|
|
|
|
After the index is built, substring filters use it automatically:
|
|
|
|
```python
|
|
table.search().where("contains(text, 'needle')").limit(10).to_pandas()
|
|
```
|
|
|
|
`list_indices()` reports the index type as `"NGram"`.
|
|
|
|
<Note>
|
|
Lance 15.0.0-beta.21 writes new NGram indexes using physical row addresses. On
|
|
tables with stable row IDs, rebuild legacy NGram indexes that store row IDs
|
|
before consolidating their segments. Consolidation rejects these legacy
|
|
row-ID segments. Tables without stable row IDs retain the earlier index format.
|
|
</Note>
|
|
|
|
## R-tree index for geospatial filters {#rtree}
|
|
|
|
The `RTREE` index is a scalar index over a column of GeoArrow geometries. It
|
|
stores the bounding box of every geometry and accelerates spatial filters, on
|
|
their own or as the prefilter of a vector search. Use it when queries restrict
|
|
results to a region, such as the scenes over an area of interest, the places
|
|
inside a city, or the log records along a route.
|
|
|
|
### Store geometry as GeoArrow {#rtree-geoarrow}
|
|
|
|
A column holds geometry when its Arrow field carries GeoArrow extension
|
|
metadata: `ARROW:extension:name` names the geometry type, such as
|
|
`geoarrow.point`, `geoarrow.linestring`, `geoarrow.polygon` or
|
|
`geoarrow.multipolygon` for native coordinates, or `geoarrow.wkb` for
|
|
well-known binary. LanceDB keeps that metadata when it stores the column.
|
|
|
|
You can build the field with PyArrow alone. A point is a struct of `x` and `y`
|
|
coordinates:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexRtreeData}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
Libraries such as [`geoarrow-rust-core`](https://pypi.org/project/geoarrow-rust-core/)
|
|
(`geoarrow.rust.core`) produce arrays with this metadata already, so a table
|
|
built from them works the same way.
|
|
|
|
### Create an R-tree index {#rtree-create}
|
|
|
|
Pass the `RTree` config in Python, `Index.rtree()` in TypeScript, or
|
|
`Index::RTree` in Rust. The optional page size sets the maximum number of
|
|
entries in each R-tree page; it must be at least 2 and defaults to 4096.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexRtreeCreate}
|
|
</CodeBlock>
|
|
|
|
```typescript TypeScript icon="square-js"
|
|
import { Index } from "@lancedb/lancedb";
|
|
|
|
await table.createIndex("location", { config: Index.rtree() });
|
|
```
|
|
|
|
```rust Rust icon="rust"
|
|
use lancedb::index::Index;
|
|
use lancedb::index::scalar::RTreeIndexBuilder;
|
|
|
|
table
|
|
.create_index(&["location"], Index::RTree(RTreeIndexBuilder::default()))
|
|
.execute()
|
|
.await?;
|
|
```
|
|
</CodeGroup>
|
|
|
|
`list_indices()` reports the index type as `"RTree"`, and `index_stats()`
|
|
reports it as `"RTREE"`. In the Rust crate, building the index on a local
|
|
table requires the `geo` feature; the Python and TypeScript packages include
|
|
it. In the embedded library, `optimize()` adds new rows to the index. Rows
|
|
that are not indexed yet are still filtered, just without the index.
|
|
|
|
### Filter with spatial predicates {#rtree-filter}
|
|
|
|
Spatial predicates go in `where()` like any other filter. Build constant
|
|
geometries with `ST_GeomFromText('<WKT>')` or `ST_Point(x, y)`:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexRtreeFilter}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
The index answers `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`,
|
|
`ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` between the
|
|
indexed column and a constant geometry, in either argument order, as well as
|
|
`IS NULL` on the column. A spatial predicate combined
|
|
with other conditions through `AND` still uses the index; one combined through
|
|
`OR` with a condition on an unindexed column does not.
|
|
|
|
The R-tree compares bounding boxes, so it returns a superset of the answer:
|
|
every row whose bounding box overlaps the query geometry's bounding box. LanceDB
|
|
then evaluates the exact predicate on those candidate rows, so the results are
|
|
the same with or without the index. A point just outside a triangle but inside
|
|
the triangle's bounding box is read, then discarded.
|
|
|
|
Other spatial functions, such as `ST_Distance(location, ST_Point(x, y)) < d`
|
|
for a radius filter, work in filters but are evaluated row by row, without the
|
|
index. `ST_DWithin` is not available. To use the index for a radius filter,
|
|
pair the distance check with an indexed predicate on a bounding polygon:
|
|
`ST_Intersects(location, <box>) AND ST_Distance(location, <center>) < d`.
|
|
|
|
Spatial functions are planar: they treat coordinates as points on a flat
|
|
plane, and `ST_Distance` returns a distance in the units of the column's
|
|
coordinates. For longitude and latitude, `d` is in degrees, not meters, and a
|
|
degree of longitude shrinks toward the poles. Project the data to a metric
|
|
coordinate system first if you need distances in meters.
|
|
|
|
### Combine with vector search {#rtree-vector-search}
|
|
|
|
A spatial filter on a vector search is a prefilter by default: the R-tree
|
|
narrows the candidates first, and the nearest neighbors are found among the
|
|
rows that match.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexRtreeVector}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
With `prefilter=False` in Python, or `postfilter()` in TypeScript, the filter
|
|
is applied to the nearest neighbors instead, without the index, so it can
|
|
return fewer rows than the limit.
|
|
|
|
### Check that the index is used {#rtree-explain}
|
|
|
|
An indexed spatial filter appears as a `ScalarIndexQuery` on the R-tree in the
|
|
query plan:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexRtreeExplain}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
<Note title="Remote tables">
|
|
On a remote table, `create_index` sends the request with the `RTREE` index
|
|
type, and spatial filters are sent to the server as written. Whether the
|
|
server can build the index and evaluate `ST_*` functions depends on its
|
|
version.
|
|
</Note>
|
|
|
|
## 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
|
|
</Note>
|
|
|
|
### 1\. Define UUID Type
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexUuidType}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
### 2\. Generate UUID Data
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexUuidData}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
### 3\. Create Table with UUID Column
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexUuidTable}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
### 4\. Create and Wait for the Index
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexUuidWait}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
### 5\. Perform Operations with the UUID Index
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexUuidUpsert}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
## 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.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{ScalarIndexNestedFields}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
<Note>
|
|
Composite indexes that cover multiple columns aren't supported yet. Each
|
|
`create_index` call must target a single (possibly nested) field path.
|
|
</Note>
|