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
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user