Coverage Report

Created: 2026-05-12 18:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/match.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exprs/function/match.h"
19
20
#include <hs/hs.h>
21
22
#include "core/field.h"
23
#include "runtime/query_context.h"
24
#include "runtime/runtime_state.h"
25
#include "storage/index/index_reader_helper.h"
26
#include "storage/index/inverted/analyzer/analyzer.h"
27
#include "util/debug_points.h"
28
29
namespace doris {
30
31
namespace {
32
33
506
const InvertedIndexAnalyzerCtx* get_match_analyzer_ctx(FunctionContext* context) {
34
506
    if (context == nullptr) {
35
0
        return nullptr;
36
0
    }
37
506
    auto* analyzer_ctx = reinterpret_cast<const InvertedIndexAnalyzerCtx*>(
38
506
            context->get_function_state(FunctionContext::THREAD_LOCAL));
39
506
    if (analyzer_ctx == nullptr) {
40
0
        analyzer_ctx = reinterpret_cast<const InvertedIndexAnalyzerCtx*>(
41
0
                context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
42
0
    }
43
506
    return analyzer_ctx;
44
506
}
45
46
} // namespace
47
48
Status FunctionMatchBase::evaluate_inverted_index(
49
        const ColumnsWithTypeAndName& arguments,
50
        const std::vector<IndexFieldNameAndTypePair>& data_type_with_names,
51
        std::vector<segment_v2::IndexIterator*> iterators, uint32_t num_rows,
52
        const InvertedIndexAnalyzerCtx* analyzer_ctx,
53
4.67k
        segment_v2::InvertedIndexResultBitmap& bitmap_result) const {
54
4.67k
    DCHECK(arguments.size() == 1);
55
4.67k
    DCHECK(data_type_with_names.size() == 1);
56
4.67k
    DCHECK(iterators.size() == 1);
57
4.67k
    auto* iter = iterators[0];
58
4.67k
    auto data_type_with_name = data_type_with_names[0];
59
4.67k
    if (iter == nullptr) {
60
0
        return Status::OK();
61
0
    }
62
4.67k
    const std::string& function_name = get_name();
63
64
4.67k
    if (function_name == MATCH_PHRASE_FUNCTION || function_name == MATCH_PHRASE_PREFIX_FUNCTION ||
65
4.67k
        function_name == MATCH_PHRASE_EDGE_FUNCTION) {
66
545
        auto reader = iter->get_reader(InvertedIndexReaderType::FULLTEXT);
67
545
        if (reader && !segment_v2::IndexReaderHelper::is_support_phrase(reader)) {
68
2
            return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>(
69
2
                    "phrase queries require setting support_phrase = true");
70
2
        }
71
545
    }
72
4.66k
    Field param_value;
73
4.66k
    arguments[0].column->get(0, param_value);
74
4.66k
    if (param_value.is_null()) {
75
        // if query value is null, skip evaluate inverted index
76
0
        return Status::OK();
77
0
    }
78
4.66k
    auto param_type = arguments[0].type->get_primitive_type();
79
4.66k
    if (!is_string_type(param_type)) {
80
0
        return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>(
81
0
                "arguments for match must be string");
82
0
    }
83
4.66k
    InvertedIndexParam param;
84
4.66k
    param.column_name = data_type_with_name.first;
85
4.66k
    param.column_type = data_type_with_name.second;
86
4.66k
    param.query_value = param_value;
87
4.66k
    param.query_type = get_query_type_from_fn_name();
88
4.66k
    param.num_rows = num_rows;
89
4.66k
    param.roaring = std::make_shared<roaring::Roaring>();
90
4.66k
    param.analyzer_ctx = analyzer_ctx;
91
4.68k
    if (is_string_type(param_type)) {
92
4.68k
        RETURN_IF_ERROR(iter->read_from_index(&param));
93
18.4E
    } else {
94
18.4E
        return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>(
95
18.4E
                "invalid params type for FunctionMatchBase::evaluate_inverted_index {}",
96
18.4E
                param_type);
97
18.4E
    }
98
4.68k
    std::shared_ptr<roaring::Roaring> null_bitmap = std::make_shared<roaring::Roaring>();
99
4.69k
    if (iter->has_null()) {
100
4.69k
        segment_v2::InvertedIndexQueryCacheHandle null_bitmap_cache_handle;
101
4.69k
        RETURN_IF_ERROR(iter->read_null_bitmap(&null_bitmap_cache_handle));
102
4.69k
        null_bitmap = null_bitmap_cache_handle.get_bitmap();
103
4.69k
    }
104
4.68k
    segment_v2::InvertedIndexResultBitmap result(param.roaring, null_bitmap);
105
4.68k
    bitmap_result = result;
106
4.68k
    bitmap_result.mask_out_null();
107
108
4.68k
    return Status::OK();
109
4.68k
}
110
Status FunctionMatchBase::execute_impl(FunctionContext* context, Block& block,
111
                                       const ColumnNumbers& arguments, uint32_t result,
112
505
                                       size_t input_rows_count) const {
113
505
    ColumnPtr& column_ptr = block.get_by_position(arguments[1]).column;
114
505
    DataTypePtr& type_ptr = block.get_by_position(arguments[1]).type;
115
116
505
    auto format_options = DataTypeSerDe::get_default_format_options();
117
505
    auto time_zone = cctz::utc_time_zone();
118
505
    format_options.timezone =
119
18.4E
            (context && context->state()) ? &context->state()->timezone_obj() : &time_zone;
120
121
505
    auto match_query_str = type_ptr->to_string(*column_ptr, 0, format_options);
122
505
    std::string column_name = block.get_by_position(arguments[0]).name;
123
18.4E
    VLOG_DEBUG << "begin to execute match directly, column_name=" << column_name
124
18.4E
               << ", match_query_str=" << match_query_str;
125
505
    auto* analyzer_ctx = get_match_analyzer_ctx(context);
126
505
    const ColumnPtr source_col =
127
505
            block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
128
505
    const auto* values = check_and_get_column<ColumnString>(source_col.get());
129
505
    const ColumnArray* array_col = nullptr;
130
505
    if (is_column<ColumnArray>(source_col.get())) {
131
11
        array_col = check_and_get_column<ColumnArray>(source_col.get());
132
11
        if (array_col && !array_col->get_data().is_column_string()) {
133
0
            return Status::NotSupported(fmt::format(
134
0
                    "unsupported nested array of type {} for function {}",
135
0
                    is_column_nullable(array_col->get_data()) ? array_col->get_data().get_name()
136
0
                                                              : array_col->get_data().get_name(),
137
0
                    get_name()));
138
0
        }
139
140
11
        if (is_column_nullable(array_col->get_data())) {
141
11
            const auto& array_nested_null_column =
142
11
                    reinterpret_cast<const ColumnNullable&>(array_col->get_data());
143
11
            values = check_and_get_column<ColumnString>(
144
11
                    *(array_nested_null_column.get_nested_column_ptr()));
145
11
        } else {
146
            // array column element is always set Nullable for now.
147
0
            values = check_and_get_column<ColumnString>(*(array_col->get_data_ptr()));
148
0
        }
149
494
    } else if (const auto* nullable = check_and_get_column<ColumnNullable>(source_col.get())) {
150
0
        values = check_and_get_column<ColumnString>(*nullable->get_nested_column_ptr());
151
0
    }
152
153
505
    if (!values) {
154
0
        LOG(WARNING) << "Illegal column " << source_col->get_name();
155
0
        return Status::InternalError("Not supported input column types");
156
0
    }
157
    // result column
158
505
    auto res = ColumnUInt8::create();
159
505
    ColumnUInt8::Container& vec_res = res->get_data();
160
    // set default value to 0, and match functions only need to set 1/true
161
505
    vec_res.resize_fill(input_rows_count);
162
505
    RETURN_IF_ERROR(execute_match(context, column_name, match_query_str, input_rows_count, values,
163
505
                                  analyzer_ctx, (array_col ? &(array_col->get_offsets()) : nullptr),
164
505
                                  vec_res));
165
502
    block.replace_by_position(result, std::move(res));
166
167
502
    return Status::OK();
168
505
}
169
170
inline doris::segment_v2::InvertedIndexQueryType FunctionMatchBase::get_query_type_from_fn_name()
171
4.68k
        const {
172
4.68k
    std::string fn_name = get_name();
173
4.68k
    if (fn_name == MATCH_ANY_FUNCTION) {
174
3.42k
        return doris::segment_v2::InvertedIndexQueryType::MATCH_ANY_QUERY;
175
3.42k
    } else if (fn_name == MATCH_ALL_FUNCTION) {
176
678
        return doris::segment_v2::InvertedIndexQueryType::MATCH_ALL_QUERY;
177
678
    } else if (fn_name == MATCH_PHRASE_FUNCTION) {
178
514
        return doris::segment_v2::InvertedIndexQueryType::MATCH_PHRASE_QUERY;
179
514
    } else if (fn_name == MATCH_PHRASE_PREFIX_FUNCTION) {
180
35
        return doris::segment_v2::InvertedIndexQueryType::MATCH_PHRASE_PREFIX_QUERY;
181
35
    } else if (fn_name == MATCH_PHRASE_REGEXP_FUNCTION) {
182
22
        return doris::segment_v2::InvertedIndexQueryType::MATCH_REGEXP_QUERY;
183
22
    } else if (fn_name == MATCH_PHRASE_EDGE_FUNCTION) {
184
3
        return doris::segment_v2::InvertedIndexQueryType::MATCH_PHRASE_EDGE_QUERY;
185
3
    }
186
0
    return doris::segment_v2::InvertedIndexQueryType::UNKNOWN_QUERY;
187
4.68k
}
188
189
std::vector<TermInfo> FunctionMatchBase::analyse_query_str_token(
190
        const InvertedIndexAnalyzerCtx* analyzer_ctx, const std::string& match_query_str,
191
506
        const std::string& column_name) const {
192
506
    std::vector<TermInfo> query_tokens;
193
506
    if (analyzer_ctx == nullptr) {
194
3
        return query_tokens;
195
3
    }
196
197
503
    VLOG_DEBUG << "begin to run " << get_name() << ", parser_type: "
198
0
               << inverted_index_parser_type_to_string(analyzer_ctx->parser_type);
199
200
    // Decision is based on parser_type (from index properties):
201
    // - PARSER_NONE: no tokenization (keyword/exact match)
202
    // - Other parsers: tokenize using the analyzer
203
503
    if (!analyzer_ctx->should_tokenize()) {
204
        // Keyword index: all strings (including empty) are valid tokens for exact match.
205
        // Empty string is a valid value in keyword index and should be matchable.
206
4
        query_tokens.emplace_back(match_query_str);
207
4
        return query_tokens;
208
4
    }
209
210
    // Safety check: if analyzer is nullptr but tokenization is expected, fall back to no tokenization
211
499
    if (analyzer_ctx->analyzer == nullptr) {
212
0
        VLOG_DEBUG << "Analyzer is nullptr, falling back to no tokenization";
213
        // For fallback case, also allow empty strings to be matched
214
0
        query_tokens.emplace_back(match_query_str);
215
0
        return query_tokens;
216
0
    }
217
218
    // Tokenize using the analyzer
219
499
    auto reader = doris::segment_v2::inverted_index::InvertedIndexAnalyzer::create_reader(
220
499
            analyzer_ctx->char_filter_map);
221
499
    reader->init(match_query_str.data(), (int)match_query_str.size(), true);
222
499
    query_tokens = doris::segment_v2::inverted_index::InvertedIndexAnalyzer::get_analyse_result(
223
499
            reader, analyzer_ctx->analyzer.get());
224
499
    return query_tokens;
225
499
}
226
227
inline std::vector<TermInfo> FunctionMatchBase::analyse_data_token(
228
        const std::string& column_name, const InvertedIndexAnalyzerCtx* analyzer_ctx,
229
        const ColumnString* string_col, int32_t current_block_row_idx,
230
25.3k
        const ColumnArray::Offsets64* array_offsets, int32_t& current_src_array_offset) const {
231
25.3k
    std::vector<TermInfo> data_tokens;
232
25.3k
    if (analyzer_ctx == nullptr) {
233
0
        return data_tokens;
234
0
    }
235
236
    // Determine tokenization strategy based on parser_type
237
25.3k
    const bool should_tokenize =
238
25.3k
            analyzer_ctx->should_tokenize() && analyzer_ctx->analyzer != nullptr;
239
240
25.3k
    if (array_offsets) {
241
13
        for (auto next_src_array_offset = (*array_offsets)[current_block_row_idx];
242
28
             current_src_array_offset < next_src_array_offset; ++current_src_array_offset) {
243
15
            const auto& str_ref = string_col->get_data_at(current_src_array_offset);
244
15
            if (!should_tokenize) {
245
0
                data_tokens.emplace_back(str_ref.to_string());
246
0
                continue;
247
0
            }
248
15
            auto reader = doris::segment_v2::inverted_index::InvertedIndexAnalyzer::create_reader(
249
15
                    analyzer_ctx->char_filter_map);
250
15
            reader->init(str_ref.data, (int)str_ref.size, true);
251
15
            data_tokens =
252
15
                    doris::segment_v2::inverted_index::InvertedIndexAnalyzer::get_analyse_result(
253
15
                            reader, analyzer_ctx->analyzer.get());
254
15
        }
255
25.3k
    } else {
256
25.3k
        const auto& str_ref = string_col->get_data_at(current_block_row_idx);
257
25.3k
        if (!should_tokenize) {
258
15
            data_tokens.emplace_back(str_ref.to_string());
259
25.3k
        } else {
260
25.3k
            auto reader = doris::segment_v2::inverted_index::InvertedIndexAnalyzer::create_reader(
261
25.3k
                    analyzer_ctx->char_filter_map);
262
25.3k
            reader->init(str_ref.data, (int)str_ref.size, true);
263
25.3k
            data_tokens =
264
25.3k
                    doris::segment_v2::inverted_index::InvertedIndexAnalyzer::get_analyse_result(
265
25.3k
                            reader, analyzer_ctx->analyzer.get());
266
25.3k
        }
267
25.3k
    }
268
25.3k
    return data_tokens;
269
25.3k
}
270
271
506
Status FunctionMatchBase::check(FunctionContext* context, const std::string& function_name) const {
272
506
    if (!context->state()->query_options().enable_match_without_inverted_index) {
273
2
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
274
2
                "{} not support execute_match", function_name);
275
2
    }
276
277
504
    DBUG_EXECUTE_IF("match.invert_index_not_support_execute_match", {
278
504
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
279
504
                "debug point: {} not support execute_match", function_name);
280
504
    });
281
282
504
    return Status::OK();
283
504
}
284
285
Status FunctionMatchAny::execute_match(FunctionContext* context, const std::string& column_name,
286
                                       const std::string& match_query_str, size_t input_rows_count,
287
                                       const ColumnString* string_col,
288
                                       const InvertedIndexAnalyzerCtx* analyzer_ctx,
289
                                       const ColumnArray::Offsets64* array_offsets,
290
314
                                       ColumnUInt8::Container& result) const {
291
314
    RETURN_IF_ERROR(check(context, name));
292
293
314
    auto query_tokens = analyse_query_str_token(analyzer_ctx, match_query_str, column_name);
294
314
    if (query_tokens.empty()) {
295
6
        VLOG_DEBUG << fmt::format(
296
0
                "token parser result is empty for query, "
297
0
                "please check your query: '{}' and index parser: '{}'",
298
0
                match_query_str,
299
0
                analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
300
0
                             : "unknown");
301
6
        return Status::OK();
302
6
    }
303
304
308
    auto current_src_array_offset = 0;
305
20.4k
    for (int i = 0; i < input_rows_count; i++) {
306
20.1k
        auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
307
20.1k
                                              array_offsets, current_src_array_offset);
308
309
        // TODO: more efficient impl
310
20.9k
        for (auto& term_info : query_tokens) {
311
20.9k
            auto it =
312
73.6k
                    std::find_if(data_tokens.begin(), data_tokens.end(), [&](const TermInfo& info) {
313
73.6k
                        return info.get_single_term() == term_info.get_single_term();
314
73.6k
                    });
315
20.9k
            if (it != data_tokens.end()) {
316
11.6k
                result[i] = true;
317
11.6k
                break;
318
11.6k
            }
319
20.9k
        }
320
20.1k
    }
