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
@@ -261,6 +261,49 @@ using an underlying bitmap index.
|
||||
|
||||
***
|
||||
|
||||
### plugin()
|
||||
|
||||
```ts
|
||||
static plugin(indexType, params?): Index
|
||||
```
|
||||
|
||||
Create a scalar index of a type recognized by a registered database plugin.
|
||||
|
||||
Use this for index types without a dedicated factory on `Index`.
|
||||
Prefer a dedicated factory when one is available.
|
||||
|
||||
An unknown plugin name or invalid parameters cause `createIndex` to fail.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **indexType**: `string`
|
||||
The index type, case-insensitive.
|
||||
Surrounding whitespace is ignored. Must not be empty.
|
||||
|
||||
* **params?**: `string` \| `Record`<`string`, `unknown`>
|
||||
The index parameters, as an object 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.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Index`](Index.md)
|
||||
|
||||
#### Throws
|
||||
|
||||
If `indexType` is empty, or `params` is not a JSON object.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
await table.createIndex("id", {
|
||||
config: Index.plugin("bloomfilter", { number_of_items: 4096 }),
|
||||
});
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### rtree()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -362,6 +362,51 @@ server can build the index and evaluate `ST_*` functions depends on its
|
||||
version.
|
||||
</Note>
|
||||
|
||||
## Create a plugin index by name
|
||||
|
||||
LanceDB can create a scalar index of any type recognized by a registered database
|
||||
plugin. For index types without a dedicated configuration, pass the type name and
|
||||
optional parameters using `ScalarPlugin` in Python, `Index.plugin()` in TypeScript,
|
||||
or `Index::Plugin(PluginIndexBuilder)` in Rust. Prefer a dedicated configuration,
|
||||
such as `BTree`, when one is available.
|
||||
|
||||
Index type names are case-insensitive. Surrounding whitespace is ignored.
|
||||
Parameters are a JSON object and are passed as given. Each plugin defines its
|
||||
parameters and defaults; refer to the plugin's documentation for guidance.
|
||||
Python and TypeScript also accept parameters as a string holding a JSON object.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from lancedb.index import ScalarPlugin
|
||||
|
||||
await tbl.create_index(
|
||||
"id", config=ScalarPlugin("bloomfilter", {"number_of_items": 4096})
|
||||
)
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="square-js"
|
||||
import { Index } from "@lancedb/lancedb";
|
||||
|
||||
await tbl.createIndex("id", {
|
||||
config: Index.plugin("bloomfilter", { number_of_items: 4096 }),
|
||||
});
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::index::Index;
|
||||
use lancedb::index::scalar::PluginIndexBuilder;
|
||||
use serde_json::json;
|
||||
|
||||
let bloom_filter = PluginIndexBuilder::new("bloomfilter")?
|
||||
.params(json!({"number_of_items": 4096}))?;
|
||||
tbl.create_index(&["id"], Index::Plugin(bloom_filter))
|
||||
.execute()
|
||||
.await?;
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
An unknown plugin name or invalid parameters cause index creation to fail.
|
||||
|
||||
## Index UUID Columns
|
||||
|
||||
LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys.
|
||||
|
||||
@@ -1595,6 +1595,91 @@ describe("remote connection", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses an explicit type and nested params for remote scalar plugin indexes", async () => {
|
||||
const createIndexBodies: Record<string, unknown>[] = [];
|
||||
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const path = req.url ?? "";
|
||||
if (path.endsWith("/describe/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
name: "t",
|
||||
version: 1,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int32" }, nullable: false },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.endsWith("/create_index/")) {
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => {
|
||||
raw += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
createIndexBodies.push(JSON.parse(raw));
|
||||
res.writeHead(200).end();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404).end();
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("t");
|
||||
await table.createIndex("id", { config: Index.plugin(" ZoneMap ") });
|
||||
await table.createIndex("id", {
|
||||
config: Index.plugin("bloomfilter", {
|
||||
// biome-ignore lint/style/useNamingConvention: plugin param name
|
||||
number_of_items: 4096,
|
||||
column: "not_id",
|
||||
}),
|
||||
name: "id_bloom",
|
||||
});
|
||||
await table.createIndex("id", {
|
||||
config: Index.plugin("bloomfilter", '{"probability": 0.01}'),
|
||||
});
|
||||
await table.createIndex("id", { config: Index.plugin("zonemap", {}) });
|
||||
},
|
||||
);
|
||||
|
||||
expect(createIndexBodies).toEqual([
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
{ column: "id", index_type: "PLUGIN", plugin_type: "ZONEMAP" },
|
||||
{
|
||||
column: "id",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
index_type: "PLUGIN",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
plugin_type: "BLOOMFILTER",
|
||||
name: "id_bloom",
|
||||
// biome-ignore lint/style/useNamingConvention: plugin param name
|
||||
params: { number_of_items: 4096, column: "not_id" },
|
||||
},
|
||||
{
|
||||
column: "id",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
index_type: "PLUGIN",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
plugin_type: "BLOOMFILTER",
|
||||
params: { probability: 0.01 },
|
||||
},
|
||||
{
|
||||
column: "id",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
index_type: "PLUGIN",
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
plugin_type: "ZONEMAP",
|
||||
params: {},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("diffs and cherry-picks remote branches", async () => {
|
||||
const sampleDiff = {
|
||||
fromBranch: "exp",
|
||||
|
||||
@@ -1933,6 +1933,74 @@ describe("When creating an index", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
["ZoneMap", undefined, "ZoneMap"],
|
||||
["BTREE", undefined, "BTree"],
|
||||
[
|
||||
"bloomfilter",
|
||||
// biome-ignore lint/style/useNamingConvention: plugin param name
|
||||
{ number_of_items: 64, probability: 0.01 },
|
||||
"BloomFilter",
|
||||
],
|
||||
["bloomfilter", '{"number_of_items": 64}', "BloomFilter"],
|
||||
])(
|
||||
"create a scalar plugin index by name (%s, %p)",
|
||||
async (indexType, params, expectedType) => {
|
||||
await tbl.createIndex("id", {
|
||||
config: Index.plugin(indexType, params),
|
||||
name: "id_plugin",
|
||||
});
|
||||
|
||||
const indices = await tbl.listIndices();
|
||||
expect(indices).toHaveLength(1);
|
||||
expect(indices[0].name).toBe("id_plugin");
|
||||
expect(indices[0].indexType).toBe(expectedType);
|
||||
expect(indices[0].columns).toEqual(["id"]);
|
||||
|
||||
const query = tbl.query().where("id = 42");
|
||||
expect(await query.explainPlan()).toContain("ScalarIndexQuery");
|
||||
expect(await query.toArray()).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
test("lists a scalar plugin without a LanceDB type by its own name", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const textTbl = await db.createTable("minhash", [
|
||||
{ text: "alpha beta" },
|
||||
{ text: "beta gamma" },
|
||||
]);
|
||||
await textTbl.createIndex("text", { config: Index.plugin("minhashlsh") });
|
||||
|
||||
const indices = await textTbl.listIndices();
|
||||
expect(indices).toHaveLength(1);
|
||||
expect(indices[0].indexType).toBe("MinHashLsh");
|
||||
});
|
||||
|
||||
test("rejects invalid scalar plugin configs", async () => {
|
||||
expect(() => Index.plugin("")).toThrow("must not be empty");
|
||||
expect(() => Index.plugin(" ")).toThrow("must not be empty");
|
||||
expect(() => Index.plugin("zonemap", "[1]")).toThrow(
|
||||
"must be a JSON object, got an array",
|
||||
);
|
||||
expect(() => Index.plugin("zonemap", "null")).toThrow(
|
||||
"must be a JSON object, got null",
|
||||
);
|
||||
expect(() => Index.plugin("zonemap", "{not json")).toThrow(
|
||||
"not valid JSON",
|
||||
);
|
||||
expect(() =>
|
||||
Index.plugin("zonemap", [1] as unknown as Record<string, unknown>),
|
||||
).toThrow("must be a JSON object, got an array");
|
||||
|
||||
await expect(
|
||||
tbl.createIndex("id", { config: Index.plugin("NoSuchPlugin") }),
|
||||
).rejects.toThrow("No scalar index plugin found for name 'nosuchplugin'");
|
||||
await expect(
|
||||
tbl.createIndex("id", { config: Index.plugin("ngram") }),
|
||||
).rejects.toThrow(/ngram/i);
|
||||
expect(await tbl.listIndices()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("should be able to get index stats", async () => {
|
||||
await tbl.createIndex("id");
|
||||
|
||||
|
||||
@@ -893,6 +893,37 @@ export class Index {
|
||||
return new Index(LanceDbIndex.rtree(pageSize));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a scalar index of a type recognized by a registered database plugin.
|
||||
*
|
||||
* Use this for index types without a dedicated factory on `Index`.
|
||||
* Prefer a dedicated factory when one is available.
|
||||
*
|
||||
* An unknown plugin name or invalid parameters cause `createIndex` to fail.
|
||||
*
|
||||
* @param indexType - The index type, case-insensitive.
|
||||
* Surrounding whitespace is ignored. Must not be empty.
|
||||
* @param params - The index parameters, as an object 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.
|
||||
* @throws If `indexType` is empty, or `params` is not a JSON object.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await table.createIndex("id", {
|
||||
* config: Index.plugin("bloomfilter", { number_of_items: 4096 }),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
static plugin(indexType: string, params?: Record<string, unknown> | string) {
|
||||
const paramsJson =
|
||||
params === undefined || typeof params === "string"
|
||||
? params
|
||||
: JSON.stringify(params);
|
||||
return new Index(LanceDbIndex.plugin(indexType, paramsJson));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a full text search index
|
||||
*
|
||||
|
||||
+13
-1
@@ -5,7 +5,7 @@ use std::sync::Mutex;
|
||||
|
||||
use lancedb::index::Index as LanceDbIndex;
|
||||
use lancedb::index::scalar::{
|
||||
BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, RTreeIndexBuilder,
|
||||
BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder,
|
||||
};
|
||||
use lancedb::index::vector::{
|
||||
IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder,
|
||||
@@ -228,6 +228,18 @@ impl Index {
|
||||
}
|
||||
}
|
||||
|
||||
/// `params_json`, if set, must be a string holding a JSON object.
|
||||
#[napi(factory)]
|
||||
pub fn plugin(index_type: String, params_json: Option<String>) -> napi::Result<Self> {
|
||||
let mut builder = PluginIndexBuilder::new(index_type).default_error()?;
|
||||
if let Some(params_json) = params_json {
|
||||
builder = builder.params_json(params_json).default_error()?;
|
||||
}
|
||||
Ok(Self {
|
||||
inner: Mutex::new(Some(LanceDbIndex::Plugin(builder))),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi(factory)]
|
||||
pub fn rtree(page_size: Option<u32>) -> napi::Result<Self> {
|
||||
let mut builder = RTreeIndexBuilder::default();
|
||||
|
||||
+6
-1
@@ -1314,7 +1314,12 @@ pub struct IndexConfig {
|
||||
|
||||
impl From<lancedb::index::IndexConfig> for IndexConfig {
|
||||
fn from(value: lancedb::index::IndexConfig) -> Self {
|
||||
let index_type = format!("{:?}", value.index_type);
|
||||
// A registered plugin's type is its display name, such as "MinHashLsh",
|
||||
// which `Debug` would render as `Custom("MinHashLsh")`.
|
||||
let index_type = match value.index_type {
|
||||
lancedb::index::IndexType::Custom(name) => name,
|
||||
index_type => format!("{index_type:?}"),
|
||||
};
|
||||
Self {
|
||||
index_type,
|
||||
columns: value.columns,
|
||||
|
||||
@@ -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}]
|
||||
)
|
||||
|
||||
+25
-4
@@ -7,10 +7,10 @@ use lancedb::index::vector::{
|
||||
IvfPqIndexBuilder, IvfRqIndexBuilder, IvfSqIndexBuilder,
|
||||
};
|
||||
use lancedb::index::{
|
||||
Index as LanceDbIndex,
|
||||
Index as LanceDbIndex, IndexType,
|
||||
scalar::{
|
||||
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
|
||||
RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
},
|
||||
};
|
||||
use pyo3::IntoPyObject;
|
||||
@@ -129,6 +129,15 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
}
|
||||
Ok(LanceDbIndex::RTree(builder))
|
||||
}
|
||||
"ScalarPlugin" => {
|
||||
let params = source.extract::<ScalarPluginParams>()?;
|
||||
let invalid = |err: lancedb::Error| PyValueError::new_err(err.to_string());
|
||||
let mut builder = PluginIndexBuilder::new(params.index_type).map_err(invalid)?;
|
||||
if let Some(json) = params.params_json {
|
||||
builder = builder.params_json(json).map_err(invalid)?;
|
||||
}
|
||||
Ok(LanceDbIndex::Plugin(builder))
|
||||
}
|
||||
"FTS" => {
|
||||
let params = source.extract::<FtsParams>()?;
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
@@ -303,7 +312,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, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
not_supported
|
||||
))),
|
||||
}
|
||||
@@ -312,6 +321,13 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct ScalarPluginParams {
|
||||
index_type: String,
|
||||
#[pyo3(attribute("_params_json"))]
|
||||
params_json: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct FtsParams {
|
||||
with_position: bool,
|
||||
@@ -554,7 +570,12 @@ fn parse_index_details(py: Python<'_>, s: String) -> Py<PyAny> {
|
||||
|
||||
impl IndexConfig {
|
||||
pub fn from_lancedb(py: Python<'_>, value: lancedb::index::IndexConfig) -> Self {
|
||||
let index_type = format!("{:?}", value.index_type);
|
||||
// A registered plugin's type is its display name, such as "MinHashLsh",
|
||||
// which `Debug` would render as `Custom("MinHashLsh")`.
|
||||
let index_type = match value.index_type {
|
||||
IndexType::Custom(name) => name,
|
||||
index_type => format!("{index_type:?}"),
|
||||
};
|
||||
Self {
|
||||
index_type,
|
||||
columns: value.columns,
|
||||
|
||||
@@ -16,7 +16,8 @@ use crate::{DistanceType, Error, Result, job::Job, table::BaseTable};
|
||||
use self::{
|
||||
scalar::{
|
||||
BTreeIndexBuilder, BitmapIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder,
|
||||
LabelListIndexBuilder, NGramIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
LabelListIndexBuilder, NGramIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder,
|
||||
ZoneMapIndexBuilder,
|
||||
},
|
||||
vector::{
|
||||
IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder,
|
||||
@@ -74,6 +75,24 @@ pub enum Index {
|
||||
/// Native creation requires the `geo` feature.
|
||||
RTree(RTreeIndexBuilder),
|
||||
|
||||
/// Configure a scalar index of a type recognized by a registered database plugin.
|
||||
///
|
||||
/// Select the type by name and provide optional JSON parameters with
|
||||
/// [`PluginIndexBuilder`]. Prefer a dedicated variant when one is available.
|
||||
///
|
||||
/// ```
|
||||
/// use lancedb::index::{Index, scalar::PluginIndexBuilder};
|
||||
///
|
||||
/// # async fn create_zonemap(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// table
|
||||
/// .create_index(&["timestamp"], Index::Plugin(PluginIndexBuilder::new("zonemap")?))
|
||||
/// .execute()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
Plugin(PluginIndexBuilder),
|
||||
|
||||
/// Full text search index using BM25.
|
||||
///
|
||||
/// Supports strings, lists of strings, and `lance.json` logical fields
|
||||
|
||||
@@ -204,6 +204,110 @@ impl RTreeIndexBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Configure a scalar index of a type recognized by a registered database plugin.
|
||||
///
|
||||
/// Use this for index types without a dedicated builder. Prefer a dedicated
|
||||
/// builder, such as [`ZoneMapIndexBuilder`] or [`BloomFilterIndexBuilder`], when
|
||||
/// one is available.
|
||||
///
|
||||
/// Index type names are case-insensitive. Surrounding whitespace is ignored.
|
||||
/// Parameters are optional and, if given, must be a JSON object. They are passed
|
||||
/// as given. Each plugin defines its parameters and defaults; refer to the
|
||||
/// plugin's documentation for guidance.
|
||||
///
|
||||
/// An unknown plugin name or invalid parameters cause index creation to fail.
|
||||
///
|
||||
/// ```
|
||||
/// use lancedb::index::{Index, scalar::PluginIndexBuilder};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// # async fn create_plugin_index(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// let bloom_filter = PluginIndexBuilder::new("bloomfilter")?
|
||||
/// .params(json!({"number_of_items": 4096, "probability": 0.01}))?;
|
||||
/// table
|
||||
/// .create_index(&["id"], Index::Plugin(bloom_filter))
|
||||
/// .execute()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PluginIndexBuilder {
|
||||
pub(crate) index_type: String,
|
||||
pub(crate) params: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
}
|
||||
|
||||
impl PluginIndexBuilder {
|
||||
/// Select the scalar index type named `index_type`.
|
||||
///
|
||||
/// The name is trimmed and lower-cased. Returns
|
||||
/// [`Error::InvalidInput`](crate::Error::InvalidInput) if it is empty.
|
||||
pub fn new(index_type: impl Into<String>) -> crate::Result<Self> {
|
||||
let index_type = index_type.into().trim().to_lowercase();
|
||||
if index_type.is_empty() {
|
||||
return Err(crate::Error::InvalidInput {
|
||||
message: "a scalar index plugin name must not be empty".into(),
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
index_type,
|
||||
params: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the index parameters, which must be a JSON object.
|
||||
///
|
||||
/// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) for any
|
||||
/// other JSON value, including `null`.
|
||||
pub fn params(mut self, params: serde_json::Value) -> crate::Result<Self> {
|
||||
match params {
|
||||
serde_json::Value::Object(params) => {
|
||||
self.params = Some(params);
|
||||
Ok(self)
|
||||
}
|
||||
other => Err(crate::Error::InvalidInput {
|
||||
message: format!(
|
||||
"scalar index plugin params must be a JSON object, got {}",
|
||||
json_kind(&other)
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the index parameters from a JSON string, which must hold an object.
|
||||
///
|
||||
/// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) if the string
|
||||
/// is not valid JSON or holds anything but an object.
|
||||
pub fn params_json(self, params: impl AsRef<str>) -> crate::Result<Self> {
|
||||
let params =
|
||||
serde_json::from_str(params.as_ref()).map_err(|e| crate::Error::InvalidInput {
|
||||
message: format!("scalar index plugin params are not valid JSON: {e}"),
|
||||
})?;
|
||||
self.params(params)
|
||||
}
|
||||
|
||||
/// The index type name, trimmed and lower-cased.
|
||||
pub fn index_type(&self) -> &str {
|
||||
&self.index_type
|
||||
}
|
||||
|
||||
/// The index parameters, if set.
|
||||
pub fn parameters(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
|
||||
self.params.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
fn json_kind(value: &serde_json::Value) -> &'static str {
|
||||
match value {
|
||||
serde_json::Value::Null => "null",
|
||||
serde_json::Value::Bool(_) => "a boolean",
|
||||
serde_json::Value::Number(_) => "a number",
|
||||
serde_json::Value::String(_) => "a string",
|
||||
serde_json::Value::Array(_) => "an array",
|
||||
serde_json::Value::Object(_) => "an object",
|
||||
}
|
||||
}
|
||||
|
||||
pub use lance_index::scalar::FullTextSearchQuery;
|
||||
pub use lance_index::scalar::InvertedIndexParams as FtsIndexBuilder;
|
||||
pub use lance_index::scalar::InvertedIndexParams;
|
||||
@@ -267,4 +371,66 @@ mod tests {
|
||||
}
|
||||
assert!(RTreeIndexBuilder::default().page_size(2).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_index_builder_normalizes_the_name() {
|
||||
for name in ["zonemap", "ZoneMap", "ZONEMAP", " zonemap\t"] {
|
||||
assert_eq!(
|
||||
PluginIndexBuilder::new(name).unwrap().index_type(),
|
||||
"zonemap"
|
||||
);
|
||||
}
|
||||
for name in ["", " ", "\n"] {
|
||||
assert!(matches!(
|
||||
PluginIndexBuilder::new(name),
|
||||
Err(crate::Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_index_builder_accepts_only_object_params() {
|
||||
let builder = PluginIndexBuilder::new("bloomfilter").unwrap();
|
||||
assert_eq!(builder.parameters(), None);
|
||||
|
||||
let expected = serde_json::json!({"number_of_items": 4096});
|
||||
let from_value = builder.clone().params(expected.clone()).unwrap();
|
||||
let from_json = builder
|
||||
.clone()
|
||||
.params_json(r#"{"number_of_items": 4096}"#)
|
||||
.unwrap();
|
||||
assert_eq!(from_value, from_json);
|
||||
assert_eq!(from_value.parameters(), Some(expected.as_object().unwrap()));
|
||||
assert_eq!(
|
||||
builder
|
||||
.clone()
|
||||
.params(serde_json::json!({}))
|
||||
.unwrap()
|
||||
.parameters(),
|
||||
Some(&serde_json::Map::new())
|
||||
);
|
||||
|
||||
for (params, kind) in [
|
||||
(serde_json::Value::Null, "null"),
|
||||
(serde_json::json!(true), "a boolean"),
|
||||
(serde_json::json!(1), "a number"),
|
||||
(serde_json::json!("x"), "a string"),
|
||||
(serde_json::json!([1]), "an array"),
|
||||
] {
|
||||
let json = params.to_string();
|
||||
for result in [
|
||||
builder.clone().params(params),
|
||||
builder.clone().params_json(json),
|
||||
] {
|
||||
let Err(crate::Error::InvalidInput { message }) = result else {
|
||||
panic!("non-object params must be rejected");
|
||||
};
|
||||
assert!(message.ends_with(kind), "{message}");
|
||||
}
|
||||
}
|
||||
let Err(crate::Error::InvalidInput { message }) = builder.params_json("{not json") else {
|
||||
panic!("malformed JSON must be rejected");
|
||||
};
|
||||
assert!(message.contains("not valid JSON"), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,6 +842,12 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
Index::NGram(p) => ("NGRAM", Some(to_json(p)?)),
|
||||
Index::BloomFilter(p) => ("BLOOM_FILTER", Some(to_json(p)?)),
|
||||
Index::RTree(p) => ("RTREE", Some(to_json(p)?)),
|
||||
// Keep generic plugin requests distinct from built-in index handling.
|
||||
// The plugin's params are nested below rather than flattened.
|
||||
Index::Plugin(p) => {
|
||||
body["plugin_type"] = p.index_type().to_uppercase().into();
|
||||
("PLUGIN", None)
|
||||
}
|
||||
Index::FTS(p) => {
|
||||
validate_fts_field(&field)?;
|
||||
let mut params = to_json(p)?;
|
||||
@@ -880,6 +886,14 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
body[key] = value.clone();
|
||||
}
|
||||
}
|
||||
// A plugin's params are arbitrary, so they go under a single `params`
|
||||
// key. Flattened, they could overwrite request fields such as `column`,
|
||||
// `name`, `replace` or `branch`.
|
||||
if let Index::Plugin(plugin) = &index.index
|
||||
&& let Some(params) = plugin.parameters()
|
||||
{
|
||||
body["params"] = serde_json::Value::Object(params.clone());
|
||||
}
|
||||
self.apply_branch_body(&mut body);
|
||||
|
||||
let request = request.json(&body);
|
||||
@@ -9564,6 +9578,103 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Generic index requests use `PLUGIN` and a separate `plugin_type`. Params
|
||||
/// stay nested so they cannot replace routing fields or request metadata.
|
||||
#[tokio::test]
|
||||
async fn test_create_plugin_index_nests_params() {
|
||||
use crate::index::scalar::PluginIndexBuilder;
|
||||
|
||||
let colliding_params = json!({
|
||||
"column": "not_a",
|
||||
"name": "not_my_index",
|
||||
"replace": true,
|
||||
"index_type": "BTREE",
|
||||
"plugin_type": "ZONEMAP",
|
||||
"branch": "not_my_branch",
|
||||
"keys": ["label", "confidence"],
|
||||
});
|
||||
let cases = [
|
||||
(
|
||||
PluginIndexBuilder::new(" ZoneMap ").unwrap(),
|
||||
None,
|
||||
true,
|
||||
json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"}),
|
||||
),
|
||||
(
|
||||
PluginIndexBuilder::new("BloomFilter")
|
||||
.unwrap()
|
||||
.params(json!({"number_of_items": 4096}))
|
||||
.unwrap(),
|
||||
None,
|
||||
true,
|
||||
json!({
|
||||
"column": "a",
|
||||
"index_type": "PLUGIN",
|
||||
"plugin_type": "BLOOMFILTER",
|
||||
"params": {"number_of_items": 4096},
|
||||
}),
|
||||
),
|
||||
(
|
||||
PluginIndexBuilder::new("listelement")
|
||||
.unwrap()
|
||||
.params(colliding_params.clone())
|
||||
.unwrap(),
|
||||
Some("my_index"),
|
||||
false,
|
||||
json!({
|
||||
"column": "a",
|
||||
"index_type": "PLUGIN",
|
||||
"plugin_type": "LISTELEMENT",
|
||||
"name": "my_index",
|
||||
"replace": false,
|
||||
"params": colliding_params,
|
||||
}),
|
||||
),
|
||||
(
|
||||
PluginIndexBuilder::new("zonemap")
|
||||
.unwrap()
|
||||
.params(json!({}))
|
||||
.unwrap(),
|
||||
None,
|
||||
true,
|
||||
json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP", "params": {}}),
|
||||
),
|
||||
];
|
||||
|
||||
for (plugin, name, replace, expected_body) in cases {
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
match request.url().path() {
|
||||
"/v1/table/my_table/describe/" => {
|
||||
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(describe_response(&schema))
|
||||
.unwrap()
|
||||
}
|
||||
"/v1/table/my_table/create_index/" => {
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
assert_eq!(body, expected_body);
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body("{}".to_string())
|
||||
.unwrap()
|
||||
}
|
||||
path => panic!("Unexpected path: {}", path),
|
||||
}
|
||||
});
|
||||
|
||||
let mut builder = table
|
||||
.create_index(&["a"], Index::Plugin(plugin))
|
||||
.replace(replace);
|
||||
if let Some(name) = name {
|
||||
builder = builder.name(name.to_string());
|
||||
}
|
||||
builder.execute().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_index_returns_job() {
|
||||
let describe_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
|
||||
@@ -366,6 +366,15 @@ impl NativeTable {
|
||||
ScalarIndexParams::for_builtin(BuiltinIndexType::RTree).with_params(¶ms),
|
||||
))
|
||||
}
|
||||
// Lance resolves the plugin by name and the plugin checks the column
|
||||
// and the parameters, so there is nothing to validate here.
|
||||
Index::Plugin(plugin) => {
|
||||
let mut params = ScalarIndexParams::new(plugin.index_type);
|
||||
params.params = plugin
|
||||
.params
|
||||
.map(|params| serde_json::Value::Object(params).to_string());
|
||||
Ok(Box::new(params))
|
||||
}
|
||||
Index::FTS(fts_opts) => {
|
||||
validate_fts_field(field)?;
|
||||
Ok(Box::new(fts_opts))
|
||||
@@ -532,6 +541,7 @@ impl NativeTable {
|
||||
Index::NGram(_) => IndexType::NGram,
|
||||
Index::BloomFilter(_) => IndexType::BloomFilter,
|
||||
Index::RTree(_) => IndexType::RTree,
|
||||
Index::Plugin(_) => IndexType::Scalar,
|
||||
Index::FTS(_) => IndexType::Inverted,
|
||||
Index::IvfFlat(_)
|
||||
| Index::IvfSq(_)
|
||||
@@ -1850,6 +1860,191 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lance's built-in plugins, created by name through the generic path, are
|
||||
/// listed with the same type as their dedicated builders and serve filters.
|
||||
#[tokio::test]
|
||||
async fn test_create_plugin_index() {
|
||||
use crate::index::IndexType;
|
||||
use crate::index::scalar::PluginIndexBuilder;
|
||||
|
||||
for (name, params, column, index_type, predicate, expected_rows) in [
|
||||
(
|
||||
"ZoneMap",
|
||||
None,
|
||||
"id",
|
||||
IndexType::ZoneMap,
|
||||
"id >= 2 AND id < 4",
|
||||
2,
|
||||
),
|
||||
(
|
||||
"bloomfilter",
|
||||
Some(serde_json::json!({"number_of_items": 2, "probability": 0.01})),
|
||||
"text",
|
||||
IndexType::BloomFilter,
|
||||
"text = 'abc'",
|
||||
1,
|
||||
),
|
||||
("BTREE", None, "id", IndexType::BTree, "id = 3", 1),
|
||||
] {
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let batch = record_batch!(
|
||||
("id", Int32, [1, 2, 3, 4]),
|
||||
("text", Utf8, [Some("abc"), Some("xyz"), None, Some("")])
|
||||
)
|
||||
.unwrap();
|
||||
let table = conn.create_table("plugin", batch).execute().await.unwrap();
|
||||
|
||||
let mut plugin = PluginIndexBuilder::new(name).unwrap();
|
||||
if let Some(params) = params.clone() {
|
||||
plugin = plugin.params(params).unwrap();
|
||||
}
|
||||
table
|
||||
.create_index(&[column], Index::Plugin(plugin))
|
||||
.name("plugin_idx".into())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let indices = table.list_indices().await.unwrap();
|
||||
assert_eq!(indices.len(), 1);
|
||||
assert_eq!(indices[0].index_type, index_type, "{name}");
|
||||
assert_eq!(indices[0].columns, [column]);
|
||||
let stats = table.index_stats("plugin_idx").await.unwrap().unwrap();
|
||||
assert_eq!(stats.index_type, index_type);
|
||||
assert_eq!(stats.num_indexed_rows, 4);
|
||||
|
||||
// Lance trained the plugin with the given params, not its defaults.
|
||||
if let Some(params) = params {
|
||||
let dataset = table.as_native().unwrap().dataset.get().await.unwrap();
|
||||
let stats: serde_json::Value =
|
||||
serde_json::from_str(&dataset.index_statistics("plugin_idx").await.unwrap())
|
||||
.unwrap();
|
||||
for (key, value) in params.as_object().unwrap() {
|
||||
assert_eq!(&stats["indices"][0][key], value, "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
let query = table.query().only_if(predicate);
|
||||
let plan = query.explain_plan(false).await.unwrap();
|
||||
assert!(plan.contains("ScalarIndexQuery"), "{name}: {plan}");
|
||||
let batches = query
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
|
||||
expected_rows,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A plugin LanceDB has no type for is listed as `Custom` with the name
|
||||
/// the plugin reports.
|
||||
#[tokio::test]
|
||||
async fn test_create_plugin_index_without_lancedb_type_is_listed_as_custom() {
|
||||
use crate::index::IndexType;
|
||||
use crate::index::scalar::PluginIndexBuilder;
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let batch = record_batch!((
|
||||
"value",
|
||||
Utf8,
|
||||
["alpha beta", "beta gamma", "gamma delta", "delta alpha"]
|
||||
))
|
||||
.unwrap();
|
||||
let table = conn.create_table("custom", batch).execute().await.unwrap();
|
||||
table
|
||||
.create_index(
|
||||
&["value"],
|
||||
Index::Plugin(PluginIndexBuilder::new("MinHashLSH").unwrap()),
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let indices = table.list_indices().await.unwrap();
|
||||
assert_eq!(indices.len(), 1);
|
||||
assert_eq!(
|
||||
indices[0].index_type,
|
||||
IndexType::Custom("MinHashLsh".into())
|
||||
);
|
||||
assert_eq!(indices[0].index_type.to_string(), "MinHashLsh");
|
||||
assert_eq!(indices[0].columns, ["value"]);
|
||||
}
|
||||
|
||||
/// Lance's errors for an unknown plugin, a column the plugin cannot index
|
||||
/// and params the plugin rejects reach the caller, through both execute
|
||||
/// paths, and leave no index behind.
|
||||
#[tokio::test]
|
||||
async fn test_create_plugin_index_errors() {
|
||||
use crate::index::scalar::PluginIndexBuilder;
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let batch =
|
||||
record_batch!(("id", Int32, [1, 2, 3]), ("text", Utf8, ["a", "b", "c"])).unwrap();
|
||||
let table = conn.create_table("errors", batch).execute().await.unwrap();
|
||||
|
||||
let plugin = |name: &str| PluginIndexBuilder::new(name).unwrap();
|
||||
for (column, index, expected) in [
|
||||
(
|
||||
"id",
|
||||
plugin("NoSuchPlugin"),
|
||||
"No scalar index plugin found for name 'nosuchplugin'",
|
||||
),
|
||||
("id", plugin("ngram"), "ngram"),
|
||||
(
|
||||
"text",
|
||||
plugin("bloomfilter")
|
||||
.params(serde_json::json!({"number_of_items": "many"}))
|
||||
.unwrap(),
|
||||
"invalid type: string \"many\", expected u64",
|
||||
),
|
||||
] {
|
||||
let error = table
|
||||
.create_index(&[column], Index::Plugin(index.clone()))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.to_lowercase()
|
||||
.contains(&expected.to_lowercase()),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
let error = table
|
||||
.create_index(&[column], Index::Plugin(index))
|
||||
.execute_async()
|
||||
.await
|
||||
.unwrap()
|
||||
.wait()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.to_lowercase()
|
||||
.contains(&expected.to_lowercase()),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
assert!(table.list_indices().await.unwrap().is_empty());
|
||||
|
||||
// A missing column is still caught before any build starts.
|
||||
assert!(
|
||||
table
|
||||
.create_index(&["missing"], Index::Plugin(plugin("zonemap")))
|
||||
.execute_async()
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "geo")]
|
||||
#[tokio::test]
|
||||
async fn test_create_rtree_index() {
|
||||
|
||||
Reference in New Issue
Block a user