diff --git a/docs/src/js/interfaces/FtsOptions.md b/docs/src/js/interfaces/FtsOptions.md index 654fa138f..6248f8132 100644 --- a/docs/src/js/interfaces/FtsOptions.md +++ b/docs/src/js/interfaces/FtsOptions.md @@ -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 diff --git a/docs/src/js/interfaces/TokenizeOptions.md b/docs/src/js/interfaces/TokenizeOptions.md index 8ef15d03d..4f85186da 100644 --- a/docs/src/js/interfaces/TokenizeOptions.md +++ b/docs/src/js/interfaces/TokenizeOptions.md @@ -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 diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 2b245ff27..cf20dfbe8 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.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 & { 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; + 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", () => { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 3ea261e39..52acfdc9f 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -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, ); } diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index b4bdf1a9e..9410612d8 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -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, ), ); } diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index e1f888f78..80ac1eb86 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -36,6 +36,82 @@ impl Index { } } +/// Code-analyzer options shared by `Index.fts` and `tokenize`. +struct CodeAnalyzerOptions { + analyzer: Option, + split_identifiers: Option, + split_on_numerics: Option, + preserve_original: Option, + index_operators: Option, +} + +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, + ) -> napi::Result> { + 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, ngram_max_length: Option, prefix_only: Option, + analyzer: Option, + split_identifiers: Option, + split_on_numerics: Option, + preserve_original: Option, + index_operators: Option, ) -> napi::Result> { 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, prefix_only: Option, block_size: Option, + analyzer: Option, + split_identifiers: Option, + split_on_numerics: Option, + preserve_original: Option, + index_operators: Option, ) -> napi::Result { 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!(