mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat: create any registered Lance scalar index plugin by name (#5004)
Closes #4933 Adds a generic configuration for creating a scalar index of any type recognized by a registered database plugin, using its type name and optional JSON parameters. Index types without a dedicated SDK configuration can use the same API. - **Rust:** `Index::Plugin(PluginIndexBuilder)`, with JSON-object parameters through `.params(...)` or `.params_json(...)`. - **Python:** `ScalarPlugin(index_type, params=None)`, accepting a dict or JSON-object string. - **TypeScript:** `Index.plugin(indexType, params?)`, accepting an object or JSON-object string. - Type names are case-insensitive and surrounding whitespace is ignored. Empty names and non-object parameters are rejected. - Native index introspection preserves existing built-in types and exposes other registered plugin types through `Custom`. The guide and SDK references describe index creation, parameter ownership, and errors consistently. They recommend a dedicated configuration when one exists and refer readers to the plugin’s documentation for parameter names and defaults. The TypeScript reference is regenerated from its source JSDoc. ## Remote request format Generic requests use `index_type: "PLUGIN"` and a separate upper-cased `plugin_type`. Arbitrary parameters stay nested under `params`, preserving omitted parameters versus an explicit empty object. This separates the generic path from built-in handling and prevents parameters from overwriting request fields. ## Validation - 52 targeted tests passed: 15 Rust, 22 Python, and 15 TypeScript. - Two Rust plugin doctests passed. - Rust Clippy, the Node build and lint, changed-file Python lint, TypeDoc generation, Vale, and the MkDocs SDK-reference build passed. - Request tests cover Python sync/async calls, object and JSON-string inputs, normalization, omitted and empty parameters, and collisions with request metadata. - Repository-wide Ruff reports existing findings in untouched documentation examples. Strict Mintlify validation reports four missing snippet-export warnings, also reproduced on the unmodified commit. ## Follow-ups - Replace the built-in examples with a widely available custom plugin when one is available, as discussed in review. - Remote `list_indices()` and `index_stats()` still parse a fixed set of type names; accepting unrecognized plugin types through a `Custom` fallback remains separate. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ef59dcfe80
commit
5f87e18541
@@ -27,6 +27,7 @@ from .index import (
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -682,6 +683,7 @@ class Table:
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -708,6 +710,7 @@ class Table:
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Literal, Optional
|
||||
import json
|
||||
from typing import Any, Dict, List, Literal, Optional, Union
|
||||
|
||||
from ._lancedb import (
|
||||
IndexConfig,
|
||||
@@ -186,6 +187,84 @@ class RTree:
|
||||
page_size: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScalarPlugin:
|
||||
"""Configure a scalar index of a type recognized by a registered database plugin.
|
||||
|
||||
Use this for index types without a dedicated configuration class.
|
||||
Prefer a dedicated class, such as [BTree][lancedb.index.BTree], when one
|
||||
is available.
|
||||
|
||||
An unknown plugin name or invalid parameters cause index creation to fail.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> from lancedb.index import ScalarPlugin
|
||||
>>> ScalarPlugin("bloomfilter", params={"number_of_items": 4096})
|
||||
ScalarPlugin(index_type='bloomfilter', params={'number_of_items': 4096})
|
||||
|
||||
Pass it as ``config`` to ``create_index``:
|
||||
|
||||
>>> table.create_index( # doctest: +SKIP
|
||||
... "id",
|
||||
... config=ScalarPlugin("bloomfilter", '{"probability": 0.01}'),
|
||||
... )
|
||||
|
||||
Attributes
|
||||
----------
|
||||
index_type: str
|
||||
The index type, case-insensitive. Surrounding whitespace is ignored.
|
||||
Must not be empty.
|
||||
params: dict or str, optional
|
||||
The index parameters, as a dict or as a string holding a JSON object.
|
||||
They are passed as given. Each plugin defines its parameters and
|
||||
defaults; refer to the plugin's documentation for guidance.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``index_type`` is empty, or ``params`` is a string that is not a
|
||||
JSON object.
|
||||
TypeError
|
||||
If ``index_type`` is not a string, or ``params`` is not a dict, a
|
||||
string or None.
|
||||
"""
|
||||
|
||||
index_type: str
|
||||
params: Optional[Union[Dict[str, Any], str]] = None
|
||||
|
||||
def __post_init__(self):
|
||||
if not isinstance(self.index_type, str):
|
||||
raise TypeError(
|
||||
"ScalarPlugin index_type must be a str, got "
|
||||
+ type(self.index_type).__name__
|
||||
)
|
||||
if not self.index_type.strip():
|
||||
raise ValueError("ScalarPlugin index_type must not be empty")
|
||||
if isinstance(self.params, str):
|
||||
try:
|
||||
parsed = json.loads(self.params)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"ScalarPlugin params are not valid JSON: {e}") from e
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError(
|
||||
"ScalarPlugin params must be a JSON object, got "
|
||||
+ type(parsed).__name__
|
||||
)
|
||||
elif self.params is not None and not isinstance(self.params, dict):
|
||||
raise TypeError(
|
||||
"ScalarPlugin params must be a dict, a JSON string or None, got "
|
||||
+ type(self.params).__name__
|
||||
)
|
||||
|
||||
@property
|
||||
def _params_json(self) -> Optional[str]:
|
||||
# Read by the native layer, which checks again that this is an object.
|
||||
if self.params is None or isinstance(self.params, str):
|
||||
return self.params
|
||||
return json.dumps(self.params)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FTS:
|
||||
"""Describe a FTS index configuration.
|
||||
@@ -1041,4 +1120,5 @@ __all__ = [
|
||||
"Fm",
|
||||
"NGram",
|
||||
"RTree",
|
||||
"ScalarPlugin",
|
||||
]
|
||||
|
||||
@@ -619,7 +619,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, NGram, ZoneMap, RTree, FTS.
|
||||
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
|
||||
replace : bool, default True
|
||||
Whether to replace an existing index on this column.
|
||||
wait_timeout : timedelta, optional
|
||||
|
||||
@@ -82,6 +82,7 @@ from .index import (
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -354,6 +355,7 @@ IndexConfigType = Union[
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
]
|
||||
|
||||
@@ -2028,7 +2030,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, RTree, FTS.
|
||||
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
|
||||
replace : bool, default True
|
||||
Whether to replace an existing index on this column.
|
||||
exist_ok : bool, default False
|
||||
@@ -5162,7 +5164,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, RTree, FTS.
|
||||
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
|
||||
replace : bool, default True
|
||||
Whether to replace an existing index on this column.
|
||||
exist_ok : bool, default False
|
||||
@@ -7873,6 +7875,7 @@ class AsyncTable:
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
]
|
||||
] = None,
|
||||
@@ -7955,13 +7958,14 @@ class AsyncTable:
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
),
|
||||
):
|
||||
raise TypeError(
|
||||
"config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
|
||||
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
|
||||
" but got " + str(type(config))
|
||||
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree,"
|
||||
" ScalarPlugin, or FTS, but got " + str(type(config))
|
||||
)
|
||||
try:
|
||||
await self._inner.create_index(
|
||||
@@ -8002,6 +8006,7 @@ class AsyncTable:
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
]
|
||||
] = None,
|
||||
|
||||
@@ -26,6 +26,7 @@ from lancedb.index import (
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -687,6 +688,132 @@ async def test_create_zonemap_index(db_async):
|
||||
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
|
||||
|
||||
|
||||
def plugin_table_data():
|
||||
return pa.table(
|
||||
{"id": [1, 2, 3, 4], "text": ["abc", "xyz", None, ""]},
|
||||
schema=pa.schema([("id", pa.int32()), ("text", pa.string())]),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"index_type, params, column, expected_type, predicate, expected_ids",
|
||||
[
|
||||
("ZoneMap", None, "id", "ZoneMap", "id >= 2 AND id < 4", [2, 3]),
|
||||
(" BTREE ", None, "id", "BTree", "id = 3", [3]),
|
||||
(
|
||||
"bloomfilter",
|
||||
{"number_of_items": 2, "probability": 0.01},
|
||||
"text",
|
||||
"BloomFilter",
|
||||
"text = 'abc'",
|
||||
[1],
|
||||
),
|
||||
(
|
||||
"BloomFilter",
|
||||
'{"number_of_items": 2}',
|
||||
"text",
|
||||
"BloomFilter",
|
||||
"text = 'abc'",
|
||||
[1],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_create_scalar_plugin_index(
|
||||
db_async, index_type, params, column, expected_type, predicate, expected_ids
|
||||
):
|
||||
# Lance's built-in plugins, created by name, are listed with the same type
|
||||
# as their dedicated configs and serve the filters those configs serve.
|
||||
table = await db_async.create_table("plugin_table", plugin_table_data())
|
||||
config = ScalarPlugin(index_type, params)
|
||||
await table.create_index(column, config=config, name="plugin_idx")
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert [(i.name, i.index_type, i.columns) for i in indices] == [
|
||||
("plugin_idx", expected_type, [column])
|
||||
]
|
||||
stats = await table.index_stats("plugin_idx")
|
||||
assert stats.num_indexed_rows == 4
|
||||
|
||||
query = table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan()
|
||||
result = await query.to_arrow()
|
||||
assert sorted(result["id"].to_pylist()) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scalar_plugin_without_lancedb_type_lists_plugin_name(db_async):
|
||||
data = pa.table({"text": ["alpha beta", "beta gamma", "gamma delta"]})
|
||||
table = await db_async.create_table("minhash_table", data)
|
||||
await table.create_index("text", config=ScalarPlugin("minhashlsh"))
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].index_type == "MinHashLsh"
|
||||
assert 'index_type="MinHashLsh"' in repr(indices[0])
|
||||
stats = await table.index_stats(indices[0].name)
|
||||
assert stats.index_type == "MinHashLsh"
|
||||
|
||||
|
||||
def test_scalar_plugin_sync_table_and_job(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("plugin_table", plugin_table_data())
|
||||
|
||||
table.create_index("id", config=ScalarPlugin("zonemap"))
|
||||
job = table.create_index_async(
|
||||
"text",
|
||||
config=ScalarPlugin("bloomfilter", {"probability": 0.01}),
|
||||
name="text_bloom",
|
||||
)
|
||||
job.wait()
|
||||
|
||||
types = {index.name: index.index_type for index in table.list_indices()}
|
||||
assert types == {"id_idx": "ZoneMap", "text_bloom": "BloomFilter"}
|
||||
assert "ScalarIndexQuery" in table.search().where("text = 'abc'").explain_plan()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs, error, match",
|
||||
[
|
||||
({"index_type": ""}, ValueError, "must not be empty"),
|
||||
({"index_type": " "}, ValueError, "must not be empty"),
|
||||
({"index_type": None}, TypeError, "index_type must be a str"),
|
||||
({"index_type": "zonemap", "params": "[1]"}, ValueError, "got list"),
|
||||
({"index_type": "zonemap", "params": "null"}, ValueError, "got NoneType"),
|
||||
({"index_type": "zonemap", "params": "{x"}, ValueError, "not valid JSON"),
|
||||
({"index_type": "zonemap", "params": [1]}, TypeError, "got list"),
|
||||
({"index_type": "zonemap", "params": 1}, TypeError, "got int"),
|
||||
],
|
||||
)
|
||||
def test_scalar_plugin_rejects_invalid_config(kwargs, error, match):
|
||||
with pytest.raises(error, match=match):
|
||||
ScalarPlugin(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scalar_plugin_errors_reach_the_caller(db_async):
|
||||
table = await db_async.create_table("plugin_table", plugin_table_data())
|
||||
|
||||
# The native layer checks the params again, after the dataclass is mutated.
|
||||
config = ScalarPlugin("zonemap")
|
||||
config.params = "[1]"
|
||||
with pytest.raises(ValueError, match="must be a JSON object, got an array"):
|
||||
await table.create_index("id", config=config)
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="No scalar index plugin found for name 'nosuchplugin'"
|
||||
):
|
||||
await table.create_index("id", config=ScalarPlugin("NoSuchPlugin"))
|
||||
with pytest.raises(ValueError, match="ngram index can only be created on a Utf8"):
|
||||
await table.create_index("id", config=ScalarPlugin("ngram"))
|
||||
with pytest.raises(RuntimeError, match='invalid type: string "many"'):
|
||||
await table.create_index(
|
||||
"text",
|
||||
config=ScalarPlugin("bloomfilter", {"number_of_items": "many"}),
|
||||
)
|
||||
assert await table.list_indices() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bitmap_index(some_table: AsyncTable):
|
||||
await some_table.create_index("id", config=Bitmap())
|
||||
|
||||
@@ -3526,6 +3526,74 @@ def test_remote_create_rtree_index():
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_remote_scalar_plugin_nests_params(use_async):
|
||||
from lancedb.index import ScalarPlugin
|
||||
|
||||
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/":
|
||||
fields = [{"name": "id", "type": {"type": "int32"}, "nullable": False}]
|
||||
request.wfile.write(
|
||||
json.dumps({"version": 1, "schema": {"fields": fields}}).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}")
|
||||
|
||||
cases = [
|
||||
(ScalarPlugin(" ZoneMap "), {}),
|
||||
(
|
||||
ScalarPlugin("bloomfilter", {"number_of_items": 4096, "column": "not_id"}),
|
||||
{"name": "id_bloom", "replace": False},
|
||||
),
|
||||
(ScalarPlugin("bloomfilter", '{"probability": 0.01}'), {}),
|
||||
(ScalarPlugin("zonemap", {}), {}),
|
||||
]
|
||||
|
||||
if use_async:
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
table = await db.open_table("test")
|
||||
for config, options in cases:
|
||||
await table.create_index("id", config=config, **options)
|
||||
else:
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = db.open_table("test")
|
||||
for config, options in cases:
|
||||
table.create_index("id", config=config, **options)
|
||||
|
||||
assert received_requests == [
|
||||
{"column": "id", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"},
|
||||
{
|
||||
"column": "id",
|
||||
"index_type": "PLUGIN",
|
||||
"plugin_type": "BLOOMFILTER",
|
||||
"name": "id_bloom",
|
||||
"replace": False,
|
||||
"params": {"number_of_items": 4096, "column": "not_id"},
|
||||
},
|
||||
{
|
||||
"column": "id",
|
||||
"index_type": "PLUGIN",
|
||||
"plugin_type": "BLOOMFILTER",
|
||||
"params": {"probability": 0.01},
|
||||
},
|
||||
{
|
||||
"column": "id",
|
||||
"index_type": "PLUGIN",
|
||||
"plugin_type": "ZONEMAP",
|
||||
"params": {},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user