LanceDB Node.js 全文本搜索选项(FullTextSearchOptions)详解:columns 配置、FTS 索引与底层实现
LanceDB Node.js 全文本搜索选项(FullTextSearchOptions)详解:columns 配置、FTS 索引与底层实现
本篇技术指南围绕 @lancedb/lancedb 的全文本搜索选项 FullTextSearchOptions 展开,讲解如何在 LanceDB 表中为字符串列创建 FTS(Full Text Search)索引,并通过 columns 选项精确控制检索范围。读完本文,你将掌握 FTS 索引的完整配置参数(分词器、停用词、词干化、位置信息等)、全文本搜索的调用方式(含短语查询与混合检索),以及从 TypeScript 到 Rust 原生层的参数传递链路。
FullTextSearchOptions 接口概览
FullTextSearchOptions 是控制一次全文本搜索行为的选项接口,定义于 nodejs/lancedb/query.ts,对应官方接口文档 docs/src/js/interfaces/FullTextSearchOptions.md。该接口当前只声明了一个属性:
export interface FullTextSearchOptions {
/**
* The columns to search
*
* If not specified, all indexed columns will be searched.
* For now, only one column can be searched.
*/
columns?: string | string[];
}
- 类型:
string | string[](可选,即Partial<FullTextSearchOptions>可接受); - 语义:指定要搜索的列;
- 默认行为:不指定时搜索所有已建立索引的列;
- 当前限制:现阶段实际只支持搜索一列。
它被导出在包入口 nodejs/lancedb/index.ts 中,与 FullTextQuery、MatchQuery 等类型并列,供使用者直接 import:
import { FullTextSearchOptions, connect, Index } from "@lancedb/lancedb";
columns 属性的取值与语义
columns 接受单个字符串或字符串数组,两种写法等价:
// 单列写法
table.search("lancedb", {
queryType: "fts",
columns: "text",
});
// 数组写法(仅包含一列)
table.search("lancedb", {
queryType: "fts",
columns: ["text"],
});
在 fullTextSearch 方法实现 中可以看到,TypeScript 层会将字符串统一归一化为数组,再下传给原生层:
fullTextSearch(
query: string | FullTextQuery,
options?: Partial<FullTextSearchOptions>,
): this {
let columns: string[] | null = null;
if (options) {
if (typeof options.columns === "string") {
columns = [options.columns];
} else if (Array.isArray(options.columns)) {
columns = options.columns;
}
}
this.doCall((inner: NativeQueryType) => {
if (typeof query === "string") {
inner.fullTextSearch({ query: query, columns: columns });
} else {
inner.fullTextSearch({ query: query.inner });
}
});
return this;
}
两点值得注意:
- 列过滤发生在查询阶段:
columns只约束“搜哪些列”,并不要求这些列都有索引。若指定的列未建立 FTS 索引,查询会在原生层报错(见下文parse_fts_query中with_columns失败时的错误信息)。 - 多列与短语查询互斥:Rust 侧解析逻辑(nodejs/src/query.rs)明确判断,当查询文本以双引号包裹(短语查询)且
columns多于一个时会直接返回错误"Phrase queries cannot be used with multiple columns."。
前置条件:为字符串列创建 FTS 索引
全文本搜索必须基于 FTS 索引运行。LanceDB 通过 Index.fts() 创建索引,其入口在 nodejs/lancedb/indices.ts:
static fts(options?: Partial<FtsOptions>) {
return new Index(
LanceDbIndex.fts(
options?.withPosition,
options?.baseTokenizer,
options?.language,
options?.maxTokenLength,
options?.lowercase,
options?.stem,
options?.removeStopWords,
options?.customStopWords,
options?.asciiFolding,
options?.ngramMinLength,
options?.ngramMaxLength,
options?.prefixOnly,
options?.blockSize,
),
);
}
最小可用示例(来自仓库自测脚本 nodejs/test/fixtures/auto_fts_search.cjs):
const db = await connect(dir.name);
const table = await db.createTable("docs", [{ text: "hello world" }]);
await table.createIndex("text", { config: Index.fts() });
const rows = await table.search("hello").toArray();
assert.equal(rows[0].text, "hello world");
也可以为嵌套字段建索引,例如对 payload.text 这种深层字符串列(见 nodejs/test/table.test.ts 中的 Index.fts({ withPosition: false }) 用例)。
FTS 索引的完整配置项(FtsOptions)
Index.fts() 接受的 FtsOptions(定义见 nodejs/lancedb/indices.ts 与接口文档 docs/src/js/interfaces/FtsOptions.md)控制索引构建时的分词与压缩行为,全部为可选参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
withPosition |
boolean |
true |
是否在索引中保存 token 位置。设为 false 可缩小索引体积、加快构建,但将不再支持短语查询 |
baseTokenizer |
BaseTokenizer |
"simple" |
建索引用的分词器,见下表 |
language |
string |
未设置 | 词干化(stemming)与停用词所用语言;仅在 stem 或 removeStopWords 为 true 时生效 |
maxTokenLength |
number |
未设置 | 最大 token 长度,超过该长度的 token 会被忽略 |
lowercase |
boolean |
未设置 | 是否将 token 转为小写 |
stem |
boolean |
未设置 | 是否对 token 做词干化(还原词形,如 running → run) |
removeStopWords |
boolean |
未设置 | 是否移除停用词 |
customStopWords |
string[] |
未设置 | 自定义停用词,替换 language 的内置停用词表。undefined 保留内置词表;空数组 [] 表示显式去掉全部停用词。仅在 removeStopWords 为 true 时生效 |
asciiFolding |
boolean |
未设置 | 是否移除标点/进行 ASCII 折叠(将重音字符归一化为基础拉丁字母) |
ngramMinLength |
number |
未设置 | ngram 最小长度(配合 ngram 分词器使用) |
ngramMaxLength |
number |
未设置 | ngram 最大长度 |
prefixOnly |
boolean |
未设置 | ngram 分词器是否只索引 token 前缀 |
blockSize |
128 | 256 |
128 |
每个压缩 posting 块包含的文档数。设为 256 会启用实验性 FTS V3 格式,可能带来破坏性变更 |
分词器(baseTokenizer)类型
BaseTokenizer 类型(nodejs/lancedb/indices.ts)目前包括以下取值:
"simple":默认分词器,以空白和标点作为分隔符切分文本;"whitespace":仅以空白作为分隔符切分文本;"raw":不做切分,将整个文本当作单个 token 索引;"icu":基于 ICU 词典的词语切分(适合中文等无空格语言);"icu/split":ICU 切分 + simple 风格的分隔符切分;ngram:n-gram 分词,配合ngramMinLength/ngramMaxLength/prefixOnly使用;jieba/${string}:基于 jieba 的分词(中文场景);lindera/${string}:基于 lindera 的分词(日文等场景)。
远程表场景下,这些选项会原样序列化到 HTTP 请求体中。仓库测试 nodejs/test/remote.test.ts 验证了 blockSize: 256、removeStopWords: true、customStopWords: ["the"] 会被编码为 block_size、custom_stop_words 等字段发送给服务端。
发起全文本搜索的三种方式
方式一:table.search(query, "fts")
最直接的入口,search 的第二个参数指定查询类型:
const results = await table
.search("common", "fts")
.select(["id"])
.limit(4)
.toArray();
该方式返回 AutoQuery 实例(见 docs/src/js/classes/AutoQuery.md),其行为在 nodejs/test/query.test.ts 中有大量覆盖,例如 FTS 结果的 schema 返回、limit 与 offset 的分页语义(先应用 FTS 的 limit,再做 offset 偏移)等。
方式二:table.query().fullTextSearch(query, options)
链式构建查询,options 即本文主角 Partial<FullTextSearchOptions>:
const rows = await table
.query()
.fullTextSearch("hello", { columns: "text" })
.limit(10)
.toArray();
方式三:混合检索(向量 + 全文 + 重排序)
将全文本搜索与向量最近邻检索结合,再用 Reranker 融合结果。仓库示例见 nodejs/test/rerankers.test.ts:
const result = await table
.query()
.nearestTo([0.1, 0.1])
.fullTextSearch("dog")
.rerank(await RRFReranker.create())
.select(["text"])
.limit(5)
.toArray();
其中 RRFReranker 来自 @lancedb/lancedb 的 rerankers 命名空间(nodejs/lancedb/rerankers/rrf.ts),可选用内置 RRF 或自定义 Reranker。
底层实现:columns 如何传递到原生层
FullTextSearchOptions.columns 的传递链分两层:
- TypeScript 层(nodejs/lancedb/query.ts):将
string归一化为string[],构造{ query, columns }对象调用 napi 方法; - Rust 层(nodejs/src/query.rs):
parse_fts_query从对象中读取query与columns字段:
let mut query_text = query_text;
let columns = query.get::<Option<Vec<String>>>("columns")?.flatten();
let is_phrase =
query_text.len() >= 2 && query_text.starts_with('"') && query_text.ends_with('"');
let is_multi_match = columns.as_ref().map(|cols| cols.len() > 1).unwrap_or(false);
if is_phrase {
query_text = query_text[1..query_text.len() - 1].to_string();
}
let query: FtsQuery = match (is_phrase, is_multi_match) {
(false, _) => MatchQuery::new(query_text).into(),
(true, false) => PhraseQuery::new(query_text).into(),
(true, true) => {
return Err(napi::Error::from_reason(
"Phrase queries cannot be used with multiple columns.",
));
}
};
let mut query = FullTextSearchQuery::new_query(query);
if let Some(cols) = columns
&& !cols.is_empty()
{
query = query.with_columns(&cols).map_err(|e| {
napi::Error::from_reason(format!("Failed to set full text search columns: {}", e))
})?;
}
从这段代码可以推断出几个关键行为:
- 字符串查询的自动识别:双引号包裹的文本会被识别为
PhraseQuery(短语查询),其余为MatchQuery;短语查询不支持多列,会直接报错; - 列过滤用
with_columns:当columns非空时通过with_columns限定搜索列,若列名非法或未索引则抛出"Failed to set full text search columns"错误; - 全文结果按 BM25 相关性排序:在 Index.fts 的文档注释 中明确说明,全文本搜索结果按 BM25 相关性打分排序,且可与过滤器(
where)组合使用。
进阶:使用 FullTextQuery 对象构造复杂查询
当查询需求超出纯字符串时,可传入 FullTextQuery 接口(docs/src/js/interfaces/FullTextQuery.md)。仓库内置了多种查询类(见 docs/src/js/classes 下的 MatchQuery、PhraseQuery、BooleanQuery、MultiMatchQuery、BoostQuery),例如 MatchQuery(nodejs/lancedb/query.ts)支持模糊匹配、boost 权重与操作符组合:
new MatchQuery("dog", "text", {
boost: 1.5,
fuzziness: 1,
maxExpansions: 50,
operator: Operator.Or,
prefixLength: 0,
});
此时 FullTextSearchOptions.columns 不再生效——从 fullTextSearch 实现 可以看到,传入 FullTextQuery 对象时只下发 { query: query.inner },列信息由查询对象自身的构造参数(如 MatchQuery 的 column)携带。
限制与最佳实践小结
- 列限制:现阶段一次全文本搜索只能搜一列;不传
columns则搜索所有已索引列; - 短语查询:依赖
withPosition: true构建的索引(默认开启);若建索引时关闭位置信息,短语查询将不可用; - 多列 + 短语互斥:带双引号的短语查询配合多个列会报错;
- 建索引与查询分离:索引配置(
FtsOptions)在建索引时一次性确定分词、停用词、压缩等行为,而查询选项(FullTextSearchOptions)只控制本次搜索的列范围,两者职责不同,配置索引时应前瞻性地为后续查询形态(如短语、模糊、多语言)留好余地; - 推荐实践:查询时配合
.select([...])只取需要的列以降低 I/O 延迟(LanceDB 列式存储可按列精确裁剪),并用.limit()/.offset()控制分页。