Skip to main content

mito2/sst/index/handler/builtin/
fulltext.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
15//! Planning and creator adapter for the fulltext index.
16
17use std::sync::Arc;
18
19use async_trait::async_trait;
20use common_error::ext::BoxedError;
21use datatypes::arrow::record_batch::RecordBatch;
22use datatypes::schema::FulltextBackend;
23use index::target::IndexTarget;
24
25use crate::config::FulltextIndexConfig;
26use crate::read::Batch;
27use crate::sst::file::FileMeta;
28use crate::sst::index::fulltext_index;
29use crate::sst::index::fulltext_index::creator::{FulltextIndexer, FulltextTarget};
30use crate::sst::index::handler::builtin::{
31    builtin_is_current, column_target_id, normalize_entries, target_column_id,
32};
33use crate::sst::index::handler::{
34    BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
35};
36use crate::sst::index::kind::IndexKind;
37use crate::sst::index::puffin_manager::SstPuffinWriter;
38use crate::sst::index::{CompletedEntry, IndexBuildType};
39
40/// Resolved column targets and configuration shared across output files.
41#[derive(Debug)]
42pub(crate) struct FulltextPlan {
43    config: FulltextIndexConfig,
44    entries: Vec<PlanEntry>,
45    targets: Vec<FulltextTarget>,
46}
47
48impl FulltextPlan {
49    /// Resolves targets without opening SST data or creating output files.
50    pub(crate) fn plan(
51        config: &FulltextIndexConfig,
52        context: &PlanContext<'_>,
53    ) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
54        let create = match context.build_type {
55            IndexBuildType::Flush => config.create_on_flush.auto(),
56            IndexBuildType::Compact => config.create_on_compaction.auto(),
57            _ => true,
58        };
59        if !create {
60            return Ok(None);
61        }
62        let mut targets = Vec::new();
63        let mut entries = Vec::new();
64        for column in &context.metadata.column_metadatas {
65            for (target, options) in
66                FulltextIndexer::targets(column, &context.build_type).map_err(BoxedError::new)?
67            {
68                entries.push(PlanEntry {
69                    column_id: target_column_id(&target),
70                    kind: IndexKind::Fulltext,
71                    format_version: if options.backend == FulltextBackend::Bloom {
72                        u32::from(fulltext_index::FULLTEXT_BLOOM_VERSION)
73                    } else {
74                        0
75                    },
76                });
77                targets.push((
78                    column.column_id,
79                    column.column_schema.name.clone(),
80                    target,
81                    options,
82                ));
83            }
84        }
85        normalize_entries(&mut entries);
86        if entries.is_empty() {
87            return Ok(None);
88        }
89        Ok(Some(Arc::new(Self {
90            config: config.clone(),
91            entries,
92            targets,
93        })))
94    }
95}
96
97#[async_trait]
98impl PlannedIndex for FulltextPlan {
99    fn kinds(&self) -> &[IndexKind] {
100        &[IndexKind::Fulltext]
101    }
102
103    fn entries(&self) -> &[PlanEntry] {
104        &self.entries
105    }
106
107    async fn build(
108        &self,
109        context: &BuildContext<'_>,
110    ) -> Result<Option<Box<dyn IndexCreator>>, BoxedError> {
111        FulltextIndexer::new_with_targets(
112            &context.metadata.region_id,
113            &context.output.file_id(),
114            context.intermediate_manager,
115            context.metadata,
116            self.config.compress,
117            self.config.mem_threshold_on_create(),
118            self.targets.clone(),
119        )
120        .await
121        .map(|creator| creator.map(|c| Box::new(c) as Box<dyn IndexCreator>))
122        .map_err(BoxedError::new)
123    }
124
125    fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool {
126        builtin_is_current(file, context)
127    }
128}
129
130#[async_trait]
131impl IndexCreator for FulltextIndexer {
132    async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> {
133        Self::update(self, batch).await.map_err(BoxedError::new)
134    }
135
136    async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> {
137        Self::update_flat(self, batch)
138            .await
139            .map_err(BoxedError::new)
140    }
141
142    async fn finish(
143        &mut self,
144        writer: &mut SstPuffinWriter,
145    ) -> Result<Vec<CompletedEntry>, BoxedError> {
146        let mut columns: Vec<_> = Self::indexed_targets(self)
147            .filter_map(column_target_id)
148            .map(Some)
149            .collect();
150        let bloom_columns: Vec<_> = self
151            .bloom_indexed_targets()
152            .filter_map(column_target_id)
153            .collect();
154        let (_, bytes) = Self::finish(self, writer).await.map_err(BoxedError::new)?;
155        if bytes == 0 {
156            return Ok(Vec::new());
157        }
158        if columns.is_empty() {
159            columns.push(None);
160        }
161        columns.sort_unstable();
162        columns.dedup();
163        Ok(columns
164            .into_iter()
165            .map(|column_id| CompletedEntry {
166                column_id,
167                kind: IndexKind::Fulltext,
168                format_version: if column_id.is_some_and(|id| bloom_columns.contains(&id)) {
169                    u32::from(fulltext_index::FULLTEXT_BLOOM_VERSION)
170                } else {
171                    0
172                },
173            })
174            .collect())
175    }
176
177    async fn abort(&mut self) -> Result<(), BoxedError> {
178        Self::abort(self).await.map_err(BoxedError::new)
179    }
180
181    fn memory_usage(&self) -> usize {
182        Self::memory_usage(self)
183    }
184
185    fn indexed_targets(&self) -> Vec<IndexTarget> {
186        Self::indexed_targets(self).cloned().collect()
187    }
188}