Skip to content

feat: expose the RTREE index in the Python and TypeScript SDKs - #4555

Closed
sarwarbhuiyan wants to merge 8 commits into
mainfrom
feat/rtree-index-python-typescript
Closed

sarwarbhuiyan wants to merge 8 commits into
mainfrom
feat/rtree-index-python-typescript

Conversation

@sarwarbhuiyan

@sarwarbhuiyan sarwarbhuiyan commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Superseded by #4942.

Part of #4554.

Motivation

Lance already stores GeoArrow geometry, builds an R-tree over it and evaluates ST_* predicates through GeoDataFusion, and the LanceDB Rust crate has Index::RTree behind its geo feature. None of that was reachable from the Python or TypeScript SDKs, which is where most people who combine vector search with a polygon, corridor or distance filter actually work: Earth observation scenes over an area of interest, mapping, robotics logs with GPS tracks. The Python SDK rejected any R-tree request, create_index(config=...) had no config for it, TypeScript had no Index.rtree(), and because neither binding built lancedb with geo, a local table could not evaluate ST_Intersects at all. The March 2026 Cloud-Native Geo embeddings sprint listed hybrid spatial + vector queries as an open need in that community (https://cloudnativegeo.org/blog/2026/04/geo-embeddings-sprint-march-2026/). The format does this already; this PR makes it reachable from the SDKs.

What changes

Python gets a lancedb.index.RTree config with an optional page_size. It is accepted by create_index(config=...) on local, async and remote tables. The type hints, literal unions and the isinstance check in AsyncTable.create_index include it. The deprecated create_scalar_index is left alone. TypeScript gets Index.rtree({ pageSize }) and an exported RTreeOptions. Both go through the existing PyO3/napi bindings to Index::RTree(RTreeIndexBuilder), so the Rust RemoteTable already serialises it as index_type: "RTREE" plus page_size when set; nothing rejects it client side.

import pyarrow as pa
from lancedb.index import RTree

# A GeoArrow point column is a struct of x and y with GeoArrow extension metadata.
point = pa.struct([("x", pa.float64()), ("y", pa.float64())])
schema = pa.schema([
    pa.field("name", pa.string()),
    pa.field("location", point, metadata={"ARROW:extension:name": "geoarrow.point"}),
    pa.field("vector", pa.list_(pa.float32(), 2)),
])
rows = [
    {"name": "Ferry Building", "location": {"x": -122.3937, "y": 37.7955}, "vector": [0.7, 0.3]},
    {"name": "Oakland Museum", "location": {"x": -122.2638, "y": 37.7987}, "vector": [1.0, 0.05]},
]
table = db.create_table("places", pa.Table.from_pylist(rows, schema=schema))
table.create_index("location", config=RTree())

in_sf = (
    "ST_Within(location, ST_GeomFromText("
    "'POLYGON ((-122.52 37.70, -122.35 37.70, -122.35 37.83, -122.52 37.83, -122.52 37.70))'))"
)
# The spatial prefilter runs on the R-tree before the nearest-neighbor search.
table.search([1.0, 0.0]).where(in_sf).limit(10).to_list()
import { Index } from "@lancedb/lancedb";

await table.createIndex("location", { config: Index.rtree() });
await table.query().nearestTo([1.0, 0.0]).where(inSf).limit(10).toArray();

The scalar index page in docs/web gets an R-tree section: how to store GeoArrow geometry (plain PyArrow is enough; geoarrow-rust-core arrays work too), creating the index in Python, TypeScript and Rust, which predicates the index answers, the bounding-box candidate semantics, spatial prefilters on vector search, and how to check the plan. The Python examples come from a new test in docs/web-tests/py, and the TypeScript reference in docs/src/js is regenerated.

Design decisions

Enabling geo in the Python and Node packages. Without the feature the new config would only work against a remote table: a local create_index fails with an error naming the missing feature, and ST_* filters fail at planning. Since wheels and npm packages are prebuilt, an opt-in Cargo feature would not help users, so I added lancedb/geo to both default feature sets. pylance already ships it this way: Lance lists geo among its default features and pylance keeps them. The cost:

  • 32 more crates (geo, geoarrow-*, geodatafusion, rstar, spade, i_overlay, wkb, wkt, ...), all pure Rust under MIT, Apache-2.0, ISC or BSD-3-Clause, which deny.toml already allows. Cargo.lock doesn't change, because the lock already carried them for the Rust crate's feature, and the checked-in third-party license files already name them (at older versions, since those files are regenerated separately with make licenses).
  • Release wheel (macOS arm64, maturin build --release --strip, which is what pypi-publish.yml runs minus --features fp16kernels): the wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%), and the stripped _lancedb.abi3.so inside it from 156.1 MB to 163.6 MB (+7.5 MB, +4.8%). I measured the macOS arm64 Python wheel only; the Linux x86_64 manylinux wheel and the Node addon still need measuring before merge.
  • The checked-in RUST_THIRD_PARTY_LICENSES.html files (root, python/, nodejs/) are regenerated with cargo about in this PR, so the shipped notices list the geo crates at the versions actually linked. They hadn't been regenerated since February, so the diff also picks up unrelated dependency changes since then. The Python and npm license lists don't change, since geo adds no pip or npm packages.
  • Build time: clean release builds of the wheel took 23m16s without geo and 21m33s with it on a 14-core Apple Silicon machine. The run without geo shared the machine with other jobs, so the two numbers don't show a measurable difference in either direction.

