mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(nodejs): expose code analyzer options on FtsOptions and tokenize (#4889)
Completes #4364 together with #4756, which did the Python side. ## Changes - `Index.fts()` / `FtsOptions` and `tokenize()` gain `analyzer` (`"text"` or `"code"`), `splitIdentifiers`, `splitOnNumerics`, `preserveOriginal` and `indexOperators`. All are optional, so existing indexes and calls behave as before. - Validation matches the Python SDK: `analyzer: "code"` with a `baseTokenizer` other than `"code"` or `"simple"` is rejected, `analyzer: "text"` with `baseTokenizer: "code"` is rejected, and turning on a code flag without the code analyzer is rejected. Passing a flag as `false` is always allowed. The checks live in one helper used by both `fts` and `tokenize`. - The option docs state the defaults (`analyzer: "code"` alone keeps identifiers whole; `splitOnNumerics` and `preserveOriginal` only matter with `splitIdentifiers: true`) and link the two Lance limitations noted on #4756 (lance#9674 and lance#9658). Shared presets can still include extra fields. For example, a preset can carry the index name for `createIndex()` alongside the analyzer options used by `Index.fts()` and `tokenize()`. ## Tests The Node tests check exact tokens from both the named index and standalone tokenization, whole identifiers, subword matches, shared presets and invalid combinations of known options. With the rebuilt native addon, the full local Jest run passed 2,045 tests across 37 suites, with 27 tests skipped. TypeScript checks, lint and API reference regeneration also passed. --------- Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -10,6 +10,24 @@ Options to create a full text search index
|
||||
|
||||
## Properties
|
||||
|
||||
### analyzer?
|
||||
|
||||
```ts
|
||||
optional analyzer: "code" | "text";
|
||||
```
|
||||
|
||||
The analyzer family to use.
|
||||
|
||||
"code" selects the code analyzer, which is the same as
|
||||
`baseTokenizer: "code"`. "text" selects a text-family analyzer with the
|
||||
selected `baseTokenizer`. When it is not set, the analyzer is inferred
|
||||
from `baseTokenizer`.
|
||||
|
||||
"code" cannot be combined with a `baseTokenizer` other than "simple" or
|
||||
"code", and "text" cannot be combined with `baseTokenizer: "code"`.
|
||||
|
||||
***
|
||||
|
||||
### asciiFolding?
|
||||
|
||||
```ts
|
||||
@@ -73,6 +91,18 @@ replaces it with no stop words.
|
||||
|
||||
***
|
||||
|
||||
### indexOperators?
|
||||
|
||||
```ts
|
||||
optional indexOperators: boolean;
|
||||
```
|
||||
|
||||
Index code operators such as `::`, `->` and `!=`.
|
||||
|
||||
The code analyzer default is false.
|
||||
|
||||
***
|
||||
|
||||
### language?
|
||||
|
||||
```ts
|
||||
@@ -135,6 +165,19 @@ whether to only index the prefix of the token for ngram tokenizer
|
||||
|
||||
***
|
||||
|
||||
### preserveOriginal?
|
||||
|
||||
```ts
|
||||
optional preserveOriginal: boolean;
|
||||
```
|
||||
|
||||
Also index the complete identifier next to its subwords.
|
||||
|
||||
The code analyzer default is true, but this only takes effect when
|
||||
`splitIdentifiers` is true.
|
||||
|
||||
***
|
||||
|
||||
### removeStopWords?
|
||||
|
||||
```ts
|
||||
@@ -145,6 +188,39 @@ whether to remove stop words
|
||||
|
||||
***
|
||||
|
||||
### splitIdentifiers?
|
||||
|
||||
```ts
|
||||
optional splitIdentifiers: boolean;
|
||||
```
|
||||
|
||||
Split code identifiers such as `camelCase` and `snake_case` into subwords.
|
||||
|
||||
Setting this to true requires the code analyzer. The default is false, so
|
||||
`analyzer: "code"` alone keeps identifiers whole.
|
||||
|
||||
Note: with the default `preserveOriginal`, partial-identifier AND and
|
||||
phrase queries on JSON columns can miss matches
|
||||
(https://github.com/lance-format/lance/issues/9674). Spell phrase queries
|
||||
with the same identifier boundaries as the indexed text
|
||||
(https://github.com/lance-format/lance/issues/9658).
|
||||
|
||||
***
|
||||
|
||||
### splitOnNumerics?
|
||||
|
||||
```ts
|
||||
optional splitOnNumerics: boolean;
|
||||
```
|
||||
|
||||
Split identifier subwords at letter and number boundaries, for example
|
||||
`utf8` into `utf` and `8`.
|
||||
|
||||
The code analyzer default is true, but this only takes effect when
|
||||
`splitIdentifiers` is true.
|
||||
|
||||
***
|
||||
|
||||
### stem?
|
||||
|
||||
```ts
|
||||
|
||||
@@ -10,6 +10,16 @@ Options for tokenizing a full-text search query without a table index.
|
||||
|
||||
## Properties
|
||||
|
||||
### analyzer?
|
||||
|
||||
```ts
|
||||
optional analyzer: "code" | "text";
|
||||
```
|
||||
|
||||
The analyzer family to use. See [FtsOptions.analyzer](FtsOptions.md#analyzer).
|
||||
|
||||
***
|
||||
|
||||
### asciiFolding?
|
||||
|
||||
```ts
|
||||
@@ -45,6 +55,16 @@ replaces it with no stop words.
|
||||
|
||||
***
|
||||
|
||||
### indexOperators?
|
||||
|
||||
```ts
|
||||
optional indexOperators: boolean;
|
||||
```
|
||||
|
||||
Emit code operators such as `::`, `->` and `!=`.
|
||||
|
||||
***
|
||||
|
||||
### language?
|
||||
|
||||
```ts
|
||||
@@ -105,6 +125,16 @@ Whether to only emit token prefixes for the n-gram tokenizer.
|
||||
|
||||
***
|
||||
|
||||
### preserveOriginal?
|
||||
|
||||
```ts
|
||||
optional preserveOriginal: boolean;
|
||||
```
|
||||
|
||||
Also emit the complete identifier next to its subwords.
|
||||
|
||||
***
|
||||
|
||||
### removeStopWords?
|
||||
|
||||
```ts
|
||||
@@ -115,6 +145,26 @@ Whether to remove stop words.
|
||||
|
||||
***
|
||||
|
||||
### splitIdentifiers?
|
||||
|
||||
```ts
|
||||
optional splitIdentifiers: boolean;
|
||||
```
|
||||
|
||||
Split code identifiers into subwords. See [FtsOptions.splitIdentifiers](FtsOptions.md#splitidentifiers).
|
||||
|
||||
***
|
||||
|
||||
### splitOnNumerics?
|
||||
|
||||
```ts
|
||||
optional splitOnNumerics: boolean;
|
||||
```
|
||||
|
||||
Split identifier subwords at letter and number boundaries.
|
||||
|
||||
***
|
||||
|
||||
### stem?
|
||||
|
||||
```ts
|
||||
|
||||
@@ -51,7 +51,7 @@ import {
|
||||
getRegistry,
|
||||
register,
|
||||
} from "../lancedb/embedding";
|
||||
import { Index } from "../lancedb/indices";
|
||||
import { type FtsOptions, Index } from "../lancedb/indices";
|
||||
import { experimentalFunctionsEnabled } from "../lancedb/native";
|
||||
import {
|
||||
BooleanQuery,
|
||||
@@ -2278,6 +2278,119 @@ describe("When creating an index", () => {
|
||||
expect(vectorIdx.numIndexedRows).toBe(300);
|
||||
expect(typeof vectorIdx.indexDetails).toBe("object");
|
||||
});
|
||||
|
||||
describe("with the code analyzer", () => {
|
||||
const text = "def parseHTTPRequest(user_id): pass";
|
||||
|
||||
async function codeTable(options: Partial<FtsOptions> & { name?: string }) {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable(
|
||||
"code_analyzer",
|
||||
[{ text }, { text: "unrelated" }],
|
||||
{ mode: "overwrite" },
|
||||
);
|
||||
await table.createIndex("text", {
|
||||
config: Index.fts(options),
|
||||
name: options.name,
|
||||
});
|
||||
return table;
|
||||
}
|
||||
|
||||
async function matches(table: Table, query: string) {
|
||||
const rows = await table.search(query, "fts").toArray();
|
||||
return rows.map((row) => row.text);
|
||||
}
|
||||
|
||||
it("uses a shared code analyzer preset with extra keys", async () => {
|
||||
const preset = {
|
||||
analyzer: "code" as const,
|
||||
splitIdentifiers: true,
|
||||
splitOnNumerics: false,
|
||||
preserveOriginal: false,
|
||||
indexOperators: true,
|
||||
name: "body_fts",
|
||||
};
|
||||
const table = await codeTable(preset);
|
||||
|
||||
for (const query of ["http", "request", "parseHTTPRequest"]) {
|
||||
expect(await matches(table, query)).toEqual([text]);
|
||||
}
|
||||
|
||||
const input = "user_id::utf8";
|
||||
const expected = ["user", "id", "::", "utf8"];
|
||||
const indexedTokens = await table.tokenize(input, {
|
||||
indexName: preset.name,
|
||||
});
|
||||
expect(indexedTokens.map((token) => token.text)).toEqual(expected);
|
||||
const directTokens = await tokenize(input, preset);
|
||||
expect(directTokens.map((token) => token.text)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("keeps identifiers whole when splitting is off", async () => {
|
||||
const table = await codeTable({
|
||||
analyzer: "code",
|
||||
splitIdentifiers: false,
|
||||
});
|
||||
|
||||
expect(await matches(table, "request")).toEqual([]);
|
||||
expect(await matches(table, "parseHTTPRequest")).toEqual([text]);
|
||||
});
|
||||
|
||||
it("treats analyzer code like the code base tokenizer", async () => {
|
||||
const table = await codeTable({ baseTokenizer: "code" });
|
||||
|
||||
expect(await matches(table, "request")).toEqual([]);
|
||||
expect(await matches(table, "parseHTTPRequest")).toEqual([text]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ analyzer: "code", baseTokenizer: "ngram" }, "requires baseTokenizer"],
|
||||
[{ analyzer: "text", baseTokenizer: "code" }, "requires analyzer 'code'"],
|
||||
[{ analyzer: "java" }, "analyzer must be"],
|
||||
[{ splitIdentifiers: true }, "require analyzer 'code'"],
|
||||
[
|
||||
{ baseTokenizer: "raw", indexOperators: true },
|
||||
"require analyzer 'code'",
|
||||
],
|
||||
])("rejects invalid options %j", async (options, message) => {
|
||||
const ftsOptions = options as Partial<FtsOptions>;
|
||||
expect(() => Index.fts(ftsOptions)).toThrow(message);
|
||||
await expect(tokenize("hello", ftsOptions)).rejects.toThrow(message);
|
||||
});
|
||||
|
||||
it.each([{ analyzer: "code" }, { baseTokenizer: "code" }] as const)(
|
||||
"tokenizes whole identifiers with %j",
|
||||
async (options) => {
|
||||
const tokens = await tokenize("parseHTTPRequest::utf8", options);
|
||||
expect(tokens.map((token) => token.text)).toEqual([
|
||||
"parsehttprequest",
|
||||
"utf8",
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps original tokens and splits numeric subwords by default", async () => {
|
||||
const tokens = await tokenize("parseHTTPRequest::utf8", {
|
||||
analyzer: "code",
|
||||
splitIdentifiers: true,
|
||||
});
|
||||
expect(tokens.map((token) => token.text)).toEqual([
|
||||
"parsehttprequest",
|
||||
"parse",
|
||||
"http",
|
||||
"request",
|
||||
"utf8",
|
||||
"utf",
|
||||
"8",
|
||||
]);
|
||||
});
|
||||
|
||||
it("allows code flags set to false on a text index", () => {
|
||||
expect(() =>
|
||||
Index.fts({ splitIdentifiers: false, indexOperators: false }),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("When querying a table", () => {
|
||||
|
||||
@@ -344,6 +344,23 @@ export interface TokenizeOptions {
|
||||
|
||||
/** Whether to only emit token prefixes for the n-gram tokenizer. */
|
||||
prefixOnly?: boolean;
|
||||
|
||||
/**
|
||||
* The analyzer family to use. See {@link FtsOptions.analyzer}.
|
||||
*/
|
||||
analyzer?: "text" | "code";
|
||||
|
||||
/** Split code identifiers into subwords. See {@link FtsOptions.splitIdentifiers}. */
|
||||
splitIdentifiers?: boolean;
|
||||
|
||||
/** Split identifier subwords at letter and number boundaries. */
|
||||
splitOnNumerics?: boolean;
|
||||
|
||||
/** Also emit the complete identifier next to its subwords. */
|
||||
preserveOriginal?: boolean;
|
||||
|
||||
/** Emit code operators such as `::`, `->` and `!=`. */
|
||||
indexOperators?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -369,6 +386,11 @@ export async function tokenize(
|
||||
options?.ngramMinLength,
|
||||
options?.ngramMaxLength,
|
||||
options?.prefixOnly,
|
||||
options?.analyzer,
|
||||
options?.splitIdentifiers,
|
||||
options?.splitOnNumerics,
|
||||
options?.preserveOriginal,
|
||||
options?.indexOperators,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -698,6 +698,57 @@ export interface FtsOptions {
|
||||
* the experimental FTS V3 format and may introduce breaking changes.
|
||||
*/
|
||||
blockSize?: 128 | 256;
|
||||
|
||||
/**
|
||||
* The analyzer family to use.
|
||||
*
|
||||
* "code" selects the code analyzer, which is the same as
|
||||
* `baseTokenizer: "code"`. "text" selects a text-family analyzer with the
|
||||
* selected `baseTokenizer`. When it is not set, the analyzer is inferred
|
||||
* from `baseTokenizer`.
|
||||
*
|
||||
* "code" cannot be combined with a `baseTokenizer` other than "simple" or
|
||||
* "code", and "text" cannot be combined with `baseTokenizer: "code"`.
|
||||
*/
|
||||
analyzer?: "text" | "code";
|
||||
|
||||
/**
|
||||
* Split code identifiers such as `camelCase` and `snake_case` into subwords.
|
||||
*
|
||||
* Setting this to true requires the code analyzer. The default is false, so
|
||||
* `analyzer: "code"` alone keeps identifiers whole.
|
||||
*
|
||||
* Note: with the default `preserveOriginal`, partial-identifier AND and
|
||||
* phrase queries on JSON columns can miss matches
|
||||
* (https://github.com/lance-format/lance/issues/9674). Spell phrase queries
|
||||
* with the same identifier boundaries as the indexed text
|
||||
* (https://github.com/lance-format/lance/issues/9658).
|
||||
*/
|
||||
splitIdentifiers?: boolean;
|
||||
|
||||
/**
|
||||
* Split identifier subwords at letter and number boundaries, for example
|
||||
* `utf8` into `utf` and `8`.
|
||||
*
|
||||
* The code analyzer default is true, but this only takes effect when
|
||||
* `splitIdentifiers` is true.
|
||||
*/
|
||||
splitOnNumerics?: boolean;
|
||||
|
||||
/**
|
||||
* Also index the complete identifier next to its subwords.
|
||||
*
|
||||
* The code analyzer default is true, but this only takes effect when
|
||||
* `splitIdentifiers` is true.
|
||||
*/
|
||||
preserveOriginal?: boolean;
|
||||
|
||||
/**
|
||||
* Index code operators such as `::`, `->` and `!=`.
|
||||
*
|
||||
* The code analyzer default is false.
|
||||
*/
|
||||
indexOperators?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1022,6 +1073,11 @@ export class Index {
|
||||
options?.ngramMaxLength,
|
||||
options?.prefixOnly,
|
||||
options?.blockSize,
|
||||
options?.analyzer,
|
||||
options?.splitIdentifiers,
|
||||
options?.splitOnNumerics,
|
||||
options?.preserveOriginal,
|
||||
options?.indexOperators,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
+104
-2
@@ -36,6 +36,82 @@ impl Index {
|
||||
}
|
||||
}
|
||||
|
||||
/// Code-analyzer options shared by `Index.fts` and `tokenize`.
|
||||
struct CodeAnalyzerOptions {
|
||||
analyzer: Option<String>,
|
||||
split_identifiers: Option<bool>,
|
||||
split_on_numerics: Option<bool>,
|
||||
preserve_original: Option<bool>,
|
||||
index_operators: Option<bool>,
|
||||
}
|
||||
|
||||
impl CodeAnalyzerOptions {
|
||||
/// Check the options against the requested base tokenizer and return the
|
||||
/// base tokenizer to use, if any. `analyzer: "code"` selects the code
|
||||
/// tokenizer when `baseTokenizer` is unset or `"simple"`.
|
||||
fn resolve_base_tokenizer(
|
||||
&self,
|
||||
base_tokenizer: Option<String>,
|
||||
) -> napi::Result<Option<String>> {
|
||||
let uses_code = match self.analyzer.as_deref() {
|
||||
None | Some("text") => base_tokenizer.as_deref() == Some("code"),
|
||||
Some("code") => true,
|
||||
Some(other) => {
|
||||
return Err(napi::Error::from_reason(format!(
|
||||
"analyzer must be 'text' or 'code', got '{other}'"
|
||||
)));
|
||||
}
|
||||
};
|
||||
match (self.analyzer.as_deref(), base_tokenizer.as_deref()) {
|
||||
(Some("text"), Some("code")) => {
|
||||
return Err(napi::Error::from_reason(
|
||||
"baseTokenizer 'code' requires analyzer 'code'",
|
||||
));
|
||||
}
|
||||
(Some("code"), Some(tokenizer)) if tokenizer != "code" && tokenizer != "simple" => {
|
||||
return Err(napi::Error::from_reason(format!(
|
||||
"analyzer 'code' requires baseTokenizer 'code', got '{tokenizer}'"
|
||||
)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let flags = [
|
||||
self.split_identifiers,
|
||||
self.split_on_numerics,
|
||||
self.preserve_original,
|
||||
self.index_operators,
|
||||
];
|
||||
if !uses_code && flags.into_iter().flatten().any(|flag| flag) {
|
||||
return Err(napi::Error::from_reason(
|
||||
"splitIdentifiers, splitOnNumerics, preserveOriginal and indexOperators \
|
||||
require analyzer 'code'",
|
||||
));
|
||||
}
|
||||
Ok(if uses_code {
|
||||
Some("code".to_string())
|
||||
} else {
|
||||
base_tokenizer
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply the explicit flags on top of the tokenizer defaults.
|
||||
fn apply(&self, mut opts: FtsIndexBuilder) -> FtsIndexBuilder {
|
||||
if let Some(value) = self.split_identifiers {
|
||||
opts = opts.split_identifiers(value);
|
||||
}
|
||||
if let Some(value) = self.split_on_numerics {
|
||||
opts = opts.split_on_numerics(value);
|
||||
}
|
||||
if let Some(value) = self.preserve_original {
|
||||
opts = opts.preserve_original(value);
|
||||
}
|
||||
if let Some(value) = self.index_operators {
|
||||
opts = opts.index_operators(value);
|
||||
}
|
||||
opts
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
#[allow(dead_code, clippy::too_many_arguments)]
|
||||
pub fn tokenize(
|
||||
@@ -51,9 +127,21 @@ pub fn tokenize(
|
||||
ngram_min_length: Option<u32>,
|
||||
ngram_max_length: Option<u32>,
|
||||
prefix_only: Option<bool>,
|
||||
analyzer: Option<String>,
|
||||
split_identifiers: Option<bool>,
|
||||
split_on_numerics: Option<bool>,
|
||||
preserve_original: Option<bool>,
|
||||
index_operators: Option<bool>,
|
||||
) -> napi::Result<Vec<FtsToken>> {
|
||||
let mut opts = FtsIndexBuilder::default();
|
||||
if let Some(base_tokenizer) = base_tokenizer {
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
analyzer,
|
||||
split_identifiers,
|
||||
split_on_numerics,
|
||||
preserve_original,
|
||||
index_operators,
|
||||
};
|
||||
if let Some(base_tokenizer) = code_options.resolve_base_tokenizer(base_tokenizer)? {
|
||||
opts = opts.base_tokenizer(base_tokenizer);
|
||||
}
|
||||
if let Some(language) = language {
|
||||
@@ -89,6 +177,7 @@ pub fn tokenize(
|
||||
if let Some(prefix_only) = prefix_only {
|
||||
opts = opts.ngram_prefix_only(prefix_only);
|
||||
}
|
||||
opts = code_options.apply(opts);
|
||||
|
||||
Ok(lancedb_tokenize(&query, &opts)
|
||||
.default_error()?
|
||||
@@ -304,14 +393,27 @@ impl Index {
|
||||
ngram_max_length: Option<u32>,
|
||||
prefix_only: Option<bool>,
|
||||
block_size: Option<u32>,
|
||||
analyzer: Option<String>,
|
||||
split_identifiers: Option<bool>,
|
||||
split_on_numerics: Option<bool>,
|
||||
preserve_original: Option<bool>,
|
||||
index_operators: Option<bool>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut opts = FtsIndexBuilder::default();
|
||||
if let Some(with_position) = with_position {
|
||||
opts = opts.with_position(with_position);
|
||||
}
|
||||
if let Some(base_tokenizer) = base_tokenizer {
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
analyzer,
|
||||
split_identifiers,
|
||||
split_on_numerics,
|
||||
preserve_original,
|
||||
index_operators,
|
||||
};
|
||||
if let Some(base_tokenizer) = code_options.resolve_base_tokenizer(base_tokenizer)? {
|
||||
opts = opts.base_tokenizer(base_tokenizer);
|
||||
}
|
||||
opts = code_options.apply(opts);
|
||||
if let Some(language) = language {
|
||||
opts = opts.language(&language).map_err(|_| {
|
||||
napi::Error::from_reason(format!(
|
||||
|
||||
Reference in New Issue
Block a user