Skip to main content

mito2/sst/index/handler/builtin/
inverted.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 inverted index.
16
17use std::num::NonZeroUsize;
18use std::sync::Arc;
19
20use arrow_schema::extension::ExtensionType;
21use async_trait::async_trait;
22use common_error::ext::BoxedError;
23use common_telemetry::warn;
24use datatypes::arrow::record_batch::RecordBatch;
25use datatypes::extension::json::Json2ExtensionType;
26use index::target::IndexTarget;
27
28use crate::config::InvertedIndexConfig;
29use crate::read::Batch;
30use crate::sst::file::FileMeta;
31use crate::sst::index::handler::builtin::{
32    builtin_is_current, column_target_id, normalize_entries, target_column_id,
33};
34use crate::sst::index::handler::{
35    BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
36};
37use crate::sst::index::inverted_index::creator::InvertedIndexer;
38use crate::sst::index::kind::IndexKind;
39use crate::sst::index::puffin_manager::SstPuffinWriter;
40use crate::sst::index::{CompletedEntry, IndexBuildType};
41
42/// Resolved column targets and configuration shared across output files.
43#[derive(Debug)]
44pub(crate) struct InvertedPlan {
45    config: InvertedIndexConfig,
46    entries: Vec<PlanEntry>,
47    targets: Vec<IndexTarget>,
48    segment_row_count: NonZeroUsize,
49}
50
51impl InvertedPlan {
52    /// Resolves targets without opening SST data or creating output files.
53    pub(crate) fn plan(
54        config: &InvertedIndexConfig,
55        context: &PlanContext<'_>,
56    ) -> Result<Option<Arc<Self>>, BoxedError> {
57        let create = match context.build_type {
58            IndexBuildType::Flush => config.create_on_flush.auto(),
59            IndexBuildType::Compact => config.create_on_compaction.auto(),
60            _ => true,
61        };
62        if !create {
63            return Ok(None);
64        }
65        let mut targets: Vec<_> = context
66            .metadata
67            .inverted_indexed_column_ids(
68                context
69                    .index_options
70                    .inverted_index
71                    .ignore_column_ids
72                    .iter(),
73            )
74            .into_iter()
75            .map(IndexTarget::ColumnId)
76            .collect();
77        targets.extend(json_inverted_targets(context));
78        let Some(segment_row_count) =
79            NonZeroUsize::new(context.index_options.inverted_index.segment_row_count)
80        else {
81            warn!(
82                "Skip creating inverted index with zero segment row count, region_id: {}",
83                context.metadata.region_id
84            );
85            return Ok(None);
86        };
87        let mut entries: Vec<_> = targets
88            .iter()
89            .map(|target| PlanEntry {
90                column_id: target_column_id(target),
91                kind: IndexKind::Inverted,
92                format_version: 0,
93            })
94            .collect();
95        normalize_entries(&mut entries);
96        if entries.is_empty() {
97            return Ok(None);
98        }
99        Ok(Some(Arc::new(Self {
100            config: config.clone(),
101            entries,
102            targets,
103            segment_row_count,
104        })))
105    }
106}
107
108#[async_trait]
109impl PlannedIndex for InvertedPlan {
110    fn kinds(&self) -> &[IndexKind] {
111        &[IndexKind::Inverted]
112    }
113
114    fn entries(&self) -> &[PlanEntry] {
115        &self.entries
116    }
117
118    async fn build(
119        &self,
120        context: &BuildContext<'_>,
121    ) -> Result<Option<Box<dyn IndexCreator>>, BoxedError> {
122        // Segments may span row groups; readers split them at row group boundaries.
123        Ok(Some(Box::new(InvertedIndexer::new(
124            context.output.file_id(),
125            context.metadata,
126            context.intermediate_manager.clone(),
127            self.config.mem_threshold_on_create(),
128            self.segment_row_count,
129            self.targets.clone(),
130        ))))
131    }
132
133    fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool {
134        builtin_is_current(file, context)
135    }
136}
137
138fn json_inverted_targets(context: &PlanContext<'_>) -> Vec<IndexTarget> {
139    // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes.
140    if !matches!(
141        context.build_type,
142        IndexBuildType::Flush | IndexBuildType::Compact
143    ) {
144        return Vec::new();
145    }
146
147    let mut targets = Vec::new();
148    for column in &context.metadata.column_metadatas {
149        if !column.column_schema.data_type.is_json2() {
150            continue;
151        }
152        let Ok(Some(extension)) = column.column_schema.extension_type::<Json2ExtensionType>()
153        else {
154            continue;
155        };
156        for hint in extension.metadata().json_settings().type_hints() {
157            if !hint.inverted_index
158                || !(hint.data_type.is_numeric()
159                    || hint.data_type.is_boolean()
160                    || hint.data_type.is_string())
161            {
162                continue;
163            }
164            match IndexTarget::new_json_path(column.column_id, hint.path.clone()) {
165                Ok(target) => targets.push(target),
166                Err(err) => warn!(err; "Skipping invalid JSON inverted index target"),
167            }
168        }
169    }
170    targets
171}
172
173#[async_trait]
174impl IndexCreator for InvertedIndexer {
175    async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> {
176        Self::update(self, batch).await.map_err(BoxedError::new)
177    }
178
179    async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> {
180        Self::update_flat(self, batch)
181            .await
182            .map_err(BoxedError::new)
183    }
184
185    async fn finish(
186        &mut self,
187        writer: &mut SstPuffinWriter,
188    ) -> Result<Vec<CompletedEntry>, BoxedError> {
189        let mut columns: Vec<_> = Self::indexed_targets(self)
190            .filter_map(column_target_id)
191            .map(Some)
192            .collect();
193        let (_, bytes) = Self::finish(self, writer).await.map_err(BoxedError::new)?;
194        if bytes == 0 {
195            return Ok(Vec::new());
196        }
197        if columns.is_empty() {
198            columns.push(None);
199        }
200        columns.sort_unstable();
201        columns.dedup();
202        Ok(columns
203            .into_iter()
204            .map(|column_id| CompletedEntry {
205                column_id,
206                kind: IndexKind::Inverted,
207                format_version: 0,
208            })
209            .collect())
210    }
211
212    async fn abort(&mut self) -> Result<(), BoxedError> {
213        Self::abort(self).await.map_err(BoxedError::new)
214    }
215
216    fn memory_usage(&self) -> usize {
217        Self::memory_usage(self)
218    }
219
220    fn indexed_targets(&self) -> Vec<IndexTarget> {
221        Self::indexed_targets(self).cloned().collect()
222    }
223
224    fn needs_dense_pk(&self) -> bool {
225        true
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use datatypes::data_type::ConcreteDataType;
232    use datatypes::extension::json::JsonMetadata;
233    use datatypes::json::{JsonSettings, JsonTypeHint};
234    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
235
236    use super::*;
237    use crate::region::options::IndexOptions;
238    use crate::test_util::sst_util;
239
240    #[test]
241    fn test_json_inverted_plan_preserves_build_scope() {
242        let mut metadata = sst_util::sst_region_metadata();
243        let column = &mut metadata.column_metadatas[2].column_schema;
244        column.data_type = ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
245        column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new(
246            JsonSettings::try_new(
247                vec![JsonTypeHint {
248                    path: vec!["value".into()],
249                    data_type: ConcreteDataType::int64_datatype(),
250                    inverted_index: true,
251                    skipping_index: None,
252                    fulltext_index: None,
253                }],
254                Some(0),
255            )
256            .unwrap(),
257        ))));
258        let metadata = Arc::new(metadata);
259        let options = IndexOptions::default();
260        let config = InvertedIndexConfig::default();
261
262        for (build_type, expected_columns) in [
263            (IndexBuildType::Flush, vec![0, 2]),
264            (IndexBuildType::Compact, vec![0, 2]),
265            (IndexBuildType::Manual, vec![0]),
266            (IndexBuildType::SchemaChange, vec![0]),
267        ] {
268            let context = PlanContext {
269                metadata: &metadata,
270                index_options: &options,
271                build_type: build_type.clone(),
272                existing_indexes: &[],
273            };
274            let plan = InvertedPlan::plan(&config, &context).unwrap().unwrap();
275            let columns: Vec<_> = plan
276                .targets
277                .iter()
278                .map(|target| match target {
279                    IndexTarget::ColumnId(id) => *id,
280                    IndexTarget::JsonPath(path) => path.column_id(),
281                })
282                .collect();
283            assert_eq!(columns, expected_columns, "{build_type:?}");
284        }
285    }
286}