Names. The config is RTree and the factory Index.rtree(), matching Index::RTree in Rust and the "RTree" that list_indices() already reports; "RTREE" is the wire name and the index_stats() name, as for the other scalar indexes.

create_scalar_index is unchanged. It is deprecated in favour of create_index(config=...), so RTREE is only reachable through create_index(config=RTree()), and the docs point there.

No new test dependency. GeoArrow columns are ordinary Arrow arrays with ARROW:extension:name metadata, so the tests build points, polygons and multipolygons with PyArrow and apache-arrow directly instead of pulling in geoarrow-rust-core.

What I verified about ST_* predicates

I checked these by running queries against a local table built from this branch, not by reading code alone, and the tests pin the main ones:

  • ST_Intersects, ST_Within, ST_Contains, ST_Touches and ST_CoveredBy work in .where() on local tables, and so does IS NULL on the geometry column. With an R-tree and the column as the first argument, each of them shows ScalarIndexQuery ... @geom_idx(RTree) in the plan. Lance's parser routes ST_Crosses, ST_Overlaps and ST_Covers to the index the same way; I didn't run those three.
  • Results are exact. With a triangle whose bounding box covers 25 grid points, analyze_plan() shows the scan reading 25 candidate rows and returning the 15 inside the triangle; the results match those of the same query without the index.
  • A spatial filter combined with other conditions through AND still uses the index; through OR with an unindexed column it falls back to a scan.
  • On a vector search, the default prefilter runs the R-tree query under the KNN scan, so the nearest neighbors are found among matching rows. prefilter=False / postfilter() applies the predicate as a FilterExec after the search instead.
  • Point, linestring, polygon, multipolygon and geoarrow.wkb columns can all be indexed and filtered. optimize() folds appended rows into the index, and unindexed rows are still filtered correctly before that.
  • ST_Distance works in filters but scans every row, and ST_DWithin is not registered by GeoDataFusion (planning error; fix: register Lance SQL functions for RTE filters #3794 proposes a rewrite). A radius filter can still use the index when it is paired with a bounding polygon: ST_Intersects(geom, <box>) AND ST_Distance(geom, <center>) < d.
  • Spatial functions are planar, so ST_Distance is in the column's coordinate units (degrees for lon/lat). The docs say so.
  • The argument order matters. With the constant first, the index is not used, and the asymmetric predicates return wrong results: ST_Contains(<triangle>, geom) returns no rows where ST_Within(geom, <triangle>) returns the interior points. This reaches writes too: delete("NOT ST_Contains(<triangle>, geom)") deletes every row. This reproduces in pylance 14.0.0b12 as well. The cause is upstream: GeoDataFusion's relate_impl evaluates geom.relate(prepared), i.e. relate(B, A), in its scalar-first branch (relate.rs); it is still there in GeoDataFusion 0.6.0. The same function panics on a NULL constant geometry (ST_Intersects(geom, ST_GeomFromText(NULL))) when there is no index to short-circuit it; in Python that surfaces as RustPanic. The docstrings and the docs page tell users to write the column first, including in delete()/update() conditions.

Blocked on upstream

This PR should not merge until Lance picks up a GeoDataFusion release that fixes the argument-order bug, because it turns geo on for every Python and Node install and the bug reaches delete(), update() and merge_insert(). The upstream fix with regression tests is datafusion-contrib/geodatafusion#111: it evaluates prepared.relate(geom) when the constant is the first argument and returns NULL instead of panicking on a NULL constant. The tests in test_index.py that pin the correct behaviour (constant-first reads with and without the index, a delete, an update, and the NULL-constant case) are marked xfail(strict=True), so they start failing loudly when the Lance bump lands and the markers can be removed.

Testing

  • Python: new tests in test_index.py: index creation, list_indices/index_stats; ST_Intersects, ST_Within, ST_Contains, ST_Covers, ST_CoveredBy and ST_Touches on points and ST_Intersects, ST_Contains, ST_Covers, ST_Crosses, ST_Overlaps and ST_Touches on polygons, each checked to use the index and to match the unindexed result; exact results past the bounding box; prefilter vs postfilter on vector search; null geometries (IS NULL, IS NOT NULL, ST_* and NOT ST_* on null rows, with and without the index); a geoarrow.wkb column; append, query the unindexed rows, optimize(), query again; GeoArrow schema and values round-tripping unchanged; invalid page_size and non-geometry columns (matching the message only, not the exception type); the sync API; and the strict-xfail upstream cases above. test_remote_db.py checks the request bodies for RTree() and RTree(page_size=1024) and the client-side page_size check. The full suite with -m "not slow and not s3_test": 1971 passed, 38 skipped, 7 xfailed (the strict upstream xfails), 0 failed. Doctests for the touched modules, the new docs test in docs/web-tests/py, ruff 0.9.9 format and check, and pyright (no new errors) pass.
  • TypeScript: new tests in table.test.ts (index creation, spatial filter, prefilter vs postfilter, invalid options including negative, fractional, NaN and out-of-range pageSize, which Index.rtree now rejects before napi's wrapping u32 conversion) and remote.test.ts (request bodies). table.test.ts and remote.test.ts pass in full (613 tests), and pnpm lint and pnpm run docs are clean.
  • Rust: cargo fmt --all -- --check, cargo clippy -p lancedb-python -p lancedb-nodejs --tests -- -D warnings, and cargo test -p lancedb-python --lib.
  • mkdocs build resolves the new lancedb.index.RTree cross-references.

Follow-ups and out of scope

On a remote table the SDK sends RTREE and passes spatial filters through unchanged, so whether the server can build the index and evaluate ST_* functions depends on the server; the new docs note for remote tables says just that. Other follow-ups:

  • Bump Lance once it picks up the GeoDataFusion fix, remove the strict xfails and the argument-order warning, and consider rewriting constant-first predicates in Lance (ST_Contains(c, col) → ST_Within(col, c)) so they can use the index.
  • Measure the Linux x86_64 wheel and Node addon size.
  • ST_DWithin (fix: register Lance SQL functions for RTE filters #3794).
  • The docs section lives on the scalar index page. A standalone geospatial page could follow if that's preferred, and the TypeScript examples can move into docs/web-tests/ts once that package depends on a release with Index.rtree().
  • The Rust crate also has NGram, BloomFilter and ZoneMap builders that neither SDK exposes yet; I left them out to keep this PR to the R-tree.

🤖 Generated with Claude Code

sarwarbhuiyan and others added 4 commits October 15, 2026 22:51
Lance's GeoArrow support, the RTREE scalar index and the ST_* functions
from GeoDataFusion, sits behind lancedb's optional `geo` feature. Neither
binding enabled it, so a local table could neither build an R-tree nor
evaluate a spatial filter. Turn it on in both default feature sets; pylance
already ships it through Lance's default features.

The feature adds 32 pure-Rust crates, all under licenses that deny.toml
already allows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add `lancedb.index.RTree`, with an optional `page_size`, and accept it in
`create_index(config=...)` on local, remote and async tables. The
deprecated `create_scalar_index` also takes `index_type="RTREE"`. Remote
tables send `index_type: "RTREE"` and, when set, `page_size` to the server.

Tests cover point and polygon columns, spatial filters that use the index,
exact results for candidates that only match on bounding box, a spatial
prefilter on vector search, invalid options, and the remote request body.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the `Index.rtree()` factory, with an optional `pageSize`, for GeoArrow
geometry columns, and export `RTreeOptions`. Remote tables send
`index_type: "RTREE"` to the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add an R-tree section to the scalar index page: storing GeoArrow geometry,
creating the index, the spatial predicates it accelerates, its bounding-box
candidate semantics, spatial prefilters on vector search, and how to check
the query plan. The Python examples come from a new docs test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@github-actions github-actions Bot added enhancement New feature or request Python Python SDK labels Oct 16, 2026

@lancedb-gatekeeper lancedb-gatekeeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Gate recommendation: request changes.

Exposing the existing R-tree builder is a sound direction, and the documented column-first search path passes local verification. Before enabling geo in both SDK packages, correct or reject the affected asymmetric predicates in the shared evaluator so write filters cannot select unintended rows. The argument-order warning alone does not protect stored data.

Comment thread python/Cargo.toml

[features]
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"]
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enabling geo by default also exposes the documented argument reversal to write filters. A predicate intended to delete points outside a region silently deletes the inside points too. On this head, the reproduction below deletes both rows; the same predicate in update also modifies both rows. This occurs with and without an R-tree, and the Node package enables the same evaluator through its new default feature.

GeoDataFusion 0.5.0 evaluates its scalar-first/array-second branch as right.relate(left). Please correct that shared evaluation or reject the affected forms before evaluation, covering ST_Contains, ST_Within, ST_Covers, and ST_CoveredBy in reads and writes, with a wrong-row mutation regression test. A documentation workaround leaves silent unintended deletes and updates reachable; retrying cannot restore the affected rows.

Reproducer

Run from python/ using the rebuilt extension with uv run --extra tests python <script.py>:

import tempfile
import lancedb
import pyarrow as pa
from lancedb.index import RTree

point = pa.struct([("x", pa.float64()), ("y", pa.float64())])
schema = pa.schema([
    pa.field("id", pa.int64()),
    pa.field("geom", point, metadata={"ARROW:extension:name": "geoarrow.point"}),
])
data = pa.Table.from_pylist([
    {"id": 1, "geom": {"x": 1.0, "y": 1.0}},
    {"id": 2, "geom": {"x": 5.0, "y": 5.0}},
], schema=schema)

with tempfile.TemporaryDirectory() as path:
    table = lancedb.connect(path).create_table("points", data)
    table.create_index("geom", config=RTree())
    region = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
    table.delete(f"NOT ST_Contains({region}, geom)")
    actual = table.to_arrow()["id"].to_pylist()
    assert actual == [1], actual  # Actual: []; the inside point was also deleted.

Expected: the inside point (id=1) remains. Observed: AssertionError: [].

@lancedb-gatekeeper lancedb-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Oct 16, 2026
…r_index

Add tests for null geometries, geoarrow.wkb columns, append then optimize,
GeoArrow schema round trips, ST_Crosses/ST_Overlaps/ST_Covers on polygons,
and check every indexed result against the unindexed one. Pin the upstream
GeoDataFusion bugs (constant-first asymmetric predicates in queries, delete
and update; NULL constant geometry panic) as strict xfails so they flag
when Lance picks up the fix.

create_scalar_index is deprecated, so leave RTREE to create_index(config=RTree()).
…rsion

napi wraps negative numbers when converting to u32, so pageSize -1 reached
Rust as 4294967295 and passed the >= 2 check.
@lancedb-gatekeeper lancedb-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Oct 16, 2026
@sarwarbhuiyan sarwarbhuiyan added the typescript Typescript / javascript label Oct 16, 2026

@lancedb-gatekeeper lancedb-gatekeeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Gate recommendation: request changes.

Correct or reject the affected asymmetric spatial predicates in the shared evaluator across reads and writes before shipping geo by default in both SDKs. The added expected-failure tests and write-filter warnings document the behavior but leave silent unintended deletes and updates reachable.

@lancedb-gatekeeper lancedb-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Oct 16, 2026
Xuanwo added a commit to lance-format/lance that referenced this pull request Oct 23, 2026
Closes #10078

## Motivation

pylance builds with the `geo` feature, which is a default feature of the
`lance` crate, so its spatial predicates run through geodatafusion. When
the constant geometry is the first argument, geodatafusion's
`relate_impl` computes the DE-9IM matrix for (B, A) but reads it as (A,
B). As a result, `ST_Contains(<region>, geom)` returns false for the
points inside the region. `delete("NOT ST_Contains(<region>, geom)")`
deletes every row, including the ones inside the region. A NULL constant
geometry panics the scan. lancedb/lancedb#4555 is about to turn on `geo`
in the LanceDB Python and TypeScript SDKs, so more users will hit this.

The bug is in geodatafusion 0.5.0, which `main` pins, and in 0.6.0,
which #9979 moves to. The upstream fix,
datafusion-contrib/geodatafusion#111, is still open. This PR fixes the
bug in Lance, so it works with either version and doesn't wait for a
geodatafusion release.

## What changes

`lance-geo` now registers its own versions of the ten relate predicates:
`st_contains`, `st_within`, `st_covers`, `st_coveredby`, `st_crosses`,
`st_disjoint`, `st_equals`, `st_intersects`, `st_overlaps` and
`st_touches`. These replace geodatafusion's registrations of the same
names. They live in `rust/lance-geo/src/udf.rs`. That file was already
on `main`, but no `mod udf` declaration compiled it, and
`geodatafusion::register` already registers everything it listed, so
this PR replaces its contents. Each predicate wraps geodatafusion's
implementation and changes three things:

- **Scalar first, array second.** The call is evaluated as the converse
predicate with the arguments swapped: `ST_Contains(c, x)` =
`ST_Within(x, c)` and `ST_Covers(c, x)` = `ST_CoveredBy(x, c)`. The
symmetric predicates are their own converse. This uses geodatafusion's
(array, scalar) path, which is correct and keeps its prepared-geometry
fast path.
- **NULL geometry.** A NULL scalar geometry in either position returns
NULL instead of panicking.
- **Index use.** `ScalarUDFImpl::simplify` rewrites `f(<literal>, x)` to
`converse(f)(x, <literal>)`. The R-tree matcher (`visit_scalar_fn`) only
takes the indexed column from the first argument, so constant-first
predicates never used the index before this change; now they do. The
rewrite also covers second arguments that are not columns, such as
`ST_Contains(<region>, ST_Point(x, y))`.

## Design

The fix is at the UDF level rather than in the planner, because that is
the one place every evaluation path shares. All of these paths resolve
the functions by name from a registry that
`lance_geo::register_functions` fills:

- the scanner filter
- `delete`, `update` and `merge_insert` conditions
- Substrait filters
- `Dataset::sql`
- downstream sessions built with
`lance_datafusion::udf::register_functions` or `new_session_context`,
which is how LanceDB sets up its sessions

The argument-order rewrite is in the UDF's `simplify` hook rather than
in a Lance-specific planner pass. DataFusion's `ExprSimplifier` runs
that hook both for `Planner::optimize_expr` and for the DataFusion
optimizer behind `Dataset::sql`. Constant folding runs first, so
`ST_GeomFromText('...')` has already become a literal when the rewrite
sees it. The invoke-time swap is still needed for expressions that reach
execution without being simplified, such as a raw `Expr` passed to
`Scanner::filter_expr`.

There are no `Cargo.toml` or `Cargo.lock` changes.

## Affected predicates (verified)

I compared all ten relate predicates, in both argument orders, against
`geo::Relate`. The test geometries were points, lines and polygons that
lie inside a square, on its boundary, or outside it, or that overlap,
cross, equal, touch or enclose it: 156 pairs per predicate. This used a
temporary `geo` dev-dependency that is not part of this PR.

| Predicate | geodatafusion 0.5.0, scalar first | With this PR |
| --- | --- | --- |
| `ST_Contains` | 30 of 156 pairs wrong | all correct |
| `ST_Within` | 30 of 156 pairs wrong | all correct |
| `ST_Covers` | 44 of 156 pairs wrong | all correct |
| `ST_CoveredBy` | 44 of 156 pairs wrong | all correct |
| `ST_Crosses`, `ST_Overlaps` (including mixed dimensions),
`ST_Touches`, `ST_Equals`, `ST_Intersects`, `ST_Disjoint` | all correct
| all correct |

Every (array, scalar) result was already correct before this change. The
NULL panic affects all ten predicates, with the NULL in either position.

## Testing

`lance-geo` unit tests, run with `--features geo`:

- Every predicate, with the constant in either position, against
geodatafusion's (array, array) evaluation. That path relates each pair
of rows with `geo::Relate` in argument order.
- The constant-first result against the column-first converse.
- Known answers for the asymmetric predicates.
- NULL constants, typed and untyped, in both positions, on both a
non-empty and an empty batch.
- The `simplify` rewrite.
- That `register_functions` installs the wrappers.

`lance` dataset tests in `dataset_geo.rs`. Each runs with and without an
R-tree, on a dataset with several fragments that includes a NULL
geometry:

- **Reads**, through the scanner filter, `Dataset::sql`, and a
`SessionContext` set up with `register_functions` and
`LanceTableProvider`. The constant-first result must equal the
column-first converse and the expected rows. When the column is indexed,
the plan for the constant-first form must show `ScalarIndexQuery`.
- **Wrong-row mutation regressions.** `delete` with `NOT ST_Contains`,
`ST_Contains`, `NOT ST_Covers`, `NOT ST_Within` and `NOT ST_CoveredBy`,
and `update` with `ST_Contains`, `NOT ST_Contains`, `ST_Covers` and `NOT
ST_Within`. Each test asserts exactly which rows survive or change.
- **`merge_insert`** with
`WhenNotMatchedBySource::delete_if("ST_Contains(<region>, geom)")`.
- **NULL constant geometry**, in reads and in `delete`.

Python tests in `test_geo.py`: constant-first reads, `update` and
`delete`, each with and without an R-tree, plus the NULL constant.

All of the new Rust and Python tests fail when the wrappers are not
registered, and pass when they are. With only the `simplify` rewrite
disabled, results stay correct but the index-use assertions fail.

Commands run:

- `cargo fmt --all -- --check`
- `cargo clippy --profile ci --locked -p lance-geo --features geo
--all-targets -- -D warnings`
- `cargo clippy --profile ci --locked --all --tests --benches -- -D
warnings`
- `cargo test --profile ci -p lance-geo --features geo`
- `cargo test --profile ci -p lance --lib -- geo rtree st_intersects`
- `cargo test --profile ci -p lance-index --features geo --lib -- rtree
geo`
- From `python/`, with the `geo` extra installed: `uv run make lint` and
`uv run pytest python/tests/test_geo.py`. The new tests pass.
`test_staged_rtree_after_rewrite_columns` fails with the same assertion
on a build without this change.

CI installs only the `tests` and `ray` extras, so it skips `test_geo.py`
(`importorskip("geoarrow.rust.core")`). The Rust tests cover the same
behavior.

## Follow-up

Once Lance pins a geodatafusion release that includes
datafusion-contrib/geodatafusion#111, remove the argument swap and NULL
handling in `RelateUdf::invoke_with_args` in `udf.rs`. The `simplify`
rewrite does not depend on the upstream bug and keeps constant-first
predicates indexable, so it should stay.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
Xuanwo pushed a commit that referenced this pull request Nov 1, 2026
## What kind of change does this PR introduce?

Feature. Exposes the NGram scalar index in the Python SDK.

## What is the current behavior?

The NGram scalar index already exists in the Rust core (`Index::NGram`) and is accepted over the remote protocol (the `"NGRAM"` type), but the Python SDK has no way to create it. `lancedb.index` offers `BTree`, `Bitmap`, `LabelList`, `Fm`, and the vector indexes, but not `NGram`, so it cannot be built through `create_index(config=...)`.

## What is the new behavior?

Adds an `NGram` config to `lancedb.index` and wires it through the pyo3 binding:

```python
from lancedb.index import NGram

await table.create_index("text", config=NGram())
```

The NGram index accelerates substring filters such as `contains(col, 'needle')`, along with some `LIKE` and regular-expression predicates, on UTF-8 string columns. It is parameter free and uses Lance's default trigram parameters.

Changes:

- `lancedb.index`: new `NGram` dataclass, added to `__all__`.
- pyo3 binding (`python/src/index.rs`): a match arm mapping `NGram` to `LanceDbIndex::NGram`, plus the import and the error message.
- Type hints: `NGram` added to the `create_index` config unions and the isinstance check in `table.py`, the `IndexConfigType` union, and the `_lancedb.pyi` stubs; `"NGRAM"` added to the `IndexType` and `IndexStatistics.index_type` literals.
- Test: `test_create_ngram_index` covers creation, `list_indices`, `index_stats`, and that a substring filter uses the index.
- Docs: an NGram section in the scalar index guide.

This mirrors the approach used for the RTree index in #4555 (that PR keeps the RTree scope; this one adds the remaining parameter free string index).
@sarwarbhuiyan

Copy link
Copy Markdown
Contributor Author

Superseded by #4942, the same change rebased onto current main. The Lance version main pins now includes lance-format/lance#10080, which fixes the constant-first predicate bug that blocked this PR.

@sarwarbhuiyan
sarwarbhuiyan deleted the feat/rtree-index-python-typescript branch November 12, 2026 19:23
wjones127 pushed a commit that referenced this pull request Nov 19, 2026
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 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request K-changes Latest Gatekeeper recommendation requests changes. Python Python SDK typescript Typescript / javascript

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant