Coverage Report

Created: 2026-04-11 00:05

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