Coverage Report

Created: 2026-10-17 01:05

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