321
322
308
    return Status::OK();
323
314
}
324
325
Status FunctionMatchAll::execute_match(FunctionContext* context, const std::string& column_name,
326
                                       const std::string& match_query_str, size_t input_rows_count,
327
                                       const ColumnString* string_col,
328
                                       const InvertedIndexAnalyzerCtx* analyzer_ctx,
329
                                       const ColumnArray::Offsets64* array_offsets,
330
94
                                       ColumnUInt8::Container& result) const {
331
94
    RETURN_IF_ERROR(check(context, name));
332
333
94
    auto query_tokens = analyse_query_str_token(analyzer_ctx, match_query_str, column_name);
334
94
    if (query_tokens.empty()) {
335
5
        VLOG_DEBUG << fmt::format(
336
0
                "token parser result is empty for query, "
337
0
                "please check your query: '{}' and index parser: '{}'",
338
0
                match_query_str,
339
0
                analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
340
0
                             : "unknown");
341
5
        return Status::OK();
342
5
    }
343
344
89
    auto current_src_array_offset = 0;
345
1.19k
    for (int i = 0; i < input_rows_count; i++) {
346
1.10k
        auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
347
1.10k
                                              array_offsets, current_src_array_offset);
348
349
        // TODO: more efficient impl
350
1.10k
        auto find_count = 0;
351
1.35k
        for (auto& term_info : query_tokens) {
352
1.35k
            auto it =
353
9.62k
                    std::find_if(data_tokens.begin(), data_tokens.end(), [&](const TermInfo& info) {
354
9.62k
                        return info.get_single_term() == term_info.get_single_term();
355
9.62k
                    });
356
1.35k
            if (it != data_tokens.end()) {
357
398
                ++find_count;
358
961
            } else {
359
961
                break;
360
961
            }
361
1.35k
        }
362
363
1.10k
        if (find_count == query_tokens.size()) {
364
141
            result[i] = true;
365
141
        }
366
1.10k
    }
