Skip to main content

query/optimizer/
constant_term.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::fmt::Formatter;
17use std::hash::{Hash, Hasher};
18use std::sync::Arc;
19
20use arrow::array::BooleanArray;
21use common_function::scalars::matches_term::MatchesTermFinder;
22use datafusion::config::ConfigOptions;
23use datafusion::error::Result as DfResult;
24use datafusion::physical_optimizer::PhysicalOptimizerRule;
25use datafusion::physical_plan::ExecutionPlan;
26use datafusion::physical_plan::filter::{FilterExec, FilterExecBuilder};
27use datafusion_common::ScalarValue;
28use datafusion_common::tree_node::{Transformed, TreeNode};
29use datafusion_expr::ColumnarValue;
30use datafusion_physical_expr::expressions::Literal;
31use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr};
32use datatypes::arrow_array::string_array_value_at_index;
33
34/// A physical expression that uses a pre-compiled term finder for the `matches_term` function.
35///
36/// This expression optimizes the `matches_term` function by pre-compiling the term
37/// when the term is a constant value. This avoids recompiling the term for each row
38/// during execution.
39#[derive(Debug)]
40pub struct PreCompiledMatchesTermExpr {
41    /// The text column expression to search in
42    text: Arc<dyn PhysicalExpr>,
43    /// The constant term to search for
44    term: String,
45    /// The pre-compiled term finder
46    finder: MatchesTermFinder,
47
48    /// No used but show how index tokenizes the term basically.
49    /// Not precise due to column options is unknown but for debugging purpose in most cases it's enough.
50    probes: Vec<String>,
51}
52
53impl fmt::Display for PreCompiledMatchesTermExpr {
54    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55        write!(
56            f,
57            "MatchesConstTerm({}, term: \"{}\", probes: {:?})",
58            self.text, self.term, self.probes
59        )
60    }
61}
62
63impl Hash for PreCompiledMatchesTermExpr {
64    fn hash<H: Hasher>(&self, state: &mut H) {
65        self.text.hash(state);
66        self.term.hash(state);
67    }
68}
69
70impl PartialEq for PreCompiledMatchesTermExpr {
71    fn eq(&self, other: &Self) -> bool {
72        self.text.eq(&other.text) && self.term.eq(&other.term)
73    }
74}
75
76impl Eq for PreCompiledMatchesTermExpr {}
77
78impl PhysicalExpr for PreCompiledMatchesTermExpr {
79    fn as_any(&self) -> &dyn std::any::Any {
80        self
81    }
82
83    fn data_type(
84        &self,
85        _input_schema: &arrow_schema::Schema,
86    ) -> datafusion::error::Result<arrow_schema::DataType> {
87        Ok(arrow_schema::DataType::Boolean)
88    }
89
90    fn nullable(&self, input_schema: &arrow_schema::Schema) -> datafusion::error::Result<bool> {
91        self.text.nullable(input_schema)
92    }
93
94    fn evaluate(
95        &self,
96        batch: &common_recordbatch::DfRecordBatch,
97    ) -> datafusion::error::Result<ColumnarValue> {
98        let num_rows = batch.num_rows();
99
100        let text_value = self.text.evaluate(batch)?;
101        let array = text_value.into_array(num_rows)?;
102
103        let mut result = BooleanArray::builder(num_rows);
104        for index in 0..array.len() {
105            match string_array_value_at_index(&array, index) {
106                Some(text) => {
107                    result.append_value(self.finder.find(text));
108                }
109                None => {
110                    result.append_null();
111                }
112            }
113        }
114
115        Ok(ColumnarValue::Array(Arc::new(result.finish())))
116    }
117
118    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
119        vec![&self.text]
120    }
121
122    fn with_new_children(
123        self: Arc<Self>,
124        children: Vec<Arc<dyn PhysicalExpr>>,
125    ) -> datafusion::error::Result<Arc<dyn PhysicalExpr>> {
126        Ok(Arc::new(PreCompiledMatchesTermExpr {
127            text: children[0].clone(),
128            term: self.term.clone(),
129            finder: self.finder.clone(),
130            probes: self.probes.clone(),
131        }))
132    }
133
134    fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result {
135        write!(f, "{}", self)
136    }
137}
138
139/// Optimizer rule that pre-compiles constant term in `matches_term` function.
140///
141/// This optimizer looks for `matches_term` function calls where the second argument
142/// (the term to match) is a constant value. When found, it replaces the function
143/// call with a specialized `PreCompiledMatchesTermExpr` that uses a pre-compiled
144/// term finder.
145///
146/// Example:
147/// ```sql
148/// -- Before optimization:
149/// matches_term(text_column, 'constant_term')
150///
151/// -- After optimization:
152/// PreCompiledMatchesTermExpr(text_column, 'constant_term')
153/// ```
154///
155/// This optimization improves performance by:
156/// 1. Pre-compiling the term once instead of for each row
157/// 2. Using a specialized expression that avoids function call overhead
158#[derive(Debug)]
159pub struct MatchesConstantTermOptimizer;
160
161impl PhysicalOptimizerRule for MatchesConstantTermOptimizer {
162    fn optimize(
163        &self,
164        plan: Arc<dyn ExecutionPlan>,
165        _config: &ConfigOptions,
166    ) -> DfResult<Arc<dyn ExecutionPlan>> {
167        let res = plan
168            .transform_down(&|plan: Arc<dyn ExecutionPlan>| {
169                if let Some(filter) = plan.as_any().downcast_ref::<FilterExec>() {
170                    let pred = filter.predicate().clone();
171                    let new_pred = pred.transform_down(&|expr: Arc<dyn PhysicalExpr>| {
172                        if let Some(func) = expr.as_any().downcast_ref::<ScalarFunctionExpr>() {
173                            if !func.name().eq_ignore_ascii_case("matches_term") {
174                                return Ok(Transformed::no(expr));
175                            }
176                            let args = func.args();
177                            if args.len() != 2 {
178                                return Ok(Transformed::no(expr));
179                            }
180
181                            if let Some(lit) = args[1].as_any().downcast_ref::<Literal>()
182                                && let ScalarValue::Utf8(Some(term)) = lit.value()
183                            {
184                                let finder = MatchesTermFinder::new(term);
185
186                                // For debugging purpose. Not really precise but enough for most cases.
187                                let probes = term
188                                    .split(|c: char| !c.is_alphanumeric() && c != '_')
189                                    .filter(|s| !s.is_empty())
190                                    .map(|s| s.to_string())
191                                    .collect();
192
193                                let expr = PreCompiledMatchesTermExpr {
194                                    text: args[0].clone(),
195                                    term: term.clone(),
196                                    finder,
197                                    probes,
198                                };
199
200                                return Ok(Transformed::yes(Arc::new(expr)));
201                            }
202                        }
203
204                        Ok(Transformed::no(expr))
205                    })?;
206
207                    if new_pred.transformed {
208                        let exec = FilterExecBuilder::new(new_pred.data, filter.input().clone())
209                            .with_default_selectivity(filter.default_selectivity())
210                            .apply_projection_by_ref(filter.projection().as_ref())
211                            .and_then(|x| x.build())?;
212                        return Ok(Transformed::yes(Arc::new(exec) as _));
213                    }
214                }
215
216                Ok(Transformed::no(plan))
217            })?
218            .data;
219
220        Ok(res)
221    }
222
223    fn name(&self) -> &str {
224        "MatchesConstantTerm"
225    }
226
227    fn schema_check(&self) -> bool {
228        false
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use std::sync::Arc;
235
236    use arrow::array::{ArrayRef, StringArray, StringDictionaryBuilder};
237    use arrow::datatypes::{DataType, Field, Schema, UInt32Type};
238    use arrow::record_batch::RecordBatch;
239    use catalog::RegisterTableRequest;
240    use catalog::memory::MemoryCatalogManager;
241    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
242    use common_function::scalars::matches_term::MatchesTermFunction;
243    use common_function::scalars::udf::create_udf;
244    use datafusion::datasource::memory::MemorySourceConfig;
245    use datafusion::datasource::source::DataSourceExec;
246    use datafusion::physical_optimizer::PhysicalOptimizerRule;
247    use datafusion::physical_plan::filter::FilterExec;
248    use datafusion::physical_plan::get_plan_string;
249    use datafusion_common::{Column, DFSchema};
250    use datafusion_expr::expr::ScalarFunction;
251    use datafusion_expr::{Expr, Literal, ScalarUDF};
252    use datafusion_physical_expr::{ScalarFunctionExpr, create_physical_expr};
253    use datatypes::prelude::ConcreteDataType;
254    use datatypes::schema::ColumnSchema;
255    use session::context::QueryContext;
256    use table::metadata::{TableInfoBuilder, TableMetaBuilder};
257    use table::test_util::EmptyTable;
258
259    use super::*;
260    use crate::parser::QueryLanguageParser;
261    use crate::{QueryEngineFactory, QueryEngineRef};
262
263    fn create_test_batch() -> RecordBatch {
264        let schema = Schema::new(vec![Field::new("text", DataType::Utf8, true)]);
265
266        let text_array = StringArray::from(vec![
267            Some("hello world"),
268            Some("greeting"),
269            Some("hello there"),
270            None,
271        ]);
272
273        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(text_array) as ArrayRef]).unwrap()
274    }
275
276    fn create_test_engine() -> QueryEngineRef {
277        let table_name = "test".to_string();
278        let columns = vec![
279            ColumnSchema::new(
280                "text".to_string(),
281                ConcreteDataType::string_datatype(),
282                false,
283            ),
284            ColumnSchema::new(
285                "timestamp".to_string(),
286                ConcreteDataType::timestamp_millisecond_datatype(),
287                false,
288            )
289            .with_time_index(true),
290        ];
291
292        let schema = Arc::new(datatypes::schema::Schema::new(columns));
293        let table_meta = TableMetaBuilder::empty()
294            .schema(schema)
295            .primary_key_indices(vec![])
296            .value_indices(vec![0])
297            .next_column_id(2)
298            .build()
299            .unwrap();
300        let table_info = TableInfoBuilder::default()
301            .name(&table_name)
302            .meta(table_meta)
303            .build()
304            .unwrap();
305        let table = EmptyTable::from_table_info(&table_info);
306        let catalog_list = MemoryCatalogManager::with_default_setup();
307        assert!(
308            catalog_list
309                .register_table_sync(RegisterTableRequest {
310                    catalog: DEFAULT_CATALOG_NAME.to_string(),
311                    schema: DEFAULT_SCHEMA_NAME.to_string(),
312                    table_name,
313                    table_id: 1024,
314                    table,
315                })
316                .is_ok()
317        );
318        QueryEngineFactory::new(
319            catalog_list,
320            None,
321            None,
322            None,
323            None,
324            false,
325            Default::default(),
326        )
327        .query_engine()
328    }
329
330    fn matches_term_udf() -> Arc<ScalarUDF> {
331        Arc::new(create_udf(Arc::new(MatchesTermFunction::default())))
332    }
333
334    #[test]
335    fn test_matches_term_optimization() {
336        let batch = create_test_batch();
337
338        // Create a predicate with a constant pattern
339        let predicate = create_physical_expr(
340            &Expr::ScalarFunction(ScalarFunction::new_udf(
341                matches_term_udf(),
342                vec![Expr::Column(Column::from_name("text")), "hello".lit()],
343            )),
344            &DFSchema::try_from(batch.schema().clone()).unwrap(),
345            &Default::default(),
346        )
347        .unwrap();
348
349        let input = DataSourceExec::from_data_source(
350            MemorySourceConfig::try_new(&[vec![batch.clone()]], batch.schema(), None).unwrap(),
351        );
352        let filter = FilterExec::try_new(predicate, input).unwrap();
353
354        // Apply the optimizer
355        let optimizer = MatchesConstantTermOptimizer;
356        let optimized_plan = optimizer
357            .optimize(Arc::new(filter), &Default::default())
358            .unwrap();
359
360        let optimized_filter = optimized_plan
361            .as_any()
362            .downcast_ref::<FilterExec>()
363            .unwrap();
364        let predicate = optimized_filter.predicate();
365
366        // The predicate should be a PreCompiledMatchesTermExpr
367        assert!(
368            std::any::TypeId::of::<PreCompiledMatchesTermExpr>() == predicate.as_any().type_id()
369        );
370    }
371
372    #[test]
373    fn test_precompiled_matches_term_with_dictionary() {
374        let mut text = StringDictionaryBuilder::<UInt32Type>::new();
375        text.append_value("hello world");
376        text.append_value("greeting");
377        text.append_value("hello there");
378        text.append_null();
379        let schema = Arc::new(Schema::new(vec![Field::new(
380            "text",
381            DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
382            true,
383        )]));
384        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(text.finish())]).unwrap();
385        let expr = PreCompiledMatchesTermExpr {
386            text: Arc::new(datafusion_physical_expr::expressions::Column::new(
387                "text", 0,
388            )),
389            term: "hello".to_string(),
390            finder: MatchesTermFinder::new("hello"),
391            probes: vec!["hello".to_string()],
392        };
393
394        let result = expr.evaluate(&batch).unwrap().into_array(4).unwrap();
395        assert_eq!(
396            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
397            &BooleanArray::from(vec![Some(true), Some(false), Some(true), None])
398        );
399    }
400
401    #[test]
402    fn test_matches_term_no_optimization() {
403        let batch = create_test_batch();
404
405        // Create a predicate with a non-constant pattern
406        let predicate = create_physical_expr(
407            &Expr::ScalarFunction(ScalarFunction::new_udf(
408                matches_term_udf(),
409                vec![
410                    Expr::Column(Column::from_name("text")),
411                    Expr::Column(Column::from_name("text")),
412                ],
413            )),
414            &DFSchema::try_from(batch.schema().clone()).unwrap(),
415            &Default::default(),
416        )
417        .unwrap();
418
419        let input = DataSourceExec::from_data_source(
420            MemorySourceConfig::try_new(&[vec![batch.clone()]], batch.schema(), None).unwrap(),
421        );
422        let filter = FilterExec::try_new(predicate, input).unwrap();
423
424        let optimizer = MatchesConstantTermOptimizer;
425        let optimized_plan = optimizer
426            .optimize(Arc::new(filter), &Default::default())
427            .unwrap();
428
429        let optimized_filter = optimized_plan
430            .as_any()
431            .downcast_ref::<FilterExec>()
432            .unwrap();
433        let predicate = optimized_filter.predicate();
434
435        // The predicate should still be a ScalarFunctionExpr
436        assert!(std::any::TypeId::of::<ScalarFunctionExpr>() == predicate.as_any().type_id());
437    }
438
439    #[tokio::test]
440    async fn test_matches_term_optimization_from_sql() {
441        let sql = "WITH base AS (
442        SELECT text, timestamp FROM test 
443        WHERE MATCHES_TERM(text, 'hello wo_rld') 
444        AND timestamp > '2025-01-01 00:00:00'
445    ),
446    subquery1 AS (
447        SELECT * FROM base 
448        WHERE MATCHES_TERM(text, 'world')
449    ),
450    subquery2 AS (
451        SELECT * FROM test 
452        WHERE MATCHES_TERM(text, 'greeting') 
453        AND timestamp < '2025-01-02 00:00:00'
454    ),
455    union_result AS (
456        SELECT * FROM subquery1 
457        UNION ALL 
458        SELECT * FROM subquery2
459    ),
460    joined_data AS (
461        SELECT a.text, a.timestamp, b.text as other_text 
462        FROM union_result a 
463        JOIN test b ON a.timestamp = b.timestamp 
464        WHERE MATCHES_TERM(a.text, 'there')
465    )
466    SELECT text, other_text 
467    FROM joined_data 
468    WHERE MATCHES_TERM(text, '42') 
469    AND MATCHES_TERM(other_text, 'foo')";
470
471        let query_ctx = QueryContext::arc();
472
473        let stmt = QueryLanguageParser::parse_sql(sql, &query_ctx).unwrap();
474        let engine = create_test_engine();
475        let logical_plan = engine
476            .planner()
477            .plan(&stmt, query_ctx.clone())
478            .await
479            .unwrap();
480
481        let engine_ctx = engine.engine_context(query_ctx);
482        let state = engine_ctx.state();
483
484        let analyzed_plan = state
485            .analyzer()
486            .execute_and_check(logical_plan.clone(), state.config_options(), |_, _| {})
487            .unwrap();
488
489        let optimized_plan = state
490            .optimizer()
491            .optimize(analyzed_plan, state, |_, _| {})
492            .unwrap();
493
494        let physical_plan = state
495            .query_planner()
496            .create_physical_plan(&optimized_plan, state)
497            .await
498            .unwrap();
499
500        let plan_str = get_plan_string(&physical_plan).join("\n");
501        assert!(plan_str.contains("MatchesConstTerm(text@0, term: \"foo\", probes: [\"foo\"]"));
502        assert!(plan_str.contains(
503            "MatchesConstTerm(text@0, term: \"hello wo_rld\", probes: [\"hello\", \"wo_rld\"]"
504        ));
505        assert!(plan_str.contains("MatchesConstTerm(text@0, term: \"world\", probes: [\"world\"]"));
506        assert!(
507            plan_str
508                .contains("MatchesConstTerm(text@0, term: \"greeting\", probes: [\"greeting\"]")
509        );
510        assert!(plan_str.contains("MatchesConstTerm(text@0, term: \"there\", probes: [\"there\"]"));
511        assert!(plan_str.contains("MatchesConstTerm(text@0, term: \"42\", probes: [\"42\"]"));
512        assert!(!plan_str.contains("matches_term"))
513    }
514}