Coverage Report

Created: 2026-10-01 01:35

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