Skip to main content

index/fulltext_index/create/
bloom_filter.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 async_trait::async_trait;
20use common_error::ext::BoxedError;
21use puffin::puffin_manager::{PuffinWriter, PutOptions};
22use snafu::{OptionExt, ResultExt};
23use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
24
25use crate::bloom_filter::creator::BloomFilterCreator;
26use crate::external_provider::ExternalTempFileProvider;
27use crate::fulltext_index::create::FulltextIndexCreator;
28use crate::fulltext_index::error::{
29    AbortedSnafu, BiErrorsSnafu, BloomFilterFinishSnafu, ExternalSnafu, PuffinAddBlobSnafu, Result,
30    SerializeToJsonSnafu,
31};
32use crate::fulltext_index::tokenizer::{Analyzer, ScriptTokenizer};
33use crate::fulltext_index::{Config, KEY_FULLTEXT_CONFIG};
34
35const PIPE_BUFFER_SIZE_FOR_SENDING_BLOB: usize = 8192;
36
37/// `BloomFilterFulltextIndexCreator` is for creating a fulltext index using a bloom filter.
38pub struct BloomFilterFulltextIndexCreator {
39    inner: Option<BloomFilterCreator>,
40    analyzer: Analyzer,
41    config: Config,
42}
43
44impl BloomFilterFulltextIndexCreator {
45    pub fn new(
46        config: Config,
47        rows_per_segment: usize,
48        false_positive_rate: f64,
49        intermediate_provider: Arc<dyn ExternalTempFileProvider>,
50        global_memory_usage: Arc<AtomicUsize>,
51        global_memory_usage_threshold: Option<usize>,
52    ) -> Self {
53        // Both analyzers tokenize the same way: query probes must be derivable from the
54        // term alone, which a context-dependent segmenter like jieba can't provide.
55        let analyzer = Analyzer::new(Box::new(ScriptTokenizer), config.case_sensitive);
56
57        let inner = BloomFilterCreator::new(
58            rows_per_segment,
59            false_positive_rate,
60            intermediate_provider,
61            global_memory_usage,
62            global_memory_usage_threshold,
63        );
64        Self {
65            inner: Some(inner),
66            analyzer,
67            config,
68        }
69    }
70}
71
72#[async_trait]
73impl FulltextIndexCreator for BloomFilterFulltextIndexCreator {
74    async fn push_text(&mut self, text: &str) -> Result<()> {
75        let mut token_buf = Vec::new();
76        let hashes = self.analyzer.analyze_text_hashes(text, &mut token_buf);
77        self.inner
78            .as_mut()
79            .context(AbortedSnafu)?
80            .push_row_hashes(hashes)
81            .await
82            .map_err(BoxedError::new)
83            .context(ExternalSnafu)?;
84        Ok(())
85    }
86
87    async fn finish(
88        &mut self,
89        puffin_writer: &mut (impl PuffinWriter + Send),
90        blob_key: &str,
91        mut put_options: PutOptions,
92    ) -> Result<u64> {
93        // Compressing the bloom filter doesn't reduce the size but hurts read performance.
94        // Always disable compression here.
95        put_options.compression = None;
96
97        let creator = self.inner.as_mut().context(AbortedSnafu)?;
98
99        let (tx, rx) = tokio::io::duplex(PIPE_BUFFER_SIZE_FOR_SENDING_BLOB);
100
101        let property_key = KEY_FULLTEXT_CONFIG.to_string();
102        let property_value = serde_json::to_string(&self.config).context(SerializeToJsonSnafu)?;
103
104        let (index_finish, puffin_add_blob) = futures::join!(
105            creator.finish(tx.compat_write()),
106            puffin_writer.put_blob(
107                blob_key,
108                rx.compat(),
109                put_options,
110                HashMap::from([(property_key, property_value)]),
111            )
112        );
113
114        match (
115            puffin_add_blob.context(PuffinAddBlobSnafu),
116            index_finish.context(BloomFilterFinishSnafu),
117        ) {
118            (Err(e1), Err(e2)) => BiErrorsSnafu {
119                first: Box::new(e1),
120                second: Box::new(e2),
121            }
122            .fail()?,
123
124            (Ok(_), e @ Err(_)) => e?,
125            (e @ Err(_), Ok(_)) => e.map(|_| ())?,
126            (Ok(written_bytes), Ok(_)) => {
127                return Ok(written_bytes);
128            }
129        }
130        Ok(0)
131    }
132
133    async fn abort(&mut self) -> Result<()> {
134        self.inner.take().context(AbortedSnafu)?;
135        Ok(())
136    }
137
138    fn memory_usage(&self) -> usize {
139        self.inner
140            .as_ref()
141            .map(|i| i.memory_usage())
142            .unwrap_or_default()
143    }
144}