Run a complete full-text search example
Run a complete full-text search example
Each example creates a temporary local table, runs the query and removes the
table when finished. No embedding model is needed for a text query.Each example searches the indexed
- Python: Install with
pip install lancedb, save astext_search.py, then runpython text_search.py. - TypeScript: Install with
npm install @lancedb/lancedb, save astext_search.mts, then runnode text_search.mtswith Node.js 22.18 or later. - Rust: Download and extract the complete Rust examples, then run
cargo run --locked --bin text_searchfrom the extracted directory.
text column and returns the puppy record.
Higher _score values rank first; they are relevance scores, not probabilities.Basic usage
The steps below create a table, index itstext column and search for a word.
For a standalone program with imports and sample data, expand the complete
example above.
Create the sample table
First, open or create the table you want to search:Build the text index
Create a full-text search index on your text column: For asynchronous Python index creation, useawait table.create_index("text", config=FTS()). See FTS index.
table.wait_for_index(["text_idx"])
or TypeScript’s await tbl.waitForIndex(["text_idx"], 300) before querying it.
Use your actual index name if you chose a different one.
Run the query
Perform full-text search and retrieve results:fts_columns="text" in synchronous Python,
especially when the table contains multiple text indexes.
A string query can also invoke an embedding function when the table has
embedding metadata. Use
query_type="fts" in Python when you specifically
want full-text search.fts_columns or the query builder’s nearest_to_text(..., columns=...); in TypeScript, use query().nearestToText(..., columns). The newer Lance-native FTS does not accept legacy Tantivy-only index parameters.
BM25 scores depend on the indexed corpus and its term statistics. Compare
rankings on the dataset you will search; treat scores as relative relevance
values rather than probabilities.
Keeping the index up to date
In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. Search includes those rows by scanning them, but that work can increase query latency. Calloptimize() to update the index:
table.index_stats(...) and optimize when the
unindexed data adds too much work. .fast_search() skips unindexed rows, so
use it only when omitting recent records is acceptable.
Enterprise manages index updates automatically. You do not call optimize()
on an Enterprise table.
Choose the matching behavior
Use a metadata predicate to restrict qualifying records. See
filtering options for prefiltering and postfiltering.
Enterprise SQL provides
fts() for scored text retrieval.
Configure tokenization and matching
Tokenize Table Data
The default tokenizer splits text at whitespace and punctuation, lowercases tokens and removes tokens longer than 40 characters. Stemming, stop-word removal and accent folding are also enabled by default. Stemming is useful for improving search results by reducing words to their root form, e.g. “running” to “run”. LanceDB supports stemming for Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. You should set thebase_tokenizer parameter rather than tokenizer_name because you cannot customize the tokenizer if tokenizer_name is specified.
Tokenization and language filters are separate settings. base_tokenizer controls how text is split into searchable tokens. language controls stemming and stop-word removal when stem=True or remove_stop_words=True; choose the tokenizer for CJK or mixed-language segmentation.
For example, to enable stemming for English:
base_tokenizer:"simple"language: Englishwith_position: falsemax_token_length: 40lower_case: truestem: trueremove_stop_words: trueascii_folding: truecustom_stop_words:None; pass alist[str]to drop additional words beyond the language defaults. Requiresremove_stop_words=True.
base_tokenizer="icu" for unicode-aware word segmentation on mixed-language text. ICU stands for International Components for Unicode. The ICU tokenizer uses bundled ICU4X segmenter data, so it does not require external tokenizer model files. It is a good default when documents mix languages or include scripts where the simple tokenizer would keep an unspaced span as one large token.
The Python API also supports tokenizer implementations that load language model files. Use base_tokenizer="jieba/default" for Jieba tokenization, which segments Chinese text into searchable word tokens when the text is written without spaces between words. Use Lindera-backed tokenizers for dictionary-based East Asian morphological segmentation, such as base_tokenizer="lindera/ipadic" for Japanese or base_tokenizer="lindera/ko-dic" for Korean when you have installed and compiled that Lindera model. These are language-specific tokenizers; ICU is the broader mixed-language option.
lance/language_models, or you can set LANCE_LANGUAGE_MODEL_HOME to point to a different model root:
jieba/default is resolved under <model-home>/jieba/default/..., lindera/ipadic under <model-home>/lindera/ipadic/..., and lindera/ko-dic under <model-home>/lindera/ko-dic/....
Model files must be installed where indexing and queries run: on your machine
for LanceDB Embedded, or on the Enterprise cluster for an Enterprise table.
Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. If you use another stemming language, such as Arabic, Greek, Romanian, Tamil, or Turkish, set
remove_stop_words=False or pass custom_stop_words.ascii_folding=True to match accented and unaccented forms, such as
“é” and “e”:
Filtering Options
Usewhere(...) to restrict text results to rows that match a predicate.
Prefiltering applies the restriction before retrieval; postfiltering removes
nonmatching candidates afterward and can leave fewer results.
With pre-filtering:
Phrase vs. Terms Queries
For full-text search you can specify either a phrase query like"the old man and the sea",
or a terms search query like old man sea.
Enable token positions to search for phrases. Set remove_stop_words=False if you also need to match common words such as “the” and “and”:
Fuzzy Search
Fuzzy search allows you to find matches even when the search terms contain typos or slight variations. LanceDB uses the classic Levenshtein distance to find similar terms within a specified edit distance.
For a complete walkthrough that creates a sample table and demonstrates fuzzy search and relevance boosting, see the worked example below.
Search for Substring
LanceDB supports searching for substrings in the text column, you can set thebase_tokenizer parameter to "ngram" to enable this feature, and use the parameters ngram_min_length and ngram_max_length to control the length of the substrings:
Expected performance at scale
Enterprise At 1 billion rows, LanceDB Enterprise reaches p50 62 ms and p99 274 ms on fully cached data with no custom tuning — a representative floor to plan around, not a ceiling. Measured under a mixed workload of phrase, match-any and match-all queries, with an ICU-tokenized FTS v3 index (positions and lowercasing enabled, stemming disabled). The exact numbers depend on your deployment’s shape (cluster size, storage class, dataset); for higher performance, talk to the sales team.Fuzzy Search and Boosting Example
Worked examples: fuzzy, phrase, boosted and Boolean queries
Worked examples: fuzzy, phrase, boosted and Boolean queries
Generate Data
Run the following steps in order. They use a temporary local database with four records, so the same data is available for each query.Create Table
Construct the index for these examples
Create a full-text search index on the first text column:Basic and Fuzzy Search
Now we can perform basic, fuzzy, and prefix match searches:Basic Exact Search
Fuzzy Search with Typos
Require an exact prefix in fuzzy matching
prefix_length keeps the first characters unchanged when matching a misspelled term. It does not turn a short query into a prefix-completion search.Phrase Match
Phrase matching enables you to search for exact sequences of words. Unlike regular text search which matches individual terms independently, phrase matching requires words to appear in the specified order with no intervening terms.Phrase queries are supported but only for a single column; providing multiple columns with a quoted phrase raises an error.
- Searching for specific multi-word expressions
- Matching exact titles or quotes
- Finding precise word combinations in a specific order
Flexible Phrase Match
To provide more flexible phrase matching, LanceDB supports theslop parameter. This allows you to match phrases where the terms appear close to each other, with gaps between them. The slop value limits the extra positions allowed in the phrase.For example, the phrase query “puppy merrily” would not return any results by default. However, if you set slop=1, it will match phrases like “puppy jumps merrily”, “puppy runs merrily”, and similar variations where one word appears between “puppy” and “merrily”.Search with Boosting
Boosting allows you to control the relative importance of different search terms or fields in your queries. This feature is particularly useful when you need to:- Prioritize matches in certain columns
- Promote specific terms while demoting others
- Fine-tune relevance scoring for better search results
Search Columns as One Field
CombinedFieldsQuery is not available in Python 0.41.0. This example uses the
0.42.0b8 client. MultiMatchQuery
is available in 0.41.0, but does not have the same cross-field AND semantics.MultiMatchQuery scores each column on its own and keeps the best match.
CombinedFieldsQuery treats the columns as one field (BM25F), so with the AND
operator a row matches when every term appears in at least one of the columns.
The query below finds car in text and merrily in text2, returning rows 1
and 3. The same query with MultiMatchQuery returns no rows, because neither
column contains both words on its own.Every column must use the same tokenizer configuration. The two indexes in this
example are built with the same FTS settings. Boosts work as they do for
MultiMatchQuery: one weight per column, each at least 1.CombinedFieldsQuery convenience class and this example are specific
to the Python SDK. Rust applications can construct the core query type exposed
by lancedb::index::scalar. TypeScript and Java do not yet provide typed
convenience entry points for this query.Boolean Queries
LanceDB supports boolean logic in full-text search, allowing you to combine multiple queries usingand and or operators. This is useful when you want to match documents that satisfy multiple conditions (intersection) or at least one of several conditions (union).Combining Two Match Queries
In Python, combine twoMatchQuery objects with & for intersection or | for union. Python’s and and or operators return one operand and do not construct a boolean query.Python
[Occur, subquery] pairs to BooleanQuery. Use Must for required matches, Should for alternatives, and MustNot to exclude matches.Which queries are allowed?A boolean query must include at least one
SHOULD or MUST clause. Queries that contain only a MUST_NOT clause are not allowed.How to use booleans?
- Use
&(Python),Occur.Must(TypeScript) for intersection (documents must match all queries). - Use
|(Python),Occur.Should(TypeScript) for union (documents must match at least one query).
Clean up the example
Remove the temporary database when you have finished running the queries.Substring Search Example
Worked examples: substring search
Worked examples: substring search
LanceDB supports searching for substrings in text columns using n-gram tokenization. This is useful for finding partial matches within text content.
Setting Up the Table
First, create a table with sample text data and configure n-gram tokenization:Basic Substring Search
With the default n-gram settings (minimum length of 3), you can search for substrings of length 3 or more:Handling Short Substrings
By default, the minimum n-gram length is 3, so shorter substrings like “la” won’t match:Customizing N-gram Parameters
You can customize the n-gram behavior by adjusting the minimum length and using prefix-only matching:Testing Custom N-gram Settings
With the new settings, you can now search for shorter substrings and use prefix-only matching:Full-Text Search on Array Fields
Worked examples: searching string arrays
Worked examples: searching string arrays
LanceDB supports full-text search on string array columns, enabling efficient keyword-based search across multiple values within a single field (e.g., tags, keywords).A string-array query can return a row more than once when several elements match.
Deduplicate by your record ID if your application needs one result per row.