feat: expose the RTREE index in the Python and TypeScript SDKs (#4942)

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>
This commit is contained in:
Sarwar Bhuiyan
2026-11-18 16:43:12 -08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 2dd1a6ad25
commit 4b428101dd
25 changed files with 21398 additions and 3107 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ libc = "0.2"
pyo3-build-config = "0.29"
[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"]
fp16kernels = ["lancedb/fp16kernels"]
remote = ["lancedb/remote"]
experimental-functions = ["lancedb/experimental-functions"]
File diff suppressed because it is too large Load Diff
+3
View File
@@ -26,6 +26,7 @@ from .index import (
Fm,
NGram,
ZoneMap,
RTree,
HnswPq,
HnswSq,
HnswFlat,
@@ -604,6 +605,7 @@ class Table:
Fm,
NGram,
ZoneMap,
RTree,
FTS,
],
replace: Optional[bool],
@@ -629,6 +631,7 @@ class Table:
Fm,
NGram,
ZoneMap,
RTree,
FTS,
],
replace: Optional[bool],
+40
View File
@@ -147,6 +147,45 @@ class ZoneMap:
pass
@dataclass
class RTree:
"""Describe an RTree index configuration.
`RTree` is a scalar index on a GeoArrow geometry column, that is, a column
whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
stores the bounding box of each geometry and accelerates spatial filters
passed to ``where()``.
The index accelerates ``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, for example
``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
``geom IS NULL``. These filters can be combined with other conditions
using ``AND``.
See the R-tree section of <https://docs.lancedb.com/indexing/scalar-index>
for storing geometry, the other spatial functions, and spatial filters on
vector search.
Remote tables send the ``RTREE`` index type to the server, which must
support it.
Examples
--------
>>> config = RTree(page_size=1024)
Attributes
----------
page_size : int, optional
The maximum number of entries in each R-tree page. Must be at least 2.
``None`` uses Lance's default of 4096.
"""
page_size: Optional[int] = None
@dataclass
class FTS:
"""Describe a FTS index configuration.
@@ -1001,4 +1040,5 @@ __all__ = [
"LabelList",
"Fm",
"NGram",
"RTree",
]
+7 -1
View File
@@ -1647,6 +1647,10 @@ class LanceQueryBuilder(ABC):
-----
Calling this multiple times combines the filters with a logical AND
rather than replacing the previous filter.
Spatial predicates such as ``ST_Intersects(geom, ST_GeomFromText(...))``
work on GeoArrow columns and use an [RTree][lancedb.index.RTree] index
when one exists.
"""
self._where = _combine_where(self._where, where)
self._postfilter = not prefilter
@@ -4293,9 +4297,11 @@ class AsyncStandardQuery(AsyncQueryBase):
>>> predicate = "x > 10"
>>> predicate = "y > 0 AND y < 100"
>>> predicate = "x > 5 OR y = 'test'"
>>> predicate = "ST_Intersects(geom, ST_GeomFromText('POINT (1 2)'))"
Filtering performance can often be improved by creating a scalar index
on the filter column(s).
on the filter column(s). Spatial predicates on GeoArrow columns use an
[RTree][lancedb.index.RTree] index.
Calling this multiple times combines the filters with a logical AND
rather than replacing the previous filter.
+1 -1
View File
@@ -604,7 +604,7 @@ class RemoteTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
+10 -4
View File
@@ -80,6 +80,7 @@ from .index import (
Fm,
NGram,
ZoneMap,
RTree,
HnswPq,
HnswSq,
HnswFlat,
@@ -344,6 +345,7 @@ IndexConfigType = Union[
Fm,
NGram,
ZoneMap,
RTree,
FTS,
]
@@ -1961,7 +1963,7 @@ class Table(ABC):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
@@ -4760,7 +4762,7 @@ class LanceTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
@@ -7347,6 +7349,7 @@ class AsyncTable:
Fm,
NGram,
ZoneMap,
RTree,
FTS,
]
] = None,
@@ -7428,13 +7431,14 @@ class AsyncTable:
Fm,
NGram,
ZoneMap,
RTree,
FTS,
),
):
raise TypeError(
"config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
+ str(type(config))
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
" but got " + str(type(config))
)
try:
await self._inner.create_index(
@@ -7474,6 +7478,7 @@ class AsyncTable:
Fm,
NGram,
ZoneMap,
RTree,
FTS,
]
] = None,
@@ -9820,6 +9825,7 @@ class IndexStatistics:
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
"RTREE",
]
distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
num_indices: Optional[int] = None
+1
View File
@@ -52,6 +52,7 @@ IndexType = Literal[
"BITMAP",
"LABEL_LIST",
"NGRAM",
"RTREE",
"IVF_RQ",
]
+386
View File
@@ -3,11 +3,13 @@
from datetime import timedelta
import random
import struct
from typing import get_args, get_type_hints
import pyarrow as pa
import pytest
import pytest_asyncio
import lancedb
from lancedb import AsyncConnection, AsyncTable, connect_async
from lancedb.index import (
BTree,
@@ -23,6 +25,7 @@ from lancedb.index import (
Fm,
NGram,
ZoneMap,
RTree,
HnswPq,
HnswSq,
HnswFlat,
@@ -250,6 +253,388 @@ async def test_create_fm_index(some_table: AsyncTable):
assert indices[0].columns == ["data"]
POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
return pa.field(
name,
data_type,
metadata={
"ARROW:extension:name": extension,
"ARROW:extension:metadata": "{}",
},
)
# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
# but only the 15 with x + y <= 4 intersect the triangle itself.
TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
def grid_points(nrows: int) -> pa.Table:
"""A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
ids = list(range(nrows))
geom = pa.StructArray.from_arrays(
[
pa.array([float(i % 10) for i in ids]),
pa.array([float(i // 10) for i in ids]),
],
names=["x", "y"],
)
schema = pa.schema(
[
pa.field("id", pa.int64()),
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
pa.field("vector", pa.list_(pa.float32(), DIM)),
]
)
return pa.Table.from_arrays(
[pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
schema=schema,
)
@pytest_asyncio.fixture
async def point_table(db_async):
return await db_async.create_table("point_table", grid_points(100))
async def query_ids(query) -> list:
return (await query.to_arrow())["id"].to_pylist()
@pytest.mark.asyncio
async def test_create_rtree_index(point_table: AsyncTable):
assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
TRIANGLE_IDS
)
await point_table.create_index("geom", config=RTree())
indices = await point_table.list_indices()
assert len(indices) == 1
assert indices[0].name == "geom_idx"
assert indices[0].index_type == "RTree"
assert indices[0].columns == ["geom"]
stats = await point_table.index_stats("geom_idx")
assert stats.index_type == "RTREE"
assert stats.num_indexed_rows == 100
assert stats.num_unindexed_rows == 0
# The index narrows the scan to the bounding box; the exact predicate then
# drops the candidates that fall outside the triangle.
query = point_table.query().where(INTERSECTS_TRIANGLE)
assert "ScalarIndexQuery" in await query.explain_plan(True)
assert sorted(await query_ids(query)) == TRIANGLE_IDS
@pytest.mark.asyncio
@pytest.mark.parametrize(
"predicate, expected_ids",
[
(INTERSECTS_TRIANGLE, TRIANGLE_IDS),
(f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
(f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
(
f"ST_Touches(geom, {TRIANGLE})",
[0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
),
(f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
],
)
async def test_rtree_index_accelerates_spatial_filters(
point_table: AsyncTable, predicate: str, expected_ids: list
):
unindexed = sorted(await query_ids(point_table.query().where(predicate)))
assert unindexed == expected_ids
await point_table.create_index("geom", config=RTree())
query = point_table.query().where(predicate)
assert "ScalarIndexQuery" in await query.explain_plan(True)
assert sorted(await query_ids(query)) == expected_ids
@pytest.mark.asyncio
async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
await point_table.create_index("geom", config=RTree())
# Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
far_corner = list(range(99 * DIM, 100 * DIM))
prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
postfiltered = (
point_table.query()
.nearest_to(far_corner)
.where(INTERSECTS_TRIANGLE)
.postfilter()
.limit(5)
)
assert await query_ids(postfiltered) == []
def square(corner: float) -> list:
"""A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
@pytest_asyncio.fixture
async def polygon_table(db_async):
"""Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
schema = pa.schema(
[
pa.field("id", pa.int64()),
geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
]
)
data = pa.Table.from_arrays(
[
pa.array(range(10), pa.int64()),
pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
],
schema=schema,
)
return await db_async.create_table("polygons", data)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"predicate, expected_ids",
[
("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
(
"ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
[2, 4],
),
(
"ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
[1, 5],
),
],
)
async def test_create_rtree_index_on_polygons(
polygon_table: AsyncTable, predicate: str, expected_ids: list
):
assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
expected_ids
)
await polygon_table.create_index("area", config=RTree(page_size=2))
assert (await polygon_table.list_indices())[0].index_type == "RTree"
query = polygon_table.query().where(predicate)
assert "ScalarIndexQuery" in await query.explain_plan(True)
assert sorted(await query_ids(query)) == expected_ids
@pytest.mark.asyncio
async def test_rtree_index_with_null_geometries(db_async):
# Every third row has no geometry; the others sit on the diagonal at (i, i).
geom = pa.array(
[None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
POINT_TYPE,
)
schema = pa.schema(
[
pa.field("id", pa.int64()),
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
]
)
table = await db_async.create_table(
"nulls",
pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
)
box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
expected = {
"geom IS NULL": [0, 3, 6, 9],
"geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
# Row 0 is inside the box but has no geometry, so it matches neither.
f"ST_Intersects(geom, {box})": [1],
f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
}
for predicate, ids in expected.items():
assert sorted(await query_ids(table.query().where(predicate))) == ids
await table.create_index("geom", config=RTree())
for predicate, ids in expected.items():
assert sorted(await query_ids(table.query().where(predicate))) == ids
for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
True
)
@pytest.mark.asyncio
async def test_create_rtree_index_on_wkb(db_async):
"""GeoParquet and GeoPandas data usually arrives as well-known binary."""
def wkb_point(x: float, y: float) -> bytes:
# Byte order (1 = little endian), geometry type (1 = point), x, y.
return struct.pack("<BIdd", 1, 1, x, y)
schema = pa.schema(
[
pa.field("id", pa.int64()),
geoarrow_field("geom", "geoarrow.wkb", pa.binary()),
]
)
data = pa.Table.from_arrays(
[
pa.array(range(100), pa.int64()),
pa.array([wkb_point(i % 10, i // 10) for i in range(100)], pa.binary()),
],
schema=schema,
)
table = await db_async.create_table("wkb", data)
assert sorted(await query_ids(table.query().where(INTERSECTS_TRIANGLE))) == (
TRIANGLE_IDS
)
await table.create_index("geom", config=RTree())
query = table.query().where(INTERSECTS_TRIANGLE)
assert "ScalarIndexQuery" in await query.explain_plan(True)
assert sorted(await query_ids(query)) == TRIANGLE_IDS
@pytest.mark.asyncio
async def test_rtree_index_after_append_and_optimize(point_table: AsyncTable):
await point_table.create_index("geom", config=RTree())
# Rows 100..199 continue the grid above the first one, at y = 10..19.
await point_table.add(grid_points(200).slice(100))
across_both = (
"ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 9, 2 9, 2 11, 0 11, 0 9))'))"
)
expected = [90, 91, 92, 100, 101, 102, 110, 111, 112]
stats = await point_table.index_stats("geom_idx")
assert stats is not None
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (100, 100)
assert sorted(await query_ids(point_table.query().where(across_both))) == expected
await point_table.optimize()
stats = await point_table.index_stats("geom_idx")
assert stats is not None
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (200, 0)
query = point_table.query().where(across_both)
assert "ScalarIndexQuery" in await query.explain_plan(True)
assert sorted(await query_ids(query)) == expected
@pytest.mark.asyncio
async def test_geoarrow_column_round_trips(point_table: AsyncTable):
"""Enabling geo support must not change how GeoArrow columns are stored or read."""
expected = grid_points(100)
schema = await point_table.schema()
assert schema.field("geom").metadata == expected.schema.field("geom").metadata
assert schema.field("geom").type == POINT_TYPE
data = (await point_table.query().to_arrow()).sort_by("id")
assert data["geom"].to_pylist() == expected["geom"].to_pylist()
assert sorted(await query_ids(point_table.query().where("id < 3"))) == [0, 1, 2]
# Asymmetric predicates with the constant geometry first. GeoDataFusion once
# evaluated these with the arguments swapped, so a write filter silently matched
# the wrong rows. Only the three interior points are contained, the boundary
# points are also covered, and no point contains or covers the triangle.
CONSTANT_FIRST_CASES = [
(f"ST_Contains({TRIANGLE}, geom)", [11, 12, 21]),
(f"ST_Covers({TRIANGLE}, geom)", TRIANGLE_IDS),
(f"ST_Within({TRIANGLE}, geom)", []),
(f"ST_CoveredBy({TRIANGLE}, geom)", []),
(f"ST_Intersects({TRIANGLE}, geom)", TRIANGLE_IDS),
]
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
async def test_spatial_filter_constant_first(
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
):
if indexed:
await point_table.create_index("geom", config=RTree())
query = point_table.query().where(predicate)
assert sorted(await query_ids(query)) == expected_ids
if indexed:
assert "ScalarIndexQuery" in await query.explain_plan(True)
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
async def test_delete_with_constant_first_spatial_filter(
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
):
if indexed:
await point_table.create_index("geom", config=RTree())
# Delete every row the predicate rejects; exactly the matching rows survive.
await point_table.delete(f"NOT {predicate}")
assert sorted(await query_ids(point_table.query())) == expected_ids
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
async def test_update_with_constant_first_spatial_filter(
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
):
if indexed:
await point_table.create_index("geom", config=RTree())
# Map each matching id to a negative one (-id - 1 keeps row 0 distinct).
await point_table.update(updates_sql={"id": "-id - 1"}, where=predicate)
updated = await query_ids(point_table.query().where("id < 0"))
assert sorted(-new_id - 1 for new_id in updated) == expected_ids
assert await point_table.count_rows() == 100
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
async def test_spatial_filter_with_null_constant(point_table: AsyncTable, indexed):
if indexed:
await point_table.create_index("geom", config=RTree())
null_geometry = "ST_GeomFromText(CAST(NULL AS VARCHAR))"
for predicate in [
f"ST_Intersects(geom, {null_geometry})",
f"ST_Within(geom, {null_geometry})",
]:
assert await query_ids(point_table.query().where(predicate)) == []
@pytest.mark.asyncio
async def test_create_rtree_index_rejects_invalid_input(point_table: AsyncTable):
with pytest.raises(ValueError, match="page_size must be at least 2"):
await point_table.create_index("geom", config=RTree(page_size=1))
# Only the message is part of the contract, not the exception type.
with pytest.raises(Exception, match="GeoArrow"):
await point_table.create_index("id", config=RTree())
assert await point_table.list_indices() == []
def test_create_rtree_index_sync(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("points", grid_points(100))
table.create_index("geom", config=RTree())
assert [index.index_type for index in table.list_indices()] == ["RTree"]
table.create_index("geom", config=RTree(page_size=16), name="geom_rtree")
assert table.index_stats("geom_rtree").index_type == "RTREE"
query = table.search().where(INTERSECTS_TRIANGLE).limit(100)
assert "ScalarIndexQuery" in query.explain_plan(True)
assert sorted(query.to_arrow()["id"].to_pylist()) == TRIANGLE_IDS
@pytest.mark.asyncio
async def test_create_ngram_index(db_async):
# NGram indexes accelerate substring filters on UTF-8 string columns.
@@ -615,6 +1000,7 @@ def test_index_statistics_index_type_lists_all_supported_values():
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
"RTREE",
}
assert (
+49
View File
@@ -3344,6 +3344,55 @@ def test_remote_json_fts_config(server_version):
assert request["block_size"] == 256
def test_remote_create_rtree_index():
from lancedb.index import RTree
received_requests = []
def handler(request):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
if request.path == "/v1/table/test/describe/":
point = {
"name": "geom",
"type": {
"type": "struct",
"fields": [
{"name": "x", "type": {"type": "double"}, "nullable": False},
{"name": "y", "type": {"type": "double"}, "nullable": False},
],
},
"nullable": True,
"metadata": {"ARROW:extension:name": "geoarrow.point"},
}
request.wfile.write(
json.dumps({"version": 1, "schema": {"fields": [point]}}).encode()
)
elif request.path == "/v1/table/test/create_index/":
received_requests.append(read_json_body(request))
request.wfile.write(b"{}")
else:
raise AssertionError(f"Unexpected request: {request.path}")
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
table.create_index("geom", config=RTree())
table.create_index("geom", config=RTree(page_size=1024), name="geom_rtree")
with pytest.raises(ValueError, match="page_size must be at least 2"):
table.create_index("geom", config=RTree(page_size=1))
assert received_requests == [
{"column": "geom", "index_type": "RTREE"},
{
"column": "geom",
"index_type": "RTREE",
"name": "geom_rtree",
"page_size": 1024,
},
]
@pytest.mark.parametrize(
"rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
)
+17 -2
View File
@@ -10,7 +10,7 @@ use lancedb::index::{
Index as LanceDbIndex,
scalar::{
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
ZoneMapIndexBuilder,
RTreeIndexBuilder, ZoneMapIndexBuilder,
},
};
use pyo3::IntoPyObject;
@@ -119,6 +119,16 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
"ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
"RTree" => {
let params = source.extract::<RTreeParams>()?;
let mut builder = RTreeIndexBuilder::default();
if let Some(page_size) = params.page_size {
builder = builder
.page_size(page_size)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
Ok(LanceDbIndex::RTree(builder))
}
"FTS" => {
let params = source.extract::<FtsParams>()?;
let code_options = CodeAnalyzerOptions {
@@ -293,7 +303,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
}
not_supported => Err(PyValueError::new_err(format!(
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
not_supported
))),
}
@@ -327,6 +337,11 @@ struct FtsParams {
index_operators: Option<bool>,
}
#[derive(FromPyObject)]
struct RTreeParams {
page_size: Option<u32>,
}
#[derive(FromPyObject)]
struct IvfFlatParams {
distance_type: String,