Elffuss BraidHub

kikocis/lancedb public

main · 9.2 KiBRenderedRawPermalink
1# Full-text search
2
3LanceDB provides support for full-text search via Lance (before via [Tantivy](https://github.com/quickwit-oss/tantivy) (Python only)), allowing you to incorporate keyword-based search (based on BM25) in your retrieval solutions.
4
5Currently, the Lance full text search is missing some features that are in the Tantivy full text search. This includes query parser and customizing the tokenizer. Thus, in Python, Tantivy is still the default way to do full text search and many of the instructions below apply just to Tantivy-based indices.
6
7
8## Installation (Only for Tantivy-based FTS)
9
10!!! note
11 No need to install the tantivy dependency if using native FTS
12
13To use full-text search, install the dependency [`tantivy-py`](https://github.com/quickwit-oss/tantivy-py):
14
15```sh
16# Say you want to use tantivy==0.20.1
17pip install tantivy==0.20.1
18```
19
20## Example
21
22Consider that we have a LanceDB table named `my_table`, whose string column `text` we want to index and query via keyword search, the FTS index must be created before you can search via keywords.
23
24=== "Python"
25
26 ```python
27 import lancedb
28
29 uri = "data/sample-lancedb"
30 db = lancedb.connect(uri)
31
32 table = db.create_table(
33 "my_table",
34 data=[
35 {"vector": [3.1, 4.1], "text": "Frodo was a happy puppy"},
36 {"vector": [5.9, 26.5], "text": "There are several kittens playing"},
37 ],
38 )
39
40 # passing `use_tantivy=False` to use lance FTS index
41 # `use_tantivy=True` by default
42 table.create_fts_index("text")
43 table.search("puppy").limit(10).select(["text"]).to_list()
44 # [{'text': 'Frodo was a happy puppy', '_score': 0.6931471824645996}]
45 # ...
46 ```
47
48=== "TypeScript"
49
50 ```typescript
51 import * as lancedb from "@lancedb/lancedb";
52 const uri = "data/sample-lancedb"
53 const db = await lancedb.connect(uri);
54
55 const data = [
56 { vector: [3.1, 4.1], text: "Frodo was a happy puppy" },
57 { vector: [5.9, 26.5], text: "There are several kittens playing" },
58 ];
59 const tbl = await db.createTable("my_table", data, { mode: "overwrite" });
60 await tbl.createIndex("text", {
61 config: lancedb.Index.fts(),
62 });
63
64 await tbl
65 .search("puppy", queryType="fts")
66 .select(["text"])
67 .limit(10)
68 .toArray();
69 ```
70
71=== "Rust"
72
73 ```rust
74 let uri = "data/sample-lancedb";
75 let db = connect(uri).execute().await?;
76 let initial_data: Box<dyn RecordBatchReader + Send> = create_some_records()?;
77 let tbl = db
78 .create_table("my_table", initial_data)
79 .execute()
80 .await?;
81 tbl
82 .create_index(&["text"], Index::FTS(FtsIndexBuilder::default()))
83 .execute()
84 .await?;
85
86 tbl
87 .query()
88 .full_text_search(FullTextSearchQuery::new("puppy".to_owned()))
89 .select(lancedb::query::Select::Columns(vec!["text".to_owned()]))
90 .limit(10)
91 .execute()
92 .await?;
93 ```
94
95It would search on all indexed columns by default, so it's useful when there are multiple indexed columns.
96For now, this is supported in tantivy way only.
97
98Passing `fts_columns="text"` if you want to specify the columns to search, but it's not available for Tantivy-based full text search.
99
100!!! note
101 LanceDB automatically searches on the existing FTS index if the input to the search is of type `str`. If you provide a vector as input, LanceDB will search the ANN index instead.
102
103## Tokenization
104By default the text is tokenized by splitting on punctuation and whitespaces and then removing tokens that are longer than 40 chars. For more language specific tokenization then provide the argument tokenizer_name with the 2 letter language code followed by "_stem". So for english it would be "en_stem".
105
106For now, only the Tantivy-based FTS index supports to specify the tokenizer, so it's only available in Python with `use_tantivy=True`.
107
108=== "use_tantivy=True"
109
110 ```python
111 table.create_fts_index("text", use_tantivy=True, tokenizer_name="en_stem")
112 ```
113
114=== "use_tantivy=False"
115
116 [**Not supported yet**](https://github.com/lancedb/lance/issues/1195)
117
118the following [languages](https://docs.rs/tantivy/latest/tantivy/tokenizer/enum.Language.html) are currently supported.
119
120## Index multiple columns
121
122If you have multiple string columns to index, there's no need to combine them manually -- simply pass them all as a list to `create_fts_index`:
123
124=== "use_tantivy=True"
125
126 ```python
127 table.create_fts_index(["text1", "text2"])
128 ```
129
130=== "use_tantivy=False"
131
132 [**Not supported yet**](https://github.com/lancedb/lance/issues/1195)
133
134Note that the search API call does not change - you can search over all indexed columns at once.
135
136## Filtering
137
138Currently the LanceDB full text search feature supports *post-filtering*, meaning filters are
139applied on top of the full text search results. This can be invoked via the familiar
140`where` syntax:
141
142=== "Python"
143
144 ```python
145 table.search("puppy").limit(10).where("meta='foo'").to_list()
146 ```
147
148=== "TypeScript"
149
150 ```typescript
151 await tbl
152 .search("apple")
153 .select(["id", "doc"])
154 .limit(10)
155 .where("meta='foo'")
156 .toArray();
157 ```
158
159=== "Rust"
160
161 ```rust
162 table
163 .query()
164 .full_text_search(FullTextSearchQuery::new(words[0].to_owned()))
165 .select(lancedb::query::Select::Columns(vec!["doc".to_owned()]))
166 .limit(10)
167 .only_if("meta='foo'")
168 .execute()
169 .await?;
170 ```
171
172## Sorting
173
174!!! warning "Warn"
175 Sorting is available for only Tantivy-based FTS
176
177You can pre-sort the documents by specifying `ordering_field_names` when
178creating the full-text search index. Once pre-sorted, you can then specify
179`ordering_field_name` while searching to return results sorted by the given
180field. For example,
181
182```python
183table.create_fts_index(["text_field"], use_tantivy=True, ordering_field_names=["sort_by_field"])
184
185(table.search("terms", ordering_field_name="sort_by_field")
186 .limit(20)
187 .to_list())
188```
189
190!!! note
191 If you wish to specify an ordering field at query time, you must also
192 have specified it during indexing time. Otherwise at query time, an
193 error will be raised that looks like `ValueError: The field does not exist: xxx`
194
195!!! note
196 The fields to sort on must be of typed unsigned integer, or else you will see
197 an error during indexing that looks like
198 `TypeError: argument 'value': 'float' object cannot be interpreted as an integer`.
199
200!!! note
201 You can specify multiple fields for ordering at indexing time.
202 But at query time only one ordering field is supported.
203
204
205## Phrase queries vs. terms queries
206
207!!! warning "Warn"
208 Lance-based FTS doesn't support queries using boolean operators `OR`, `AND`.
209
210For full-text search you can specify either a **phrase** query like `"the old man and the sea"`,
211or a **terms** search query like `"(Old AND Man) AND Sea"`. For more details on the terms
212query syntax, see Tantivy's [query parser rules](https://docs.rs/tantivy/latest/tantivy/query/struct.QueryParser.html).
213
214!!! tip "Note"
215 The query parser will raise an exception on queries that are ambiguous. For example, in the query `they could have been dogs OR cats`, `OR` is capitalized so it's considered a keyword query operator. But it's ambiguous how the left part should be treated. So if you submit this search query as is, you'll get `Syntax Error: they could have been dogs OR cats`.
216
217 ```py
218 # This raises a syntax error
219 table.search("they could have been dogs OR cats")
220 ```
221
222 On the other hand, lowercasing `OR` to `or` will work, because there are no capitalized logical operators and
223 the query is treated as a phrase query.
224
225 ```py
226 # This works!
227 table.search("they could have been dogs or cats")
228 ```
229
230It can be cumbersome to have to remember what will cause a syntax error depending on the type of
231query you want to perform. To make this simpler, when you want to perform a phrase query, you can
232enforce it in one of two ways:
233
2341. Place the double-quoted query inside single quotes. For example, `table.search('"they could have been dogs OR cats"')` is treated as
235a phrase query.
2361. Explicitly declare the `phrase_query()` method. This is useful when you have a phrase query that
237itself contains double quotes. For example, `table.search('the cats OR dogs were not really "pets" at all').phrase_query()`
238is treated as a phrase query.
239
240In general, a query that's declared as a phrase query will be wrapped in double quotes during parsing, with nested
241double quotes replaced by single quotes.
242
243
244## Configurations (Only for Tantivy-based FTS)
245
246By default, LanceDB configures a 1GB heap size limit for creating the index. You can
247reduce this if running on a smaller node, or increase this for faster performance while
248indexing a larger corpus.
249
250```python
251# configure a 512MB heap size
252heap = 1024 * 1024 * 512
253table.create_fts_index(["text1", "text2"], writer_heap_size=heap, replace=True)
254```
255
256## Current limitations
257
258For that Tantivy-based FTS:
259
2601. Currently we do not yet support incremental writes.
261 If you add data after FTS index creation, it won't be reflected
262 in search results until you do a full reindex.
263
2642. We currently only support local filesystem paths for the FTS index.
265 This is a tantivy limitation. We've implemented an object store plugin
266 but there's no way in tantivy-py to specify to use it.