Skip to main content

mito2/sst/index/fulltext_index/
creator.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::sync::Arc;
17use std::sync::atomic::AtomicUsize;
18
19use api::v1::SemanticType;
20use arrow_schema::extension::ExtensionType;
21use common_telemetry::warn;
22use datatypes::arrow::array::{Array, LargeStringArray, StringArray};
23use datatypes::arrow::datatypes::DataType;
24use datatypes::arrow::record_batch::RecordBatch;
25use datatypes::extension::json::Json2ExtensionType;
26use datatypes::schema::{FulltextAnalyzer, FulltextBackend};
27use datatypes::vectors::VectorRef;
28use index::fulltext_index::create::{
29    BloomFilterFulltextIndexCreator, FulltextIndexCreator, TantivyFulltextIndexCreator,
30};
31use index::fulltext_index::{Analyzer, Config};
32use index::target::IndexTarget;
33use puffin::blob_metadata::CompressionCodec;
34use puffin::puffin_manager::PutOptions;
35use snafu::{OptionExt, ResultExt, ensure};
36use store_api::metadata::RegionMetadataRef;
37use store_api::storage::{ConcreteDataType, FileId, RegionId};
38
39use crate::error::{
40    CastVectorSnafu, ComputeArrowSnafu, CreateFulltextCreatorSnafu, DataTypeMismatchSnafu,
41    FulltextFinishSnafu, FulltextPushTextSnafu, IndexOptionsSnafu, InvalidRecordBatchSnafu,
42    OperateAbortedIndexSnafu, Result,
43};
44use crate::read::Batch;
45use crate::sst::index::column::extract_json_type_hint_values;
46use crate::sst::index::fulltext_index::{INDEX_BLOB_TYPE_BLOOM, INDEX_BLOB_TYPE_TANTIVY};
47use crate::sst::index::intermediate::{
48    IntermediateLocation, IntermediateManager, TempFileProvider,
49};
50use crate::sst::index::puffin_manager::SstPuffinWriter;
51use crate::sst::index::statistics::{ByteCount, RowCount, Statistics};
52use crate::sst::index::{IndexBuildType, TYPE_FULLTEXT_INDEX};
53
54/// Resolved column identity, name, target and options retained by a build plan.
55pub(crate) type FulltextTarget = (
56    store_api::storage::ColumnId,
57    String,
58    IndexTarget,
59    datatypes::schema::FulltextOptions,
60);
61
62/// `FulltextIndexer` is responsible for creating fulltext indexes for SST files.
63pub struct FulltextIndexer {
64    /// Creators for each column.
65    creators: HashMap<IndexTarget, SingleCreator>,
66    /// Whether the index creation was aborted.
67    aborted: bool,
68    /// Statistics of index creation.
69    stats: Statistics,
70}
71
72impl FulltextIndexer {
73    /// Creates a new `FulltextIndexer`.
74    #[cfg(test)]
75    pub async fn new(
76        region_id: &RegionId,
77        sst_file_id: &FileId,
78        intermediate_manager: &IntermediateManager,
79        metadata: &RegionMetadataRef,
80        compress: bool,
81        mem_limit: usize,
82        build_type: IndexBuildType,
83    ) -> Result<Option<Self>> {
84        let mut targets = Vec::new();
85        for column in &metadata.column_metadatas {
86            for (target, options) in Self::targets(column, &build_type)? {
87                targets.push((
88                    column.column_id,
89                    column.column_schema.name.clone(),
90                    target,
91                    options,
92                ));
93            }
94        }
95        Self::new_with_targets(
96            region_id,
97            sst_file_id,
98            intermediate_manager,
99            metadata,
100            compress,
101            mem_limit,
102            targets,
103        )
104        .await
105    }
106
107    /// Creates one file-level creator from already resolved targets.
108    pub(crate) async fn new_with_targets(
109        region_id: &RegionId,
110        sst_file_id: &FileId,
111        intermediate_manager: &IntermediateManager,
112        metadata: &RegionMetadataRef,
113        compress: bool,
114        mem_limit: usize,
115        targets: Vec<FulltextTarget>,
116    ) -> Result<Option<Self>> {
117        let mut creators = HashMap::new();
118        let global_memory_usage = Arc::new(AtomicUsize::new(0));
119
120        for (column_id, column_name, target, options) in targets {
121            // fulltext_path generates a fresh UUID for each target, so JSON paths
122            // in the same column use separate intermediate directories.
123            let intm_path = intermediate_manager.fulltext_path(region_id, sst_file_id, column_id);
124
125            let config = Config {
126                analyzer: match options.analyzer {
127                    FulltextAnalyzer::English => Analyzer::English,
128                    FulltextAnalyzer::Chinese => Analyzer::Chinese,
129                },
130                case_sensitive: options.case_sensitive,
131            };
132
133            let inner = match options.backend {
134                FulltextBackend::Tantivy => {
135                    let creator = TantivyFulltextIndexCreator::new(&intm_path, config, mem_limit)
136                        .await
137                        .context(CreateFulltextCreatorSnafu)?;
138                    AltFulltextCreator::Tantivy(creator)
139                }
140                FulltextBackend::Bloom => {
141                    let temp_file_provider = Arc::new(TempFileProvider::new(
142                        IntermediateLocation::new(&metadata.region_id, sst_file_id),
143                        intermediate_manager.clone(),
144                    ));
145                    let creator = BloomFilterFulltextIndexCreator::new(
146                        config,
147                        options.granularity as _,
148                        options.false_positive_rate(),
149                        temp_file_provider,
150                        global_memory_usage.clone(),
151                        Some(mem_limit),
152                    );
153                    AltFulltextCreator::Bloom(creator)
154                }
155            };
156
157            creators.insert(
158                target.clone(),
159                SingleCreator {
160                    target,
161                    column_name,
162                    inner,
163                    compress,
164                },
165            );
166        }
167        Ok((!creators.is_empty()).then(move || Self {
168            creators,
169            aborted: false,
170            stats: Statistics::new(TYPE_FULLTEXT_INDEX),
171        }))
172    }
173
174    /// Resolves all targets of one column without creating index state.
175    pub(crate) fn targets(
176        column: &store_api::metadata::ColumnMetadata,
177        build_type: &IndexBuildType,
178    ) -> Result<Vec<(IndexTarget, datatypes::schema::FulltextOptions)>> {
179        // Tag columns don't support fulltext index now.
180        // If we need to support fulltext index for tag columns, we also need to parse
181        // the codec and handle sparse encoding for flat format specially.
182        if column.semantic_type == SemanticType::Tag {
183            common_telemetry::debug!(
184                "Skip creating fulltext index for tag column {}",
185                column.column_schema.name
186            );
187            return Ok(Vec::new());
188        }
189
190        let options = column
191            .column_schema
192            .fulltext_options()
193            .context(IndexOptionsSnafu {
194                column_name: &column.column_schema.name,
195            })?;
196
197        let mut targets = Vec::new();
198        if let Some(options) = options.filter(|options| options.enable) {
199            targets.push((IndexTarget::ColumnId(column.column_id), options));
200        }
201        // Only flush and compaction builds collect JSON targets; manual and schema-change
202        // rebuilds skip them because existing SSTs may not materialize the current hints.
203        // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes.
204        if matches!(build_type, IndexBuildType::Flush | IndexBuildType::Compact)
205            && column.column_schema.data_type.is_json2()
206            && let Some(extension) = column
207                .column_schema
208                .extension_type::<Json2ExtensionType>()
209                .context(IndexOptionsSnafu {
210                    column_name: &column.column_schema.name,
211                })?
212        {
213            for hint in extension.metadata().json_settings().type_hints() {
214                let Some(options) = hint.fulltext_index.as_ref().filter(|o| o.enable) else {
215                    continue;
216                };
217                match IndexTarget::new_json_path(column.column_id, hint.path.clone()) {
218                    Ok(target) => targets.push((target, options.clone())),
219                    Err(err) => {
220                        warn!(
221                            err;
222                            "Skip invalid JSON fulltext index target, column_id: {}, path: {:?}",
223                            column.column_id,
224                            hint.path
225                        );
226                    }
227                }
228            }
229        }
230        Ok(targets)
231    }
232
233    /// Updates the index with the given batch.
234    pub async fn update(&mut self, batch: &mut Batch) -> Result<()> {
235        ensure!(!self.aborted, OperateAbortedIndexSnafu);
236
237        if let Err(update_err) = self.do_update(batch).await {
238            if let Err(err) = self.do_abort().await {
239                if cfg!(any(test, feature = "test")) {
240                    panic!("Failed to abort index creator, err: {err}");
241                } else {
242                    warn!(err; "Failed to abort index creator");
243                }
244            }
245            return Err(update_err);
246        }
247
248        Ok(())
249    }
250
251    /// Updates the fulltext index with the given flat format RecordBatch.
252    pub async fn update_flat(&mut self, batch: &RecordBatch) -> Result<()> {
253        ensure!(!self.aborted, OperateAbortedIndexSnafu);
254
255        if batch.num_rows() == 0 {
256            return Ok(());
257        }
258
259        if let Err(update_err) = self.do_update_flat(batch).await {
260            if let Err(err) = self.do_abort().await {
261                if cfg!(any(test, feature = "test")) {
262                    panic!("Failed to abort index creator, err: {err}");
263                } else {
264                    warn!(err; "Failed to abort index creator");
265                }
266            }
267            return Err(update_err);
268        }
269
270        Ok(())
271    }
272
273    /// Finalizes the index creation.
274    pub async fn finish(
275        &mut self,
276        puffin_writer: &mut SstPuffinWriter,
277    ) -> Result<(RowCount, ByteCount)> {
278        ensure!(!self.aborted, OperateAbortedIndexSnafu);
279
280        match self.do_finish(puffin_writer).await {
281            Ok(()) => Ok((self.stats.row_count(), self.stats.byte_count())),
282            Err(finish_err) => {
283                if let Err(err) = self.do_abort().await {
284                    if cfg!(any(test, feature = "test")) {
285                        panic!("Failed to abort index creator, err: {err}");
286                    } else {
287                        warn!(err; "Failed to abort index creator");
288                    }
289                }
290                Err(finish_err)
291            }
292        }
293    }
294
295    /// Aborts the index creation.
296    pub async fn abort(&mut self) -> Result<()> {
297        if self.aborted {
298            return Ok(());
299        }
300
301        self.do_abort().await
302    }
303
304    /// Returns the memory usage of the index creator.
305    pub fn memory_usage(&self) -> usize {
306        self.creators.values().map(|c| c.inner.memory_usage()).sum()
307    }
308
309    /// Returns the targets indexed by this creator.
310    pub fn indexed_targets(&self) -> impl Iterator<Item = &IndexTarget> {
311        self.creators.keys()
312    }
313
314    /// Returns the targets indexed with the bloom backend.
315    pub fn bloom_indexed_targets(&self) -> impl Iterator<Item = &IndexTarget> {
316        self.creators
317            .values()
318            .filter(|c| matches!(c.inner, AltFulltextCreator::Bloom(_)))
319            .map(|c| &c.target)
320    }
321}
322
323impl FulltextIndexer {
324    async fn do_update(&mut self, batch: &mut Batch) -> Result<()> {
325        let mut guard = self.stats.record_update();
326        guard.inc_row_count(batch.num_rows());
327
328        for creator in self.creators.values_mut() {
329            creator.update(batch).await?;
330        }
331
332        Ok(())
333    }
334
335    async fn do_update_flat(&mut self, batch: &RecordBatch) -> Result<()> {
336        let mut guard = self.stats.record_update();
337        guard.inc_row_count(batch.num_rows());
338
339        for creator in self.creators.values_mut() {
340            creator.update_flat(batch).await?;
341        }
342
343        Ok(())
344    }
345
346    async fn do_finish(&mut self, puffin_writer: &mut SstPuffinWriter) -> Result<()> {
347        let mut guard = self.stats.record_finish();
348
349        let mut written_bytes = 0;
350        for creator in self.creators.values_mut() {
351            written_bytes += creator.finish(puffin_writer).await?;
352        }
353
354        guard.inc_byte_count(written_bytes);
355        Ok(())
356    }
357
358    async fn do_abort(&mut self) -> Result<()> {
359        let _guard = self.stats.record_cleanup();
360
361        self.aborted = true;
362
363        for (_, mut creator) in self.creators.drain() {
364            creator.abort().await?;
365        }
366
367        Ok(())
368    }
369}
370
371/// `SingleCreator` is a creator for a single column.
372struct SingleCreator {
373    /// Column or JSON path to index.
374    target: IndexTarget,
375    /// Column name.
376    column_name: String,
377    /// Inner creator.
378    inner: AltFulltextCreator,
379    /// Whether the index should be compressed.
380    compress: bool,
381}
382
383impl SingleCreator {
384    async fn update(&mut self, batch: &mut Batch) -> Result<()> {
385        let column_id = match &self.target {
386            IndexTarget::ColumnId(id) => *id,
387            IndexTarget::JsonPath(path) => {
388                let root = batch
389                    .field_col_value(path.column_id())
390                    .with_context(|| InvalidRecordBatchSnafu {
391                        reason: format!("Missing JSON fulltext column {}", path.column_id()),
392                    })?
393                    .data
394                    .to_arrow_array();
395                let values = extract_json_type_hint_values(&root, path.path())?;
396                return self.push_json_values(values).await;
397            }
398        };
399        let text_column = batch.fields().iter().find(|c| c.column_id == column_id);
400        match text_column {
401            Some(column) => {
402                let data = column
403                    .data
404                    .cast(&ConcreteDataType::string_datatype())
405                    .context(CastVectorSnafu {
406                        from: column.data.data_type(),
407                        to: ConcreteDataType::string_datatype(),
408                    })?;
409
410                for i in 0..batch.num_rows() {
411                    let data = data.get_ref(i);
412                    let text = data
413                        .try_into_string()
414                        .context(DataTypeMismatchSnafu)?
415                        .unwrap_or_default();
416                    self.inner.push_text(text).await?;
417                }
418            }
419            _ => {
420                // If the column is not found in the batch, push empty text.
421                // Ensure that the number of texts pushed is the same as the number of rows in the SST,
422                // so that the texts are aligned with the row ids.
423                for _ in 0..batch.num_rows() {
424                    self.inner.push_text("").await?;
425                }
426            }
427        }
428
429        Ok(())
430    }
431
432    async fn update_flat(&mut self, batch: &RecordBatch) -> Result<()> {
433        if let IndexTarget::JsonPath(path) = &self.target {
434            let root = batch.column_by_name(&self.column_name).with_context(|| {
435                InvalidRecordBatchSnafu {
436                    reason: format!("Missing JSON fulltext column {}", self.column_name),
437                }
438            })?;
439            let values = extract_json_type_hint_values(root, path.path())?;
440            return self.push_json_values(values).await;
441        }
442        // Find the column in the RecordBatch by name
443        if let Some(column_array) = batch.column_by_name(&self.column_name) {
444            // Convert Arrow array to string array.
445            // TODO(yingwen): Use Utf8View later if possible.
446            match column_array.data_type() {
447                DataType::Utf8 => {
448                    let string_array = column_array.as_any().downcast_ref::<StringArray>().unwrap();
449                    for text_opt in string_array.iter() {
450                        let text = text_opt.unwrap_or_default();
451                        self.inner.push_text(text).await?;
452                    }
453                }
454                DataType::LargeUtf8 => {
455                    let large_string_array = column_array
456                        .as_any()
457                        .downcast_ref::<LargeStringArray>()
458                        .unwrap();
459                    for text_opt in large_string_array.iter() {
460                        let text = text_opt.unwrap_or_default();
461                        self.inner.push_text(text).await?;
462                    }
463                }
464                _ => {
465                    // For other types, cast to Utf8 as before
466                    let array = datatypes::arrow::compute::cast(column_array, &DataType::Utf8)
467                        .context(ComputeArrowSnafu)?;
468                    let string_array = array.as_any().downcast_ref::<StringArray>().unwrap();
469                    for text_opt in string_array.iter() {
470                        let text = text_opt.unwrap_or_default();
471                        self.inner.push_text(text).await?;
472                    }
473                }
474            }
475        } else {
476            // If the column is not found in the batch, push empty text.
477            // Ensure that the number of texts pushed is the same as the number of rows in the SST,
478            // so that the texts are aligned with the row ids.
479            for _ in 0..batch.num_rows() {
480                self.inner.push_text("").await?;
481            }
482        }
483
484        Ok(())
485    }
486
487    async fn push_json_values(&mut self, values: VectorRef) -> Result<()> {
488        for row in 0..values.len() {
489            let text = values
490                .get_ref(row)
491                .try_into_string()
492                .context(DataTypeMismatchSnafu)?
493                .unwrap_or_default();
494            self.inner.push_text(text).await?;
495        }
496        Ok(())
497    }
498
499    async fn finish(&mut self, puffin_writer: &mut SstPuffinWriter) -> Result<ByteCount> {
500        let options = PutOptions {
501            compression: self.compress.then_some(CompressionCodec::Zstd),
502        };
503        self.inner
504            .finish(puffin_writer, &self.target, options)
505            .await
506    }
507
508    async fn abort(&mut self) -> Result<()> {
509        self.inner.abort(&self.target).await;
510        Ok(())
511    }
512}
513
514#[allow(dead_code, clippy::large_enum_variant)]
515/// `AltFulltextCreator` is an alternative fulltext index creator that can be either Tantivy or BloomFilter.
516enum AltFulltextCreator {
517    Tantivy(TantivyFulltextIndexCreator),
518    Bloom(BloomFilterFulltextIndexCreator),
519}
520
521impl AltFulltextCreator {
522    async fn push_text(&mut self, text: &str) -> Result<()> {
523        match self {
524            Self::Tantivy(creator) => creator.push_text(text).await.context(FulltextPushTextSnafu),
525            Self::Bloom(creator) => creator.push_text(text).await.context(FulltextPushTextSnafu),
526        }
527    }
528
529    fn memory_usage(&self) -> usize {
530        match self {
531            Self::Tantivy(creator) => creator.memory_usage(),
532            Self::Bloom(creator) => creator.memory_usage(),
533        }
534    }
535
536    async fn finish(
537        &mut self,
538        puffin_writer: &mut SstPuffinWriter,
539        target: &IndexTarget,
540        put_options: PutOptions,
541    ) -> Result<ByteCount> {
542        let target_key = target.encode();
543        match self {
544            Self::Tantivy(creator) => {
545                let blob_key = format!("{INDEX_BLOB_TYPE_TANTIVY}-{target_key}");
546                creator
547                    .finish(puffin_writer, &blob_key, put_options)
548                    .await
549                    .context(FulltextFinishSnafu)
550            }
551            Self::Bloom(creator) => {
552                let blob_key = format!("{INDEX_BLOB_TYPE_BLOOM}-{target_key}");
553                creator
554                    .finish(puffin_writer, &blob_key, put_options)
555                    .await
556                    .context(FulltextFinishSnafu)
557            }
558        }
559    }
560
561    async fn abort(&mut self, target: &IndexTarget) {
562        match self {
563            Self::Tantivy(creator) => {
564                if let Err(err) = creator.abort().await {
565                    warn!(err; "Failed to abort the fulltext index creator in the Tantivy flavor, target: {:?}", target);
566                }
567            }
568            Self::Bloom(creator) => {
569                if let Err(err) = creator.abort().await {
570                    warn!(err; "Failed to abort the fulltext index creator in the Bloom Filter flavor, target: {:?}", target);
571                }
572            }
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use std::collections::{BTreeMap, BTreeSet};
580    use std::sync::Arc;
581
582    use api::v1::SemanticType;
583    use common_base::BitVec;
584    use datatypes::arrow::array::{ArrayRef, StructArray};
585    use datatypes::arrow::buffer::NullBuffer;
586    use datatypes::arrow::datatypes::{Field, Schema};
587    use datatypes::data_type::DataType;
588    use datatypes::extension::json::{Json2ExtensionType, JsonMetadata};
589    use datatypes::json::{JsonSettings, JsonTypeHint};
590    use datatypes::schema::{ColumnSchema, FulltextAnalyzer, FulltextOptions};
591    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
592    use datatypes::vectors::{Helper, UInt8Vector, UInt64Vector};
593    use futures::FutureExt;
594    use futures::future::BoxFuture;
595    use index::fulltext_index::search::RowId;
596    use object_store::ObjectStore;
597    use object_store::services::Memory;
598    use puffin::puffin_manager::{PuffinManager, PuffinWriter};
599    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
600    use store_api::region_request::PathType;
601    use store_api::storage::{ColumnId, ConcreteDataType, FileId, RegionId};
602
603    use super::*;
604    use crate::access_layer::RegionFilePathFactory;
605    use crate::read::{Batch, BatchColumn};
606    use crate::sst::file::{RegionFileId, RegionIndexId};
607    use crate::sst::index::fulltext_index::applier::FulltextIndexApplier;
608    use crate::sst::index::fulltext_index::applier::builder::{
609        FulltextQuery, FulltextRequest, FulltextTerm,
610    };
611    use crate::sst::index::puffin_manager::PuffinManagerFactory;
612
613    #[tokio::test]
614    async fn test_json_fulltext_build_and_prune_both_formats() {
615        for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] {
616            for (flat, build_type) in [
617                (false, IndexBuildType::Flush),
618                (false, IndexBuildType::Compact),
619                (true, IndexBuildType::Flush),
620                (true, IndexBuildType::Compact),
621            ] {
622                let (dir, factory) =
623                    PuffinManagerFactory::new_for_test_async("json_fulltext").await;
624                let options = FulltextOptions::new(
625                    true,
626                    FulltextAnalyzer::English,
627                    false,
628                    backend.clone(),
629                    1,
630                    0.01,
631                )
632                .unwrap();
633                let hints = ["message", "other/\".field"].map(|name| JsonTypeHint {
634                    path: vec![name.into()],
635                    data_type: ConcreteDataType::string_datatype(),
636                    inverted_index: false,
637                    skipping_index: None,
638                    fulltext_index: Some(options.clone()),
639                });
640                let mut column = ColumnSchema::new(
641                    "attrs",
642                    ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())),
643                    true,
644                );
645                column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new(
646                    JsonSettings::try_new(hints.to_vec(), Some(0)).unwrap(),
647                ))));
648                let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2));
649                builder.push_column_metadata(ColumnMetadata {
650                    column_schema: column,
651                    semantic_type: SemanticType::Field,
652                    column_id: 1,
653                });
654                builder.push_column_metadata(ColumnMetadata {
655                    column_schema: ColumnSchema::new(
656                        "ts",
657                        ConcreteDataType::timestamp_millisecond_datatype(),
658                        false,
659                    ),
660                    semantic_type: SemanticType::Timestamp,
661                    column_id: 2,
662                });
663                let metadata = Arc::new(builder.build().unwrap());
664                let file_id = FileId::random();
665                let manager = new_intm_mgr(dir.path().to_string_lossy()).await;
666                for rebuild_type in [IndexBuildType::Manual, IndexBuildType::SchemaChange] {
667                    assert!(
668                        FulltextIndexer::new(
669                            &metadata.region_id,
670                            &file_id,
671                            &manager,
672                            &metadata,
673                            false,
674                            1024,
675                            rebuild_type,
676                        )
677                        .await
678                        .unwrap()
679                        .is_none()
680                    );
681                }
682                let mut creator = FulltextIndexer::new(
683                    &metadata.region_id,
684                    &file_id,
685                    &manager,
686                    &metadata,
687                    false,
688                    1024,
689                    build_type,
690                )
691                .await
692                .unwrap()
693                .unwrap();
694                let messages: ArrayRef = Arc::new(StringArray::from(vec![
695                    Some("alpha"),
696                    None,
697                    Some("beta"),
698                    Some("alpha"),
699                ]));
700                let other: ArrayRef = Arc::new(StringArray::from(vec![
701                    Some("beta"),
702                    None,
703                    Some("alpha"),
704                    Some(""),
705                ]));
706                let root: ArrayRef = Arc::new(StructArray::new(
707                    vec![
708                        Field::new("message", messages.data_type().clone(), true),
709                        Field::new("other/\".field", other.data_type().clone(), true),
710                    ]
711                    .into(),
712                    vec![messages, other],
713                    Some(NullBuffer::from(vec![true, false, true, true])),
714                ));
715                for start in [0, 2] {
716                    let array = root.slice(start, 2);
717                    if flat {
718                        let batch = RecordBatch::try_new(
719                            Arc::new(Schema::new(vec![Field::new(
720                                "attrs",
721                                array.data_type().clone(),
722                                true,
723                            )])),
724                            vec![array],
725                        )
726                        .unwrap();
727                        creator.update_flat(&batch).await.unwrap();
728                    } else {
729                        let mut batch = Batch::new(
730                            vec![],
731                            Arc::new(UInt64Vector::from_vec(vec![0, 1])),
732                            Arc::new(UInt64Vector::from_vec(vec![0, 0])),
733                            Arc::new(UInt8Vector::from_vec(vec![1, 1])),
734                            vec![BatchColumn {
735                                column_id: 1,
736                                data: Helper::try_into_vector(array).unwrap(),
737                            }],
738                        )
739                        .unwrap();
740                        creator.update(&mut batch).await.unwrap();
741                    }
742                }
743                assert_eq!(creator.indexed_targets().count(), hints.len());
744                assert!(
745                    creator
746                        .indexed_targets()
747                        .all(|target| matches!(target, IndexTarget::JsonPath(_)))
748                );
749                let bloom_targets: BTreeSet<_> = creator.bloom_indexed_targets().collect();
750                if backend == FulltextBackend::Bloom {
751                    assert_eq!(bloom_targets, creator.indexed_targets().collect());
752                } else {
753                    assert!(bloom_targets.is_empty());
754                }
755                let store = mock_object_store();
756                let puffin = factory.build(
757                    store.clone(),
758                    RegionFilePathFactory::new("json_test".into(), PathType::Bare),
759                );
760                let index_id =
761                    RegionIndexId::new(RegionFileId::new(metadata.region_id, file_id), 0);
762                let mut writer = puffin.writer(&index_id).await.unwrap();
763                let (rows, bytes) = creator.finish(&mut writer).await.unwrap();
764                assert_eq!(rows, 4);
765                assert!(bytes > 0);
766                writer.finish().await.unwrap();
767                let cache = Arc::new(
768                    crate::cache::index::bloom_filter_index::BloomFilterIndexCache::new(
769                        1024 * 1024,
770                        1024 * 1024,
771                        1024,
772                    ),
773                );
774                for (path, term, expected) in [
775                    ("message", "alpha", vec![0, 3]),
776                    ("other/\".field", "alpha", vec![2]),
777                    ("message", "hidden", vec![]),
778                    ("message", "absent", vec![]),
779                ] {
780                    let target = IndexTarget::new_json_path(1, vec![path.into()]).unwrap();
781                    let request = match backend {
782                        FulltextBackend::Tantivy => FulltextRequest {
783                            queries: vec![FulltextQuery(term.into())],
784                            ..Default::default()
785                        },
786                        FulltextBackend::Bloom => FulltextRequest {
787                            terms: vec![FulltextTerm {
788                                col_lowered: false,
789                                term: term.into(),
790                            }],
791                            ..Default::default()
792                        },
793                    };
794                    let applier = FulltextIndexApplier::new(
795                        "json_test".into(),
796                        PathType::Bare,
797                        store.clone(),
798                        BTreeMap::from([
799                            (target, request.clone()),
800                            (
801                                IndexTarget::new_json_path(1, vec!["missing".into()]).unwrap(),
802                                request,
803                            ),
804                        ]),
805                        factory.clone(),
806                        &metadata,
807                    )
808                    .with_bloom_filter_cache(Some(cache.clone()));
809                    let requests = applier.compatible_requests_for_sst(&metadata).unwrap();
810                    assert_eq!(requests.len(), 1);
811                    for change in 0..3 {
812                        let mut changed_hints = hints.to_vec();
813                        for hint in &mut changed_hints {
814                            let options = hint.fulltext_index.as_mut().unwrap();
815                            match change {
816                                0 => options.analyzer = FulltextAnalyzer::Chinese,
817                                1 => options.case_sensitive = true,
818                                _ => {
819                                    options.backend = match backend {
820                                        FulltextBackend::Bloom => FulltextBackend::Tantivy,
821                                        FulltextBackend::Tantivy => FulltextBackend::Bloom,
822                                    }
823                                }
824                            }
825                        }
826                        let mut changed = (*metadata).clone();
827                        changed.column_metadatas[0]
828                            .column_schema
829                            .with_extension_type(&Json2ExtensionType::new(Arc::new(
830                                JsonMetadata::new(
831                                    JsonSettings::try_new(changed_hints, Some(0)).unwrap(),
832                                ),
833                            )));
834                        assert_eq!(
835                            applier.compatible_requests_for_sst(&changed).is_some(),
836                            change == 0 && backend == FulltextBackend::Bloom,
837                        );
838                    }
839                    assert!(
840                        applier
841                            .compatible_requests_for_sst(&mock_region_metadata(backend.clone()))
842                            .is_none()
843                    );
844                    for _ in 0..2 {
845                        match backend {
846                            FulltextBackend::Tantivy => {
847                                let rows = applier
848                                    .apply_fine(index_id, None, &requests, None)
849                                    .await
850                                    .unwrap()
851                                    .unwrap();
852                                assert_eq!(
853                                    rows.into_iter().collect::<Vec<_>>(),
854                                    expected.iter().map(|v| *v as RowId).collect::<Vec<_>>()
855                                );
856                            }
857                            FulltextBackend::Bloom => {
858                                let ranges = applier
859                                    .apply_coarse(
860                                        index_id,
861                                        None,
862                                        [(4, true)].into_iter(),
863                                        &requests,
864                                        None,
865                                    )
866                                    .await
867                                    .unwrap()
868                                    .unwrap();
869                                let rows: Vec<_> = ranges[0].1.iter().cloned().flatten().collect();
870                                // A Bloom filter may retain extra rows, but must retain every match.
871                                assert!(expected.iter().all(|row| rows.contains(row)));
872                                if expected.is_empty() {
873                                    assert!(
874                                        rows.len() < 4,
875                                        "path={path}, term={term}, flat={flat}, rows={rows:?}"
876                                    );
877                                }
878                            }
879                        }
880                    }
881                }
882            }
883        }
884    }
885
886    fn mock_object_store() -> ObjectStore {
887        ObjectStore::new(Memory::default()).unwrap()
888    }
889
890    async fn new_intm_mgr(path: impl AsRef<str>) -> IntermediateManager {
891        IntermediateManager::init_fs(path).await.unwrap()
892    }
893
894    fn mock_region_metadata(backend: FulltextBackend) -> RegionMetadataRef {
895        let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2));
896        builder
897            .push_column_metadata(ColumnMetadata {
898                column_schema: ColumnSchema::new(
899                    "text_english_case_sensitive",
900                    ConcreteDataType::string_datatype(),
901                    true,
902                )
903                .with_fulltext_options(FulltextOptions::new_unchecked(
904                    true,
905                    FulltextAnalyzer::English,
906                    true,
907                    backend.clone(),
908                    1,
909                    0.01,
910                ))
911                .unwrap(),
912                semantic_type: SemanticType::Field,
913                column_id: 1,
914            })
915            .push_column_metadata(ColumnMetadata {
916                column_schema: ColumnSchema::new(
917                    "text_english_case_insensitive",
918                    ConcreteDataType::string_datatype(),
919                    true,
920                )
921                .with_fulltext_options(FulltextOptions::new_unchecked(
922                    true,
923                    FulltextAnalyzer::English,
924                    false,
925                    backend.clone(),
926                    1,
927                    0.01,
928                ))
929                .unwrap(),
930                semantic_type: SemanticType::Field,
931                column_id: 2,
932            })
933            .push_column_metadata(ColumnMetadata {
934                column_schema: ColumnSchema::new(
935                    "text_chinese",
936                    ConcreteDataType::string_datatype(),
937                    true,
938                )
939                .with_fulltext_options(FulltextOptions::new_unchecked(
940                    true,
941                    FulltextAnalyzer::Chinese,
942                    false,
943                    backend.clone(),
944                    1,
945                    0.01,
946                ))
947                .unwrap(),
948                semantic_type: SemanticType::Field,
949                column_id: 3,
950            })
951            .push_column_metadata(ColumnMetadata {
952                column_schema: ColumnSchema::new(
953                    "ts",
954                    ConcreteDataType::timestamp_millisecond_datatype(),
955                    false,
956                ),
957                semantic_type: SemanticType::Timestamp,
958                column_id: 4,
959            });
960
961        Arc::new(builder.build().unwrap())
962    }
963
964    fn new_batch(
965        rows: &[(
966            Option<&str>, // text_english_case_sensitive
967            Option<&str>, // text_english_case_insensitive
968            Option<&str>, // text_chinese
969        )],
970    ) -> Batch {
971        let mut vec_english_sensitive =
972            ConcreteDataType::string_datatype().create_mutable_vector(0);
973        let mut vec_english_insensitive =
974            ConcreteDataType::string_datatype().create_mutable_vector(0);
975        let mut vec_chinese = ConcreteDataType::string_datatype().create_mutable_vector(0);
976
977        for (text_english_case_sensitive, text_english_case_insensitive, text_chinese) in rows {
978            match text_english_case_sensitive {
979                Some(s) => vec_english_sensitive.push_value_ref(&(*s).into()),
980                None => vec_english_sensitive.push_null(),
981            }
982            match text_english_case_insensitive {
983                Some(s) => vec_english_insensitive.push_value_ref(&(*s).into()),
984                None => vec_english_insensitive.push_null(),
985            }
986            match text_chinese {
987                Some(s) => vec_chinese.push_value_ref(&(*s).into()),
988                None => vec_chinese.push_null(),
989            }
990        }
991
992        let num_rows = vec_english_sensitive.len();
993        Batch::new(
994            vec![],
995            Arc::new(UInt64Vector::from_iter_values(
996                (0..num_rows).map(|n| n as u64),
997            )),
998            Arc::new(UInt64Vector::from_iter_values(std::iter::repeat_n(
999                0, num_rows,
1000            ))),
1001            Arc::new(UInt8Vector::from_iter_values(std::iter::repeat_n(
1002                1, num_rows,
1003            ))),
1004            vec![
1005                BatchColumn {
1006                    column_id: 1,
1007                    data: vec_english_sensitive.to_vector(),
1008                },
1009                BatchColumn {
1010                    column_id: 2,
1011                    data: vec_english_insensitive.to_vector(),
1012                },
1013                BatchColumn {
1014                    column_id: 3,
1015                    data: vec_chinese.to_vector(),
1016                },
1017            ],
1018        )
1019        .unwrap()
1020    }
1021
1022    /// Applier factory that can handle both queries and terms.
1023    ///
1024    /// It builds a fulltext index with the given data rows, and returns a function
1025    /// that can handle both queries and terms in a single request.
1026    ///
1027    /// The function takes two parameters:
1028    /// - `queries`: A list of (ColumnId, query_string) pairs for fulltext queries
1029    /// - `terms`: A list of (ColumnId, [(bool, String)]) for fulltext terms, where bool indicates if term is lowercased
1030    async fn build_fulltext_applier_factory(
1031        prefix: &str,
1032        backend: FulltextBackend,
1033        rows: &[(
1034            Option<&str>, // text_english_case_sensitive
1035            Option<&str>, // text_english_case_insensitive
1036            Option<&str>, // text_chinese
1037        )],
1038    ) -> impl Fn(
1039        Vec<(ColumnId, &str)>,
1040        Vec<(ColumnId, Vec<(bool, &str)>)>,
1041        Option<BitVec>,
1042    ) -> BoxFuture<'static, Option<BTreeSet<RowId>>> {
1043        let (d, factory) = PuffinManagerFactory::new_for_test_async(prefix).await;
1044        let table_dir = "table0".to_string();
1045        let sst_file_id = FileId::random();
1046        let object_store = mock_object_store();
1047        let region_metadata = mock_region_metadata(backend.clone());
1048        let intm_mgr = new_intm_mgr(d.path().to_string_lossy()).await;
1049
1050        let mut indexer = FulltextIndexer::new(
1051            &region_metadata.region_id,
1052            &sst_file_id,
1053            &intm_mgr,
1054            &region_metadata,
1055            true,
1056            1024,
1057            IndexBuildType::Flush,
1058        )
1059        .await
1060        .unwrap()
1061        .unwrap();
1062
1063        let mut batch = new_batch(rows);
1064        indexer.update(&mut batch).await.unwrap();
1065
1066        let puffin_manager = factory.build(
1067            object_store.clone(),
1068            RegionFilePathFactory::new(table_dir.clone(), PathType::Bare),
1069        );
1070        let region_file_id = RegionFileId::new(region_metadata.region_id, sst_file_id);
1071        let index_id = RegionIndexId::new(region_file_id, 0);
1072        let mut writer = puffin_manager.writer(&index_id).await.unwrap();
1073        let _ = indexer.finish(&mut writer).await.unwrap();
1074        writer.finish().await.unwrap();
1075
1076        move |queries: Vec<(ColumnId, &str)>,
1077              terms_requests: Vec<(ColumnId, Vec<(bool, &str)>)>,
1078              coarse_mask: Option<BitVec>| {
1079            let _d = &d;
1080            let table_dir = table_dir.clone();
1081            let object_store = object_store.clone();
1082            let factory = factory.clone();
1083
1084            let mut requests: BTreeMap<IndexTarget, FulltextRequest> = BTreeMap::new();
1085
1086            // Add queries
1087            for (column_id, query) in queries {
1088                requests
1089                    .entry(IndexTarget::ColumnId(column_id))
1090                    .or_default()
1091                    .queries
1092                    .push(FulltextQuery(query.to_string()));
1093            }
1094
1095            // Add terms
1096            for (column_id, terms) in terms_requests {
1097                let fulltext_terms = terms
1098                    .into_iter()
1099                    .map(|(col_lowered, term)| FulltextTerm {
1100                        col_lowered,
1101                        term: term.to_string(),
1102                    })
1103                    .collect::<Vec<_>>();
1104
1105                requests
1106                    .entry(IndexTarget::ColumnId(column_id))
1107                    .or_default()
1108                    .terms
1109                    .extend(fulltext_terms);
1110            }
1111
1112            let applier = FulltextIndexApplier::new(
1113                table_dir,
1114                PathType::Bare,
1115                object_store,
1116                requests,
1117                factory,
1118                &region_metadata,
1119            );
1120
1121            let requests = applier
1122                .compatible_requests_for_sst(&region_metadata)
1123                .unwrap();
1124            let backend = backend.clone();
1125            async move {
1126                match backend {
1127                    FulltextBackend::Tantivy => applier
1128                        .apply_fine(index_id, None, &requests, None)
1129                        .await
1130                        .unwrap(),
1131                    FulltextBackend::Bloom => {
1132                        let coarse_mask = coarse_mask.unwrap_or_default();
1133                        let row_groups = (0..coarse_mask.len()).map(|i| (1, coarse_mask[i]));
1134                        // row group id == row id
1135                        let resp = applier
1136                            .apply_coarse(index_id, None, row_groups, &requests, None)
1137                            .await
1138                            .unwrap();
1139                        resp.map(|r| {
1140                            r.into_iter()
1141                                .filter(|(_, ranges)| !ranges.is_empty())
1142                                .map(|(row_group_id, _)| row_group_id as RowId)
1143                                .collect()
1144                        })
1145                    }
1146                }
1147            }
1148            .boxed()
1149        }
1150    }
1151
1152    fn rows(row_ids: impl IntoIterator<Item = RowId>) -> BTreeSet<RowId> {
1153        row_ids.into_iter().collect()
1154    }
1155
1156    #[tokio::test]
1157    async fn test_fulltext_bloom_shared_memory_spills() {
1158        let dir = common_test_util::temp_dir::create_temp_dir("shared_fulltext_memory");
1159        let metadata = mock_region_metadata(FulltextBackend::Bloom);
1160        let manager = new_intm_mgr(dir.path().to_string_lossy()).await;
1161        let mut indexer = FulltextIndexer::new(
1162            &metadata.region_id,
1163            &FileId::random(),
1164            &manager,
1165            &metadata,
1166            false,
1167            2 * 1024 * 1024,
1168            IndexBuildType::Flush,
1169        )
1170        .await
1171        .unwrap()
1172        .unwrap();
1173        // Each target stays below 2 MB on its own; together they exceed the
1174        // shared threshold and must spill finalized Bloom filters to disk.
1175        for creator in indexer.creators.values_mut() {
1176            for row in 0..20_000 {
1177                creator.inner.push_text(&format!("row{row}")).await.unwrap();
1178            }
1179        }
1180        let mut directories = vec![dir.path().join("__intm")];
1181        let mut spilled = false;
1182        while let Some(directory) = directories.pop() {
1183            for entry in std::fs::read_dir(directory).unwrap() {
1184                let entry = entry.unwrap();
1185                if entry.file_type().unwrap().is_dir() {
1186                    directories.push(entry.path());
1187                } else {
1188                    spilled = true;
1189                }
1190            }
1191        }
1192        assert!(spilled, "combined memory usage must trigger spilling");
1193        indexer.abort().await.unwrap();
1194    }
1195
1196    #[tokio::test]
1197    async fn test_fulltext_index_basic_case_sensitive_tantivy() {
1198        let applier_factory = build_fulltext_applier_factory(
1199            "test_fulltext_index_basic_case_sensitive_tantivy_",
1200            FulltextBackend::Tantivy,
1201            &[
1202                (Some("hello"), None, None),
1203                (Some("world"), None, None),
1204                (None, None, None),
1205                (Some("Hello, World"), None, None),
1206            ],
1207        )
1208        .await;
1209
1210        let row_ids = applier_factory(vec![(1, "hello")], vec![], None).await;
1211        assert_eq!(row_ids, Some(rows([0])));
1212
1213        let row_ids = applier_factory(vec![(1, "world")], vec![], None).await;
1214        assert_eq!(row_ids, Some(rows([1])));
1215
1216        let row_ids = applier_factory(vec![(1, "Hello")], vec![], None).await;
1217        assert_eq!(row_ids, Some(rows([3])));
1218
1219        let row_ids = applier_factory(vec![(1, "World")], vec![], None).await;
1220        assert_eq!(row_ids, Some(rows([3])));
1221
1222        // Terms are left to the bloom backend.
1223        let row_ids = applier_factory(vec![], vec![(1, vec![(false, "hello")])], None).await;
1224        assert_eq!(row_ids, None);
1225    }
1226
1227    #[tokio::test]
1228    async fn test_fulltext_index_basic_case_sensitive_bloom() {
1229        let applier_factory = build_fulltext_applier_factory(
1230            "test_fulltext_index_basic_case_sensitive_bloom_",
1231            FulltextBackend::Bloom,
1232            &[
1233                (Some("hello"), None, None),
1234                (Some("world"), None, None),
1235                (None, None, None),
1236                (Some("Hello, World"), None, None),
1237            ],
1238        )
1239        .await;
1240
1241        let row_ids = applier_factory(
1242            vec![],
1243            vec![(1, vec![(false, "hello")])],
1244            Some(BitVec::from_slice(&[0b1111])),
1245        )
1246        .await;
1247        assert_eq!(row_ids, Some(rows([0])));
1248
1249        let row_ids = applier_factory(
1250            vec![],
1251            vec![(1, vec![(false, "hello")])],
1252            Some(BitVec::from_slice(&[0b1110])), // row 0 is filtered out
1253        )
1254        .await;
1255        assert_eq!(row_ids, Some(rows([])));
1256
1257        let row_ids = applier_factory(
1258            vec![],
1259            vec![(1, vec![(true, "hello")])],
1260            Some(BitVec::from_slice(&[0b1111])),
1261        )
1262        .await;
1263        assert_eq!(row_ids, None);
1264
1265        let row_ids = applier_factory(
1266            vec![],
1267            vec![(1, vec![(false, "world")])],
1268            Some(BitVec::from_slice(&[0b1111])),
1269        )
1270        .await;
1271        assert_eq!(row_ids, Some(rows([1])));
1272
1273        let row_ids = applier_factory(
1274            vec![],
1275            vec![(1, vec![(false, "world")])],
1276            Some(BitVec::from_slice(&[0b1101])), // row 1 is filtered out
1277        )
1278        .await;
1279        assert_eq!(row_ids, Some(rows([])));
1280
1281        let row_ids = applier_factory(
1282            vec![],
1283            vec![(1, vec![(true, "world")])],
1284            Some(BitVec::from_slice(&[0b1111])),
1285        )
1286        .await;
1287        assert_eq!(row_ids, None);
1288
1289        let row_ids = applier_factory(
1290            vec![],
1291            vec![(1, vec![(false, "Hello")])],
1292            Some(BitVec::from_slice(&[0b1111])),
1293        )
1294        .await;
1295        assert_eq!(row_ids, Some(rows([3])));
1296
1297        let row_ids = applier_factory(
1298            vec![],
1299            vec![(1, vec![(false, "Hello")])],
1300            Some(BitVec::from_slice(&[0b0111])), // row 3 is filtered out
1301        )
1302        .await;
1303        assert_eq!(row_ids, Some(rows([])));
1304
1305        let row_ids = applier_factory(
1306            vec![],
1307            vec![(1, vec![(true, "Hello")])],
1308            Some(BitVec::from_slice(&[0b1111])),
1309        )
1310        .await;
1311        assert_eq!(row_ids, None);
1312
1313        let row_ids = applier_factory(
1314            vec![],
1315            vec![(1, vec![(false, "Hello, World")])],
1316            Some(BitVec::from_slice(&[0b1111])),
1317        )
1318        .await;
1319        assert_eq!(row_ids, Some(rows([3])));
1320
1321        let row_ids = applier_factory(
1322            vec![],
1323            vec![(1, vec![(false, "Hello, World")])],
1324            Some(BitVec::from_slice(&[0b0111])), // row 3 is filtered out
1325        )
1326        .await;
1327        assert_eq!(row_ids, Some(rows([])));
1328
1329        let row_ids = applier_factory(
1330            vec![],
1331            vec![(1, vec![(true, "Hello, World")])],
1332            Some(BitVec::from_slice(&[0b1111])),
1333        )
1334        .await;
1335        assert_eq!(row_ids, None);
1336    }
1337
1338    #[tokio::test]
1339    async fn test_fulltext_index_basic_case_insensitive_tantivy() {
1340        let applier_factory = build_fulltext_applier_factory(
1341            "test_fulltext_index_basic_case_insensitive_tantivy_",
1342            FulltextBackend::Tantivy,
1343            &[
1344                (None, Some("hello"), None),
1345                (None, None, None),
1346                (None, Some("world"), None),
1347                (None, Some("Hello, World"), None),
1348            ],
1349        )
1350        .await;
1351
1352        let row_ids = applier_factory(vec![(2, "hello")], vec![], None).await;
1353        assert_eq!(row_ids, Some(rows([0, 3])));
1354
1355        let row_ids = applier_factory(vec![(2, "world")], vec![], None).await;
1356        assert_eq!(row_ids, Some(rows([2, 3])));
1357
1358        let row_ids = applier_factory(vec![(2, "Hello")], vec![], None).await;
1359        assert_eq!(row_ids, Some(rows([0, 3])));
1360
1361        let row_ids = applier_factory(vec![(2, "World")], vec![], None).await;
1362        assert_eq!(row_ids, Some(rows([2, 3])));
1363    }
1364
1365    #[tokio::test]
1366    async fn test_fulltext_index_basic_case_insensitive_bloom() {
1367        let applier_factory = build_fulltext_applier_factory(
1368            "test_fulltext_index_basic_case_insensitive_bloom_",
1369            FulltextBackend::Bloom,
1370            &[
1371                (None, Some("hello"), None),
1372                (None, None, None),
1373                (None, Some("world"), None),
1374                (None, Some("Hello, World"), None),
1375            ],
1376        )
1377        .await;
1378
1379        let row_ids = applier_factory(
1380            vec![],
1381            vec![(2, vec![(false, "hello")])],
1382            Some(BitVec::from_slice(&[0b1111])),
1383        )
1384        .await;
1385        assert_eq!(row_ids, Some(rows([0, 3])));
1386
1387        let row_ids = applier_factory(
1388            vec![],
1389            vec![(2, vec![(false, "hello")])],
1390            Some(BitVec::from_slice(&[0b1110])), // row 0 is filtered out
1391        )
1392        .await;
1393        assert_eq!(row_ids, Some(rows([3])));
1394
1395        let row_ids = applier_factory(
1396            vec![],
1397            vec![(2, vec![(false, "world")])],
1398            Some(BitVec::from_slice(&[0b1111])),
1399        )
1400        .await;
1401        assert_eq!(row_ids, Some(rows([2, 3])));
1402
1403        let row_ids = applier_factory(
1404            vec![],
1405            vec![(2, vec![(false, "world")])],
1406            Some(BitVec::from_slice(&[0b1011])), // row 2 is filtered out
1407        )
1408        .await;
1409        assert_eq!(row_ids, Some(rows([3])));
1410
1411        let row_ids = applier_factory(
1412            vec![],
1413            vec![(2, vec![(false, "Hello")])],
1414            Some(BitVec::from_slice(&[0b1111])),
1415        )
1416        .await;
1417        assert_eq!(row_ids, Some(rows([0, 3])));
1418
1419        let row_ids = applier_factory(
1420            vec![],
1421            vec![(2, vec![(false, "Hello")])],
1422            Some(BitVec::from_slice(&[0b0111])), // row 3 is filtered out
1423        )
1424        .await;
1425        assert_eq!(row_ids, Some(rows([0])));
1426
1427        let row_ids = applier_factory(
1428            vec![],
1429            vec![(2, vec![(false, "World")])],
1430            Some(BitVec::from_slice(&[0b1111])),
1431        )
1432        .await;
1433        assert_eq!(row_ids, Some(rows([2, 3])));
1434
1435        let row_ids = applier_factory(
1436            vec![],
1437            vec![(2, vec![(false, "World")])],
1438            Some(BitVec::from_slice(&[0b0111])), // row 3 is filtered out
1439        )
1440        .await;
1441        assert_eq!(row_ids, Some(rows([2])));
1442
1443        let row_ids = applier_factory(
1444            vec![],
1445            vec![(2, vec![(true, "hello")])],
1446            Some(BitVec::from_slice(&[0b1111])),
1447        )
1448        .await;
1449        assert_eq!(row_ids, Some(rows([0, 3])));
1450    }
1451
1452    #[tokio::test]
1453    async fn test_fulltext_index_basic_chinese_tantivy() {
1454        let applier_factory = build_fulltext_applier_factory(
1455            "test_fulltext_index_basic_chinese_tantivy_",
1456            FulltextBackend::Tantivy,
1457            &[
1458                (None, None, Some("你好")),
1459                (None, None, None),
1460                (None, None, Some("世界")),
1461                (None, None, Some("你好,世界")),
1462            ],
1463        )
1464        .await;
1465
1466        let row_ids = applier_factory(vec![(3, "你好")], vec![], None).await;
1467        assert_eq!(row_ids, Some(rows([0, 3])));
1468
1469        let row_ids = applier_factory(vec![(3, "世界")], vec![], None).await;
1470        assert_eq!(row_ids, Some(rows([2, 3])));
1471    }
1472
1473    #[tokio::test]
1474    async fn test_fulltext_index_basic_chinese_bloom() {
1475        let applier_factory = build_fulltext_applier_factory(
1476            "test_fulltext_index_basic_chinese_bloom_",
1477            FulltextBackend::Bloom,
1478            &[
1479                (None, None, Some("你好")),
1480                (None, None, None),
1481                (None, None, Some("世界")),
1482                (None, None, Some("你好,世界")),
1483            ],
1484        )
1485        .await;
1486
1487        let row_ids = applier_factory(
1488            vec![],
1489            vec![(3, vec![(false, "你好")])],
1490            Some(BitVec::from_slice(&[0b1111])),
1491        )
1492        .await;
1493        assert_eq!(row_ids, Some(rows([0, 3])));
1494
1495        let row_ids = applier_factory(
1496            vec![],
1497            vec![(3, vec![(false, "你好")])],
1498            Some(BitVec::from_slice(&[0b1110])), // row 0 is filtered out
1499        )
1500        .await;
1501        assert_eq!(row_ids, Some(rows([3])));
1502
1503        let row_ids = applier_factory(
1504            vec![],
1505            vec![(3, vec![(false, "世界")])],
1506            Some(BitVec::from_slice(&[0b1111])),
1507        )
1508        .await;
1509        assert_eq!(row_ids, Some(rows([2, 3])));
1510
1511        let row_ids = applier_factory(
1512            vec![],
1513            vec![(3, vec![(false, "世界")])],
1514            Some(BitVec::from_slice(&[0b1011])), // row 2 is filtered out
1515        )
1516        .await;
1517        assert_eq!(row_ids, Some(rows([3])));
1518    }
1519
1520    #[tokio::test]
1521    async fn test_fulltext_index_multi_terms_case_sensitive_bloom() {
1522        let applier_factory = build_fulltext_applier_factory(
1523            "test_fulltext_index_multi_terms_case_sensitive_bloom_",
1524            FulltextBackend::Bloom,
1525            &[
1526                (Some("Hello"), None, None),
1527                (Some("World"), None, None),
1528                (None, None, None),
1529                (Some("Hello, World"), None, None),
1530            ],
1531        )
1532        .await;
1533
1534        let row_ids = applier_factory(
1535            vec![],
1536            vec![(1, vec![(false, "hello"), (false, "world")])],
1537            Some(BitVec::from_slice(&[0b1111])),
1538        )
1539        .await;
1540        assert_eq!(row_ids, Some(rows([])));
1541
1542        let row_ids = applier_factory(
1543            vec![],
1544            vec![(1, vec![(false, "Hello"), (false, "World")])],
1545            Some(BitVec::from_slice(&[0b1111])),
1546        )
1547        .await;
1548        assert_eq!(row_ids, Some(rows([3])));
1549
1550        let row_ids = applier_factory(
1551            vec![],
1552            vec![(1, vec![(true, "Hello"), (false, "World")])],
1553            Some(BitVec::from_slice(&[0b1111])),
1554        )
1555        .await;
1556        assert_eq!(row_ids, Some(rows([1, 3])));
1557
1558        let row_ids = applier_factory(
1559            vec![],
1560            vec![(1, vec![(false, "Hello"), (true, "World")])],
1561            Some(BitVec::from_slice(&[0b1111])),
1562        )
1563        .await;
1564        assert_eq!(row_ids, Some(rows([0, 3])));
1565
1566        let row_ids = applier_factory(
1567            vec![],
1568            vec![(1, vec![(true, "Hello"), (true, "World")])],
1569            Some(BitVec::from_slice(&[0b1111])),
1570        )
1571        .await;
1572        assert_eq!(row_ids, None);
1573    }
1574
1575    #[tokio::test]
1576    async fn test_fulltext_index_multi_terms_case_insensitive_bloom() {
1577        let applier_factory = build_fulltext_applier_factory(
1578            "test_fulltext_index_multi_terms_case_insensitive_bloom_",
1579            FulltextBackend::Bloom,
1580            &[
1581                (None, Some("hello"), None),
1582                (None, None, None),
1583                (None, Some("world"), None),
1584                (None, Some("Hello, World"), None),
1585            ],
1586        )
1587        .await;
1588
1589        let row_ids = applier_factory(
1590            vec![],
1591            vec![(2, vec![(false, "hello"), (false, "world")])],
1592            Some(BitVec::from_slice(&[0b1111])),
1593        )
1594        .await;
1595        assert_eq!(row_ids, Some(rows([3])));
1596
1597        let row_ids = applier_factory(
1598            vec![],
1599            vec![(2, vec![(true, "hello"), (false, "world")])],
1600            Some(BitVec::from_slice(&[0b1111])),
1601        )
1602        .await;
1603        assert_eq!(row_ids, Some(rows([3])));
1604
1605        let row_ids = applier_factory(
1606            vec![],
1607            vec![(2, vec![(false, "hello"), (true, "world")])],
1608            Some(BitVec::from_slice(&[0b1111])),
1609        )
1610        .await;
1611        assert_eq!(row_ids, Some(rows([3])));
1612
1613        let row_ids = applier_factory(
1614            vec![],
1615            vec![(2, vec![(true, "hello"), (true, "world")])],
1616            Some(BitVec::from_slice(&[0b1111])),
1617        )
1618        .await;
1619        assert_eq!(row_ids, Some(rows([3])));
1620    }
1621
1622    #[tokio::test]
1623    async fn test_fulltext_index_multi_columns_tantivy() {
1624        let applier_factory = build_fulltext_applier_factory(
1625            "test_fulltext_index_multi_columns_tantivy_",
1626            FulltextBackend::Tantivy,
1627            &[
1628                (Some("Hello"), None, Some("你好")),
1629                (Some("World"), Some("world"), None),
1630                (None, Some("World"), Some("世界")),
1631                (
1632                    Some("Hello, World"),
1633                    Some("Hello, World"),
1634                    Some("你好,世界"),
1635                ),
1636            ],
1637        )
1638        .await;
1639
1640        let row_ids = applier_factory(vec![(1, "Hello"), (3, "你好")], vec![], None).await;
1641        assert_eq!(row_ids, Some(rows([0, 3])));
1642
1643        let row_ids = applier_factory(vec![(1, "World"), (2, "World")], vec![], None).await;
1644        assert_eq!(row_ids, Some(rows([1, 3])));
1645    }
1646
1647    #[tokio::test]
1648    async fn test_fulltext_index_multi_columns_bloom() {
1649        let applier_factory = build_fulltext_applier_factory(
1650            "test_fulltext_index_multi_columns_bloom_",
1651            FulltextBackend::Bloom,
1652            &[
1653                (Some("Hello"), None, Some("你好")),
1654                (Some("World"), Some("world"), None),
1655                (None, Some("World"), Some("世界")),
1656                (
1657                    Some("Hello, World"),
1658                    Some("Hello, World"),
1659                    Some("你好,世界"),
1660                ),
1661            ],
1662        )
1663        .await;
1664
1665        let row_ids = applier_factory(
1666            vec![],
1667            vec![
1668                (1, vec![(false, "Hello")]),
1669                (2, vec![(false, "world")]),
1670                (3, vec![(false, "你好")]),
1671            ],
1672            Some(BitVec::from_slice(&[0b1111])),
1673        )
1674        .await;
1675        assert_eq!(row_ids, Some(rows([3])));
1676
1677        let row_ids = applier_factory(
1678            vec![],
1679            vec![(1, vec![(false, "World")]), (2, vec![(false, "World")])],
1680            Some(BitVec::from_slice(&[0b1111])),
1681        )
1682        .await;
1683        assert_eq!(row_ids, Some(rows([1, 3])));
1684    }
1685}