-
Notifications
You must be signed in to change notification settings - Fork 638
feat: inverted index for contains_tokens #4489
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
westonpace
merged 5 commits into
lance-format:main
from
wojiaodoubao:contains_tokens_use_index
Aug 28, 2025
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,6 +13,8 @@ use std::{ | |
| ops::Range, | ||
| }; | ||
|
|
||
| use crate::metrics::NoOpMetricsCollector; | ||
| use crate::prefilter::NoFilter; | ||
| use arrow::{ | ||
| array::LargeBinaryBuilder, | ||
| datatypes::{self, Float32Type, Int32Type, UInt64Type}, | ||
|
|
@@ -33,10 +35,11 @@ use datafusion::physical_plan::stream::RecordBatchStreamAdapter; | |
| use datafusion_common::DataFusionError; | ||
| use deepsize::DeepSizeOf; | ||
| use fst::{Automaton, IntoStreamer, Streamer}; | ||
| use futures::{stream, StreamExt, TryStreamExt}; | ||
| use futures::{stream, FutureExt, StreamExt, TryStreamExt}; | ||
| use itertools::Itertools; | ||
| use lance_arrow::{iter_str_array, RecordBatchExt}; | ||
| use lance_core::cache::{CacheKey, LanceCache}; | ||
| use lance_core::utils::mask::RowIdTreeMap; | ||
| use lance_core::utils::{ | ||
| mask::RowIdMask, | ||
| tracing::{IO_TYPE_LOAD_SCALAR_PART, TRACE_IO_EVENTS}, | ||
|
|
@@ -46,6 +49,7 @@ use lance_core::{Error, Result, ROW_ID, ROW_ID_FIELD}; | |
| use roaring::RoaringBitmap; | ||
| use snafu::location; | ||
| use std::sync::LazyLock; | ||
| use tantivy::tokenizer::Language; | ||
| use tracing::{info, instrument}; | ||
|
|
||
| use super::{ | ||
|
|
@@ -69,7 +73,7 @@ use super::{ | |
| use super::{wand::*, InvertedIndexBuilder, InvertedIndexParams}; | ||
| use crate::frag_reuse::FragReuseIndex; | ||
| use crate::scalar::{ | ||
| AnyQuery, IndexReader, IndexStore, MetricsCollector, SargableQuery, ScalarIndex, SearchResult, | ||
| AnyQuery, IndexReader, IndexStore, MetricsCollector, ScalarIndex, SearchResult, TokenQuery, | ||
| }; | ||
| use crate::Index; | ||
| use crate::{prefilter::PreFilter, scalar::inverted::iter::take_fst_keys}; | ||
|
|
@@ -94,6 +98,8 @@ pub static SCORE_FIELD: LazyLock<Field> = | |
| LazyLock::new(|| Field::new(SCORE_COL, DataType::Float32, true)); | ||
| pub static FTS_SCHEMA: LazyLock<SchemaRef> = | ||
| LazyLock::new(|| Arc::new(Schema::new(vec![ROW_ID_FIELD.clone(), SCORE_FIELD.clone()]))); | ||
| static ROW_ID_SCHEMA: LazyLock<SchemaRef> = | ||
| LazyLock::new(|| Arc::new(Schema::new(vec![ROW_ID_FIELD.clone()]))); | ||
|
|
||
| #[derive(Clone)] | ||
| pub struct InvertedIndex { | ||
|
|
@@ -320,6 +326,43 @@ impl Index for InvertedIndex { | |
| } | ||
| } | ||
|
|
||
| impl InvertedIndex { | ||
| /// Whether the query can use the current index. | ||
| pub fn is_query_allowed(&self, query: &TokenQuery) -> bool { | ||
| match query { | ||
| TokenQuery::TokensContains(_) => { | ||
| self.params.base_tokenizer == "simple" | ||
| && self.params.max_token_length.is_none() | ||
| && self.params.language == Language::English | ||
| && !self.params.stem | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Search docs match the input text. | ||
| async fn do_search(&self, text: &str) -> Result<RecordBatch> { | ||
| let params = FtsSearchParams::new(); | ||
| let mut tokenizer = self.tokenizer.clone(); | ||
| let tokens = collect_tokens(text, &mut tokenizer, None); | ||
|
|
||
| let (doc_ids, _) = self | ||
| .bm25_search( | ||
| tokens.into(), | ||
| params.into(), | ||
| Operator::And, | ||
| Arc::new(NoFilter), | ||
| Arc::new(NoOpMetricsCollector), | ||
| ) | ||
| .boxed() | ||
| .await?; | ||
|
|
||
| Ok(RecordBatch::try_new( | ||
| ROW_ID_SCHEMA.clone(), | ||
| vec![Arc::new(UInt64Array::from(doc_ids))], | ||
| )?) | ||
| } | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl ScalarIndex for InvertedIndex { | ||
| // return the row ids of the documents that contain the query | ||
|
|
@@ -329,11 +372,20 @@ impl ScalarIndex for InvertedIndex { | |
| query: &dyn AnyQuery, | ||
| _metrics: &dyn MetricsCollector, | ||
| ) -> Result<SearchResult> { | ||
| let query = query.as_any().downcast_ref::<SargableQuery>().unwrap(); | ||
| return Err(Error::invalid_input( | ||
| format!("unsupported query {:?} for inverted index", query), | ||
| location!(), | ||
| )); | ||
| let query = query.as_any().downcast_ref::<TokenQuery>().unwrap(); | ||
|
|
||
| match query { | ||
| TokenQuery::TokensContains(text) => { | ||
| let records = self.do_search(text).await?; | ||
| let row_ids = records | ||
| .column(0) | ||
| .as_any() | ||
| .downcast_ref::<UInt64Array>() | ||
| .unwrap(); | ||
| let row_ids = row_ids.iter().flatten().collect_vec(); | ||
| Ok(SearchResult::AtMost(RowIdTreeMap::from_iter(row_ids))) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. prob we can do this better in the future, if the tokenizer wouldn't change the original texts, we can return |
||
| } | ||
| } | ||
| } | ||
|
|
||
| fn can_remap(&self) -> bool { | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There might be a few pieces of glue missing. I think we need a
TokenQueryParser(see https://github.com/lancedb/lance/blob/60711f360b7f8692df44a0e84c98c8fdff2897a3/rust/lance-index/src/scalar/expression.rs#L348 for theTextQueryParser).We also need to register the token query parser here: https://github.com/lancedb/lance/blob/60711f360b7f8692df44a0e84c98c8fdff2897a3/rust/lance/src/index.rs#L1361
Can we call
is_query_allowedin the registration function (scalar_index_info)? This way we can skip the scalar index entirely if it is not eligible. ReturningAtLeastwith zero rows might lead to bad performance (the planner will think we are doing a scalar index optimized search and make certain decisions based on that)Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We already have a FtsQueryParser which parses
contains_tokensinto TokenQuery::TokensContains. Actually you implemented it (^-^). Shall we can just rely on FtsQueryParser?Thanks your nice suggestion, let me fix it.