Skip to main content

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