367
368
89
    return Status::OK();
369
94
}
370
371
Status FunctionMatchPhrase::execute_match(FunctionContext* context, const std::string& column_name,
372
                                          const std::string& match_query_str,
373
                                          size_t input_rows_count, const ColumnString* string_col,
374
                                          const InvertedIndexAnalyzerCtx* analyzer_ctx,
375
                                          const ColumnArray::Offsets64* array_offsets,
376
84
                                          ColumnUInt8::Container& result) const {
377
84
    RETURN_IF_ERROR(check(context, name));
378
379
83
    auto query_tokens = analyse_query_str_token(analyzer_ctx, match_query_str, column_name);
380
83
    if (query_tokens.empty()) {
381
7
        VLOG_DEBUG << fmt::format(
382
0
                "token parser result is empty for query, "
383
0
                "please check your query: '{}' and index parser: '{}'",
384
0
                match_query_str,
385
0
                analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
386
0
                             : "unknown");
387
7
        return Status::OK();
388
7
    }
389
390
76
    auto current_src_array_offset = 0;
391
1.16k
    for (int i = 0; i < input_rows_count; i++) {
392
1.08k
        auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
393
1.08k
                                              array_offsets, current_src_array_offset);
394
395
        // TODO: more efficient impl
396
1.08k
        bool matched = false;
397
1.08k
        auto data_it = data_tokens.begin();
398
2.16k
        while (data_it != data_tokens.end()) {
399
            // find position of first token
400
8.63k
            data_it = std::find_if(data_it, data_tokens.end(), [&](const TermInfo& info) {
401
8.63k
                return info.get_single_term() == query_tokens[0].get_single_term();
402
8.63k
            });
403
1.19k
            if (data_it != data_tokens.end()) {
404
234
                matched = true;
405
234
                auto data_it_next = ++data_it;
406
234
                auto query_it = query_tokens.begin() + 1;
407
                // compare query_tokens after the first to data_tokens one by one
408
356
                while (query_it != query_tokens.end()) {
409
238
                    if (data_it_next == data_tokens.end() ||
410
238
                        data_it_next->get_single_term() != query_it->get_single_term()) {
411
116
                        matched = false;
412
116
                        break;
413
116
                    }
414
122
                    query_it++;
415
122
                    data_it_next++;
416
122
                }
417
418
234
                if (matched) {
419
118
                    break;
420
118
                }
421
234
            }
422
1.19k
        }
423
424
        // check matched
425
1.08k
        if (matched) {
426
118
            result[i] = true;
427
118
        }
428
1.08k
    }
