diff --git a/Cargo.lock b/Cargo.lock index 6287647a518..be666357c5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1657,7 +1657,7 @@ dependencies = [ "maybe-owned", "rustix 1.0.7", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -6157,7 +6157,7 @@ dependencies = [ [[package]] name = "greptime-proto" version = "0.1.0" -source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=9eb24ddd94ddb9295bff9e596834832a7d8ba008#9eb24ddd94ddb9295bff9e596834832a7d8ba008" +source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=f5ab772b697b571e2c27b7d74fab98bac27046ae#f5ab772b697b571e2c27b7d74fab98bac27046ae" dependencies = [ "prost 0.14.1", "prost-types 0.14.1", @@ -6769,7 +6769,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.5.10", + "socket2 0.6.4", "tokio", "tower-service", "tracing", @@ -8030,7 +8030,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", - "windows-targets 0.53.5", + "windows-targets 0.48.5", ] [[package]] @@ -9332,7 +9332,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -11605,7 +11605,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1" dependencies = [ "heck 0.5.0", - "itertools 0.10.5", + "itertools 0.11.0", "log", "multimap", "once_cell", @@ -11653,7 +11653,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "syn 2.0.117", @@ -11666,7 +11666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "syn 2.0.117", @@ -13222,7 +13222,7 @@ dependencies = [ "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14146,7 +14146,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14717,7 +14717,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -15342,7 +15342,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.0.7", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a6f77b1e9de..f65afb1455a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,7 +164,7 @@ fs2 = "0.4" fst = "0.4.7" futures = "0.3" futures-util = "0.3" -greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "9eb24ddd94ddb9295bff9e596834832a7d8ba008" } +greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "f5ab772b697b571e2c27b7d74fab98bac27046ae" } hdfs-native = "0.14.6" hex = "0.4" hostname = "0.4.0" diff --git a/src/api/src/v1/column_def.rs b/src/api/src/v1/column_def.rs index b1d2f0841d5..a7fd7fe4ad4 100644 --- a/src/api/src/v1/column_def.rs +++ b/src/api/src/v1/column_def.rs @@ -280,6 +280,52 @@ pub fn as_skipping_index_type(skipping_index_type: PbSkippingIndexType) -> Skipp } } +/// Converts fulltext options for a JSON2 type hint to the wire representation. +pub fn json_fulltext_options_to_proto( + options: FulltextOptions, +) -> crate::v1::JsonFulltextIndexOptions { + crate::v1::JsonFulltextIndexOptions { + analyzer: match options.analyzer { + FulltextAnalyzer::English => Analyzer::English.into(), + FulltextAnalyzer::Chinese => Analyzer::Chinese.into(), + }, + case_sensitive: options.case_sensitive, + backend: match options.backend { + FulltextBackend::Bloom => PbFulltextBackend::Bloom.into(), + FulltextBackend::Tantivy => PbFulltextBackend::Tantivy.into(), + }, + granularity: options.granularity, + false_positive_rate: options.false_positive_rate(), + } +} + +/// Validates fulltext options received for a JSON2 type hint. +/// The presence of these options enables the fulltext index. +pub fn json_fulltext_options_from_proto( + options: crate::v1::JsonFulltextIndexOptions, +) -> datatypes::error::Result { + let analyzer = Analyzer::try_from(options.analyzer).map_err(|_| { + datatypes::error::InvalidFulltextOptionSnafu { + msg: format!("Unknown fulltext analyzer: {}", options.analyzer), + } + .build() + })?; + let backend = PbFulltextBackend::try_from(options.backend).map_err(|_| { + datatypes::error::InvalidFulltextOptionSnafu { + msg: format!("Unknown fulltext backend: {}", options.backend), + } + .build() + })?; + FulltextOptions::new( + true, + as_fulltext_option_analyzer(analyzer), + options.case_sensitive, + as_fulltext_option_backend(backend), + options.granularity, + options.false_positive_rate, + ) +} + /// Validates skipping options received for a JSON2 type hint. pub fn json_skipping_options_from_proto( options: crate::v1::JsonSkippingIndexOptions, @@ -299,7 +345,6 @@ pub fn json_skipping_options_from_proto( #[cfg(test)] mod tests { - use common_base::readable_size::ReadableSize; use datatypes::data_type::ConcreteDataType; use datatypes::schema::{CompressionOptions, FulltextAnalyzer, FulltextBackend}; @@ -307,6 +352,26 @@ mod tests { use super::*; use crate::v1::ColumnDataType; + #[test] + fn json_fulltext_options_roundtrip() { + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + let options = + FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05) + .unwrap(); + let wire = json_fulltext_options_to_proto(options.clone()); + assert_eq!(options, json_fulltext_options_from_proto(wire).unwrap()); + let mut invalid = wire; + invalid.backend = 99; + assert!(json_fulltext_options_from_proto(invalid).is_err()); + let mut invalid = wire; + invalid.analyzer = 99; + assert!(json_fulltext_options_from_proto(invalid).is_err()); + let mut invalid = wire; + invalid.granularity = 0; + assert!(json_fulltext_options_from_proto(invalid).is_err()); + } + } + #[test] fn test_try_as_column_schema() { let column_def = ColumnDef { diff --git a/src/common/function/src/scalars/matches.rs b/src/common/function/src/scalars/matches.rs index 109ad1daeb2..67abe944da2 100644 --- a/src/common/function/src/scalars/matches.rs +++ b/src/common/function/src/scalars/matches.rs @@ -23,7 +23,7 @@ use datafusion::common::{DFSchema, Result as DfResult}; use datafusion::execution::SessionStateBuilder; use datafusion::logical_expr::{self, ColumnarValue, Expr, Volatility}; use datafusion::physical_planner::{DefaultPhysicalPlanner, PhysicalPlanner}; -use datafusion_common::DataFusionError; +use datafusion_common::{DataFusionError, ScalarValue}; use datafusion_expr::physical_planning_context::PhysicalPlanningContext; use datafusion_expr::{ScalarFunctionArgs, Signature}; use datatypes::arrow::array::RecordBatch; @@ -101,14 +101,19 @@ impl Function for MatchesFunction { impl MatchesFunction { fn eval(&self, data_array: ArrayRef, pattern: &str) -> DfResult { + let data_type = data_array.data_type(); + if !data_type.is_string() { + return Err(DataFusionError::Execution(format!( + "unsupported datatype {data_type}" + ))); + } let col_name = "data"; let parser_context = ParserContext::default(); let raw_ast = parser_context.parse_pattern(pattern)?; let ast = raw_ast.transform_ast()?; - let like_expr = ast.into_like_expr(col_name); - - let input_schema = Self::input_schema(); + let like_expr = ast.into_like_expr(col_name, data_type); + let input_schema = Self::input_schema(data_type); let session_state = SessionStateBuilder::new().with_default_features().build(); let planner = DefaultPhysicalPlanner::default(); let physical_expr = planner.create_physical_expr( @@ -119,7 +124,7 @@ impl MatchesFunction { )?; let arrow_schema = Arc::new(input_schema.as_arrow().clone()); - let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array]).unwrap(); + let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array])?; let num_rows = input_record_batch.num_rows(); let result = physical_expr.evaluate(&input_record_batch)?; @@ -128,9 +133,9 @@ impl MatchesFunction { Ok(ColumnarValue::Array(Arc::new(result_array))) } - fn input_schema() -> DFSchema { + fn input_schema(data_type: &DataType) -> DFSchema { DFSchema::from_unqualified_fields( - [Arc::new(Field::new("data", DataType::Utf8, true))].into(), + [Arc::new(Field::new("data", data_type.clone(), true))].into(), HashMap::new(), ) .unwrap() @@ -165,10 +170,10 @@ enum BinaryOp { } impl PatternAst { - fn into_like_expr(self, column: &str) -> Expr { + fn into_like_expr(self, column: &str, data_type: &DataType) -> Expr { match self { PatternAst::Literal { op, pattern } => { - let expr = Self::convert_literal(column, &pattern); + let expr = Self::convert_literal(column, &pattern, data_type); match op { UnaryOp::Must => expr, UnaryOp::Optional => expr, @@ -181,7 +186,7 @@ impl PatternAst { } let exprs = children .into_iter() - .map(|child| child.into_like_expr(column)); + .map(|child| child.into_like_expr(column, data_type)); // safety: children is not empty match op { BinaryOp::And => exprs.reduce(Expr::and).unwrap(), @@ -189,7 +194,7 @@ impl PatternAst { } } PatternAst::Group { op, child } => { - let child = child.into_like_expr(column); + let child = child.into_like_expr(column, data_type); match op { UnaryOp::Must => child, UnaryOp::Optional => child, @@ -199,11 +204,14 @@ impl PatternAst { } } - fn convert_literal(column: &str, pattern: &str) -> Expr { - logical_expr::col(column).like(logical_expr::lit(format!( - "%{}%", - crate::utils::escape_like_pattern(pattern) - ))) + fn convert_literal(column: &str, pattern: &str, data_type: &DataType) -> Expr { + let pattern = Some(format!("%{}%", crate::utils::escape_like_pattern(pattern))); + let pattern = match data_type { + DataType::Utf8View => ScalarValue::Utf8View(pattern), + DataType::LargeUtf8 => ScalarValue::LargeUtf8(pattern), + _ => ScalarValue::Utf8(pattern), + }; + logical_expr::col(column).like(Expr::Literal(pattern, None)) } /// Transform this AST with preset rules to make it correct. @@ -836,7 +844,6 @@ impl Tokenizer { #[cfg(test)] mod test { use datafusion::arrow::array::StringArray; - use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; use super::*; @@ -1294,6 +1301,32 @@ mod test { } } + #[test] + fn evaluate_matches_string_layouts() { + let input: ArrayRef = Arc::new(StringArray::from(vec![ + Some("error timeout"), + Some("healthy"), + None, + ])); + let function = MatchesFunction::default(); + for data_type in [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View] { + let input = datatypes::arrow::compute::cast(&input, &data_type).unwrap(); + for (pattern, expected) in [ + ("error", vec![Some(true), Some(false), None]), + ("error AND timeout", vec![Some(true), Some(false), None]), + ("error OR healthy", vec![Some(true), Some(true), None]), + ] { + let expected: ArrayRef = Arc::new(BooleanArray::from(expected)); + let actual = function + .eval(input.clone(), pattern) + .unwrap() + .to_array(3) + .unwrap(); + assert_eq!(expected.as_ref(), actual.as_ref(), "{data_type}, {pattern}"); + } + } + } + #[test] fn evaluate_matches() { let input_data = vec![ diff --git a/src/common/grpc-expr/src/alter.rs b/src/common/grpc-expr/src/alter.rs index dda1d84015a..f92e1456c2a 100644 --- a/src/common/grpc-expr/src/alter.rs +++ b/src/common/grpc-expr/src/alter.rs @@ -17,6 +17,7 @@ use api::v1::add_column_location::LocationType; use api::v1::alter_table_expr::Kind; use api::v1::column_def::{ as_fulltext_option_analyzer, as_fulltext_option_backend, as_skipping_index_type, + json_fulltext_options_from_proto, }; use api::v1::{ AddColumnLocation as Location, AlterTableExpr, Analyzer, CreateTableExpr, DropColumns, @@ -75,6 +76,16 @@ fn json_settings_from_proto(settings: api::v1::JsonSettings) -> Result, + pub skipping_index: Option, + /// Optional fulltext configuration for a string path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fulltext_index: Option, } /// Specifies how encoding handles a value that does not match its JSON2 type hint. @@ -218,8 +222,24 @@ fn validate_type_hints(type_hints: &[JsonTypeHint]) -> Result<()> { let mut object = JsonObjectType::new(); for hint in type_hints { + if let Some(options) = &hint.fulltext_index { + if !hint.data_type.is_string() { + return InvalidJson2SettingsSnafu { + reason: "JSON2 FULLTEXT index only supports string type hints", + } + .fail(); + } + FulltextOptions::new( + options.enable, + options.analyzer.clone(), + options.case_sensitive, + options.backend.clone(), + options.granularity, + options.false_positive_rate(), + )?; + } if let Some(options) = &hint.skipping_index { - crate::schema::SkippingIndexOptions::new( + SkippingIndexOptions::new( options.granularity, options.false_positive_rate(), options.index_type.clone(), @@ -748,6 +768,28 @@ mod tests { &struct_value.items()[index] } + #[test] + fn test_fulltext_settings_roundtrip() { + let old = + r#"{"type_hints":[{"path":["message"],"type":{"String":{}},"inverted_index":false}]}"#; + let legacy: JsonSettings = serde_json::from_str(old).unwrap(); + assert!(legacy.type_hints()[0].fulltext_index.is_none()); + let mut hints = legacy.type_hints().to_vec(); + hints[0].fulltext_index = Some(crate::schema::FulltextOptions { + enable: true, + ..Default::default() + }); + let settings = JsonSettings::try_new(hints.clone(), Some(0)).unwrap(); + assert_eq!( + settings, + serde_json::from_str::(&serde_json::to_string(&settings).unwrap()) + .unwrap() + ); + assert!(!settings.equivalent(&legacy)); + hints[0].data_type = ConcreteDataType::int64_datatype(); + assert!(JsonSettings::try_new(hints, Some(0)).is_err()); + } + #[test] fn test_skipping_index_settings_roundtrip() { let old = r#"{"type_hints":[{"path":["service","name"],"type":{"String":{}},"inverted_index":true}]}"#; @@ -774,12 +816,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["count".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ]; let settings = JsonSettings::try_new(hints.clone(), Some(10))?; @@ -852,12 +896,14 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["user".to_string(), "name".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -874,12 +920,14 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["user".to_string(), "name".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ]; @@ -920,6 +968,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index, skipping_index: None, + fulltext_index: None, }; let serialized = json!({"type_hints": [hint.clone()]}); assert_eq!( @@ -955,6 +1004,7 @@ mod tests { data_type, inverted_index: false, skipping_index: None, + fulltext_index: None, }; assert!( JsonSettings::try_new( @@ -1019,6 +1069,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, )?; @@ -1050,12 +1101,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["to_int".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -1091,6 +1144,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, )?; @@ -1253,6 +1307,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }]; let settings = JsonSettings::try_new(type_hints, None)?; @@ -1286,6 +1341,7 @@ mod tests { data_type: ConcreteDataType::uint64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }]; let settings = JsonSettings::try_new(type_hints, None)?; @@ -1321,6 +1377,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }]; let settings = JsonSettings::try_new(type_hints, None)?; @@ -1347,6 +1404,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }]; let settings = JsonSettings::try_new(type_hints, None)?; @@ -1373,6 +1431,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }]; let settings = JsonSettings::try_new(type_hints, None)?; @@ -1388,12 +1447,14 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["user".to_string(), "name".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ]; let settings = JsonSettings::try_new(type_hints, None)?; diff --git a/src/datatypes/src/vectors/json/array.rs b/src/datatypes/src/vectors/json/array.rs index 48644ad5c58..6da59df5fde 100644 --- a/src/datatypes/src/vectors/json/array.rs +++ b/src/datatypes/src/vectors/json/array.rs @@ -644,6 +644,7 @@ mod test { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; diff --git a/src/datatypes/src/vectors/json/builder.rs b/src/datatypes/src/vectors/json/builder.rs index 515bd8ec3e5..cf6ce129c3d 100644 --- a/src/datatypes/src/vectors/json/builder.rs +++ b/src/datatypes/src/vectors/json/builder.rs @@ -1062,18 +1062,21 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["commit".to_string(), "operation".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["time_us".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], Some(0), @@ -1170,6 +1173,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(2), )?; @@ -1336,6 +1340,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(8), )?; diff --git a/src/mito2/src/cache/index/result_cache.rs b/src/mito2/src/cache/index/result_cache.rs index 75dd9794ef2..982aa4ece71 100644 --- a/src/mito2/src/cache/index/result_cache.rs +++ b/src/mito2/src/cache/index/result_cache.rs @@ -20,7 +20,7 @@ use index::inverted_index::search::predicate::{Predicate, RangePredicate}; use index::target::IndexTarget; use moka::notification::RemovalCause; use moka::sync::Cache; -use store_api::storage::{ColumnId, FileId}; +use store_api::storage::FileId; use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, CACHE_HIT, CACHE_MISS}; use crate::sst::index::fulltext_index::applier::builder::{ @@ -123,7 +123,7 @@ pub enum PredicateKey { impl PredicateKey { /// Creates a new fulltext index key. - pub fn new_fulltext(predicates: Arc>) -> Self { + pub fn new_fulltext(predicates: Arc>) -> Self { Self::Fulltext(FulltextIndexKey::new(predicates)) } @@ -156,17 +156,18 @@ impl PredicateKey { /// Key for fulltext index queries. #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] pub struct FulltextIndexKey { - predicates: Arc>, + predicates: Arc>, mem_usage: usize, } impl FulltextIndexKey { /// Creates a new fulltext index key with the given predicates. /// Calculates memory usage based on the size of queries and terms. - pub fn new(predicates: Arc>) -> Self { + pub fn new(predicates: Arc>) -> Self { let mem_usage = predicates - .values() - .map(|request| { + .iter() + .map(|(target, request)| { + let target_size = target.approx_mem_size(); let query_size = request .queries .iter() @@ -182,7 +183,7 @@ impl FulltextIndexKey { .iter() .map(|like| like.pattern.len() + size_of::()) .sum::(); - query_size + term_size + like_size + target_size + query_size + term_size + like_size }) .sum(); Self { @@ -377,7 +378,7 @@ mod tests { terms: vec![], likes: vec![], }; - predicates1.insert(1, request1); + predicates1.insert(IndexTarget::ColumnId(1), request1); let key1 = PredicateKey::new_fulltext(Arc::new(predicates1)); let selection1 = Arc::new(RowGroupSelection::default()); @@ -392,7 +393,7 @@ mod tests { terms: vec![], likes: vec![], }; - predicates2.insert(1, request2); + predicates2.insert(IndexTarget::ColumnId(1), request2); let key2 = PredicateKey::new_fulltext(Arc::new(predicates2)); let selection2 = Arc::new(RowGroupSelection::default()); @@ -463,7 +464,7 @@ mod tests { }], likes: vec![], }; - predicates1.insert(1, request1); + predicates1.insert(IndexTarget::ColumnId(1), request1); let key1 = PredicateKey::new_fulltext(Arc::new(predicates1)); let selection1 = Arc::new(RowGroupSelection::new(100, 250)); let weight1 = diff --git a/src/mito2/src/compaction/json2.rs b/src/mito2/src/compaction/json2.rs index faa7eb6c434..cc73d93704d 100644 --- a/src/mito2/src/compaction/json2.rs +++ b/src/mito2/src/compaction/json2.rs @@ -284,6 +284,7 @@ fn select_dynamic_hints( data_type: ConcreteDataType::from_arrow_type(&stat.data_type.as_arrow_type()), inverted_index: false, skipping_index: None, + fulltext_index: None, }) .collect() } @@ -380,6 +381,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(2), )?; @@ -437,6 +439,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -492,6 +495,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -513,12 +517,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["source_only".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -586,6 +592,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -596,12 +603,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["promoted".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], Some(0), diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs index f1a1bb36eec..11829dcca2e 100644 --- a/src/mito2/src/compaction/multi_region/tests.rs +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -1008,6 +1008,7 @@ fn json2_hint(path: &str, data_type: ConcreteDataType) -> JsonTypeHint { data_type, inverted_index: false, skipping_index: None, + fulltext_index: None, } } diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index e1de64c1122..ef7e89171ea 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -2054,6 +2054,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 881a72ead83..eb95a5ffedd 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -655,6 +655,7 @@ impl IndexerBuilderImpl { &self.metadata, self.fulltext_index_config.compress, mem_limit, + self.build_type.clone(), ) .await; diff --git a/src/mito2/src/sst/index/bloom_filter/applier.rs b/src/mito2/src/sst/index/bloom_filter/applier.rs index 0f97e89a0fa..82ec09dd718 100644 --- a/src/mito2/src/sst/index/bloom_filter/applier.rs +++ b/src/mito2/src/sst/index/bloom_filter/applier.rs @@ -47,6 +47,7 @@ use crate::metrics::INDEX_APPLY_ELAPSED; use crate::sst::file::RegionIndexId; use crate::sst::index::bloom_filter::INDEX_BLOB_TYPE; pub use crate::sst::index::bloom_filter::applier::builder::BloomFilterIndexApplierBuilder; +use crate::sst::index::column::skipping_target_data_type; use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory}; use crate::sst::index::{TYPE_BLOOM_FILTER_INDEX, trigger_index_background_download}; @@ -232,9 +233,9 @@ impl BloomFilterIndexApplier { .map(|(i, range)| (*i, vec![range.clone()])) .collect::>(); - for (column_id, predicates) in predicates { + for (target, predicates) in predicates { let blob = match self - .blob_reader(file_id, column_id, file_size_hint, metrics.as_deref_mut()) + .blob_reader(file_id, target, file_size_hint, metrics.as_deref_mut()) .await? { Some(blob) => blob, @@ -250,7 +251,7 @@ impl BloomFilterIndexApplier { let reader = CachedBloomFilterIndexBlobReader::new( file_id.file_id(), file_id.version, - column_id.clone(), + target.clone(), Tag::Skipping, blob_size, BloomFilterReaderImpl::new(blob), @@ -291,16 +292,16 @@ impl BloomFilterIndexApplier { /// Creates a blob reader from the cached or remote index file. /// - /// Returus `None` if the column does not have an index. + /// Returns `None` if the target does not have an index. async fn blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, metrics: Option<&mut BloomFilterIndexApplyMetrics>, ) -> Result> { let reader = match self - .cached_blob_reader(file_id, column_id, file_size_hint) + .cached_blob_reader(file_id, target, file_size_hint) .await { Ok(Some(puffin_reader)) => puffin_reader, @@ -309,17 +310,17 @@ impl BloomFilterIndexApplier { m.blob_cache_miss += 1; } if let Err(err) = other { - // Blob not found means no index for this column + // Blob not found means no index for this target. if is_blob_not_found(&err) { return Ok(None); } warn!(err; "An unexpected error occurred while reading the cached index file. Fallback to remote index file.") } let res = self - .remote_blob_reader(file_id, column_id, file_size_hint) + .remote_blob_reader(file_id, target, file_size_hint) .await; if let Err(err) = res { - // Blob not found means no index for this column + // Blob not found means no index for this target. if is_blob_not_found(&err) { return Ok(None); } @@ -337,7 +338,7 @@ impl BloomFilterIndexApplier { async fn cached_blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, ) -> Result> { let Some(file_cache) = &self.file_cache else { @@ -357,7 +358,7 @@ impl BloomFilterIndexApplier { file_cache.local_store(), WriteCachePathProvider::new(file_cache.clone()), ); - let blob_name = Self::target_blob_name(column_id); + let blob_name = Self::target_blob_name(target); let reader = puffin_manager .reader(&file_id) @@ -374,8 +375,8 @@ impl BloomFilterIndexApplier { } // TODO(ruihang): use the same util with the code in creator - fn target_blob_name(column_id: &IndexTarget) -> String { - let target_key = column_id.encode(); + fn target_blob_name(target: &IndexTarget) -> String { + let target_key = target.encode(); format!("{INDEX_BLOB_TYPE}-{target_key}") } @@ -383,7 +384,7 @@ impl BloomFilterIndexApplier { async fn remote_blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, ) -> Result { let path_factory = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type); @@ -402,7 +403,7 @@ impl BloomFilterIndexApplier { .build(self.object_store.clone(), path_factory) .with_puffin_metadata_cache(self.puffin_metadata_cache.clone()); - let blob_name = Self::target_blob_name(column_id); + let blob_name = Self::target_blob_name(target); puffin_manager .reader(&file_id) @@ -440,19 +441,17 @@ impl BloomFilterIndexApplier { sst_metadata: &RegionMetadataRef, ) -> Option>>> { let mut has_type_mismatch = false; - let mut compatible_col_ids = Vec::new(); + let mut compatible_targets = Vec::new(); - for (col_id, expected) in &self.expected_predicate_target_types { - if crate::sst::index::column::skipping_target_data_type(sst_metadata, col_id).as_ref() - != Some(expected) - { + for (target, expected) in &self.expected_predicate_target_types { + if skipping_target_data_type(sst_metadata, target).as_ref() != Some(expected) { has_type_mismatch = true; continue; } - compatible_col_ids.push(col_id.clone()); + compatible_targets.push(target.clone()); } - if compatible_col_ids.is_empty() { + if compatible_targets.is_empty() { return None; } @@ -461,9 +460,9 @@ impl BloomFilterIndexApplier { } let mut compatible_predicates = BTreeMap::new(); - for col_id in compatible_col_ids { - if let Some(predicates) = self.default_predicates.get(&col_id) { - compatible_predicates.insert(col_id, predicates.clone()); + for target in compatible_targets { + if let Some(predicates) = self.default_predicates.get(&target) { + compatible_predicates.insert(target, predicates.clone()); } } @@ -531,6 +530,7 @@ mod tests { path: vec!["value".into()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, + fulltext_index: None, skipping_index: Some( SkippingIndexOptions::new(2, 0.01, Default::default()).unwrap(), ), diff --git a/src/mito2/src/sst/index/bloom_filter/applier/builder.rs b/src/mito2/src/sst/index/bloom_filter/applier/builder.rs index 29012c951f8..97e9e96d5af 100644 --- a/src/mito2/src/sst/index/bloom_filter/applier/builder.rs +++ b/src/mito2/src/sst/index/bloom_filter/applier/builder.rs @@ -35,6 +35,7 @@ use crate::cache::file_cache::FileCacheRef; use crate::cache::index::bloom_filter_index::BloomFilterIndexCacheRef; use crate::error::{ColumnNotFoundSnafu, ConvertValueSnafu, EncodeSnafu, Result}; use crate::sst::index::bloom_filter::applier::BloomFilterIndexApplier; +use crate::sst::index::column::{json_index_target, skipping_target_data_type}; use crate::sst::index::puffin_manager::PuffinManagerFactory; pub struct BloomFilterIndexApplierBuilder<'a> { @@ -143,15 +144,14 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { fn expected_predicate_target_types(&self) -> BTreeMap { self.predicates .keys() - .filter_map(|col_id| { - let ty = - crate::sst::index::column::skipping_target_data_type(self.metadata, col_id)?; - Some((col_id.clone(), ty)) + .filter_map(|target| { + let ty = skipping_target_data_type(self.metadata, target)?; + Some((target.clone(), ty)) }) .collect() } - /// Helper function to get the column id and type + /// Returns a column target and its type. fn column_target_and_type( &self, column_name: &str, @@ -173,9 +173,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if let Expr::Column(column) = expr { return self.column_target_and_type(&column.name); } - crate::sst::index::column::json_index_target(self.metadata, expr, |hint| { - hint.skipping_index.is_some() - }) + json_index_target(self.metadata, expr, |hint| hint.skipping_index.is_some()) } /// Collects an equality expression (column = value) @@ -186,12 +184,12 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if lit.is_null() { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(col)? else { + let Some((target, data_type)) = self.expr_to_index_target(col)? else { return Ok(()); }; let value = encode_lit(lit, data_type)?; self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: BTreeSet::from([value]), @@ -206,7 +204,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(&in_list.expr)? else { + let Some((target, data_type)) = self.expr_to_index_target(&in_list.expr)? else { return Ok(()); }; @@ -222,7 +220,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if !valid_predicates.is_empty() { self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: valid_predicates, @@ -258,7 +256,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if lit.is_null() { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(col)? else { + let Some((target, data_type)) = self.expr_to_index_target(col)? else { return Ok(()); }; @@ -266,7 +264,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { inlist.insert(encode_lit(lit, data_type.clone())?); if Self::collect_or_eq_list_rec(col, &data_type, or_list, &mut inlist)? { self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: inlist }); } diff --git a/src/mito2/src/sst/index/column.rs b/src/mito2/src/sst/index/column.rs index ea1993fc33c..b892cd4436c 100644 --- a/src/mito2/src/sst/index/column.rs +++ b/src/mito2/src/sst/index/column.rs @@ -20,13 +20,15 @@ use datatypes::arrow::array::{Array, ArrayRef, StructArray}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::data_type::{ConcreteDataType, DataType}; use datatypes::extension::json::Json2ExtensionType; +use datatypes::json::JsonTypeHint; +use datatypes::schema::FulltextOptions; use datatypes::vectors::{Helper, VectorRef}; use index::target::IndexTarget; use snafu::{OptionExt, ResultExt}; use store_api::metadata::RegionMetadata; use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME; -use crate::error::{ConvertVectorSnafu, InvalidRecordBatchSnafu, Result}; +use crate::error::{ConvertVectorSnafu, IndexOptionsSnafu, InvalidRecordBatchSnafu, Result}; use crate::sst::parquet::format::PrimaryKeyArray; /// Extracts leaf values for a JSON type hint at the given path. @@ -94,7 +96,7 @@ pub(crate) fn column_index_rows( pub(crate) fn json_index_target( metadata: &RegionMetadata, expr: &Expr, - enabled: impl Fn(&datatypes::json::JsonTypeHint) -> bool, + enabled: impl Fn(&JsonTypeHint) -> bool, ) -> Result> { let Expr::ScalarFunction(func) = expr else { return Ok(None); @@ -193,6 +195,54 @@ pub(crate) fn skipping_target_data_type( .map(|hint| hint.data_type.clone()) } +/// Resolves enabled fulltext options using a column or string hint's metadata. +pub(crate) fn fulltext_target_options( + metadata: &RegionMetadata, + target: &IndexTarget, +) -> Result> { + let path = match target { + IndexTarget::ColumnId(id) => { + let Some(column) = metadata.column_by_id(*id) else { + return Ok(None); + }; + if !column.column_schema.data_type.is_string() { + return Ok(None); + } + return column + .column_schema + .fulltext_options() + .with_context(|_| IndexOptionsSnafu { + column_name: &column.column_schema.name, + }) + .map(|options| options.filter(|options| options.enable)); + } + IndexTarget::JsonPath(path) => path, + }; + let Some(column) = metadata.column_by_id(path.column_id()) else { + return Ok(None); + }; + if !column.column_schema.data_type.is_json2() { + return Ok(None); + } + let Some(extension) = column + .column_schema + .extension_type::() + .with_context(|_| IndexOptionsSnafu { + column_name: &column.column_schema.name, + })? + else { + return Ok(None); + }; + Ok(extension + .metadata() + .json_settings() + .type_hints() + .iter() + .find(|hint| hint.path == path.path() && hint.data_type.is_string()) + .and_then(|hint| hint.fulltext_index.clone()) + .filter(|options| options.enable)) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -200,10 +250,49 @@ mod tests { use datatypes::arrow::array::{Int64Array, NullArray}; use datatypes::arrow::buffer::NullBuffer; use datatypes::arrow::datatypes::Field; + use datatypes::schema::{ColumnSchema, FulltextOptions}; use datatypes::value::Value; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; use super::*; + #[test] + fn test_fulltext_target_options_requires_string_column() { + let options = FulltextOptions { + enable: true, + ..Default::default() + }; + for data_type in [ + ConcreteDataType::string_datatype(), + ConcreteDataType::int64_datatype(), + ] { + let expected = data_type.is_string().then_some(options.clone()); + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("value", data_type, true) + .with_fulltext_options(options.clone()) + .unwrap(), + column_id: 1, + semantic_type: SemanticType::Field, + }); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + column_id: 2, + semantic_type: SemanticType::Timestamp, + }); + let metadata = builder.build().unwrap(); + assert_eq!( + fulltext_target_options(&metadata, &IndexTarget::ColumnId(1)).unwrap(), + expected + ); + } + } + #[test] fn test_extract_json_type_hint_values_null_type() { let nulls: ArrayRef = Arc::new(NullArray::new(2)); diff --git a/src/mito2/src/sst/index/fulltext_index/applier.rs b/src/mito2/src/sst/index/fulltext_index/applier.rs index 792c6319f85..1b4fe7fc3d2 100644 --- a/src/mito2/src/sst/index/fulltext_index/applier.rs +++ b/src/mito2/src/sst/index/fulltext_index/applier.rs @@ -21,6 +21,7 @@ use std::time::Instant; use common_base::range_read::RangeReader; use common_base::term_token::{extract_like_probes, extract_term_probes}; use common_telemetry::{tracing, warn}; +use datatypes::schema::{FulltextBackend, FulltextOptions}; use index::bloom_filter::applier::{BloomFilterApplier, InListPredicate}; use index::bloom_filter::reader::{BloomFilterReadMetrics, BloomFilterReaderImpl}; use index::fulltext_index::Config; @@ -30,21 +31,21 @@ use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; use puffin::puffin_manager::{GuardWithMetadata, PuffinManager, PuffinReader}; use snafu::ResultExt; +use store_api::metadata::RegionMetadata; use store_api::region_request::PathType; -use store_api::storage::ColumnId; use crate::access_layer::{RegionFilePathFactory, WriteCachePathProvider}; use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey}; use crate::cache::index::bloom_filter_index::{ BloomFilterIndexCacheRef, CachedBloomFilterIndexBlobReader, Tag, }; -use crate::cache::index::result_cache::PredicateKey; use crate::error::{ ApplyBloomFilterIndexSnafu, ApplyFulltextIndexSnafu, MetadataSnafu, PuffinBuildReaderSnafu, PuffinReadBlobSnafu, Result, }; use crate::metrics::INDEX_APPLY_ELAPSED; use crate::sst::file::RegionIndexId; +use crate::sst::index::column::fulltext_target_options; use crate::sst::index::fulltext_index::applier::builder::FulltextRequest; use crate::sst::index::fulltext_index::{INDEX_BLOB_TYPE_BLOOM, INDEX_BLOB_TYPE_TANTIVY}; use crate::sst::index::puffin_manager::{ @@ -146,16 +147,16 @@ impl FulltextIndexApplyMetrics { /// `FulltextIndexApplier` is responsible for applying fulltext index to the provided SST files pub struct FulltextIndexApplier { /// Requests to be applied. - requests: Arc>, + requests: Arc>, + + /// Expected fulltext settings from the current schema. + expected_options: BTreeMap, /// The source of the index. index_source: IndexSource, /// Cache for bloom filter index. bloom_filter_index_cache: Option, - - /// Predicate key. Used to identify the predicate and fetch result from cache. - predicate_key: PredicateKey, } pub type FulltextIndexApplierRef = Arc; @@ -166,20 +167,56 @@ impl FulltextIndexApplier { table_dir: String, path_type: PathType, store: ObjectStore, - requests: BTreeMap, + requests: BTreeMap, puffin_manager_factory: PuffinManagerFactory, + metadata: &RegionMetadata, ) -> Self { + let expected_options = requests + .keys() + .filter_map(|target| { + fulltext_target_options(metadata, target) + .inspect_err(|err| warn!(err; "Failed to resolve expected fulltext options for {target:?}")) + .ok() + .flatten() + .map(|options| (target.clone(), options)) + }) + .collect(); let requests = Arc::new(requests); let index_source = IndexSource::new(table_dir, path_type, puffin_manager_factory, store); Self { - predicate_key: PredicateKey::new_fulltext(requests.clone()), requests, + expected_options, index_source, bloom_filter_index_cache: None, } } + /// Keeps ordinary string columns and JSON paths with compatible saved fulltext settings. + /// Returns `None` when no compatible request remains for this SST. + pub fn compatible_requests_for_sst( + &self, + metadata: &RegionMetadata, + ) -> Option>> { + if self + .requests + .keys() + .all(|target| self.is_target_compatible(metadata, target)) + { + return Some(self.requests.clone()); + } + let requests: BTreeMap<_, _> = self + .requests + .iter() + .filter(|(target, _)| self.is_target_compatible(metadata, target)) + .map(|(target, request)| (target.clone(), request.clone())) + .collect(); + if requests.is_empty() { + return None; + } + Some(Arc::new(requests)) + } + /// Sets the file cache. pub fn with_file_cache(mut self, file_cache: Option) -> Self { self.index_source.set_file_cache(file_cache); @@ -205,9 +242,28 @@ impl FulltextIndexApplier { self } - /// Returns the predicate key. - pub fn predicate_key(&self) -> &PredicateKey { - &self.predicate_key + fn is_target_compatible(&self, metadata: &RegionMetadata, target: &IndexTarget) -> bool { + let Some(expected) = self.expected_options.get(target) else { + return false; + }; + if let IndexTarget::ColumnId(id) = target { + // Rebuilding an ordinary column's index does not update Parquet metadata. + // Check only its type here; index readers use the actual blob's config. + return metadata + .column_by_id(*id) + .is_some_and(|column| column.column_schema.data_type.is_string()); + } + let Some(actual) = fulltext_target_options(metadata, target) + .inspect_err(|err| warn!(err; "Failed to resolve SST fulltext options for {target:?}")) + .ok() + .flatten() + else { + return false; + }; + // JSON path hints can change backend, case sensitivity, and analyzer. + expected.backend == actual.backend + && expected.case_sensitive == actual.case_sensitive + && (expected.backend == FulltextBackend::Bloom || expected.analyzer == actual.analyzer) } } @@ -218,6 +274,7 @@ impl FulltextIndexApplier { /// # Arguments /// * `file_id` - The region file ID to apply predicates to /// * `file_size_hint` - Optional hint for file size to avoid extra metadata reads + /// * `requests` - Compatible requests for this SST /// * `metrics` - Optional mutable reference to collect metrics on demand #[tracing::instrument( skip_all, @@ -227,12 +284,13 @@ impl FulltextIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, + requests: &BTreeMap, mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>> { let apply_start = Instant::now(); let mut row_ids: Option> = None; - for (column_id, request) in self.requests.iter() { + for (target, request) in requests.iter() { // Tantivy tokens don't follow `matches_term` boundaries, e.g. `SimpleTokenizer` // keeps "错误error日志" as one token, so terms and patterns are left to the // bloom backend. @@ -244,7 +302,7 @@ impl FulltextIndexApplier { .apply_fine_one_column( file_size_hint, file_id, - *column_id, + target, request, metrics.as_deref_mut(), ) @@ -283,11 +341,11 @@ impl FulltextIndexApplier { &self, file_size_hint: Option, file_id: RegionIndexId, - column_id: ColumnId, + target: &IndexTarget, request: &FulltextRequest, metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>> { - let target_key = IndexTarget::ColumnId(column_id).encode(); + let target_key = target.encode(); let blob_key = format!("{INDEX_BLOB_TYPE_TANTIVY}-{target_key}"); let dir = self .index_source @@ -342,6 +400,7 @@ impl FulltextIndexApplier { /// * `file_id` - The region file ID to apply predicates to /// * `file_size_hint` - Optional hint for file size to avoid extra metadata reads /// * `row_groups` - Iterator of row group lengths and whether to search in the row group + /// * `requests` - Compatible requests for this SST /// * `metrics` - Optional mutable reference to collect metrics on demand #[allow(clippy::type_complexity)] #[tracing::instrument( @@ -353,6 +412,7 @@ impl FulltextIndexApplier { file_id: RegionIndexId, file_size_hint: Option, row_groups: impl Iterator, + requests: &BTreeMap, mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>)>>> { let apply_start = Instant::now(); @@ -360,7 +420,7 @@ impl FulltextIndexApplier { let (input, mut output) = Self::init_coarse_output(row_groups); let mut applied = false; - for (column_id, request) in self.requests.iter() { + for (target, request) in requests.iter() { if request.terms.is_empty() && request.likes.is_empty() { continue; } @@ -369,7 +429,7 @@ impl FulltextIndexApplier { .apply_coarse_one_column( file_id, file_size_hint, - *column_id, + target, request, &mut output, metrics.as_deref_mut(), @@ -400,12 +460,12 @@ impl FulltextIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, - column_id: ColumnId, + target: &IndexTarget, request: &FulltextRequest, output: &mut [(usize, Vec>)], mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result { - let target_key = IndexTarget::ColumnId(column_id).encode(); + let target_key = target.encode(); let blob_key = format!("{INDEX_BLOB_TYPE_BLOOM}-{target_key}"); let Some(reader) = self .index_source @@ -432,7 +492,7 @@ impl FulltextIndexApplier { let reader = CachedBloomFilterIndexBlobReader::new( file_id.file_id(), file_id.version, - IndexTarget::ColumnId(column_id), + target.clone(), Tag::Fulltext, blob_size, BloomFilterReaderImpl::new(range_reader), @@ -542,6 +602,7 @@ impl FulltextIndexApplier { } /// The source of the index. +#[derive(Clone)] struct IndexSource { table_dir: String, @@ -755,17 +816,159 @@ impl IndexSource { #[cfg(test)] mod tests { + use api::v1::SemanticType; use common_function::scalars::matches_term::MatchesTermFinder; use datatypes::arrow::array::{Scalar, StringArray}; use datatypes::arrow::compute::kernels::comparison::like; + use datatypes::data_type::ConcreteDataType; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::{JsonSettings, JsonTypeHint}; + use datatypes::schema::{ColumnSchema, FulltextAnalyzer}; use index::fulltext_index::Analyzer; use index::fulltext_index::tokenizer::{self, ScriptTokenizer}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; use super::*; + use crate::cache::index::result_cache::PredicateKey; use crate::sst::index::fulltext_index::applier::builder::{FulltextLike, FulltextTerm}; + #[test] + fn test_json_fulltext_sst_compatibility() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_block("json_fulltext_plan"); + let ordinary = IndexTarget::ColumnId(1); + let path = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + let other = IndexTarget::new_json_path(3, vec!["other".into()]).unwrap(); + let missing = IndexTarget::new_json_path(3, vec!["missing".into()]).unwrap(); + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + let options = FulltextOptions { + enable: true, + backend: backend.clone(), + ..Default::default() + }; + let metadata = json_metadata(Some(options.clone())); + let requests = BTreeMap::from([ + (ordinary.clone(), FulltextRequest::default()), + (path.clone(), FulltextRequest::default()), + (other.clone(), FulltextRequest::default()), + ]); + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + requests, + factory.clone(), + &metadata, + ); + let unchanged = applier.compatible_requests_for_sst(&metadata).unwrap(); + assert!(Arc::ptr_eq(&unchanged, &applier.requests)); + for name in [ + "granularity", + "false_positive_rate", + "analyzer", + "case_sensitive", + "backend", + "disabled", + "missing", + ] { + let mut changed = options.clone(); + match name { + "granularity" => changed.granularity += 1, + "false_positive_rate" => changed.false_positive_rate_in_10000 += 1, + "analyzer" => changed.analyzer = FulltextAnalyzer::Chinese, + "case_sensitive" => changed.case_sensitive = true, + "backend" => { + changed.backend = if backend == FulltextBackend::Bloom { + FulltextBackend::Tantivy + } else { + FulltextBackend::Bloom + }; + } + "disabled" => changed.enable = false, + "missing" => {} + _ => unreachable!(), + } + let compatible = matches!(name, "granularity" | "false_positive_rate") + || (name == "analyzer" && backend == FulltextBackend::Bloom); + let sst = json_metadata((name != "missing").then_some(changed)); + let requests = applier.compatible_requests_for_sst(&sst).unwrap(); + assert!(requests.contains_key(&ordinary)); + assert!(requests.contains_key(&other)); + assert_eq!( + requests.contains_key(&path), + compatible, + "{backend:?}, {name}" + ); + assert_eq!(Arc::ptr_eq(&requests, &applier.requests), compatible); + assert_eq!( + PredicateKey::new_fulltext(requests) + == PredicateKey::new_fulltext(applier.requests.clone()), + compatible, + ); + } + // An unresolved query-side target must not become compatible merely + // because the expected options map has no entry for it. + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(missing.clone(), FulltextRequest::default())]), + factory.clone(), + &metadata, + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_none()); + // Missing current options are also fail-closed even if the SST has them. + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(path.clone(), FulltextRequest::default())]), + factory.clone(), + &json_metadata(None), + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_none()); + } + } + + #[test] + fn test_ordinary_fulltext_sst_compatibility() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_block("ordinary_fulltext_plan"); + let metadata = mock_metadata_with_fulltext(FulltextBackend::Bloom); + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(IndexTarget::ColumnId(1), FulltextRequest::default())]), + factory, + &metadata, + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_some()); + assert!( + applier + .compatible_requests_for_sst(&mock_metadata_with_fulltext(FulltextBackend::Tantivy)) + .is_some() + ); + let mut non_string = metadata.clone(); + non_string.column_metadatas[0].column_schema.data_type = ConcreteDataType::int64_datatype(); + assert!(applier.compatible_requests_for_sst(&non_string).is_none()); + assert!( + applier + .compatible_requests_for_sst(&mock_metadata_without_fulltext()) + .is_some() + ); + let mut disabled = metadata.clone(); + disabled.column_metadatas[0] + .column_schema + .set_fulltext_options(&FulltextOptions { + enable: false, + ..Default::default() + }) + .unwrap(); + assert!(applier.compatible_requests_for_sst(&disabled).is_some()); + } + /// A `matches_term` or `LIKE` predicate on `col`, or on `lower(col)` when `lowered`. enum Predicate<'a> { Term(&'a str), @@ -995,4 +1198,78 @@ mod tests { } } } + pub(crate) fn json_metadata(options: Option) -> RegionMetadata { + let mut builder = RegionMetadataBuilder::from_existing(mock_metadata_with_fulltext( + FulltextBackend::Bloom, + )); + let mut column = + ColumnSchema::new("attrs", ConcreteDataType::json2(Default::default()), true); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + JsonSettings::try_new( + vec![ + JsonTypeHint { + path: vec!["message".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: options, + }, + JsonTypeHint { + path: vec!["other".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: Some(FulltextOptions { + enable: true, + ..Default::default() + }), + }, + ], + Some(0), + ) + .unwrap(), + )))); + builder.push_column_metadata(ColumnMetadata { + column_schema: column, + semantic_type: SemanticType::Field, + column_id: 3, + }); + builder.build().unwrap() + } + + pub(crate) fn mock_metadata_without_fulltext() -> RegionMetadata { + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Field, + column_id: 1, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }); + + builder.build().unwrap() + } + + pub(crate) fn mock_metadata_with_fulltext(backend: FulltextBackend) -> RegionMetadata { + let mut metadata = mock_metadata_without_fulltext(); + metadata.column_metadatas[0] + .column_schema + .set_fulltext_options(&FulltextOptions { + enable: true, + backend, + ..Default::default() + }) + .unwrap(); + RegionMetadataBuilder::from_existing(metadata) + .build() + .unwrap() + } } diff --git a/src/mito2/src/sst/index/fulltext_index/applier/builder.rs b/src/mito2/src/sst/index/fulltext_index/applier/builder.rs index 23122bc5416..ee3fe243f72 100644 --- a/src/mito2/src/sst/index/fulltext_index/applier/builder.rs +++ b/src/mito2/src/sst/index/fulltext_index/applier/builder.rs @@ -15,19 +15,21 @@ use std::collections::BTreeMap; use common_base::term_token::extract_like_probes; +use common_telemetry::warn; use datafusion_common::ScalarValue; use datafusion_expr::expr::{Like, ScalarFunction}; use datafusion_expr::{BinaryExpr, Expr, Operator}; use datatypes::schema::FulltextBackend; +use index::target::IndexTarget; use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; use store_api::metadata::RegionMetadata; use store_api::region_request::PathType; -use store_api::storage::{ColumnId, ConcreteDataType}; use crate::cache::file_cache::FileCacheRef; use crate::cache::index::bloom_filter_index::BloomFilterIndexCacheRef; use crate::error::Result; +use crate::sst::index::column::{fulltext_target_options, json_index_target}; use crate::sst::index::fulltext_index::applier::FulltextIndexApplier; use crate::sst::index::puffin_manager::PuffinManagerFactory; @@ -143,6 +145,7 @@ impl<'a> FulltextIndexApplierBuilder<'a> { self.store, requests, self.puffin_manager_factory, + self.metadata, ) .with_file_cache(self.file_cache) .with_puffin_metadata_cache(self.puffin_metadata_cache) @@ -153,135 +156,132 @@ impl<'a> FulltextIndexApplierBuilder<'a> { fn extract_requests( expr: &Expr, metadata: &'a RegionMetadata, - requests: &mut BTreeMap, + requests: &mut BTreeMap, ) { + if let Expr::BinaryExpr(BinaryExpr { + left, + op: Operator::And, + right, + }) = expr + { + Self::extract_requests(left, metadata, requests); + Self::extract_requests(right, metadata, requests); + return; + } + if let Err(err) = Self::extract_request(expr, metadata, requests) { + warn!(err; "Failed to extract fulltext index predicate from {expr}"); + } + } + + fn extract_request( + expr: &Expr, + metadata: &RegionMetadata, + requests: &mut BTreeMap, + ) -> Result<()> { match expr { - Expr::BinaryExpr(BinaryExpr { - left, - op: Operator::And, - right, - }) => { - Self::extract_requests(left, metadata, requests); - Self::extract_requests(right, metadata, requests); - } Expr::Like(like) => { - if let Some((column_id, like)) = Self::expr_to_like(metadata, like) { - requests.entry(column_id).or_default().likes.push(like); + if let Some((target, like)) = Self::expr_to_like(metadata, like)? { + requests.entry(target).or_default().likes.push(like); } } Expr::ScalarFunction(func) => { - if let Some((column_id, query)) = Self::expr_to_query(metadata, func) { - requests.entry(column_id).or_default().queries.push(query); - } else if let Some((column_id, term)) = Self::expr_to_term(metadata, func) { - requests.entry(column_id).or_default().terms.push(term); + if let Some((target, query)) = Self::expr_to_query(metadata, func)? { + requests.entry(target).or_default().queries.push(query); + } else if let Some((target, term)) = Self::expr_to_term(metadata, func)? { + requests.entry(target).or_default().terms.push(term); } } _ => {} } + Ok(()) } fn expr_to_query( metadata: &RegionMetadata, f: &ScalarFunction, - ) -> Option<(ColumnId, FulltextQuery)> { + ) -> Result> { if f.name() != "matches" { - return None; + return Ok(None); } if f.args.len() != 2 { - return None; + return Ok(None); } - let Expr::Column(c) = &f.args[0] else { - return None; - }; - let column = metadata.column_by_name(&c.name)?; - - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - - let Expr::Literal(ScalarValue::Utf8(Some(query)), _) = &f.args[1] else { - return None; + let Some(target) = Self::index_target_from_expr(metadata, &f.args[0])? else { + return Ok(None); }; - Some((column.column_id, FulltextQuery(query.clone()))) + let Expr::Literal( + ScalarValue::Utf8(Some(query)) + | ScalarValue::LargeUtf8(Some(query)) + | ScalarValue::Utf8View(Some(query)), + _, + ) = &f.args[1] + else { + return Ok(None); + }; + + Ok(Some((target, FulltextQuery(query.clone())))) } fn expr_to_term( metadata: &RegionMetadata, f: &ScalarFunction, - ) -> Option<(ColumnId, FulltextTerm)> { + ) -> Result> { if f.name() != "matches_term" { - return None; + return Ok(None); } if f.args.len() != 2 { - return None; + return Ok(None); } - let mut lowered = false; - let column; - match &f.args[0] { - Expr::Column(c) => { - column = c; - } - Expr::ScalarFunction(f) => { - let lower_arg = Self::extract_lower_arg(f)?; - lowered = true; - if let Expr::Column(c) = lower_arg { - column = c; - } else { - return None; - } - } - _ => return None, - } - - let column = metadata.column_by_name(&column.name)?; - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - - let Expr::Literal(ScalarValue::Utf8(Some(term)), _) = &f.args[1] else { - return None; + let (expr, lowered) = Self::unwrap_lower(&f.args[0]); + let Some(target) = Self::index_target_from_expr(metadata, expr)? else { + return Ok(None); }; - Some(( - column.column_id, + let Expr::Literal( + ScalarValue::Utf8(Some(term)) + | ScalarValue::LargeUtf8(Some(term)) + | ScalarValue::Utf8View(Some(term)), + _, + ) = &f.args[1] + else { + return Ok(None); + }; + + Ok(Some(( + target, FulltextTerm { col_lowered: lowered, term: term.clone(), }, - )) + ))) } - fn expr_to_like(metadata: &RegionMetadata, like: &Like) -> Option<(ColumnId, FulltextLike)> { + fn expr_to_like( + metadata: &RegionMetadata, + like: &Like, + ) -> Result> { // `ILIKE` uses Unicode case folding, which disagrees with the index's // `to_lowercase` on characters like 'ſ', so its probes could miss rows. if like.negated || like.case_insensitive { - return None; + return Ok(None); } // Probes assume arrow's default `\` escape. if !matches!(like.escape_char, None | Some('\\')) { - return None; + return Ok(None); } - let (c, col_lowered) = match like.expr.as_ref() { - Expr::Column(c) => (c, false), - Expr::ScalarFunction(f) => match Self::extract_lower_arg(f)? { - Expr::Column(c) => (c, true), - _ => return None, - }, - _ => return None, + let (expr, col_lowered) = Self::unwrap_lower(&like.expr); + let Some(target) = Self::index_target_from_expr(metadata, expr)? else { + return Ok(None); }; - let column = metadata.column_by_name(&c.name)?; - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - // `LIKE` is common on unindexed columns and with patterns like '%word%' that have - // no probe; skip them instead of opening every SST's index for nothing. - let options = column.column_schema.fulltext_options().ok()??; - if !options.enable || options.backend != FulltextBackend::Bloom { - return None; + let Some(options) = fulltext_target_options(metadata, &target)? else { + return Ok(None); + }; + if options.backend != FulltextBackend::Bloom { + return Ok(None); } let Expr::Literal( @@ -291,19 +291,57 @@ impl<'a> FulltextIndexApplierBuilder<'a> { _, ) = like.pattern.as_ref() else { - return None; + return Ok(None); }; if extract_like_probes(pattern).is_empty() { - return None; + return Ok(None); } - Some(( - column.column_id, + Ok(Some(( + target, FulltextLike { col_lowered, pattern: pattern.clone(), }, - )) + ))) + } + + /// Resolves a column reference or JSON path expression to a single index target. + /// Returns `None` for unsupported expressions without traversing their children. + fn index_target_from_expr( + metadata: &RegionMetadata, + expr: &Expr, + ) -> Result> { + if let Expr::Column(col) = expr { + let Some(col) = metadata.column_by_name(&col.name) else { + return Ok(None); + }; + if !col.column_schema.data_type.is_string() { + return Ok(None); + } + let target = IndexTarget::ColumnId(col.column_id); + return Ok(fulltext_target_options(metadata, &target)?.map(|_| target)); + } + let Some((target, ty)) = json_index_target(metadata, expr, |hint| { + hint.fulltext_index + .as_ref() + .is_some_and(|options| options.enable) + })? + else { + return Ok(None); + }; + Ok(ty.is_string().then_some(target)) + } + + /// Returns the inner expression and `true` for `lower(expr)`, or the original + /// expression and `false` otherwise. + fn unwrap_lower(expr: &Expr) -> (&Expr, bool) { + if let Expr::ScalarFunction(func) = expr + && let Some(inner) = Self::extract_lower_arg(func) + { + return (inner, true); + } + (expr, false) } fn extract_lower_arg(lower_func: &ScalarFunction) -> Option<&Expr> { @@ -315,10 +353,6 @@ impl<'a> FulltextIndexApplierBuilder<'a> { return None; } - if lower_func.args.len() != 1 { - return None; - } - Some(&lower_func.args[0]) } } @@ -327,40 +361,125 @@ impl<'a> FulltextIndexApplierBuilder<'a> { mod tests { use std::sync::Arc; - use api::v1::SemanticType; use common_function::function::FunctionRef; use common_function::function_factory::ScalarFunctionFactory; + use common_function::scalars::json::json_get::JsonGetWithType; use common_function::scalars::matches::MatchesFunction; use common_function::scalars::matches_term::MatchesTermFunction; + use common_function::scalars::udf::create_udf; use datafusion::functions::string::lower; use datafusion_common::Column; use datafusion_expr::expr::{Like, ScalarFunction}; use datafusion_expr::{Literal, ScalarUDF}; - use datatypes::schema::{ColumnSchema, FulltextAnalyzer, FulltextOptions}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - use store_api::storage::RegionId; + use datatypes::schema::{FULLTEXT_KEY, FulltextOptions}; + use store_api::metadata::RegionMetadataBuilder; use super::*; + use crate::sst::index::fulltext_index::applier::tests::{ + json_metadata, mock_metadata_with_fulltext, mock_metadata_without_fulltext, + }; + + #[test] + fn test_json_fulltext_predicate_extraction() { + let options = FulltextOptions { + enable: true, + ..Default::default() + }; + let metadata = json_metadata(Some(options)); + let target = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + for literal in [ + ScalarValue::Utf8(Some("error timeout".into())), + ScalarValue::LargeUtf8(Some("error timeout".into())), + ScalarValue::Utf8View(Some("error timeout".into())), + ] { + let expr = json_expr("$.message", Some(ScalarValue::Utf8View(None))); + let query = ScalarFunction::new_udf( + matches_func(), + vec![expr.clone(), Expr::Literal(literal.clone(), None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &query).unwrap(), + Some((target.clone(), FulltextQuery("error timeout".into()))) + ); + for lowered in [false, true] { + let expr = if lowered { + lower().call(vec![expr.clone()]) + } else { + expr.clone() + }; + let term = ScalarFunction::new_udf( + matches_term_func(), + vec![expr.clone(), Expr::Literal(literal.clone(), None)], + ); + let (actual, term) = FulltextIndexApplierBuilder::expr_to_term(&metadata, &term) + .unwrap() + .unwrap(); + assert_eq!(actual, target); + assert_eq!( + term, + FulltextTerm { + col_lowered: lowered, + term: "error timeout".into() + } + ); + let like = Like::new( + false, + Box::new(expr), + Box::new(Expr::Literal(literal.clone(), None)), + None, + false, + ); + let (actual, like) = FulltextIndexApplierBuilder::expr_to_like(&metadata, &like) + .unwrap() + .unwrap(); + assert_eq!(actual, target); + assert_eq!( + like, + FulltextLike { + col_lowered: lowered, + pattern: "error timeout".into() + } + ); + } + } + for expr in [ + json_expr("$.missing", None), + json_expr("$.message", Some(ScalarValue::Int64(None))), + ] { + assert!( + FulltextIndexApplierBuilder::index_target_from_expr(&metadata, &expr) + .unwrap() + .is_none() + ); + } + for options in [None, Some(FulltextOptions::default())] { + let metadata = json_metadata(options); + let path = json_expr("$.message", None); + for expr in [ + matches_func().call(vec![path.clone(), "error".lit()]), + matches_term_func().call(vec![path.clone(), "error".lit()]), + path.like("%error timeout%".lit()), + ] { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert!(requests.is_empty(), "{expr}"); + } + } + } + + fn json_expr(path: &str, ty: Option) -> Expr { + let mut args = vec![datafusion_expr::col("attrs"), datafusion_expr::lit(path)]; + if let Some(ty) = ty { + args.push(Expr::Literal(ty, None)); + } + Expr::ScalarFunction(ScalarFunction::new_udf( + Arc::new(create_udf(Arc::new(JsonGetWithType::default()))), + args, + )) + } fn mock_metadata() -> RegionMetadata { - let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }); - - builder.build().unwrap() + mock_metadata_with_fulltext(FulltextBackend::Bloom) } fn matches_func() -> Arc { @@ -377,19 +496,74 @@ mod tests { ) } + #[test] + fn test_ordinary_fulltext_requests_require_enabled_index() { + for options in [ + None, + Some(FulltextOptions::default()), + Some(FulltextOptions { + enable: true, + ..Default::default() + }), + Some(FulltextOptions { + enable: true, + backend: FulltextBackend::Tantivy, + ..Default::default() + }), + ] { + let enabled = options.as_ref().is_some_and(|options| options.enable); + let bloom_enabled = options + .as_ref() + .is_some_and(|options| options.enable && options.backend == FulltextBackend::Bloom); + let mut metadata = mock_metadata_without_fulltext(); + if let Some(options) = options { + metadata.column_metadatas[0] + .column_schema + .set_fulltext_options(&options) + .unwrap(); + } + let column = datafusion_expr::col("text"); + let expressions = [ + ( + matches_func().call(vec![column.clone(), "error".lit()]), + enabled, + ), + ( + matches_term_func().call(vec![column.clone(), "error".lit()]), + enabled, + ), + ( + matches_term_func() + .call(vec![lower().call(vec![column.clone()]), "error".lit()]), + enabled, + ), + (column.like("%error timeout retry%".lit()), bloom_enabled), + ]; + for (expr, expected) in expressions { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!(!requests.is_empty(), expected, "{expr}"); + } + } + } + #[test] fn test_expr_to_query_basic() { let metadata = mock_metadata(); - - let func = ScalarFunction { - args: vec![Expr::Column(Column::from_name("text")), "foo".lit()], - func: matches_func(), - }; - - let (column_id, query) = - FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); - assert_eq!(query, FulltextQuery("foo".to_string())); + for literal in [ + ScalarValue::Utf8(Some("foo".into())), + ScalarValue::LargeUtf8(Some("foo".into())), + ScalarValue::Utf8View(Some("foo".into())), + ] { + let func = ScalarFunction::new_udf( + matches_func(), + vec![datafusion_expr::col("text"), Expr::Literal(literal, None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).unwrap(), + Some((IndexTarget::ColumnId(1), FulltextQuery("foo".into()))) + ); + } } #[test] @@ -401,7 +575,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -413,7 +591,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -425,7 +607,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -437,28 +623,36 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] fn test_expr_to_term_basic() { let metadata = mock_metadata(); - - let func = ScalarFunction { - args: vec![Expr::Column(Column::from_name("text")), "foo".lit()], - func: matches_term_func(), - }; - - let (column_id, term) = - FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); - assert_eq!( - term, - FulltextTerm { - col_lowered: false, - term: "foo".to_string(), - } - ); + for literal in [ + ScalarValue::Utf8(Some("foo".into())), + ScalarValue::LargeUtf8(Some("foo".into())), + ScalarValue::Utf8View(Some("foo".into())), + ] { + let func = ScalarFunction::new_udf( + matches_term_func(), + vec![datafusion_expr::col("text"), Expr::Literal(literal, None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(), + Some(( + IndexTarget::ColumnId(1), + FulltextTerm { + col_lowered: false, + term: "foo".into() + } + )) + ); + } } #[test] @@ -475,9 +669,10 @@ mod tests { func: matches_term_func(), }; - let (column_id, term) = - FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); + let (target, term) = FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .unwrap(); + assert_eq!(target, IndexTarget::ColumnId(1)); assert_eq!( term, FulltextTerm { @@ -496,7 +691,11 @@ mod tests { func: matches_term_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -508,7 +707,11 @@ mod tests { func: matches_func(), // Using 'matches' instead of 'matches_term' }; - assert!(FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -551,42 +754,12 @@ mod tests { FulltextIndexApplierBuilder::extract_requests(&matches_expr, &metadata, &mut requests); assert_eq!(requests.len(), 1); - let request = requests.get(&1).unwrap(); + let request = requests.get(&IndexTarget::ColumnId(1)).unwrap(); assert_eq!(request.queries.len(), 1); assert_eq!(request.terms.len(), 0); assert_eq!(request.queries[0], FulltextQuery("foo".to_string())); } - fn mock_metadata_with_fulltext(backend: FulltextBackend) -> RegionMetadata { - let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true) - .with_fulltext_options(FulltextOptions::new_unchecked( - true, - FulltextAnalyzer::English, - false, - backend, - 10240, - 0.01, - )) - .unwrap(), - semantic_type: SemanticType::Field, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }); - - builder.build().unwrap() - } - #[test] fn test_expr_to_like() { let like = |negated, case_insensitive, escape_char, pattern: &str| Like { @@ -603,9 +776,10 @@ mod tests { FulltextIndexApplierBuilder::expr_to_like( &bloom, &like(false, false, escape_char, "%foo bar baz%") - ), + ) + .unwrap(), Some(( - 1, + IndexTarget::ColumnId(1), FulltextLike { col_lowered: false, pattern: "%foo bar baz%".to_string(), @@ -621,9 +795,9 @@ mod tests { ..like(false, false, None, "%foo bar baz%") }; assert_eq!( - FulltextIndexApplierBuilder::expr_to_like(&bloom, &lowered), + FulltextIndexApplierBuilder::expr_to_like(&bloom, &lowered).unwrap(), Some(( - 1, + IndexTarget::ColumnId(1), FulltextLike { col_lowered: true, pattern: "%foo bar baz%".to_string(), @@ -639,25 +813,105 @@ mod tests { like(false, false, None, "%foo%"), ] { assert_eq!( - FulltextIndexApplierBuilder::expr_to_like(&bloom, &like), + FulltextIndexApplierBuilder::expr_to_like(&bloom, &like).unwrap(), None ); } // Only columns with a bloom fulltext index. for metadata in [ - mock_metadata(), + mock_metadata_without_fulltext(), mock_metadata_with_fulltext(FulltextBackend::Tantivy), ] { assert_eq!( FulltextIndexApplierBuilder::expr_to_like( &metadata, &like(false, false, None, "%foo bar baz%") - ), + ) + .unwrap(), None ); } } + #[test] + fn test_extract_requests_boolean_boundaries() { + let metadata = json_metadata(Some(FulltextOptions { + enable: true, + ..Default::default() + })); + let ordinary = matches_func().call(vec![datafusion_expr::col("text"), "error".lit()]); + let json = matches_term_func().call(vec![json_expr("$.message", None), "error".lit()]); + let ordinary_target = IndexTarget::ColumnId(1); + let json_target = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + for (expr, expected) in [ + ( + ordinary.clone().and(json.clone()), + vec![ordinary_target.clone(), json_target], + ), + (ordinary.clone().or(json.clone()), vec![]), + (Expr::Not(Box::new(json.clone())), vec![]), + ( + ordinary.clone().and(json.or(ordinary.clone())), + vec![ordinary_target], + ), + ] { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!( + requests.keys().cloned().collect::>(), + expected, + "{expr}" + ); + } + } + + #[test] + fn test_extract_requests_keeps_valid_conjunct_on_error() { + let mut metadata = json_metadata(Some(FulltextOptions { + enable: true, + ..Default::default() + })); + let column = &mut metadata.column_metadatas[0].column_schema; + let mut options = column.metadata().clone(); + options.insert(FULLTEXT_KEY.into(), "invalid json".into()); + *column = column.clone().with_metadata(options); + let metadata = RegionMetadataBuilder::from_existing(metadata) + .build() + .unwrap(); + let column = datafusion_expr::col("text"); + let valid = matches_term_func().call(vec![json_expr("$.message", None), "error".lit()]); + let expected = BTreeMap::from([( + IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(), + FulltextRequest { + terms: vec![FulltextTerm { + col_lowered: false, + term: "error".into(), + }], + ..Default::default() + }, + )]); + for invalid in [ + matches_func().call(vec![column.clone(), "error".lit()]), + matches_term_func().call(vec![column.clone(), "error".lit()]), + column.like("%error timeout%".lit()), + ] { + let mut requests = BTreeMap::new(); + assert!( + FulltextIndexApplierBuilder::extract_request(&invalid, &metadata, &mut requests) + .is_err() + ); + assert!(requests.is_empty()); + for expr in [ + invalid.clone().and(valid.clone()), + valid.clone().and(invalid), + ] { + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!(requests, expected, "{expr}"); + requests.clear(); + } + } + } + #[test] fn test_extract_multiple_requests() { let metadata = mock_metadata(); @@ -685,7 +939,7 @@ mod tests { FulltextIndexApplierBuilder::extract_requests(&binary_expr, &metadata, &mut requests); assert_eq!(requests.len(), 1); - let request = requests.get(&1).unwrap(); + let request = requests.get(&IndexTarget::ColumnId(1)).unwrap(); assert_eq!(request.queries.len(), 1); assert_eq!(request.terms.len(), 1); assert_eq!(request.queries[0], FulltextQuery("foo".to_string())); diff --git a/src/mito2/src/sst/index/fulltext_index/creator.rs b/src/mito2/src/sst/index/fulltext_index/creator.rs index df2b314b5d1..4c5b482d0fa 100644 --- a/src/mito2/src/sst/index/fulltext_index/creator.rs +++ b/src/mito2/src/sst/index/fulltext_index/creator.rs @@ -17,11 +17,14 @@ use std::sync::Arc; use std::sync::atomic::AtomicUsize; use api::v1::SemanticType; +use arrow_schema::extension::ExtensionType; use common_telemetry::warn; use datatypes::arrow::array::{Array, LargeStringArray, StringArray}; use datatypes::arrow::datatypes::DataType; use datatypes::arrow::record_batch::RecordBatch; +use datatypes::extension::json::Json2ExtensionType; use datatypes::schema::{FulltextAnalyzer, FulltextBackend}; +use datatypes::vectors::VectorRef; use index::fulltext_index::create::{ BloomFilterFulltextIndexCreator, FulltextIndexCreator, TantivyFulltextIndexCreator, }; @@ -29,28 +32,29 @@ use index::fulltext_index::{Analyzer, Config}; use index::target::IndexTarget; use puffin::blob_metadata::CompressionCodec; use puffin::puffin_manager::PutOptions; -use snafu::{ResultExt, ensure}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; -use store_api::storage::{ColumnId, ConcreteDataType, FileId, RegionId}; +use store_api::storage::{ConcreteDataType, FileId, RegionId}; use crate::error::{ CastVectorSnafu, ComputeArrowSnafu, CreateFulltextCreatorSnafu, DataTypeMismatchSnafu, - FulltextFinishSnafu, FulltextPushTextSnafu, IndexOptionsSnafu, OperateAbortedIndexSnafu, - Result, + FulltextFinishSnafu, FulltextPushTextSnafu, IndexOptionsSnafu, InvalidRecordBatchSnafu, + OperateAbortedIndexSnafu, Result, }; use crate::read::Batch; -use crate::sst::index::TYPE_FULLTEXT_INDEX; +use crate::sst::index::column::extract_json_type_hint_values; use crate::sst::index::fulltext_index::{INDEX_BLOB_TYPE_BLOOM, INDEX_BLOB_TYPE_TANTIVY}; use crate::sst::index::intermediate::{ IntermediateLocation, IntermediateManager, TempFileProvider, }; use crate::sst::index::puffin_manager::SstPuffinWriter; use crate::sst::index::statistics::{ByteCount, RowCount, Statistics}; +use crate::sst::index::{IndexBuildType, TYPE_FULLTEXT_INDEX}; /// `FulltextIndexer` is responsible for creating fulltext indexes for SST files. pub struct FulltextIndexer { /// Creators for each column. - creators: HashMap, + creators: HashMap, /// Whether the index creation was aborted. aborted: bool, /// Statistics of index creation. @@ -66,8 +70,10 @@ impl FulltextIndexer { metadata: &RegionMetadataRef, compress: bool, mem_limit: usize, + build_type: IndexBuildType, ) -> Result> { let mut creators = HashMap::new(); + let global_memory_usage = Arc::new(AtomicUsize::new(0)); for column in &metadata.column_metadatas { // Tag columns don't support fulltext index now. @@ -88,60 +94,89 @@ impl FulltextIndexer { column_name: &column.column_schema.name, })?; - // Relax the type constraint here as many types can be casted to string. - - let options = match options { - Some(options) if options.enable => options, - _ => continue, - }; - - let column_id = column.column_id; - let intm_path = intermediate_manager.fulltext_path(region_id, sst_file_id, column_id); - - let config = Config { - analyzer: match options.analyzer { - FulltextAnalyzer::English => Analyzer::English, - FulltextAnalyzer::Chinese => Analyzer::Chinese, - }, - case_sensitive: options.case_sensitive, - }; - - let inner = match options.backend { - FulltextBackend::Tantivy => { - let creator = TantivyFulltextIndexCreator::new(&intm_path, config, mem_limit) - .await - .context(CreateFulltextCreatorSnafu)?; - AltFulltextCreator::Tantivy(creator) + let mut targets = Vec::new(); + if let Some(options) = options.filter(|options| options.enable) { + targets.push((IndexTarget::ColumnId(column.column_id), options)); + } + // Only flush and compaction builds collect JSON targets; manual and schema-change + // rebuilds skip them because existing SSTs may not materialize the current hints. + // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. + if matches!(build_type, IndexBuildType::Flush | IndexBuildType::Compact) + && column.column_schema.data_type.is_json2() + && let Some(extension) = column + .column_schema + .extension_type::() + .context(IndexOptionsSnafu { + column_name: &column.column_schema.name, + })? + { + for hint in extension.metadata().json_settings().type_hints() { + let Some(options) = hint.fulltext_index.as_ref().filter(|o| o.enable) else { + continue; + }; + match IndexTarget::new_json_path(column.column_id, hint.path.clone()) { + Ok(target) => targets.push((target, options.clone())), + Err(err) => { + warn!( + err; + "Skip invalid JSON fulltext index target, column_id: {}, path: {:?}", + column.column_id, + hint.path + ); + } + } } - FulltextBackend::Bloom => { - let temp_file_provider = Arc::new(TempFileProvider::new( - IntermediateLocation::new(&metadata.region_id, sst_file_id), - intermediate_manager.clone(), - )); - let global_memory_usage = Arc::new(AtomicUsize::new(0)); - let creator = BloomFilterFulltextIndexCreator::new( - config, - options.granularity as _, - options.false_positive_rate(), - temp_file_provider, - global_memory_usage, - Some(mem_limit), - ); - AltFulltextCreator::Bloom(creator) - } - }; + } + for (target, options) in targets { + // fulltext_path generates a fresh UUID for each target, so JSON paths + // in the same column use separate intermediate directories. + let intm_path = + intermediate_manager.fulltext_path(region_id, sst_file_id, column.column_id); - creators.insert( - column_id, - SingleCreator { - column_id, - column_name: column.column_schema.name.clone(), - inner, - compress, - }, - ); + let config = Config { + analyzer: match options.analyzer { + FulltextAnalyzer::English => Analyzer::English, + FulltextAnalyzer::Chinese => Analyzer::Chinese, + }, + case_sensitive: options.case_sensitive, + }; + + let inner = match options.backend { + FulltextBackend::Tantivy => { + let creator = + TantivyFulltextIndexCreator::new(&intm_path, config, mem_limit) + .await + .context(CreateFulltextCreatorSnafu)?; + AltFulltextCreator::Tantivy(creator) + } + FulltextBackend::Bloom => { + let temp_file_provider = Arc::new(TempFileProvider::new( + IntermediateLocation::new(&metadata.region_id, sst_file_id), + intermediate_manager.clone(), + )); + let creator = BloomFilterFulltextIndexCreator::new( + config, + options.granularity as _, + options.false_positive_rate(), + temp_file_provider, + global_memory_usage.clone(), + Some(mem_limit), + ); + AltFulltextCreator::Bloom(creator) + } + }; + + creators.insert( + target.clone(), + SingleCreator { + target, + column_name: column.column_schema.name.clone(), + inner, + compress, + }, + ); + } } - Ok((!creators.is_empty()).then(move || Self { creators, aborted: false, @@ -225,17 +260,17 @@ impl FulltextIndexer { self.creators.values().map(|c| c.inner.memory_usage()).sum() } - /// Returns IDs of columns that the creator is responsible for. - pub fn column_ids(&self) -> impl Iterator + '_ { - self.creators.keys().copied() + /// Returns the targets indexed by this creator. + pub fn indexed_targets(&self) -> impl Iterator { + self.creators.keys() } - /// Returns IDs of columns indexed with the bloom backend. - pub fn bloom_column_ids(&self) -> impl Iterator + '_ { + /// Returns the targets indexed with the bloom backend. + pub fn bloom_indexed_targets(&self) -> impl Iterator { self.creators .values() .filter(|c| matches!(c.inner, AltFulltextCreator::Bloom(_))) - .map(|c| c.column_id) + .map(|c| &c.target) } } @@ -289,8 +324,8 @@ impl FulltextIndexer { /// `SingleCreator` is a creator for a single column. struct SingleCreator { - /// Column ID. - column_id: ColumnId, + /// Column or JSON path to index. + target: IndexTarget, /// Column name. column_name: String, /// Inner creator. @@ -301,10 +336,21 @@ struct SingleCreator { impl SingleCreator { async fn update(&mut self, batch: &mut Batch) -> Result<()> { - let text_column = batch - .fields() - .iter() - .find(|c| c.column_id == self.column_id); + let column_id = match &self.target { + IndexTarget::ColumnId(id) => *id, + IndexTarget::JsonPath(path) => { + let root = batch + .field_col_value(path.column_id()) + .with_context(|| InvalidRecordBatchSnafu { + reason: format!("Missing JSON fulltext column {}", path.column_id()), + })? + .data + .to_arrow_array(); + let values = extract_json_type_hint_values(&root, path.path())?; + return self.push_json_values(values).await; + } + }; + let text_column = batch.fields().iter().find(|c| c.column_id == column_id); match text_column { Some(column) => { let data = column @@ -338,6 +384,15 @@ impl SingleCreator { } async fn update_flat(&mut self, batch: &RecordBatch) -> Result<()> { + if let IndexTarget::JsonPath(path) = &self.target { + let root = batch.column_by_name(&self.column_name).with_context(|| { + InvalidRecordBatchSnafu { + reason: format!("Missing JSON fulltext column {}", self.column_name), + } + })?; + let values = extract_json_type_hint_values(root, path.path())?; + return self.push_json_values(values).await; + } // Find the column in the RecordBatch by name if let Some(column_array) = batch.column_by_name(&self.column_name) { // Convert Arrow array to string array. @@ -383,17 +438,29 @@ impl SingleCreator { Ok(()) } + async fn push_json_values(&mut self, values: VectorRef) -> Result<()> { + for row in 0..values.len() { + let text = values + .get_ref(row) + .try_into_string() + .context(DataTypeMismatchSnafu)? + .unwrap_or_default(); + self.inner.push_text(text).await?; + } + Ok(()) + } + async fn finish(&mut self, puffin_writer: &mut SstPuffinWriter) -> Result { let options = PutOptions { compression: self.compress.then_some(CompressionCodec::Zstd), }; self.inner - .finish(puffin_writer, &self.column_id, options) + .finish(puffin_writer, &self.target, options) .await } async fn abort(&mut self) -> Result<()> { - self.inner.abort(&self.column_id).await; + self.inner.abort(&self.target).await; Ok(()) } } @@ -423,10 +490,10 @@ impl AltFulltextCreator { async fn finish( &mut self, puffin_writer: &mut SstPuffinWriter, - column_id: &ColumnId, + target: &IndexTarget, put_options: PutOptions, ) -> Result { - let target_key = IndexTarget::ColumnId(*column_id).encode(); + let target_key = target.encode(); match self { Self::Tantivy(creator) => { let blob_key = format!("{INDEX_BLOB_TYPE_TANTIVY}-{target_key}"); @@ -445,16 +512,16 @@ impl AltFulltextCreator { } } - async fn abort(&mut self, column_id: &ColumnId) { + async fn abort(&mut self, target: &IndexTarget) { match self { Self::Tantivy(creator) => { if let Err(err) = creator.abort().await { - warn!(err; "Failed to abort the fulltext index creator in the Tantivy flavor, col_id: {:?}", column_id); + warn!(err; "Failed to abort the fulltext index creator in the Tantivy flavor, target: {:?}", target); } } Self::Bloom(creator) => { if let Err(err) = creator.abort().await { - warn!(err; "Failed to abort the fulltext index creator in the Bloom Filter flavor, col_id: {:?}", column_id); + warn!(err; "Failed to abort the fulltext index creator in the Bloom Filter flavor, target: {:?}", target); } } } @@ -468,9 +535,15 @@ mod tests { use api::v1::SemanticType; use common_base::BitVec; + use datatypes::arrow::array::{ArrayRef, StructArray}; + use datatypes::arrow::buffer::NullBuffer; + use datatypes::arrow::datatypes::{Field, Schema}; use datatypes::data_type::DataType; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::{JsonSettings, JsonTypeHint}; use datatypes::schema::{ColumnSchema, FulltextAnalyzer, FulltextOptions}; - use datatypes::vectors::{UInt8Vector, UInt64Vector}; + use datatypes::types::json_type::{JsonNativeType, JsonObjectType}; + use datatypes::vectors::{Helper, UInt8Vector, UInt64Vector}; use futures::FutureExt; use futures::future::BoxFuture; use index::fulltext_index::search::RowId; @@ -479,7 +552,7 @@ mod tests { use puffin::puffin_manager::{PuffinManager, PuffinWriter}; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; use store_api::region_request::PathType; - use store_api::storage::{ConcreteDataType, FileId, RegionId}; + use store_api::storage::{ColumnId, ConcreteDataType, FileId, RegionId}; use super::*; use crate::access_layer::RegionFilePathFactory; @@ -491,6 +564,279 @@ mod tests { }; use crate::sst::index::puffin_manager::PuffinManagerFactory; + #[tokio::test] + async fn test_json_fulltext_build_and_prune_both_formats() { + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + for (flat, build_type) in [ + (false, IndexBuildType::Flush), + (false, IndexBuildType::Compact), + (true, IndexBuildType::Flush), + (true, IndexBuildType::Compact), + ] { + let (dir, factory) = + PuffinManagerFactory::new_for_test_async("json_fulltext").await; + let options = FulltextOptions::new( + true, + FulltextAnalyzer::English, + false, + backend.clone(), + 1, + 0.01, + ) + .unwrap(); + let hints = ["message", "other/\".field"].map(|name| JsonTypeHint { + path: vec![name.into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: Some(options.clone()), + }); + let mut column = ColumnSchema::new( + "attrs", + ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())), + true, + ); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + JsonSettings::try_new(hints.to_vec(), Some(0)).unwrap(), + )))); + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); + builder.push_column_metadata(ColumnMetadata { + column_schema: column, + semantic_type: SemanticType::Field, + column_id: 1, + }); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }); + let metadata = Arc::new(builder.build().unwrap()); + let file_id = FileId::random(); + let manager = new_intm_mgr(dir.path().to_string_lossy()).await; + for rebuild_type in [IndexBuildType::Manual, IndexBuildType::SchemaChange] { + assert!( + FulltextIndexer::new( + &metadata.region_id, + &file_id, + &manager, + &metadata, + false, + 1024, + rebuild_type, + ) + .await + .unwrap() + .is_none() + ); + } + let mut creator = FulltextIndexer::new( + &metadata.region_id, + &file_id, + &manager, + &metadata, + false, + 1024, + build_type, + ) + .await + .unwrap() + .unwrap(); + let messages: ArrayRef = Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some("beta"), + Some("alpha"), + ])); + let other: ArrayRef = Arc::new(StringArray::from(vec![ + Some("beta"), + None, + Some("alpha"), + Some(""), + ])); + let root: ArrayRef = Arc::new(StructArray::new( + vec![ + Field::new("message", messages.data_type().clone(), true), + Field::new("other/\".field", other.data_type().clone(), true), + ] + .into(), + vec![messages, other], + Some(NullBuffer::from(vec![true, false, true, true])), + )); + for start in [0, 2] { + let array = root.slice(start, 2); + if flat { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "attrs", + array.data_type().clone(), + true, + )])), + vec![array], + ) + .unwrap(); + creator.update_flat(&batch).await.unwrap(); + } else { + let mut batch = Batch::new( + vec![], + Arc::new(UInt64Vector::from_vec(vec![0, 1])), + Arc::new(UInt64Vector::from_vec(vec![0, 0])), + Arc::new(UInt8Vector::from_vec(vec![1, 1])), + vec![BatchColumn { + column_id: 1, + data: Helper::try_into_vector(array).unwrap(), + }], + ) + .unwrap(); + creator.update(&mut batch).await.unwrap(); + } + } + assert_eq!(creator.indexed_targets().count(), hints.len()); + assert!( + creator + .indexed_targets() + .all(|target| matches!(target, IndexTarget::JsonPath(_))) + ); + let bloom_targets: BTreeSet<_> = creator.bloom_indexed_targets().collect(); + if backend == FulltextBackend::Bloom { + assert_eq!(bloom_targets, creator.indexed_targets().collect()); + } else { + assert!(bloom_targets.is_empty()); + } + let store = mock_object_store(); + let puffin = factory.build( + store.clone(), + RegionFilePathFactory::new("json_test".into(), PathType::Bare), + ); + let index_id = + RegionIndexId::new(RegionFileId::new(metadata.region_id, file_id), 0); + let mut writer = puffin.writer(&index_id).await.unwrap(); + let (rows, bytes) = creator.finish(&mut writer).await.unwrap(); + assert_eq!(rows, 4); + assert!(bytes > 0); + writer.finish().await.unwrap(); + let cache = Arc::new( + crate::cache::index::bloom_filter_index::BloomFilterIndexCache::new( + 1024 * 1024, + 1024 * 1024, + 1024, + ), + ); + for (path, term, expected) in [ + ("message", "alpha", vec![0, 3]), + ("other/\".field", "alpha", vec![2]), + ("message", "hidden", vec![]), + ("message", "absent", vec![]), + ] { + let target = IndexTarget::new_json_path(1, vec![path.into()]).unwrap(); + let request = match backend { + FulltextBackend::Tantivy => FulltextRequest { + queries: vec![FulltextQuery(term.into())], + ..Default::default() + }, + FulltextBackend::Bloom => FulltextRequest { + terms: vec![FulltextTerm { + col_lowered: false, + term: term.into(), + }], + ..Default::default() + }, + }; + let applier = FulltextIndexApplier::new( + "json_test".into(), + PathType::Bare, + store.clone(), + BTreeMap::from([ + (target, request.clone()), + ( + IndexTarget::new_json_path(1, vec!["missing".into()]).unwrap(), + request, + ), + ]), + factory.clone(), + &metadata, + ) + .with_bloom_filter_cache(Some(cache.clone())); + let requests = applier.compatible_requests_for_sst(&metadata).unwrap(); + assert_eq!(requests.len(), 1); + for change in 0..3 { + let mut changed_hints = hints.to_vec(); + for hint in &mut changed_hints { + let options = hint.fulltext_index.as_mut().unwrap(); + match change { + 0 => options.analyzer = FulltextAnalyzer::Chinese, + 1 => options.case_sensitive = true, + _ => { + options.backend = match backend { + FulltextBackend::Bloom => FulltextBackend::Tantivy, + FulltextBackend::Tantivy => FulltextBackend::Bloom, + } + } + } + } + let mut changed = (*metadata).clone(); + changed.column_metadatas[0] + .column_schema + .with_extension_type(&Json2ExtensionType::new(Arc::new( + JsonMetadata::new( + JsonSettings::try_new(changed_hints, Some(0)).unwrap(), + ), + ))); + assert_eq!( + applier.compatible_requests_for_sst(&changed).is_some(), + change == 0 && backend == FulltextBackend::Bloom, + ); + } + assert!( + applier + .compatible_requests_for_sst(&mock_region_metadata(backend.clone())) + .is_none() + ); + for _ in 0..2 { + match backend { + FulltextBackend::Tantivy => { + let rows = applier + .apply_fine(index_id, None, &requests, None) + .await + .unwrap() + .unwrap(); + assert_eq!( + rows.into_iter().collect::>(), + expected.iter().map(|v| *v as RowId).collect::>() + ); + } + FulltextBackend::Bloom => { + let ranges = applier + .apply_coarse( + index_id, + None, + [(4, true)].into_iter(), + &requests, + None, + ) + .await + .unwrap() + .unwrap(); + let rows: Vec<_> = ranges[0].1.iter().cloned().flatten().collect(); + // A Bloom filter may retain extra rows, but must retain every match. + assert!(expected.iter().all(|row| rows.contains(row))); + if expected.is_empty() { + assert!( + rows.len() < 4, + "path={path}, term={term}, flat={flat}, rows={rows:?}" + ); + } + } + } + } + } + } + } + } + fn mock_object_store() -> ObjectStore { ObjectStore::new(Memory::default()).unwrap() } @@ -662,6 +1008,7 @@ mod tests { ®ion_metadata, true, 1024, + IndexBuildType::Flush, ) .await .unwrap() @@ -688,12 +1035,12 @@ mod tests { let object_store = object_store.clone(); let factory = factory.clone(); - let mut requests: BTreeMap = BTreeMap::new(); + let mut requests: BTreeMap = BTreeMap::new(); // Add queries for (column_id, query) in queries { requests - .entry(column_id) + .entry(IndexTarget::ColumnId(column_id)) .or_default() .queries .push(FulltextQuery(query.to_string())); @@ -710,7 +1057,7 @@ mod tests { .collect::>(); requests - .entry(column_id) + .entry(IndexTarget::ColumnId(column_id)) .or_default() .terms .extend(fulltext_terms); @@ -722,20 +1069,25 @@ mod tests { object_store, requests, factory, + ®ion_metadata, ); + let requests = applier + .compatible_requests_for_sst(®ion_metadata) + .unwrap(); let backend = backend.clone(); async move { match backend { - FulltextBackend::Tantivy => { - applier.apply_fine(index_id, None, None).await.unwrap() - } + FulltextBackend::Tantivy => applier + .apply_fine(index_id, None, &requests, None) + .await + .unwrap(), FulltextBackend::Bloom => { let coarse_mask = coarse_mask.unwrap_or_default(); let row_groups = (0..coarse_mask.len()).map(|i| (1, coarse_mask[i])); // row group id == row id let resp = applier - .apply_coarse(index_id, None, row_groups, None) + .apply_coarse(index_id, None, row_groups, &requests, None) .await .unwrap(); resp.map(|r| { @@ -755,6 +1107,46 @@ mod tests { row_ids.into_iter().collect() } + #[tokio::test] + async fn test_fulltext_bloom_shared_memory_spills() { + let dir = common_test_util::temp_dir::create_temp_dir("shared_fulltext_memory"); + let metadata = mock_region_metadata(FulltextBackend::Bloom); + let manager = new_intm_mgr(dir.path().to_string_lossy()).await; + let mut indexer = FulltextIndexer::new( + &metadata.region_id, + &FileId::random(), + &manager, + &metadata, + false, + 2 * 1024 * 1024, + IndexBuildType::Flush, + ) + .await + .unwrap() + .unwrap(); + // Each target stays below 2 MB on its own; together they exceed the + // shared threshold and must spill finalized Bloom filters to disk. + for creator in indexer.creators.values_mut() { + for row in 0..20_000 { + creator.inner.push_text(&format!("row{row}")).await.unwrap(); + } + } + let mut directories = vec![dir.path().join("__intm")]; + let mut spilled = false; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + directories.push(entry.path()); + } else { + spilled = true; + } + } + } + assert!(spilled, "combined memory usage must trigger spilling"); + indexer.abort().await.unwrap(); + } + #[tokio::test] async fn test_fulltext_index_basic_case_sensitive_tantivy() { let applier_factory = build_fulltext_applier_factory( diff --git a/src/mito2/src/sst/index/indexer/finish.rs b/src/mito2/src/sst/index/indexer/finish.rs index 801b3a8eeb2..20b15191f2b 100644 --- a/src/mito2/src/sst/index/indexer/finish.rs +++ b/src/mito2/src/sst/index/indexer/finish.rs @@ -171,8 +171,20 @@ impl Indexer { return true; }; - let column_ids = indexer.column_ids().collect(); - index_output.fulltext_bloom_columns = indexer.bloom_column_ids().collect(); + let column_ids = indexer + .indexed_targets() + .filter_map(|target| match target { + IndexTarget::ColumnId(id) => Some(*id), + IndexTarget::JsonPath(_) => None, + }) + .collect(); + index_output.fulltext_bloom_columns = indexer + .bloom_indexed_targets() + .filter_map(|target| match target { + IndexTarget::ColumnId(id) => Some(*id), + IndexTarget::JsonPath(_) => None, + }) + .collect(); let err = match indexer.finish(puffin_writer).await { Ok((row_count, byte_count)) => { self.fill_fulltext_index_output( diff --git a/src/mito2/src/sst/index/inverted_index/applier/builder.rs b/src/mito2/src/sst/index/inverted_index/applier/builder.rs index 501f90a082e..4266734a011 100644 --- a/src/mito2/src/sst/index/inverted_index/applier/builder.rs +++ b/src/mito2/src/sst/index/inverted_index/applier/builder.rs @@ -390,6 +390,7 @@ mod tests { data_type: ConcreteDataType::float64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }], vec![], vec![JsonTypeHint { @@ -397,6 +398,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], ] { let mut sst = metadata.clone(); @@ -656,12 +658,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index, skipping_index: None, + fulltext_index: None, }) .chain(std::iter::once(JsonTypeHint { path: vec!["n".into()], data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, })) .collect(); column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( diff --git a/src/mito2/src/sst/index/inverted_index/creator.rs b/src/mito2/src/sst/index/inverted_index/creator.rs index 8c12eba6348..3ba073c32d2 100644 --- a/src/mito2/src/sst/index/inverted_index/creator.rs +++ b/src/mito2/src/sst/index/inverted_index/creator.rs @@ -713,6 +713,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }], Some(0), ) diff --git a/src/mito2/src/sst/parquet/json_align.rs b/src/mito2/src/sst/parquet/json_align.rs index aa891dcef27..19d88afa2d2 100644 --- a/src/mito2/src/sst/parquet/json_align.rs +++ b/src/mito2/src/sst/parquet/json_align.rs @@ -837,6 +837,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), ) diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index 4161290c20e..c9fdef50a14 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -977,6 +977,7 @@ impl ParquetReaderBuilder { let fulltext_filtered = self .prune_row_groups_by_fulltext_index( + read_format.metadata(), row_group_size, num_row_groups, &mut output, @@ -1016,6 +1017,7 @@ impl ParquetReaderBuilder { if !fulltext_filtered { self.prune_row_groups_by_fulltext_bloom( + read_format.metadata(), row_group_size, parquet_meta, &mut output, @@ -1030,6 +1032,7 @@ impl ParquetReaderBuilder { /// Prunes row groups by fulltext index. Returns `true` if the row groups are pruned. async fn prune_row_groups_by_fulltext_index( &self, + sst_metadata: &RegionMetadataRef, row_group_size: usize, num_row_groups: usize, output: &mut RowGroupSelection, @@ -1048,12 +1051,16 @@ impl ParquetReaderBuilder { &self.fulltext_index_appliers[..] }; for index_applier in appliers.iter().flatten() { - let predicate_key = index_applier.predicate_key(); + // Filter out index requests incompatible with this SST. + let Some(requests) = index_applier.compatible_requests_for_sst(sst_metadata) else { + continue; + }; + let predicate_key = PredicateKey::new_fulltext(requests.clone()); // Fast path: return early if the result is in the cache. let cached = self .cache_strategy .index_result_cache() - .and_then(|cache| cache.get(predicate_key, self.file_handle.file_id().file_id())); + .and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id())); if let Some(result) = cached.as_ref() && all_required_row_groups_searched(output, result) { @@ -1070,6 +1077,7 @@ impl ParquetReaderBuilder { .apply_fine( self.file_handle.index_id(), Some(file_size_hint), + &requests, metrics.fulltext_index_apply_metrics.as_mut(), ) .await; @@ -1085,7 +1093,7 @@ impl ParquetReaderBuilder { }; self.apply_index_result_and_update_cache( - predicate_key, + &predicate_key, self.file_handle.file_id().file_id(), selection, output, @@ -1291,6 +1299,7 @@ impl ParquetReaderBuilder { async fn prune_row_groups_by_fulltext_bloom( &self, + sst_metadata: &RegionMetadataRef, row_group_size: usize, parquet_meta: &ParquetMetaData, output: &mut RowGroupSelection, @@ -1309,12 +1318,16 @@ impl ParquetReaderBuilder { &self.fulltext_index_appliers[..] }; for index_applier in appliers.iter().flatten() { - let predicate_key = index_applier.predicate_key(); + // Filter out index requests incompatible with this SST. + let Some(requests) = index_applier.compatible_requests_for_sst(sst_metadata) else { + continue; + }; + let predicate_key = PredicateKey::new_fulltext(requests.clone()); // Fast path: return early if the result is in the cache. let cached = self .cache_strategy .index_result_cache() - .and_then(|cache| cache.get(predicate_key, self.file_handle.file_id().file_id())); + .and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id())); if let Some(result) = cached.as_ref() && all_required_row_groups_searched(output, result) { @@ -1343,6 +1356,7 @@ impl ParquetReaderBuilder { self.file_handle.index_id(), Some(file_size_hint), rgs, + &requests, metrics.fulltext_index_apply_metrics.as_mut(), ) .await; @@ -1363,7 +1377,7 @@ impl ParquetReaderBuilder { } self.apply_index_result_and_update_cache( - predicate_key, + &predicate_key, self.file_handle.file_id().file_id(), selection, output, diff --git a/src/operator/src/expr_helper.rs b/src/operator/src/expr_helper.rs index 1fe7be2e51f..af6c960556c 100644 --- a/src/operator/src/expr_helper.rs +++ b/src/operator/src/expr_helper.rs @@ -20,17 +20,17 @@ use std::collections::{HashMap, HashSet}; use api::helper::ColumnDataTypeWrapper; use api::v1::alter_database_expr::Kind as AlterDatabaseKind; use api::v1::alter_table_expr::Kind as AlterTableKind; -use api::v1::column_def::{options_from_column_schema, try_as_column_schema}; +use api::v1::column_def::{self, options_from_column_schema, try_as_column_schema}; use api::v1::{ AddColumn, AddColumns, AlterDatabaseExpr, AlterTableExpr, Analyzer, ColumnDataType, ColumnDataTypeExtension, CreateFlowExpr, CreateTableExpr, CreateViewExpr, DropColumn, DropColumns, DropDefaults, ExpireAfter, FulltextBackend as PbFulltextBackend, - JsonSettings as PbJsonSettings, JsonTypeHint as PbJsonTypeHint, ModifyColumnType, - ModifyColumnTypes, RenameTable, SemanticType, SetDatabaseOptions, SetDefaults, SetFulltext, - SetIndex, SetIndexes, SetInverted, SetJsonSettings, SetSkipping, SetTableOptions, - SkippingIndexType as PbSkippingIndexType, TableName, UnsetDatabaseOptions, UnsetFulltext, - UnsetIndex, UnsetIndexes, UnsetInverted, UnsetSkipping, UnsetTableOptions, set_index, - unset_index, + JsonSettings as PbJsonSettings, JsonSkippingIndexOptions, JsonTypeHint as PbJsonTypeHint, + ModifyColumnType, ModifyColumnTypes, RenameTable, SemanticType, SetDatabaseOptions, + SetDefaults, SetFulltext, SetIndex, SetIndexes, SetInverted, SetJsonSettings, SetSkipping, + SetTableOptions, SkippingIndexType as PbSkippingIndexType, TableName, UnsetDatabaseOptions, + UnsetFulltext, UnsetIndex, UnsetIndexes, UnsetInverted, UnsetSkipping, UnsetTableOptions, + set_index, unset_index, }; use common_datasource::object_store::LocalFileAccess; use common_error::ext::BoxedError; @@ -806,16 +806,15 @@ fn json_settings_to_proto(settings: JsonSettings) -> Result { data_type: data_type as i32, datatype_extension, inverted_index: hint.inverted_index, - skipping_index: hint.skipping_index.map(|options| { - api::v1::JsonSkippingIndexOptions { - granularity: options.granularity, - index_type: match options.index_type { - SkippingIndexType::BloomFilter => { - PbSkippingIndexType::BloomFilter.into() - } - }, - false_positive_rate: options.false_positive_rate(), - } + fulltext_index: hint + .fulltext_index + .map(column_def::json_fulltext_options_to_proto), + skipping_index: hint.skipping_index.map(|options| JsonSkippingIndexOptions { + granularity: options.granularity, + index_type: match options.index_type { + SkippingIndexType::BloomFilter => PbSkippingIndexType::BloomFilter.into(), + }, + false_positive_rate: options.false_positive_rate(), }), }) }) @@ -1211,11 +1210,14 @@ mod tests { use api::v1::{SetDatabaseOptions, UnsetDatabaseOptions}; use datatypes::extension::json::is_json2_extension_type; + use datatypes::json::{JsonSettings, JsonTypeHint}; + use datatypes::schema::{FulltextOptions, SkippingIndexOptions}; use datatypes::value::Value; use session::context::{QueryContext, QueryContextBuilder}; use sql::dialect::GreptimeDbDialect; use sql::parser::{ParseOptions, ParserContext}; use sql::statements::statement::Statement; + use store_api::region_request::{AlterKind as RegionAlterKind, RegionAlterRequest}; use store_api::storage::ColumnDefaultConstraint; use super::*; @@ -1861,6 +1863,71 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"; assert!(modify_column_type.target_type_extension.is_none()); } + #[test] + fn test_json_settings_roundtrip() { + let mut cases = vec![JsonSettings::default(), JsonSettings::new_v2()]; + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + let options = + FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05) + .unwrap(); + cases.push( + JsonSettings::try_new( + vec![ + JsonTypeHint { + path: vec!["nested".into(), "message".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: true, + skipping_index: Some( + SkippingIndexOptions::new(8, 0.05, SkippingIndexType::BloomFilter) + .unwrap(), + ), + fulltext_index: Some(options), + }, + JsonTypeHint { + path: vec!["count".into()], + data_type: ConcreteDataType::int64_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: None, + }, + ], + Some(0), + ) + .unwrap(), + ); + } + for settings in cases { + let wire = json_settings_to_proto(settings.clone()).unwrap(); + let set_settings = api::v1::SetJsonSettings { + column_name: "payload".into(), + settings: Some(wire), + }; + let expr = api::v1::AlterTableExpr { + kind: Some(AlterTableKind::SetJsonSettings(set_settings.clone())), + ..Default::default() + }; + let request = common_grpc_expr::alter_expr_to_request(1, expr, None).unwrap(); + let table::requests::AlterKind::SetJsonSettings { request } = request.alter_kind else { + panic!("expected JSON settings request"); + }; + assert_eq!(settings, request.settings); + let request = RegionAlterRequest::try_from(api::v1::region::AlterRequest { + kind: Some(api::v1::region::alter_request::Kind::SetJsonSettings( + set_settings, + )), + ..Default::default() + }) + .unwrap(); + let RegionAlterKind::SetJsonSettings { + settings: decoded, .. + } = request.kind + else { + panic!("expected JSON settings region request"); + }; + assert_eq!(settings, decoded); + } + } + #[test] fn test_to_alter_set_json_settings_expr() { let sql = "ALTER TABLE monitor MODIFY COLUMN payload JSON2 (service STRING INVERTED INDEX SKIPPING INDEX WITH (granularity='8'), message STRING);"; diff --git a/src/pipeline/src/etl/transform.rs b/src/pipeline/src/etl/transform.rs index 09cb0a3aa0b..ffa805dae5e 100644 --- a/src/pipeline/src/etl/transform.rs +++ b/src/pipeline/src/etl/transform.rs @@ -539,6 +539,7 @@ fn parse_json2_type_hint(value: &yaml_rust::Yaml) -> Result { data_type, inverted_index, skipping_index: None, + fulltext_index: None, }) } diff --git a/src/pipeline/src/etl/transform/transformer/greptime.rs b/src/pipeline/src/etl/transform/transformer/greptime.rs index 87430cd1f98..5df641f444c 100644 --- a/src/pipeline/src/etl/transform/transformer/greptime.rs +++ b/src/pipeline/src/etl/transform/transformer/greptime.rs @@ -1191,6 +1191,7 @@ transform: data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) @@ -1207,6 +1208,7 @@ transform: data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs b/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs index 2e350b3b9a8..6485eb2495e 100644 --- a/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs +++ b/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs @@ -775,6 +775,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/query/src/datafusion/json_expr_planner.rs b/src/query/src/datafusion/json_expr_planner.rs index 79af2405ff0..89ba57e3dbc 100644 --- a/src/query/src/datafusion/json_expr_planner.rs +++ b/src/query/src/datafusion/json_expr_planner.rs @@ -754,6 +754,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) @@ -789,12 +790,14 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["payload.cpu".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, diff --git a/src/sql/src/parsers/create_parser/json.rs b/src/sql/src/parsers/create_parser/json.rs index d13ea0fa53f..e75bbef8911 100644 --- a/src/sql/src/parsers/create_parser/json.rs +++ b/src/sql/src/parsers/create_parser/json.rs @@ -14,6 +14,7 @@ use datatypes::extension::json::JSON2_REMAINDER_FIELD_NAME; use datatypes::json::JSON2_MAX_STRUCTURED_DEPTH; +use datatypes::schema::FulltextOptions; use snafu::{ResultExt, ensure}; use sqlparser::ast::{DataType, ExactNumberInfo, ObjectName}; use sqlparser::dialect::keywords::Keyword; @@ -24,6 +25,7 @@ use crate::ast::Ident; use crate::dialect::GreptimeDbDialect; use crate::error::{InvalidSqlSnafu, Result, SyntaxSnafu}; use crate::parsers::create_parser::{INVERTED, SKIPPING}; +use crate::statements::OptionMap; use crate::statements::create::{Json2Options, JsonTypeHint}; const JSON2_TYPE_NAME: &str = "JSON2"; @@ -158,6 +160,7 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { let mut inverted_index = false; let mut skipping_index = None; + let mut fulltext_index = None; loop { if parser.parse_keywords(&[Keyword::NOT, Keyword::NULL]) @@ -238,10 +241,47 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { } skipping_index = Some( datatypes::schema::SkippingIndexOptions::try_from( - crate::statements::OptionMap::new(options).into_map(), + OptionMap::new(options).into_map(), ) .context(crate::error::SetSkippingIndexOptionSnafu)?, ); + } else if parser.parse_keyword(Keyword::FULLTEXT) { + ensure!( + matches!(data_type, DataType::String(None)), + InvalidSqlSnafu { + msg: "JSON2 FULLTEXT index only supports string type hints", + } + ); + ensure!( + parser.parse_keyword(Keyword::INDEX), + InvalidSqlSnafu { + msg: "expect INDEX after FULLTEXT keyword", + } + ); + ensure!( + fulltext_index.is_none(), + InvalidSqlSnafu { + msg: "duplicated FULLTEXT INDEX option for JSON2 type hint", + } + ); + let options = parser + .parse_options(Keyword::WITH) + .context(SyntaxSnafu)? + .into_iter() + .map(crate::util::parse_option_string) + .collect::>>()?; + for (key, _) in &options { + ensure!( + crate::parsers::utils::validate_column_fulltext_create_option(key), + InvalidSqlSnafu { + msg: format!("invalid FULLTEXT INDEX option: {key}") + } + ); + } + fulltext_index = Some( + FulltextOptions::try_from(OptionMap::new(options).into_map()) + .context(crate::error::SetFulltextOptionSnafu)?, + ); } else if matches!(parser.peek_token().token, Token::Comma | Token::RParen) { break; } else { @@ -256,6 +296,7 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { data_type, inverted_index, skipping_index, + fulltext_index, }) } @@ -341,6 +382,64 @@ mod tests { create_table.columns.remove(0) } + #[test] + fn test_json2_fulltext_index() { + use datatypes::schema::FulltextBackend; + for (options, backend) in [ + ("", FulltextBackend::Bloom), + ( + "WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')", + FulltextBackend::Tantivy, + ), + ( + "WITH (backend='bloom', granularity='8', false_positive_rate='0.05')", + FulltextBackend::Bloom, + ), + ] { + let sql = format!( + "CREATE TABLE logs (attrs JSON2 (message STRING FULLTEXT INDEX {options} SKIPPING INDEX INVERTED INDEX), ts TIMESTAMP TIME INDEX)" + ); + let column = parse_json2_column(&sql); + let options = column.extensions.json2_options.unwrap(); + let settings = options.build_json_settings().unwrap(); + let hint = &settings.type_hints()[0]; + assert_eq!(hint.fulltext_index.as_ref().unwrap().backend, backend); + assert!(hint.fulltext_index.as_ref().unwrap().enable); + assert!(hint.inverted_index); + assert!(hint.skipping_index.is_some()); + let rebuilt = parse_json2_column(&format!( + "CREATE TABLE logs (attrs JSON2 {options}, ts TIMESTAMP TIME INDEX)" + )); + assert_eq!( + settings, + rebuilt + .extensions + .json2_options + .unwrap() + .build_json_settings() + .unwrap() + ); + } + for hint in [ + "message BIGINT FULLTEXT INDEX", + "message STRING FULLTEXT INDEX FULLTEXT INDEX", + "message STRING FULLTEXT", + "message STRING FULLTEXT INDEX WITH (analyzer='unknown')", + "message STRING FULLTEXT INDEX WITH (backend='unknown')", + "message STRING FULLTEXT INDEX WITH (granularity='0')", + "message STRING FULLTEXT INDEX WITH (false_positive_rate='0')", + "message STRING FULLTEXT INDEX WITH (unknown='1')", + ] { + let sql = format!("CREATE TABLE logs (attrs JSON2 ({hint}), ts TIMESTAMP TIME INDEX)"); + let parsed = ParserContext::create_with_dialect( + &sql, + &GreptimeDbDialect {}, + ParseOptions::default(), + ); + assert!(parsed.is_err(), "{sql}"); + } + } + #[test] fn test_json2_skipping_index() { let column = parse_json2_column( diff --git a/src/sql/src/statements.rs b/src/sql/src/statements.rs index ffb00eba313..67233cce671 100644 --- a/src/sql/src/statements.rs +++ b/src/sql/src/statements.rs @@ -734,6 +734,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, )?)?; diff --git a/src/sql/src/statements/create.rs b/src/sql/src/statements/create.rs index d01ac85a5de..e0130613c01 100644 --- a/src/sql/src/statements/create.rs +++ b/src/sql/src/statements/create.rs @@ -210,6 +210,24 @@ impl Display for Json2Options { options.index_type )?; } + if let Some(options) = &hint.fulltext_index + && options.enable + { + write!( + f, + " FULLTEXT INDEX WITH (analyzer = '{}', case_sensitive = '{}', backend = '{}'", + options.analyzer, options.case_sensitive, options.backend + )?; + if options.backend == datatypes::schema::FulltextBackend::Bloom { + write!( + f, + ", granularity = '{}', false_positive_rate = '{}'", + options.granularity, + options.false_positive_rate() + )?; + } + f.write_char(')')?; + } if hint.inverted_index { f.write_str(" INVERTED INDEX")?; } @@ -229,6 +247,7 @@ impl Json2Options { data_type: sql_data_type_to_concrete_data_type(&hint.data_type)?, inverted_index: hint.inverted_index, skipping_index: hint.skipping_index.clone(), + fulltext_index: hint.fulltext_index.clone(), }) }) .collect::>>()?; @@ -246,6 +265,8 @@ pub struct JsonTypeHint { pub inverted_index: bool, /// Skipping index options for this hinted path. pub skipping_index: Option, + /// Fulltext index options for a string hinted path. + pub fulltext_index: Option, } impl Column { @@ -367,6 +388,7 @@ impl ColumnExtensions { data_type, inverted_index: hint.inverted_index, skipping_index: hint.skipping_index, + fulltext_index: hint.fulltext_index, }) }) .collect::>>()?; @@ -832,6 +854,7 @@ mod tests { data_type: DataType::Text, inverted_index: true, skipping_index: None, + fulltext_index: None, }], }); assert!(!create.consume_sql_size_budget(&mut 4096)); @@ -853,6 +876,7 @@ mod tests { data_type: DataType::Text, inverted_index: false, skipping_index: None, + fulltext_index: None, }], }; assert_eq!( @@ -1179,30 +1203,35 @@ ENGINE=mito data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["f".to_string()], data_type: ConcreteDataType::float64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["u".to_string()], data_type: ConcreteDataType::uint64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["s".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["b".to_string()], data_type: ConcreteDataType::boolean_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -1230,6 +1259,7 @@ ENGINE=mito data_type: ConcreteDataType::date_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index cf98ead1857..d80d774b7c4 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -1571,6 +1571,16 @@ fn json_settings_from_proto(settings: v1::JsonSettings) -> Result path: hint.path, data_type, inverted_index: hint.inverted_index, + fulltext_index: hint + .fulltext_index + .map(api::v1::column_def::json_fulltext_options_from_proto) + .transpose() + .map_err(|err| { + InvalidRawRegionRequestSnafu { + err: err.to_string(), + } + .build() + })?, skipping_index: hint .skipping_index .map(api::v1::column_def::json_skipping_options_from_proto) @@ -2532,6 +2542,7 @@ mod tests { data_type: ColumnDataType::String as i32, inverted_index, skipping_index: None, + fulltext_index: None, ..Default::default() }], max_auto_expanded_paths: Some(0), @@ -2617,6 +2628,7 @@ mod tests { data_type: ColumnDataType::String as i32, datatype_extension: None, inverted_index: true, + fulltext_index: None, skipping_index: Some(v1::JsonSkippingIndexOptions { granularity: 8, index_type: 0, diff --git a/tests/cases/standalone/common/types/json/json2_fulltext_index.result b/tests/cases/standalone/common/types/json/json2_fulltext_index.result new file mode 100644 index 00000000000..2efc271f9a3 --- /dev/null +++ b/tests/cases/standalone/common/types/json/json2_fulltext_index.result @@ -0,0 +1,814 @@ +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_bloom ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') +) WITH ('append_mode'='true', 'sst_format'='flat'); + +Affected Rows: 0 + +SHOW CREATE TABLE json2_fulltext_bloom; + ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_bloom | CREATE TABLE IF NOT EXISTS "json2_fulltext_bloom" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "attrs" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "nested"."message" STRING SKIPPING INDEX WITH (granularity = '10240', false_positive_rate = '0.01', type = 'BLOOM') FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') INVERTED INDEX, | +| | "nested.message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | "ordinary" STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '1'), | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true', | +| | sst_format = 'flat' | +| | ) | ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +INSERT INTO json2_fulltext_bloom VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); + +Affected Rows: 6 + +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); + ++-------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_bloom') | ++-------------------------------------------+ +| 0 | ++-------------------------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(ordinary, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message IS NULL ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.004 | +| 1970-01-01T00:00:00.005 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') OR matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(lower(attrs.nested.message), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message LIKE '%error timeout%' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE ordinary LIKE '%error timeout%' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +INSERT INTO json2_fulltext_bloom VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); + ++-------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_bloom') | ++-------------------------------------------+ +| 0 | ++-------------------------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400'); + ++--------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400') | ++--------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":7,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":7,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":7} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +ALTER TABLE json2_fulltext_bloom MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); + +Affected Rows: 0 + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +DROP TABLE json2_fulltext_bloom; + +Affected Rows: 0 + +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_tantivy ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') +) WITH ('append_mode'='true', 'sst_format'='flat'); + +Affected Rows: 0 + +SHOW CREATE TABLE json2_fulltext_tantivy; + ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_tantivy | CREATE TABLE IF NOT EXISTS "json2_fulltext_tantivy" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "attrs" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "nested"."message" STRING SKIPPING INDEX WITH (granularity = '10240', false_positive_rate = '0.01', type = 'BLOOM') FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'tantivy') INVERTED INDEX, | +| | "nested.message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'tantivy') | +| | ) NULL, | +| | "ordinary" STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'tantivy', case_sensitive = 'false'), | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true', | +| | sst_format = 'flat' | +| | ) | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +INSERT INTO json2_fulltext_tantivy VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); + +Affected Rows: 6 + +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); + ++---------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_tantivy') | ++---------------------------------------------+ +| 0 | ++---------------------------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(ordinary, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE attrs.nested.message IS NULL ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.004 | +| 1970-01-01T00:00:00.005 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') OR matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +INSERT INTO json2_fulltext_tantivy VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); + ++---------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_tantivy') | ++---------------------------------------------+ +| 0 | ++---------------------------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400'); + ++----------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400') | ++----------------------------------------------------------------+ +| 0 | ++----------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":7,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":7,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":7} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +ALTER TABLE json2_fulltext_tantivy MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); + +Affected Rows: 0 + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +DROP TABLE json2_fulltext_tantivy; + +Affected Rows: 0 + +CREATE TABLE json2_fulltext_chinese_bloom ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1') +) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_chinese_bloom VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom'); + ++---------------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom') | ++---------------------------------------------------+ +| 0 | ++---------------------------------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(j.text), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +DROP TABLE json2_fulltext_chinese_bloom; + +Affected Rows: 0 + +CREATE TABLE json2_fulltext_chinese_tantivy ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true') +) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_chinese_tantivy VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy'); + ++-----------------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy') | ++-----------------------------------------------------+ +| 0 | ++-----------------------------------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(j.text), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +DROP TABLE json2_fulltext_chinese_tantivy; + +Affected Rows: 0 + +-- Old SSTs, hint changes, restart, and backend changes. +CREATE TABLE json2_fulltext_evolution (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (1, '{"message":"error old"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (2, '{"message":"error new"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (3, '{"message":"错误 日志 error"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE json2_fulltext_evolution; + ++--------------------------+---------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++--------------------------+---------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_evolution | CREATE TABLE IF NOT EXISTS "json2_fulltext_evolution" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'Chinese', case_sensitive = 'true', backend = 'tantivy') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++--------------------------+---------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400'); + ++------------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400') | ++------------------------------------------------------------------+ +| 0 | ++------------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message BIGINT); + +Affected Rows: 0 + +SELECT COUNT(*) FROM json2_fulltext_evolution; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +DROP TABLE json2_fulltext_evolution; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/types/json/json2_fulltext_index.sql b/tests/cases/standalone/common/types/json/json2_fulltext_index.sql new file mode 100644 index 00000000000..a896d76b735 --- /dev/null +++ b/tests/cases/standalone/common/types/json/json2_fulltext_index.sql @@ -0,0 +1,233 @@ +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_bloom ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') +) WITH ('append_mode'='true', 'sst_format'='flat'); +SHOW CREATE TABLE json2_fulltext_bloom; +INSERT INTO json2_fulltext_bloom VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(ordinary, 'error') ORDER BY ts; +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message IS NULL ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') OR matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(lower(attrs.nested.message), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message LIKE '%error timeout%' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE ordinary LIKE '%error timeout%' ORDER BY ts; + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); +INSERT INTO json2_fulltext_bloom VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); +ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); +ALTER TABLE json2_fulltext_bloom MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +DROP TABLE json2_fulltext_bloom; + +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_tantivy ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') +) WITH ('append_mode'='true', 'sst_format'='flat'); +SHOW CREATE TABLE json2_fulltext_tantivy; +INSERT INTO json2_fulltext_tantivy VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(ordinary, 'error') ORDER BY ts; +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE attrs.nested.message IS NULL ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') OR matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); +INSERT INTO json2_fulltext_tantivy VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); +ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); +ALTER TABLE json2_fulltext_tantivy MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +DROP TABLE json2_fulltext_tantivy; + +CREATE TABLE json2_fulltext_chinese_bloom ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1') +) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_chinese_bloom VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); +ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom'); +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(j.text), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; +DROP TABLE json2_fulltext_chinese_bloom; + +CREATE TABLE json2_fulltext_chinese_tantivy ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true') +) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_chinese_tantivy VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); +ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy'); +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(j.text), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; +DROP TABLE json2_fulltext_chinese_tantivy; + +-- Old SSTs, hint changes, restart, and backend changes. +CREATE TABLE json2_fulltext_evolution (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_evolution VALUES (1, '{"message":"error old"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); +INSERT INTO json2_fulltext_evolution VALUES (2, '{"message":"error new"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')); +INSERT INTO json2_fulltext_evolution VALUES (3, '{"message":"错误 日志 error"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE json2_fulltext_evolution; +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message BIGINT); +SELECT COUNT(*) FROM json2_fulltext_evolution; +DROP TABLE json2_fulltext_evolution; diff --git a/tests/cases/standalone/common/types/json/json2_inverted_index.result b/tests/cases/standalone/common/types/json/json2_inverted_index.result index 8d9ee9c3ece..dddc7c405d6 100644 --- a/tests/cases/standalone/common/types/json/json2_inverted_index.result +++ b/tests/cases/standalone/common/types/json/json2_inverted_index.result @@ -136,11 +136,3 @@ CREATE TABLE json2_inverted_invalid ( Error: 2000(InvalidSyntax), Invalid SQL, error: unsupported JSON2 type hint data type: TIMESTAMP; supported types: STRING, BIGINT, BIGINT UNSIGNED, DOUBLE, BOOLEAN; supported aliases: INT64, UINT64, FLOAT64 --- JSON hints do not support fulltext indexes. -CREATE TABLE json2_inverted_invalid ( - ts TIMESTAMP TIME INDEX, - attrs JSON2 (message STRING FULLTEXT INDEX) -); - -Error: 2000(InvalidSyntax), Invalid SQL syntax: sql parser error: Expected: JSON2 type hint option, found: FULLTEXT at Line: 3, Column: 33 - diff --git a/tests/cases/standalone/common/types/json/json2_inverted_index.sql b/tests/cases/standalone/common/types/json/json2_inverted_index.sql index aad6e414cdd..fdc9e8530d9 100644 --- a/tests/cases/standalone/common/types/json/json2_inverted_index.sql +++ b/tests/cases/standalone/common/types/json/json2_inverted_index.sql @@ -65,9 +65,3 @@ CREATE TABLE json2_inverted_invalid ( ts TIMESTAMP TIME INDEX, attrs JSON2 (event_time TIMESTAMP INVERTED INDEX) ); - --- JSON hints do not support fulltext indexes. -CREATE TABLE json2_inverted_invalid ( - ts TIMESTAMP TIME INDEX, - attrs JSON2 (message STRING FULLTEXT INDEX) -); diff --git a/tests/compatibility/cases/json2_fulltext_index/case.toml b/tests/compatibility/cases/json2_fulltext_index/case.toml new file mode 100644 index 00000000000..21d4de0514a --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/case.toml @@ -0,0 +1,8 @@ +name = "json2_fulltext_index" +reason = "Old JSON2 metadata without fulltext hints remains readable after enabling path indexes." +introduced_by = "JSON2 path fulltext index" +topologies = ["standalone", "distributed"] +from_range = [">=v1.3.0"] +to_range = ["*"] +features = ["json2", "metadata", "index"] +owner = "storage" diff --git a/tests/compatibility/cases/json2_fulltext_index/setup.sql b/tests/compatibility/cases/json2_fulltext_index/setup.sql new file mode 100644 index 00000000000..57156b1104d --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/setup.sql @@ -0,0 +1,3 @@ +CREATE TABLE logs (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); +INSERT INTO logs VALUES (1, '{"message":"error old"}'); +ADMIN FLUSH_TABLE('logs'); diff --git a/tests/compatibility/cases/json2_fulltext_index/verify.result b/tests/compatibility/cases/json2_fulltext_index/verify.result new file mode 100644 index 00000000000..3d741a39bfb --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/verify.result @@ -0,0 +1,82 @@ +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +ALTER TABLE logs MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); + +Affected Rows: 0 + +INSERT INTO logs VALUES (2, '{"message":"error new"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('logs'); + ++---------------------------+ +| ADMIN FLUSH_TABLE('logs') | ++---------------------------+ +| 0 | ++---------------------------+ + +SHOW CREATE TABLE logs; + ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logs | CREATE TABLE IF NOT EXISTS "logs" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE logs; + ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logs | CREATE TABLE IF NOT EXISTS "logs" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ diff --git a/tests/compatibility/cases/json2_fulltext_index/verify.sql b/tests/compatibility/cases/json2_fulltext_index/verify.sql new file mode 100644 index 00000000000..43567267691 --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/verify.sql @@ -0,0 +1,9 @@ +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE logs MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); +INSERT INTO logs VALUES (2, '{"message":"error new"}'); +ADMIN FLUSH_TABLE('logs'); +SHOW CREATE TABLE logs; +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE logs; +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts;