Elffuss BraidHub

kikocis/lancedb public

feat: support to build FTS without positions (#1621)

Changesete67de45d10f7ad000b81d64698f415bb4a3bf4a01f836bac9b7f3a06d631b7d7
AuthorBubbleCal <bubble-cal@outlook.com> · 2024-09-10 22:51 +08:00
CommitterGitHub <noreply@github.com> · 2024-09-10 22:51 +08:00
Parents54c95f8a3bae

Browse the files at this changeset

11 files changed

modified docs/src/fts.md +2 −2
@@ -62,7 +62,7 @@
6262 });
6363
6464 await tbl
65- .search("puppy")
65+ .search("puppy", queryType="fts")
6666 .select(["text"])
6767 .limit(10)
6868 .toArray();
@@ -205,7 +205,7 @@
205205 ## Phrase queries vs. terms queries
206206
207207 !!! warning "Warn"
208- Phrase queries are available for only Tantivy-based FTS
208+ Lance-based FTS doesn't support queries combining by boolean operators `OR`, `AND`.
209209
210210 For full-text search you can specify either a **phrase** query like `"the old man and the sea"`,
211211 or a **terms** search query like `"(Old AND Man) AND Sea"`. For more details on the terms
modified nodejs/__test__/table.test.ts +32 −0
@@ -844,6 +844,38 @@
844844 expect(results[0].text).toBe(data[0].text);
845845 });
846846
847+ test("full text search without positions", async () => {
848+ const db = await connect(tmpDir.name);
849+ const data = [
850+ { text: "hello world", vector: [0.1, 0.2, 0.3] },
851+ { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
852+ ];
853+ const table = await db.createTable("test", data);
854+ await table.createIndex("text", {
855+ config: Index.fts({ withPositions: false }),
856+ });
857+
858+ const results = await table.search("hello").toArray();
859+ expect(results[0].text).toBe(data[0].text);
860+ });
861+
862+ test("full text search phrase query", async () => {
863+ const db = await connect(tmpDir.name);
864+ const data = [
865+ { text: "hello world", vector: [0.1, 0.2, 0.3] },
866+ { text: "goodbye world", vector: [0.4, 0.5, 0.6] },
867+ ];
868+ const table = await db.createTable("test", data);
869+ await table.createIndex("text", {
870+ config: Index.fts(),
871+ });
872+
873+ const results = await table.search("world").toArray();
874+ expect(results.length).toBe(2);
875+ const phraseResults = await table.search('"hello world"').toArray();
876+ expect(phraseResults.length).toBe(1);
877+ });
878+
847879 test.each([
848880 [0.4, 0.5, 0.599], // number[]
849881 Float32Array.of(0.4, 0.5, 0.599), // Float32Array
modified nodejs/lancedb/indices.ts +15 −2
@@ -113,6 +113,19 @@
113113 sampleRate?: number;
114114 }
115115
116+/**
117+ * Options to create a full text search index
118+ */
119+export interface FtsOptions {
120+ /**
121+ * Whether to build the index with positions.
122+ * True by default.
123+ * If set to false, the index will not store the positions of the tokens in the text,
124+ * which will make the index smaller and faster to build, but will not support phrase queries.
125+ */
126+ withPositions?: boolean;
127+}
128+
116129 export class Index {
117130 private readonly inner: LanceDbIndex;
118131 private constructor(inner: LanceDbIndex) {
@@ -211,8 +224,8 @@
211224 *
212225 * For now, the full text search index only supports English, and doesn't support phrase search.
213226 */
214- static fts() {
215- return new Index(LanceDbIndex.fts());
227+ static fts(options?: Partial<FtsOptions>) {
228+ return new Index(LanceDbIndex.fts(options?.withPositions));
216229 }
217230 }
218231
modified nodejs/src/index.rs +6 −2
@@ -92,9 +92,13 @@
9292 }
9393
9494 #[napi(factory)]
95- pub fn fts() -> Self {
95+ pub fn fts(with_position: Option<bool>) -> Self {
96+ let mut opts = FtsIndexBuilder::default();
97+ if let Some(with_position) = with_position {
98+ opts = opts.with_position(with_position);
99+ }
96100 Self {
97- inner: Mutex::new(Some(LanceDbIndex::FTS(FtsIndexBuilder::default()))),
101+ inner: Mutex::new(Some(LanceDbIndex::FTS(opts))),
98102 }
99103 }
100104 }
modified python/python/lancedb/index.py +2 −2
@@ -78,8 +78,8 @@
7878 For example, it works with `title`, `description`, `content`, etc.
7979 """
8080
81- def __init__(self):
82- self._inner = LanceDbIndex.fts()
81+ def __init__(self, with_position: bool = True):
82+ self._inner = LanceDbIndex.fts(with_position=with_position)
8383
8484
8585 class IvfPq:
modified python/python/lancedb/remote/table.py +1 −0
@@ -126,6 +126,7 @@
126126 column: str,
127127 *,
128128 replace: bool = False,
129+ with_position: bool = True,
129130 ):
130131 data = {
131132 "column": column,
modified python/python/lancedb/table.py +12 −1
@@ -468,6 +468,7 @@
468468 ordering_field_names: Union[str, List[str]] = None,
469469 *,
470470 replace: bool = False,
471+ with_position: bool = True,
471472 writer_heap_size: Optional[int] = 1024 * 1024 * 1024,
472473 tokenizer_name: str = "default",
473474 use_tantivy: bool = True,
@@ -500,6 +501,12 @@
500501 use_tantivy: bool, default True
501502 If True, use the legacy full-text search implementation based on tantivy.
502503 If False, use the new full-text search implementation based on lance-index.
504+ with_position: bool, default True
505+ Only available with use_tantivy=False
506+ If False, do not store the positions of the terms in the text.
507+ This can reduce the size of the index and improve indexing speed.
508+ But it will not be possible to use phrase queries.
509+
503510 """
504511 raise NotImplementedError
505512
@@ -1305,6 +1312,7 @@
13051312 ordering_field_names: Union[str, List[str]] = None,
13061313 *,
13071314 replace: bool = False,
1315+ with_position: bool = True,
13081316 writer_heap_size: Optional[int] = 1024 * 1024 * 1024,
13091317 tokenizer_name: str = "default",
13101318 use_tantivy: bool = True,
@@ -1318,7 +1326,10 @@
13181326 if exist:
13191327 fs.delete_dir(path)
13201328 self._dataset_mut.create_scalar_index(
1321- field_names, index_type="INVERTED", replace=replace
1329+ field_names,
1330+ index_type="INVERTED",
1331+ replace=replace,
1332+ with_position=with_position,
13221333 )
13231334 return
13241335
modified python/python/tests/test_fts.py +39 −2
@@ -140,8 +140,11 @@
140140
141141
142142 @pytest.mark.parametrize("use_tantivy", [True, False])
143-def test_create_inverted_index(table, use_tantivy):
144- table.create_fts_index("text", use_tantivy=use_tantivy)
143+@pytest.mark.parametrize("with_position", [True, False])
144+def test_create_inverted_index(table, use_tantivy, with_position):
145+ if use_tantivy and not with_position:
146+ pytest.skip("we don't support to build tantivy index without position")
147+ table.create_fts_index("text", use_tantivy=use_tantivy, with_position=with_position)
145148
146149
147150 def test_populate_index(tmp_path, table):
@@ -166,6 +169,40 @@
166169 assert len(results) == 5
167170
168171
172+def test_search_fts_phrase_query(table):
173+ table.create_fts_index("text", use_tantivy=False, with_position=False)
174+ try:
175+ phrase_results = table.search('"puppy runs"').limit(100).to_list()
176+ assert False
177+ except Exception:
178+ pass
179+ table.create_fts_index("text", use_tantivy=False, replace=True)
180+ results = table.search("puppy").limit(100).to_list()
181+ phrase_results = table.search('"puppy runs"').limit(100).to_list()
182+ assert len(results) > len(phrase_results)
183+ assert len(phrase_results) > 0
184+
185+
186+@pytest.mark.asyncio
187+async def test_search_fts_phrase_query_async(async_table):
188+ async_table = await async_table
189+ await async_table.create_index("text", config=FTS(with_position=False))
190+ try:
191+ phrase_results = (
192+ await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
193+ )
194+ assert False
195+ except Exception:
196+ pass
197+ await async_table.create_index("text", config=FTS())
198+ results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
199+ phrase_results = (
200+ await async_table.query().nearest_to_text('"puppy runs"').limit(100).to_list()
201+ )
202+ assert len(results) > len(phrase_results)
203+ assert len(phrase_results) > 0
204+
205+
169206 def test_search_fts_specify_column(table):
170207 table.create_fts_index("text", use_tantivy=False)
171208 table.create_fts_index("text2", use_tantivy=False)
modified python/src/index.rs +9 −4
@@ -14,6 +14,7 @@
1414
1515 use std::sync::Mutex;
1616
17+use lancedb::index::scalar::FtsIndexBuilder;
1718 use lancedb::{
1819 index::{scalar::BTreeIndexBuilder, vector::IvfPqIndexBuilder, Index as LanceDbIndex},
1920 DistanceType,
@@ -100,10 +101,14 @@
100101 }
101102
102103 #[staticmethod]
103- pub fn fts() -> PyResult<Self> {
104- Ok(Self {
105- inner: Mutex::new(Some(LanceDbIndex::FTS(Default::default()))),
106- })
104+ pub fn fts(with_position: Option<bool>) -> Self {
105+ let mut opts = FtsIndexBuilder::default();
106+ if let Some(with_position) = with_position {
107+ opts = opts.with_position(with_position);
108+ }
109+ Self {
110+ inner: Mutex::new(Some(LanceDbIndex::FTS(opts))),
111+ }
107112 }
108113 }
109114
modified rust/lancedb/src/index/scalar.rs +19 −3
@@ -51,9 +51,25 @@
5151 /// Builder for a full text search index
5252 ///
5353 /// A full text search index is an index on a string column that allows for full text search
54-#[derive(Debug, Clone, Default)]
55-pub struct FtsIndexBuilder {}
54+#[derive(Debug, Clone)]
55+pub struct FtsIndexBuilder {
56+ pub(crate) with_position: bool,
57+}
5658
57-impl FtsIndexBuilder {}
59+impl Default for FtsIndexBuilder {
60+ fn default() -> Self {
61+ Self {
62+ with_position: true,
63+ }
64+ }
65+}
66+
67+impl FtsIndexBuilder {
68+ /// Set the with_position flag
69+ pub fn with_position(mut self, with_position: bool) -> Self {
70+ self.with_position = with_position;
71+ self
72+ }
73+}
5874
5975 pub use lance_index::scalar::FullTextSearchQuery;
modified rust/lancedb/src/table.rs +13 −7
@@ -52,6 +52,7 @@
5252 use crate::connection::NoData;
5353 use crate::embeddings::{EmbeddingDefinition, EmbeddingRegistry, MaybeEmbedded, MemoryRegistry};
5454 use crate::error::{Error, Result};
55+use crate::index::scalar::FtsIndexBuilder;
5556 use crate::index::vector::{
5657 IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, VectorIndex,
5758 };
@@ -1609,7 +1610,12 @@
16091610 Ok(())
16101611 }
16111612
1612- async fn create_fts_index(&self, field: &Field, opts: IndexBuilder) -> Result<()> {
1613+ async fn create_fts_index(
1614+ &self,
1615+ field: &Field,
1616+ fts_opts: FtsIndexBuilder,
1617+ replace: bool,
1618+ ) -> Result<()> {
16131619 if !Self::supported_fts_data_type(field.data_type()) {
16141620 return Err(Error::Schema {
16151621 message: format!(
@@ -1621,16 +1627,16 @@
16211627 }
16221628
16231629 let mut dataset = self.dataset.get_mut().await?;
1624- let lance_idx_params = lance_index::scalar::ScalarIndexParams {
1625- force_index_type: Some(lance_index::scalar::ScalarIndexType::Inverted),
1630+ let fts_params = lance_index::scalar::InvertedIndexParams {
1631+ with_position: fts_opts.with_position,
16261632 };
16271633 dataset
16281634 .create_index(
16291635 &[field.name()],
1630- IndexType::Scalar,
1636+ IndexType::Inverted,
16311637 None,
1632- &lance_idx_params,
1633- opts.replace,
1638+ &fts_params,
1639+ replace,
16341640 )
16351641 .await?;
16361642 Ok(())
@@ -1802,7 +1808,7 @@
18021808 Index::BTree(_) => self.create_btree_index(field, opts).await,
18031809 Index::Bitmap(_) => self.create_bitmap_index(field, opts).await,
18041810 Index::LabelList(_) => self.create_label_list_index(field, opts).await,
1805- Index::FTS(_) => self.create_fts_index(field, opts).await,
1811+ Index::FTS(fts_opts) => self.create_fts_index(field, fts_opts, opts.replace).await,
18061812 Index::IvfPq(ivf_pq) => self.create_ivf_pq_index(ivf_pq, field, opts.replace).await,
18071813 Index::IvfHnswPq(ivf_hnsw_pq) => {
18081814 self.create_ivf_hnsw_pq_index(ivf_hnsw_pq, field, opts.replace)