429
430
76
    return Status::OK();
431
83
}
432
433
Status FunctionMatchPhrasePrefix::execute_match(
434
        FunctionContext* context, const std::string& column_name,
435
        const std::string& match_query_str, size_t input_rows_count, const ColumnString* string_col,
436
        const InvertedIndexAnalyzerCtx* analyzer_ctx, const ColumnArray::Offsets64* array_offsets,
437
8
        ColumnUInt8::Container& result) const {
438
8
    RETURN_IF_ERROR(check(context, name));
439
440
7
    auto query_tokens = analyse_query_str_token(analyzer_ctx, match_query_str, column_name);
441
7
    if (query_tokens.empty()) {
442
2
        VLOG_DEBUG << fmt::format(
443
0
                "token parser result is empty for query, "
444
0
                "please check your query: '{}' and index parser: '{}'",
445
0
                match_query_str,
446
0
                analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
447
0
                             : "unknown");
448
2
        return Status::OK();
449
2
    }
450
451
5
    int32_t current_src_array_offset = 0;
452
1.01k
    for (int i = 0; i < input_rows_count; i++) {
453
1.00k
        auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
454
1.00k
                                              array_offsets, current_src_array_offset);
455
456
1.00k
        int64_t dis_count = data_tokens.size() - query_tokens.size();
457
1.00k
        if (dis_count < 0) {
458
4
            continue;
459
4
        }
460
461
8.38k
        for (size_t j = 0; j < dis_count + 1; j++) {
462
7.50k
            if (data_tokens[j].get_single_term() == query_tokens[0].get_single_term() ||
463
7.50k
                query_tokens.size() == 1) {
464
214
                bool match = true;
465
548
                for (size_t k = 0; k < query_tokens.size(); k++) {
466
425
                    const std::string& data_token = data_tokens[j + k].get_single_term();
467
425
                    const std::string& query_token = query_tokens[k].get_single_term();
468
425
                    if (k == query_tokens.size() - 1) {
469
214
                        if (data_token.compare(0, query_token.size(), query_token) != 0) {
470
91
                            match = false;
471
91
                            break;
472
91
                        }
473
214
                    } else {
474
211
                        if (data_token != query_token) {
475
0
                            match = false;
476
0
                            break;
477
0
                        }
478
211
                    }
479
425
                }
480
214
                if (match) {
481
123
                    result[i] = true;
482
123
                    break;
483
123
                }
484
214
            }
485
7.50k
        }
486
1.00k
    }
