mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(nodejs): expose the NGram scalar index (#4908)
The Rust core (lancedb::index::scalar::NGramIndexBuilder) and the Python
SDK already support the NGram scalar index, and the Node.js SDK can
create one on Embedded with `Index.plugin("ngram")`. This change adds a
dedicated `Index.ngram()` factory. NGram is a scalar index on a UTF-8
string column that accelerates substring filters such as contains(col,
'needle'), along with some LIKE and regular-expression predicates, by
narrowing a scan to rows that share the query's trigrams.
Add an ngram() napi factory and Index.ngram() in the TypeScript SDK,
mirroring the existing btree and fm scalar index factories, with tests
for both factories. On Embedded, the query plan uses the index and the
exact substring filter excludes rows that only share the query’s
trigrams. On Enterprise, `Index.ngram()` sends `index_type: "NGRAM"`,
while `Index.plugin("ngram")` sends `index_type: "PLUGIN"` with
`plugin_type: "NGRAM"`.
---------
Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -294,6 +294,34 @@ using an underlying bitmap index.
|
||||
|
||||
***
|
||||
|
||||
### ngram()
|
||||
|
||||
```ts
|
||||
static ngram(): Index
|
||||
```
|
||||
|
||||
Create an NGram index.
|
||||
|
||||
An `NGram` index is a scalar index on a UTF-8 string column that accelerates
|
||||
substring filters such as `contains(col, 'needle')`, along with some `LIKE`
|
||||
and regular-expression predicates. It tokenizes values into overlapping
|
||||
character trigrams and narrows a scan to the rows that share the query's
|
||||
trigrams. The exact predicate is then evaluated on those candidates.
|
||||
Queries shorter than three characters fall back to a scan.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Index`](Index.md)
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
await table.createIndex("text", { config: Index.ngram() });
|
||||
const rows = await table.query().where("contains(text, 'needle')").toArray();
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### plugin()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -1970,7 +1970,7 @@ describe("remote connection", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses an explicit type and nested params for remote scalar plugin indexes", async () => {
|
||||
it("sends distinct requests for NGram and scalar plugin indexes", async () => {
|
||||
const createIndexBodies: Record<string, unknown>[] = [];
|
||||
|
||||
await withMockDatabase(
|
||||
@@ -1984,6 +1984,7 @@ describe("remote connection", () => {
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int32" }, nullable: false },
|
||||
{ name: "text", type: { type: "string" }, nullable: false },
|
||||
],
|
||||
},
|
||||
}),
|
||||
@@ -2007,6 +2008,8 @@ describe("remote connection", () => {
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("t");
|
||||
await table.createIndex("text", { config: Index.ngram() });
|
||||
await table.createIndex("text", { config: Index.plugin("ngram") });
|
||||
await table.createIndex("id", { config: Index.plugin(" ZoneMap ") });
|
||||
await table.createIndex("id", {
|
||||
config: Index.plugin("bloomfilter", {
|
||||
@@ -2024,6 +2027,10 @@ describe("remote connection", () => {
|
||||
);
|
||||
|
||||
expect(createIndexBodies).toEqual([
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
{ column: "text", index_type: "NGRAM" },
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
{ column: "text", index_type: "PLUGIN", plugin_type: "NGRAM" },
|
||||
// biome-ignore lint/style/useNamingConvention: wire format
|
||||
{ column: "id", index_type: "PLUGIN", plugin_type: "ZONEMAP" },
|
||||
{
|
||||
|
||||
@@ -1303,6 +1303,33 @@ describe("When creating an index", () => {
|
||||
expect(indices2.length).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Index.ngram()", () => Index.ngram()],
|
||||
['Index.plugin("ngram")', () => Index.plugin("ngram")],
|
||||
])("uses an NGram index for substring search via %s", async (_, config) => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const ngramTable = await db.createTable("ngram_table", [
|
||||
{ id: 0, text: "abcd" },
|
||||
// Contains both trigrams but fails the exact substring predicate.
|
||||
{ id: 1, text: "abcXbcd" },
|
||||
{ id: 2, text: "prefix abcd suffix" },
|
||||
{ id: 3, text: "unrelated" },
|
||||
]);
|
||||
await ngramTable.createIndex("text", { config: config() });
|
||||
|
||||
const indices = await ngramTable.listIndices();
|
||||
expect(indices).toEqual([
|
||||
expect.objectContaining({ indexType: "NGram", columns: ["text"] }),
|
||||
]);
|
||||
const stats = await ngramTable.indexStats(indices[0].name);
|
||||
expect(stats?.numIndexedRows).toBe(4);
|
||||
|
||||
const query = ngramTable.query().where("contains(text, 'abcd')");
|
||||
expect(await query.explainPlan(true)).toContain("ScalarIndexQuery");
|
||||
const rows = await query.toArray();
|
||||
expect(rows.map((row) => row.id).sort((a, b) => a - b)).toEqual([0, 2]);
|
||||
});
|
||||
|
||||
it("should preserve canonical nested field paths across index lifecycle", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const nestedSchema = new Schema([
|
||||
|
||||
@@ -966,6 +966,26 @@ export class Index {
|
||||
return new Index(LanceDbIndex.rtree(pageSize));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an NGram index.
|
||||
*
|
||||
* An `NGram` index is a scalar index on a UTF-8 string column that accelerates
|
||||
* substring filters such as `contains(col, 'needle')`, along with some `LIKE`
|
||||
* and regular-expression predicates. It tokenizes values into overlapping
|
||||
* character trigrams and narrows a scan to the rows that share the query's
|
||||
* trigrams. The exact predicate is then evaluated on those candidates.
|
||||
* Queries shorter than three characters fall back to a scan.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await table.createIndex("text", { config: Index.ngram() });
|
||||
* const rows = await table.query().where("contains(text, 'needle')").toArray();
|
||||
* ```
|
||||
*/
|
||||
static ngram() {
|
||||
return new Index(LanceDbIndex.ngram());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a scalar index of a type recognized by a registered database plugin.
|
||||
*
|
||||
|
||||
+9
-1
@@ -5,7 +5,7 @@ use std::sync::Mutex;
|
||||
|
||||
use lancedb::index::Index as LanceDbIndex;
|
||||
use lancedb::index::scalar::{
|
||||
BTreeIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder, FtsIndexBuilder,
|
||||
BTreeIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
|
||||
PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
};
|
||||
use lancedb::index::vector::{
|
||||
@@ -377,6 +377,14 @@ impl Index {
|
||||
})
|
||||
}
|
||||
|
||||
/// Create an NGram index using the defaults in [`NGramIndexBuilder`].
|
||||
#[napi(factory)]
|
||||
pub fn ngram() -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(Some(LanceDbIndex::NGram(NGramIndexBuilder::default()))),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(factory)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn fts(
|
||||
|
||||
Reference in New Issue
Block a user