Coverage Report

Created: 2026-04-14 07:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/function_tokenize.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/function_tokenize.h"
19
20
#include <glog/logging.h>
21
#include <rapidjson/prettywriter.h>
22
23
#include <algorithm>
24
#include <boost/regex.hpp>
25
#include <memory>
26
#include <utility>
27
28
#include "CLucene/StdHeader.h"
29
#include "CLucene/config/repl_wchar.h"
30
#include "core/block/block.h"
31
#include "core/block/column_with_type_and_name.h"
32
#include "core/column/column.h"
33
#include "core/data_type/data_type_nullable.h"
34
#include "core/data_type/data_type_number.h"
35
#include "core/string_ref.h"
36
#include "storage/index/inverted/analyzer/analyzer.h"
37
#include "storage/index/inverted/inverted_index_parser.h"
38
#include "storage/index/inverted/inverted_index_reader.h"
39
40
namespace doris {
41
using namespace doris::segment_v2::inverted_index;
42
43
150
Status parse(const std::string& str, std::map<std::string, std::string>& result) {
44
150
    boost::regex pattern(
45
150
            R"delimiter((?:'([^']*)'|"([^"]*)"|([^, ]*))\s*=\s*(?:'([^']*)'|"([^"]*)"|([^, ]*)))delimiter");
46
150
    boost::smatch matches;
47
48
150
    std::string::const_iterator searchStart(str.cbegin());
49
290
    while (boost::regex_search(searchStart, str.cend(), matches, pattern)) {
50
140
        std::string key = matches[1].length()
51
140
                                  ? matches[1].str()
52
140
                                  : (matches[2].length() ? matches[2].str() : matches[3].str());
53
140
        std::string value = matches[4].length()
54
140
                                    ? matches[4].str()
55
140
                                    : (matches[5].length() ? matches[5].str() : matches[6].str());
56
57
140
        result[key] = value;
58
59
140
        searchStart = matches.suffix().first;
60
140
    }
61
62
150
    return Status::OK();
63
150
}
64
65
void FunctionTokenize::_do_tokenize_none(const ColumnString& src_column_string,
66
40
                                         const MutableColumnPtr& dest_column_ptr) const {
67
40
    ColumnArray::Offset64 src_offsets_size = src_column_string.get_offsets().size();
68
201
    for (size_t i = 0; i < src_offsets_size; i++) {
69
161
        const StringRef tokenize_str = src_column_string.get_data_at(i);
70
71
161
        rapidjson::Document doc;
72
161
        doc.SetArray();
73
161
        rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
74
75
161
        rapidjson::Value obj(rapidjson::kObjectType);
76
161
        obj.AddMember(
77
161
                "token",
78
161
                rapidjson::Value(tokenize_str.data,
79
161
                                 static_cast<rapidjson::SizeType>(tokenize_str.size), allocator)
80
161
                        .Move(),
81
161
                allocator);
82
161
        doc.PushBack(obj, allocator);
83
84
161
        rapidjson::StringBuffer buffer;
85
161
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
86
161
        writer.SetFormatOptions(rapidjson::kFormatSingleLineArray);
87
161
        doc.Accept(writer);
88
161
        const std::string json_array_str = buffer.GetString();
89
90
161
        dest_column_ptr->insert_data(json_array_str.data(), json_array_str.size());
91
161
    }
92
40
}
93
94
void FunctionTokenize::_do_tokenize(const ColumnString& src_column_string,
95
                                    const InvertedIndexAnalyzerCtx& analyzer_ctx,
96
                                    bool support_phrase,
97
108
                                    const MutableColumnPtr& dest_column_ptr) const {
98
108
    ColumnArray::Offset64 src_offsets_size = src_column_string.get_offsets().size();
99
227
    for (size_t i = 0; i < src_offsets_size; i++) {
100
119
        const StringRef tokenize_str = src_column_string.get_data_at(i);
101
119
        if (tokenize_str.size == 0) {
102
1
            dest_column_ptr->insert_data("", 0);
103
1
            continue;
104
1
        }
105
106
118
        auto reader = InvertedIndexAnalyzer::create_reader(analyzer_ctx.char_filter_map);
107
118
        reader->init(tokenize_str.data, (int)tokenize_str.size, true);
108
118
        auto analyzer_tokens =
109
118
                InvertedIndexAnalyzer::get_analyse_result(reader, analyzer_ctx.analyzer.get());
110
111
118
        rapidjson::Document doc;
112
118
        doc.SetArray();
113
118
        rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
114
595
        for (const auto& analyzer_token : analyzer_tokens) {
115
595
            rapidjson::Value obj(rapidjson::kObjectType);
116
595
            obj.AddMember(
117
595
                    "token",
118
595
                    rapidjson::Value(analyzer_token.get_single_term().c_str(), allocator).Move(),
119
595
                    allocator);
120
595
            if (support_phrase) {
121
0
                obj.AddMember("position", analyzer_token.position, allocator);
122
0
            }
123
595
            doc.PushBack(obj, allocator);
124
595
        }
125
118
        rapidjson::StringBuffer buffer;
126
118
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
127
118
        writer.SetFormatOptions(rapidjson::kFormatSingleLineArray);
128
118
        doc.Accept(writer);
129
118
        const std::string json_array_str = buffer.GetString();
130
131
118
        dest_column_ptr->insert_data(json_array_str.data(), json_array_str.size());
132
118
    }
133
108
}
134
135
Status FunctionTokenize::execute_impl(FunctionContext* /*context*/, Block& block,
136
                                      const ColumnNumbers& arguments, uint32_t result,
137
150
                                      size_t /*input_rows_count*/) const {
138
150
    DCHECK_EQ(arguments.size(), 2);
139
150
    const auto& [src_column, left_const] =
140
150
            unpack_if_const(block.get_by_position(arguments[0]).column);
141
150
    const auto& [right_column, right_const] =
142
150
            unpack_if_const(block.get_by_position(arguments[1]).column);
143
144
150
    auto dest_column_type = std::make_shared<DataTypeString>();
145
150
    auto dest_column_ptr = dest_column_type->create_column();
146
147
150
    if (const auto* col_left = check_and_get_column<ColumnString>(src_column.get())) {
148
150
        if (const auto* col_right = check_and_get_column<ColumnString>(right_column.get())) {
149
150
            std::map<std::string, std::string> properties;
150
150
            auto st = parse(col_right->get_data_at(0).to_string(), properties);
151
150
            if (!st.ok()) {
152
0
                return st;
153
0
            }
154
150
            InvertedIndexAnalyzerConfig config;
155
150
            config.analyzer_name = get_analyzer_name_from_properties(properties);
156
150
            config.parser_type = get_inverted_index_parser_type_from_string(
157
150
                    get_parser_string_from_properties(properties));
158
150
            if (config.parser_type == InvertedIndexParserType::PARSER_UNKNOWN) {
159
2
                return Status::Error<doris::ErrorCode::INDEX_INVALID_PARAMETERS>(
160
2
                        "unsupported parser type. currently, only 'english', 'chinese', "
161
2
                        "'unicode', 'icu', 'basic' and 'ik' analyzers are supported.");
162
2
            }
163
164
            // Special handling for PARSER_NONE: return original string as single token
165
148
            if (config.analyzer_name.empty() &&
166
148
                config.parser_type == InvertedIndexParserType::PARSER_NONE) {
167
40
                _do_tokenize_none(*col_left, dest_column_ptr);
168
40
                block.replace_by_position(result, std::move(dest_column_ptr));
169
40
                return Status::OK();
170
40
            }
171
172
108
            config.parser_mode = get_parser_mode_string_from_properties(properties);
173
108
            config.char_filter_map = get_parser_char_filter_map_from_properties(properties);
174
108
            config.lower_case = get_parser_lowercase_from_properties(properties);
175
108
            config.stop_words = get_parser_stopwords_from_properties(properties);
176
108
            bool support_phrase = get_parser_phrase_support_string_from_properties(properties) ==
177
108
                                  INVERTED_INDEX_PARSER_PHRASE_SUPPORT_YES;
178
179
108
            std::shared_ptr<lucene::analysis::Analyzer> analyzer_holder;
180
108
            try {
181
108
                analyzer_holder =
182
108
                        doris::segment_v2::inverted_index::InvertedIndexAnalyzer::create_analyzer(
183
108
                                &config);
184
108
            } catch (CLuceneError& e) {
185
0
                return Status::Error<doris::ErrorCode::INVERTED_INDEX_ANALYZER_ERROR>(
186
0
                        "inverted index create analyzer failed: {}", e.what());
187
0
            } catch (Exception& e) {
188
0
                return Status::Error<doris::ErrorCode::INVERTED_INDEX_ANALYZER_ERROR>(
189
0
                        "inverted index create analyzer failed: {}", e.what());
190
0
            }
191
192
108
            InvertedIndexAnalyzerCtx analyzer_ctx;
193
108
            analyzer_ctx.analyzer_name = config.analyzer_name;
194
108
            analyzer_ctx.parser_type = config.parser_type;
195
108
            analyzer_ctx.char_filter_map = config.char_filter_map;
196
108
            analyzer_ctx.analyzer = analyzer_holder;
197
108
            _do_tokenize(*col_left, analyzer_ctx, support_phrase, dest_column_ptr);
198
199
108
            block.replace_by_position(result, std::move(dest_column_ptr));
200
108
            return Status::OK();
201
108
        }
202
150
    }
203
0
    return Status::RuntimeError("unimplemented function {}", get_name());
204
150
}
205
206
13
void register_function_tokenize(SimpleFunctionFactory& factory) {
207
13
    factory.register_function<FunctionTokenize>();
208
13
}
209
210
} // namespace doris