487
488
5
    return Status::OK();
489
7
}
490
491
Status FunctionMatchRegexp::execute_match(FunctionContext* context, const std::string& column_name,
492
                                          const std::string& match_query_str,
493
                                          size_t input_rows_count, const ColumnString* string_col,
494
                                          const InvertedIndexAnalyzerCtx* analyzer_ctx,
495
                                          const ColumnArray::Offsets64* array_offsets,
496
6
                                          ColumnUInt8::Container& result) const {
497
6
    RETURN_IF_ERROR(check(context, name));
498
499
6
    VLOG_DEBUG << "begin to run FunctionMatchRegexp::execute_match, parser_type: "
500
0
               << (analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
501
0
                                : "unknown");
502
503
6
    const std::string& pattern = match_query_str;
504
505
6
    hs_database_t* database = nullptr;
506
6
    hs_compile_error_t* compile_err = nullptr;
507
6
    hs_scratch_t* scratch = nullptr;
508
509
6
    if (hs_compile(pattern.data(), HS_FLAG_DOTALL | HS_FLAG_ALLOWEMPTY | HS_FLAG_UTF8,
510
6
                   HS_MODE_BLOCK, nullptr, &database, &compile_err) != HS_SUCCESS) {
511
1
        std::string err_message = "hyperscan compilation failed: ";
512
1
        err_message.append(compile_err->message);
513
1
        LOG(ERROR) << err_message;
514
1
        hs_free_compile_error(compile_err);
515
1
        return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>(err_message);
516
1
    }
517
518
5
    if (hs_alloc_scratch(database, &scratch) != HS_SUCCESS) {
519
0
        LOG(ERROR) << "hyperscan could not allocate scratch space.";
520
0
        hs_free_database(database);
521
0
        return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>(
522
0
                "hyperscan could not allocate scratch space.");
523
0
    }
524
525
5
    auto on_match = [](unsigned int id, unsigned long long from, unsigned long long to,
526
4.06k
                       unsigned int flags, void* context) -> int {
527
4.06k
        *((bool*)context) = true;
528
4.06k
        return 0;
529
4.06k
    };
530
531
5
    try {
532
5
        auto current_src_array_offset = 0;
533
2.00k
        for (int i = 0; i < input_rows_count; i++) {
534
2.00k
            auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
535
2.00k
                                                  array_offsets, current_src_array_offset);
536
537
9.62k
            for (auto& input : data_tokens) {
538
9.62k
                bool is_match = false;
539
9.62k
                const auto& input_str = input.get_single_term();
540
9.62k
                if (hs_scan(database, input_str.data(), (uint32_t)input_str.size(), 0, scratch,
541
9.62k
                            on_match, (void*)&is_match) != HS_SUCCESS) {
542
0
                    LOG(ERROR) << "hyperscan match failed: " << input_str;
543
0
                    break;
544
0
                }
545
546
9.62k
                if (is_match) {
547
1.06k
                    result[i] = true;
548
1.06k
                    break;
549
1.06k
                }
550
9.62k
            }
551
2.00k
        }
552
5
    }
