Coverage Report

Created: 2026-10-19 09:41

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