553
5
    _CLFINALLY({
554
5
        hs_free_scratch(scratch);
555
5
        hs_free_database(database);
556
5
    })
557
558
5
    return Status::OK();
559
5
}
560
561
Status FunctionMatchPhraseEdge::execute_match(
562
        FunctionContext* context, const std::string& column_name,
563
        const std::string& match_query_str, size_t input_rows_count, const ColumnString* string_col,
564
        const InvertedIndexAnalyzerCtx* analyzer_ctx, const ColumnArray::Offsets64* array_offsets,
565
0
        ColumnUInt8::Container& result) const {
566
0
    RETURN_IF_ERROR(check(context, name));
567
568
0
    auto query_tokens = analyse_query_str_token(analyzer_ctx, match_query_str, column_name);
569
0
    if (query_tokens.empty()) {
570
0
        VLOG_DEBUG << fmt::format(
571
0
                "token parser result is empty for query, "
572
0
                "please check your query: '{}' and index parser: '{}'",
573
0
                match_query_str,
574
0
                analyzer_ctx ? inverted_index_parser_type_to_string(analyzer_ctx->parser_type)
575
0
                             : "unknown");
576
0
        return Status::OK();
577
0
    }
578
579
0
    int32_t current_src_array_offset = 0;
580
0
    for (int i = 0; i < input_rows_count; i++) {
581
0
        auto data_tokens = analyse_data_token(column_name, analyzer_ctx, string_col, i,
582
0
                                              array_offsets, current_src_array_offset);
583
584
0
        int64_t dis_count = data_tokens.size() - query_tokens.size();
585
0
        if (dis_count < 0) {
586
0
            continue;
587
0
        }
588
589
0
        for (size_t j = 0; j < dis_count + 1; j++) {
590
0
            bool match = true;
591
0
            if (query_tokens.size() == 1) {
592
0
                if (data_tokens[j].get_single_term().find(query_tokens[0].get_single_term()) ==
593
0
                    std::string::npos) {
594
0
                    match = false;
595
0
                }
596
0
            } else {
597
0
                for (size_t k = 0; k < query_tokens.size(); k++) {
598
0
                    const std::string& data_token = data_tokens[j + k].get_single_term();
599
0
                    const std::string& query_token = query_tokens[k].get_single_term();
600
0
                    if (k == 0) {
601
0
                        if (!data_token.ends_with(query_token)) {
602
0
                            match = false;
603
0
                            break;
604
0
                        }
605
0
                    } else if (k == query_tokens.size() - 1) {
606
0
                        if (!data_token.starts_with(query_token)) {
607
0
                            match = false;
608
0
                            break;
609
0
                        }
610
0
                    } else {
611
0
                        if (data_token != query_token) {
612
0
                            match = false;
613
0
                            break;
614
0
                        }
615
0
                    }
616
0
                }
617
0
            }
618
0
            if (match) {
619
0
                result[i] = true;
620
0
                break;
621
0
            }
622
0
        }
623
0
    }
624
625
0
    return Status::OK();
626
0
}
627
628
8
void register_function_match(SimpleFunctionFactory& factory) {
629
8
    factory.register_function<FunctionMatchAny>();
630
8
    factory.register_function<FunctionMatchAll>();
631
8
    factory.register_function<FunctionMatchPhrase>();
632
8
    factory.register_function<FunctionMatchPhrasePrefix>();
633
8
    factory.register_function<FunctionMatchRegexp>();
634
8
    factory.register_function<FunctionMatchPhraseEdge>();
635
8
}
636
} // namespace doris