Coverage Report

Created: 2026-03-13 09:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/function_search.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_search.h"
19
20
#include <CLucene/config/repl_wchar.h>
21
#include <CLucene/search/Scorer.h>
22
#include <gen_cpp/Exprs_types.h>
23
#include <glog/logging.h>
24
25
#include <limits>
26
#include <memory>
27
#include <roaring/roaring.hh>
28
#include <set>
29
#include <string>
30
#include <unordered_map>
31
#include <unordered_set>
32
#include <vector>
33
34
#include "common/status.h"
35
#include "core/block/columns_with_type_and_name.h"
36
#include "core/column/column_const.h"
37
#include "core/data_type/data_type_string.h"
38
#include "exprs/function/simple_function_factory.h"
39
#include "exprs/vexpr_context.h"
40
#include "storage/index/index_file_reader.h"
41
#include "storage/index/index_query_context.h"
42
#include "storage/index/inverted/analyzer/analyzer.h"
43
#include "storage/index/inverted/inverted_index_iterator.h"
44
#include "storage/index/inverted/inverted_index_parser.h"
45
#include "storage/index/inverted/inverted_index_reader.h"
46
#include "storage/index/inverted/inverted_index_searcher.h"
47
#include "storage/index/inverted/query/query_helper.h"
48
#include "storage/index/inverted/query_v2/all_query/all_query.h"
49
#include "storage/index/inverted/query_v2/bit_set_query/bit_set_query.h"
50
#include "storage/index/inverted/query_v2/boolean_query/boolean_query_builder.h"
51
#include "storage/index/inverted/query_v2/boolean_query/operator.h"
52
#include "storage/index/inverted/query_v2/phrase_query/multi_phrase_query.h"
53
#include "storage/index/inverted/query_v2/phrase_query/phrase_query.h"
54
#include "storage/index/inverted/query_v2/regexp_query/regexp_query.h"
55
#include "storage/index/inverted/query_v2/term_query/term_query.h"
56
#include "storage/index/inverted/query_v2/wildcard_query/wildcard_query.h"
57
#include "storage/index/inverted/util/string_helper.h"
58
#include "storage/segment/segment.h"
59
#include "storage/segment/variant/nested_group_path.h"
60
#include "storage/segment/variant/nested_group_provider.h"
61
#include "storage/segment/variant/variant_column_reader.h"
62
#include "storage/types.h"
63
#include "util/string_util.h"
64
#include "util/thrift_util.h"
65
66
namespace doris {
67
68
// Build canonical DSL signature for cache key.
69
// Serializes the entire TSearchParam via Thrift binary protocol so that
70
// every field (DSL, AST root, field bindings, default_operator,
71
// minimum_should_match, etc.) is included automatically.
72
1.31k
static std::string build_dsl_signature(const TSearchParam& param) {
73
1.31k
    ThriftSerializer ser(false, 1024);
74
1.31k
    TSearchParam copy = param;
75
1.31k
    std::string sig;
76
1.31k
    auto st = ser.serialize(&copy, &sig);
77
1.31k
    if (UNLIKELY(!st.ok())) {
78
0
        LOG(WARNING) << "build_dsl_signature: Thrift serialization failed: " << st.to_string()
79
0
                     << ", caching disabled for this query";
80
0
        return "";
81
0
    }
82
1.31k
    return sig;
83
1.31k
}
84
85
// Extract segment path prefix from the first available inverted index iterator.
86
// All fields in the same segment share the same path prefix.
87
static std::string extract_segment_prefix(
88
1.28k
        const std::unordered_map<std::string, IndexIterator*>& iterators) {
89
1.28k
    for (const auto& [field_name, iter] : iterators) {
90
1.28k
        auto* inv_iter = dynamic_cast<InvertedIndexIterator*>(iter);
91
1.28k
        if (!inv_iter) continue;
92
        // Try fulltext reader first, then string type
93
1.25k
        for (auto type :
94
1.59k
             {InvertedIndexReaderType::FULLTEXT, InvertedIndexReaderType::STRING_TYPE}) {
95
1.59k
            IndexReaderType reader_type = type;
96
1.59k
            auto reader = inv_iter->get_reader(reader_type);
97
1.59k
            if (!reader) continue;
98
1.24k
            auto inv_reader = std::dynamic_pointer_cast<InvertedIndexReader>(reader);
99
1.24k
            if (!inv_reader) continue;
100
1.24k
            auto file_reader = inv_reader->get_index_file_reader();
101
1.24k
            if (!file_reader) continue;
102
1.24k
            return file_reader->get_index_path_prefix();
103
1.24k
        }
104
1.25k
    }
105
36
    VLOG_DEBUG << "extract_segment_prefix: no suitable inverted index reader found across "
106
11
               << iterators.size() << " iterators, caching disabled for this query";
107
36
    return "";
108
1.28k
}
109
110
namespace {
111
112
3
bool is_nested_group_search_supported() {
113
3
    auto provider = segment_v2::create_nested_group_read_provider();
114
3
    return provider != nullptr && provider->should_enable_nested_group_read_path();
115
3
}
116
117
class ResolverNullBitmapAdapter final : public query_v2::NullBitmapResolver {
118
public:
119
1.09k
    explicit ResolverNullBitmapAdapter(const FieldReaderResolver& resolver) : _resolver(resolver) {}
120
121
    segment_v2::IndexIterator* iterator_for(const query_v2::Scorer& /*scorer*/,
122
1.59k
                                            const std::string& logical_field) const override {
123
1.59k
        if (logical_field.empty()) {
124
0
            return nullptr;
125
0
        }
126
1.59k
        return _resolver.get_iterator(logical_field);
127
1.59k
    }
128
129
private:
130
    const FieldReaderResolver& _resolver;
131
};
132
133
void populate_binding_context(const FieldReaderResolver& resolver,
134
1.08k
                              query_v2::QueryExecutionContext* exec_ctx) {
135
1.08k
    DCHECK(exec_ctx != nullptr);
136
1.08k
    exec_ctx->readers = resolver.readers();
137
1.08k
    exec_ctx->reader_bindings = resolver.reader_bindings();
138
1.08k
    exec_ctx->field_reader_bindings = resolver.field_readers();
139
1.61k
    for (const auto& [binding_key, binding] : resolver.binding_cache()) {
140
1.61k
        if (binding_key.empty()) {
141
0
            continue;
142
0
        }
143
1.61k
        query_v2::FieldBindingContext binding_ctx;
144
1.61k
        binding_ctx.logical_field_name = binding.logical_field_name;
145
1.61k
        binding_ctx.stored_field_name = binding.stored_field_name;
146
1.61k
        binding_ctx.stored_field_wstr = binding.stored_field_wstr;
147
1.61k
        exec_ctx->binding_fields.emplace(binding_key, std::move(binding_ctx));
148
1.61k
    }
149
1.08k
}
150
151
query_v2::QueryExecutionContext build_query_execution_context(
152
        uint32_t segment_num_rows, const FieldReaderResolver& resolver,
153
1.08k
        query_v2::NullBitmapResolver* null_resolver) {
154
1.08k
    query_v2::QueryExecutionContext exec_ctx;
155
1.08k
    exec_ctx.segment_num_rows = segment_num_rows;
156
1.08k
    populate_binding_context(resolver, &exec_ctx);
157
1.08k
    exec_ctx.null_resolver = null_resolver;
158
1.08k
    return exec_ctx;
159
1.08k
}
160
161
} // namespace
162
163
Status FieldReaderResolver::resolve(const std::string& field_name,
164
                                    InvertedIndexQueryType query_type,
165
1.96k
                                    FieldReaderBinding* binding) {
166
1.96k
    DCHECK(binding != nullptr);
167
168
    // Check if this is a variant subcolumn
169
1.96k
    bool is_variant_sub = is_variant_subcolumn(field_name);
170
171
1.96k
    auto data_it = _data_type_with_names.find(field_name);
172
1.96k
    if (data_it == _data_type_with_names.end()) {
173
        // For variant subcolumns, not finding the index is normal (the subcolumn may not exist in this segment)
174
        // Return OK but with null binding to signal "no match"
175
8
        if (is_variant_sub) {
176
3
            VLOG_DEBUG << "Variant subcolumn '" << field_name
177
0
                       << "' not found in this segment, treating as no match";
178
3
            *binding = FieldReaderBinding();
179
3
            return Status::OK();
180
3
        }
181
        // For normal fields, this is an error
182
5
        return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
183
5
                "field '{}' not found in inverted index metadata", field_name);
184
8
    }
185
186
1.95k
    const auto& stored_field_name = data_it->second.first;
187
1.95k
    const auto binding_key = binding_key_for(stored_field_name, query_type);
188
189
1.95k
    auto cache_it = _cache.find(binding_key);
190
1.95k
    if (cache_it != _cache.end()) {
191
311
        *binding = cache_it->second;
192
311
        return Status::OK();
193
311
    }
194
195
1.64k
    auto iterator_it = _iterators.find(field_name);
196
1.65k
    if (iterator_it == _iterators.end() || iterator_it->second == nullptr) {
197
        // For variant subcolumns, not finding the iterator is normal
198
17
        if (is_variant_sub) {
199
0
            VLOG_DEBUG << "Variant subcolumn '" << field_name
200
0
                       << "' iterator not found in this segment, treating as no match";
201
0
            *binding = FieldReaderBinding();
202
0
            return Status::OK();
203
0
        }
204
17
        return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
205
17
                "iterator not found for field '{}'", field_name);
206
17
    }
207
208
1.62k
    auto* inverted_iterator = dynamic_cast<InvertedIndexIterator*>(iterator_it->second);
209
1.62k
    if (inverted_iterator == nullptr) {
210
2
        return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
211
2
                "iterator for field '{}' is not InvertedIndexIterator", field_name);
212
2
    }
213
214
    // For variant subcolumns, FE resolves the field pattern to a specific index and sends
215
    // its index_properties via TSearchFieldBinding. When FE picks an analyzer-based index,
216
    // upgrade EQUAL_QUERY/WILDCARD_QUERY to MATCH_ANY_QUERY so select_best_reader picks the
217
    // FULLTEXT reader instead of STRING_TYPE. Without this upgrade:
218
    // - TERM (EQUAL_QUERY) clauses would open the wrong (untokenized) index directory
219
    // - WILDCARD clauses would enumerate terms from the wrong index, returning empty results
220
    //
221
    // For regular (non-variant) columns with multiple indexes, the caller (build_leaf_query)
222
    // is responsible for passing the appropriate query_type: MATCH_ANY_QUERY for tokenized
223
    // queries (TERM) and EQUAL_QUERY for exact-match queries (EXACT). This ensures
224
    // select_best_reader picks FULLTEXT vs STRING_TYPE correctly without needing an explicit
225
    // analyzer key, since the query_type alone drives the reader type preference.
226
1.62k
    InvertedIndexQueryType effective_query_type = query_type;
227
1.62k
    auto fb_it = _field_binding_map.find(field_name);
228
1.62k
    std::string analyzer_key;
229
1.62k
    if (is_variant_sub && fb_it != _field_binding_map.end() &&
230
1.62k
        fb_it->second->__isset.index_properties && !fb_it->second->index_properties.empty()) {
231
60
        analyzer_key = normalize_analyzer_key(
232
60
                build_analyzer_key_from_properties(fb_it->second->index_properties));
233
60
        if (inverted_index::InvertedIndexAnalyzer::should_analyzer(
234
60
                    fb_it->second->index_properties) &&
235
60
            (effective_query_type == InvertedIndexQueryType::EQUAL_QUERY ||
236
60
             effective_query_type == InvertedIndexQueryType::WILDCARD_QUERY)) {
237
0
            effective_query_type = InvertedIndexQueryType::MATCH_ANY_QUERY;
238
0
        }
239
60
    }
240
241
1.62k
    Result<InvertedIndexReaderPtr> reader_result;
242
1.62k
    const auto& column_type = data_it->second.second;
243
1.62k
    if (column_type) {
244
1.61k
        reader_result = inverted_iterator->select_best_reader(column_type, effective_query_type,
245
1.61k
                                                              analyzer_key);
246
1.61k
    } else {
247
9
        reader_result = inverted_iterator->select_best_reader(analyzer_key);
248
9
    }
249
250
1.62k
    if (!reader_result.has_value()) {
251
0
        return reader_result.error();
252
0
    }
253
254
1.62k
    auto inverted_reader = reader_result.value();
255
1.62k
    if (inverted_reader == nullptr) {
256
0
        return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
257
0
                "selected reader is null for field '{}'", field_name);
258
0
    }
259
260
1.62k
    auto index_file_reader = inverted_reader->get_index_file_reader();
261
1.62k
    if (index_file_reader == nullptr) {
262
0
        return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
263
0
                "index file reader is null for field '{}'", field_name);
264
0
    }
265
266
    // Use InvertedIndexSearcherCache to avoid re-opening index files repeatedly
267
1.62k
    auto index_file_key =
268
1.62k
            index_file_reader->get_index_file_cache_key(&inverted_reader->get_index_meta());
269
1.62k
    InvertedIndexSearcherCache::CacheKey searcher_cache_key(index_file_key);
270
1.62k
    InvertedIndexCacheHandle searcher_cache_handle;
271
1.62k
    bool cache_hit = InvertedIndexSearcherCache::instance()->lookup(searcher_cache_key,
272
1.62k
                                                                    &searcher_cache_handle);
273
274
1.62k
    std::shared_ptr<lucene::index::IndexReader> reader_holder;
275
1.62k
    if (cache_hit) {
276
1.36k
        auto searcher_variant = searcher_cache_handle.get_index_searcher();
277
1.36k
        auto* searcher_ptr = std::get_if<FulltextIndexSearcherPtr>(&searcher_variant);
278
1.37k
        if (searcher_ptr != nullptr && *searcher_ptr != nullptr) {
279
1.37k
            reader_holder = std::shared_ptr<lucene::index::IndexReader>(
280
1.37k
                    (*searcher_ptr)->getReader(),
281
1.38k
                    [](lucene::index::IndexReader*) { /* lifetime managed by searcher cache */ });
282
1.37k
        }
283
1.36k
    }
284
285
1.62k
    if (!reader_holder) {
286
        // Cache miss: open directory, build IndexSearcher, insert into cache
287
276
        RETURN_IF_ERROR(
288
276
                index_file_reader->init(config::inverted_index_read_buffer_size, _context->io_ctx));
289
276
        auto directory = DORIS_TRY(
290
276
                index_file_reader->open(&inverted_reader->get_index_meta(), _context->io_ctx));
291
292
276
        auto index_searcher_builder = DORIS_TRY(
293
276
                IndexSearcherBuilder::create_index_searcher_builder(inverted_reader->type()));
294
276
        auto searcher_result =
295
276
                DORIS_TRY(index_searcher_builder->get_index_searcher(directory.get()));
296
276
        auto reader_size = index_searcher_builder->get_reader_size();
297
298
276
        auto* cache_value = new InvertedIndexSearcherCache::CacheValue(std::move(searcher_result),
299
276
                                                                       reader_size, UnixMillis());
300
276
        InvertedIndexSearcherCache::instance()->insert(searcher_cache_key, cache_value,
301
276
                                                       &searcher_cache_handle);
302
303
276
        auto new_variant = searcher_cache_handle.get_index_searcher();
304
276
        auto* new_ptr = std::get_if<FulltextIndexSearcherPtr>(&new_variant);
305
277
        if (new_ptr != nullptr && *new_ptr != nullptr) {
306
277
            reader_holder = std::shared_ptr<lucene::index::IndexReader>(
307
277
                    (*new_ptr)->getReader(),
308
277
                    [](lucene::index::IndexReader*) { /* lifetime managed by searcher cache */ });
309
277
        }
310
311
276
        if (!reader_holder) {
312
0
            return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
313
0
                    "failed to build IndexSearcher for field '{}'", field_name);
314
0
        }
315
276
    }
316
317
1.62k
    _searcher_cache_handles.push_back(std::move(searcher_cache_handle));
318
319
1.62k
    FieldReaderBinding resolved;
320
1.62k
    resolved.logical_field_name = field_name;
321
1.62k
    resolved.stored_field_name = stored_field_name;
322
1.62k
    resolved.stored_field_wstr = StringHelper::to_wstring(resolved.stored_field_name);
323
1.62k
    resolved.column_type = column_type;
324
1.62k
    resolved.query_type = effective_query_type;
325
1.62k
    resolved.inverted_reader = inverted_reader;
326
1.62k
    resolved.lucene_reader = reader_holder;
327
    // Prefer FE-provided index_properties (needed for variant subcolumn field_pattern matching)
328
    // Reuse fb_it from earlier lookup above.
329
1.64k
    if (fb_it != _field_binding_map.end() && fb_it->second->__isset.index_properties &&
330
1.62k
        !fb_it->second->index_properties.empty()) {
331
1.29k
        resolved.index_properties = fb_it->second->index_properties;
332
1.29k
    } else {
333
333
        resolved.index_properties = inverted_reader->get_index_properties();
334
333
    }
335
1.62k
    resolved.binding_key = binding_key;
336
1.62k
    resolved.analyzer_key =
337
1.62k
            normalize_analyzer_key(build_analyzer_key_from_properties(resolved.index_properties));
338
339
1.62k
    _binding_readers[binding_key] = reader_holder;
340
1.62k
    _field_readers[resolved.stored_field_wstr] = reader_holder;
341
1.62k
    _readers.emplace_back(reader_holder);
342
1.62k
    _cache.emplace(binding_key, resolved);
343
1.62k
    *binding = resolved;
344
1.62k
    return Status::OK();
345
1.62k
}
346
347
Status FunctionSearch::execute_impl(FunctionContext* /*context*/, Block& /*block*/,
348
                                    const ColumnNumbers& /*arguments*/, uint32_t /*result*/,
349
4
                                    size_t /*input_rows_count*/) const {
350
4
    return Status::RuntimeError("only inverted index queries are supported");
351
4
}
352
353
// Enhanced implementation: Handle new parameter structure (DSL + SlotReferences)
354
Status FunctionSearch::evaluate_inverted_index(
355
        const ColumnsWithTypeAndName& arguments,
356
        const std::vector<IndexFieldNameAndTypePair>& data_type_with_names,
357
        std::vector<IndexIterator*> iterators, uint32_t num_rows,
358
        const InvertedIndexAnalyzerCtx* /*analyzer_ctx*/,
359
1
        InvertedIndexResultBitmap& bitmap_result) const {
360
1
    return Status::OK();
361
1
}
362
363
Status FunctionSearch::evaluate_inverted_index_with_search_param(
364
        const TSearchParam& search_param,
365
        const std::unordered_map<std::string, IndexFieldNameAndTypePair>& data_type_with_names,
366
        std::unordered_map<std::string, IndexIterator*> iterators, uint32_t num_rows,
367
31
        InvertedIndexResultBitmap& bitmap_result, bool enable_cache) const {
368
31
    static const std::unordered_map<std::string, int> empty_field_to_column_id;
369
31
    return evaluate_inverted_index_with_search_param(
370
31
            search_param, data_type_with_names, std::move(iterators), num_rows, bitmap_result,
371
31
            enable_cache, nullptr, empty_field_to_column_id);
372
31
}
373
374
Status FunctionSearch::evaluate_inverted_index_with_search_param(
375
        const TSearchParam& search_param,
376
        const std::unordered_map<std::string, IndexFieldNameAndTypePair>& data_type_with_names,
377
        std::unordered_map<std::string, IndexIterator*> iterators, uint32_t num_rows,
378
        InvertedIndexResultBitmap& bitmap_result, bool enable_cache,
379
        const IndexExecContext* index_exec_ctx,
380
1.33k
        const std::unordered_map<std::string, int>& field_name_to_column_id) const {
381
1.33k
    const bool is_nested_query = search_param.root.clause_type == "NESTED";
382
1.33k
    if (is_nested_query && !is_nested_group_search_supported()) {
383
3
        return Status::NotSupported(
384
3
                "NESTED query requires NestedGroup support, which is unavailable in this build");
385
3
    }
386
387
1.32k
    if (!is_nested_query && (iterators.empty() || data_type_with_names.empty())) {
388
5
        LOG(INFO) << "No indexed columns or iterators available, returning empty result, dsl:"
389
5
                  << search_param.original_dsl;
390
5
        bitmap_result = InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(),
391
5
                                                  std::make_shared<roaring::Roaring>());
392
5
        return Status::OK();
393
5
    }
394
395
    // DSL result cache: reuse InvertedIndexQueryCache with SEARCH_DSL_QUERY type
396
1.32k
    auto* dsl_cache = enable_cache ? InvertedIndexQueryCache::instance() : nullptr;
397
1.32k
    std::string seg_prefix;
398
1.32k
    std::string dsl_sig;
399
1.32k
    InvertedIndexQueryCache::CacheKey dsl_cache_key;
400
1.32k
    bool cache_usable = false;
401
1.32k
    if (dsl_cache) {
402
1.28k
        seg_prefix = extract_segment_prefix(iterators);
403
1.28k
        dsl_sig = build_dsl_signature(search_param);
404
1.28k
        if (!seg_prefix.empty() && !dsl_sig.empty()) {
405
1.27k
            dsl_cache_key = InvertedIndexQueryCache::CacheKey {
406
1.27k
                    seg_prefix, "__search_dsl__", InvertedIndexQueryType::SEARCH_DSL_QUERY,
407
1.27k
                    dsl_sig};
408
1.27k
            cache_usable = true;
409
1.27k
            InvertedIndexQueryCacheHandle dsl_cache_handle;
410
1.27k
            if (dsl_cache->lookup(dsl_cache_key, &dsl_cache_handle)) {
411
176
                auto cached_bitmap = dsl_cache_handle.get_bitmap();
412
176
                if (cached_bitmap) {
413
                    // Also retrieve cached null bitmap for three-valued SQL logic
414
                    // (needed by compound operators NOT, OR, AND in VCompoundPred)
415
175
                    auto null_cache_key = InvertedIndexQueryCache::CacheKey {
416
175
                            seg_prefix, "__search_dsl__", InvertedIndexQueryType::SEARCH_DSL_QUERY,
417
175
                            dsl_sig + "__null"};
418
175
                    InvertedIndexQueryCacheHandle null_cache_handle;
419
175
                    std::shared_ptr<roaring::Roaring> null_bitmap;
420
178
                    if (dsl_cache->lookup(null_cache_key, &null_cache_handle)) {
421
178
                        null_bitmap = null_cache_handle.get_bitmap();
422
178
                    }
423
175
                    if (!null_bitmap) {
424
0
                        null_bitmap = std::make_shared<roaring::Roaring>();
425
0
                    }
426
175
                    bitmap_result =
427
175
                            InvertedIndexResultBitmap(cached_bitmap, std::move(null_bitmap));
428
175
                    return Status::OK();
429
175
                }
430
176
            }
431
1.27k
        }
432
1.28k
    }
433
434
1.14k
    auto context = std::make_shared<IndexQueryContext>();
435
1.14k
    context->collection_statistics = std::make_shared<CollectionStatistics>();
436
1.14k
    context->collection_similarity = std::make_shared<CollectionSimilarity>();
437
438
    // NESTED() queries evaluate predicates on the flattened "element space" of a nested group.
439
    // For VARIANT nested groups, the indexed lucene field (stored_field_name) uses:
440
    //   parent_unique_id + "." + <variant-relative nested path>
441
    // where the nested path is rooted at either:
442
    //   - "__D0_root__" for top-level array<object> (NESTED(data, ...))
443
    //   - "<nested_path_after_variant_root>" for object fields (NESTED(data.items, ...))
444
    //
445
    // FE field bindings are expressed using logical column paths (e.g. "data.items.msg"), so for
446
    // NESTED() we normalize stored_field_name suffix to be consistent with the nested group root.
447
1.14k
    std::unordered_map<std::string, IndexFieldNameAndTypePair> patched_data_type_with_names;
448
1.14k
    const auto* effective_data_type_with_names = &data_type_with_names;
449
1.14k
    if (is_nested_query && search_param.root.__isset.nested_path) {
450
0
        const std::string& nested_path = search_param.root.nested_path;
451
0
        const auto dot_pos = nested_path.find('.');
452
0
        const std::string root_field =
453
0
                (dot_pos == std::string::npos) ? nested_path : nested_path.substr(0, dot_pos);
454
0
        const std::string root_prefix = root_field + ".";
455
0
        const std::string array_path = (dot_pos == std::string::npos)
456
0
                                               ? std::string(segment_v2::kRootNestedGroupPath)
457
0
                                               : nested_path.substr(dot_pos + 1);
458
459
0
        bool copied = false;
460
0
        for (const auto& fb : search_param.field_bindings) {
461
0
            if (!fb.__isset.is_variant_subcolumn || !fb.is_variant_subcolumn) {
462
0
                continue;
463
0
            }
464
0
            if (fb.field_name.empty()) {
465
0
                continue;
466
0
            }
467
0
            const auto it_orig = data_type_with_names.find(fb.field_name);
468
0
            if (it_orig == data_type_with_names.end()) {
469
0
                continue;
470
0
            }
471
0
            const std::string& old_stored = it_orig->second.first;
472
0
            const auto first_dot = old_stored.find('.');
473
0
            if (first_dot == std::string::npos) {
474
0
                continue;
475
0
            }
476
0
            std::string sub_path;
477
0
            if (fb.__isset.subcolumn_path && !fb.subcolumn_path.empty()) {
478
0
                sub_path = fb.subcolumn_path;
479
0
            } else if (fb.field_name.starts_with(nested_path + ".")) {
480
0
                sub_path = fb.field_name.substr(nested_path.size() + 1);
481
0
            } else if (fb.field_name.starts_with(root_prefix)) {
482
0
                sub_path = fb.field_name.substr(root_prefix.size());
483
0
            } else {
484
0
                sub_path = fb.field_name;
485
0
            }
486
0
            if (sub_path.empty()) {
487
0
                continue;
488
0
            }
489
0
            const std::string array_prefix = array_path + ".";
490
0
            const std::string suffix_path =
491
0
                    sub_path.starts_with(array_prefix) ? sub_path : (array_prefix + sub_path);
492
0
            const std::string parent_uid = old_stored.substr(0, first_dot);
493
0
            const std::string expected_stored = parent_uid + "." + suffix_path;
494
0
            if (old_stored == expected_stored) {
495
0
                continue;
496
0
            }
497
498
0
            if (!copied) {
499
0
                patched_data_type_with_names = data_type_with_names;
500
0
                effective_data_type_with_names = &patched_data_type_with_names;
501
0
                copied = true;
502
0
            }
503
0
            auto it = patched_data_type_with_names.find(fb.field_name);
504
0
            if (it == patched_data_type_with_names.end()) {
505
0
                continue;
506
0
            }
507
0
            it->second.first = expected_stored;
508
0
        }
509
0
    }
510
511
    // Pass field_bindings to resolver for variant subcolumn detection
512
1.14k
    FieldReaderResolver resolver(*effective_data_type_with_names, iterators, context,
513
1.14k
                                 search_param.field_bindings);
514
515
1.14k
    if (is_nested_query) {
516
0
        std::shared_ptr<roaring::Roaring> row_bitmap;
517
0
        RETURN_IF_ERROR(evaluate_nested_query(search_param, search_param.root, context, resolver,
518
0
                                              num_rows, index_exec_ctx, field_name_to_column_id,
519
0
                                              row_bitmap));
520
0
        bitmap_result = InvertedIndexResultBitmap(std::move(row_bitmap),
521
0
                                                  std::make_shared<roaring::Roaring>());
522
0
        bitmap_result.mask_out_null();
523
0
        return Status::OK();
524
0
    }
525
526
    // Extract default_operator from TSearchParam (default: "or")
527
1.14k
    std::string default_operator = "or";
528
1.14k
    if (search_param.__isset.default_operator && !search_param.default_operator.empty()) {
529
1.11k
        default_operator = search_param.default_operator;
530
1.11k
    }
531
    // Extract minimum_should_match from TSearchParam (-1 means not set)
532
1.14k
    int32_t minimum_should_match = -1;
533
1.14k
    if (search_param.__isset.minimum_should_match) {
534
46
        minimum_should_match = search_param.minimum_should_match;
535
46
    }
536
537
1.14k
    query_v2::QueryPtr root_query;
538
1.14k
    std::string root_binding_key;
539
1.14k
    RETURN_IF_ERROR(build_query_recursive(search_param.root, context, resolver, &root_query,
540
1.14k
                                          &root_binding_key, default_operator,
541
1.14k
                                          minimum_should_match));
542
1.12k
    if (root_query == nullptr) {
543
0
        LOG(INFO) << "search: Query tree resolved to empty query, dsl:"
544
0
                  << search_param.original_dsl;
545
0
        bitmap_result = InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(),
546
0
                                                  std::make_shared<roaring::Roaring>());
547
0
        return Status::OK();
548
0
    }
549
550
1.12k
    ResolverNullBitmapAdapter null_resolver(resolver);
551
1.12k
    query_v2::QueryExecutionContext exec_ctx =
552
1.12k
            build_query_execution_context(num_rows, resolver, &null_resolver);
553
554
1.12k
    auto weight = root_query->weight(false);
555
1.12k
    if (!weight) {
556
0
        LOG(WARNING) << "search: Failed to build query weight";
557
0
        bitmap_result = InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(),
558
0
                                                  std::make_shared<roaring::Roaring>());
559
0
        return Status::OK();
560
0
    }
561
562
1.12k
    auto scorer = weight->scorer(exec_ctx, root_binding_key);
563
1.12k
    if (!scorer) {
564
0
        LOG(WARNING) << "search: Failed to build scorer";
565
0
        bitmap_result = InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(),
566
0
                                                  std::make_shared<roaring::Roaring>());
567
0
        return Status::OK();
568
0
    }
569
570
1.12k
    std::shared_ptr<roaring::Roaring> roaring = std::make_shared<roaring::Roaring>();
571
1.12k
    uint32_t doc = scorer->doc();
572
1.12k
    uint32_t matched_docs = 0;
573
2.98k
    while (doc != query_v2::TERMINATED) {
574
1.86k
        roaring->add(doc);
575
1.86k
        ++matched_docs;
576
1.86k
        doc = scorer->advance();
577
1.86k
    }
578
579
18.4E
    VLOG_DEBUG << "search: Query completed, matched " << matched_docs << " documents";
580
581
    // Extract NULL bitmap from three-valued logic scorer
582
    // The scorer correctly computes which documents evaluate to NULL based on query logic
583
    // For example: TRUE OR NULL = TRUE (not NULL), FALSE OR NULL = NULL
584
1.12k
    std::shared_ptr<roaring::Roaring> null_bitmap = std::make_shared<roaring::Roaring>();
585
1.12k
    if (scorer->has_null_bitmap(exec_ctx.null_resolver)) {
586
225
        const auto* bitmap = scorer->get_null_bitmap(exec_ctx.null_resolver);
587
225
        if (bitmap != nullptr) {
588
225
            *null_bitmap = *bitmap;
589
225
            VLOG_TRACE << "search: Extracted NULL bitmap with " << null_bitmap->cardinality()
590
0
                       << " NULL documents";
591
225
        }
592
225
    }
593
594
1.12k
    VLOG_TRACE << "search: Before mask - true_bitmap=" << roaring->cardinality()
595
3
               << ", null_bitmap=" << null_bitmap->cardinality();
596
597
    // Create result and mask out NULLs (SQL WHERE clause semantics: only TRUE rows)
598
1.12k
    bitmap_result = InvertedIndexResultBitmap(std::move(roaring), std::move(null_bitmap));
599
1.12k
    bitmap_result.mask_out_null();
600
601
1.12k
    VLOG_TRACE << "search: After mask - result_bitmap="
602
2
               << bitmap_result.get_data_bitmap()->cardinality();
603
604
    // Insert post-mask_out_null result into DSL cache for future reuse
605
    // Cache both data bitmap and null bitmap so compound operators (NOT, OR, AND)
606
    // can apply correct three-valued SQL logic on cache hit
607
1.12k
    if (dsl_cache && cache_usable) {
608
1.12k
        InvertedIndexQueryCacheHandle insert_handle;
609
1.12k
        dsl_cache->insert(dsl_cache_key, bitmap_result.get_data_bitmap(), &insert_handle);
610
1.12k
        if (bitmap_result.get_null_bitmap()) {
611
1.12k
            auto null_cache_key = InvertedIndexQueryCache::CacheKey {
612
1.12k
                    seg_prefix, "__search_dsl__", InvertedIndexQueryType::SEARCH_DSL_QUERY,
613
1.12k
                    dsl_sig + "__null"};
614
1.12k
            InvertedIndexQueryCacheHandle null_insert_handle;
615
1.12k
            dsl_cache->insert(null_cache_key, bitmap_result.get_null_bitmap(), &null_insert_handle);
616
1.12k
        }
617
1.12k
    }
618
619
1.12k
    return Status::OK();
620
1.12k
}
621
622
Status FunctionSearch::evaluate_nested_query(
623
        const TSearchParam& search_param, const TSearchClause& nested_clause,
624
        const std::shared_ptr<IndexQueryContext>& context, FieldReaderResolver& resolver,
625
        uint32_t num_rows, const IndexExecContext* index_exec_ctx,
626
        const std::unordered_map<std::string, int>& field_name_to_column_id,
627
7
        std::shared_ptr<roaring::Roaring>& result_bitmap) const {
628
7
    (void)field_name_to_column_id;
629
7
    if (!(nested_clause.__isset.nested_path)) {
630
2
        return Status::InvalidArgument("NESTED clause missing nested_path");
631
2
    }
632
5
    if (!(nested_clause.__isset.children) || nested_clause.children.empty()) {
633
2
        return Status::InvalidArgument("NESTED clause missing inner query");
634
2
    }
635
3
    if (result_bitmap == nullptr) {
636
2
        result_bitmap = std::make_shared<roaring::Roaring>();
637
2
    } else {
638
1
        *result_bitmap = roaring::Roaring();
639
1
    }
640
641
    // 1. Get the nested group chain directly
642
3
    std::string root_field = nested_clause.nested_path;
643
3
    auto dot_pos = nested_clause.nested_path.find('.');
644
3
    if (dot_pos != std::string::npos) {
645
1
        root_field = nested_clause.nested_path.substr(0, dot_pos);
646
1
    }
647
3
    if (index_exec_ctx == nullptr || index_exec_ctx->segment() == nullptr) {
648
3
        return Status::InvalidArgument("NESTED query requires IndexExecContext with valid segment");
649
3
    }
650
0
    auto* segment = index_exec_ctx->segment();
651
0
    const int32_t ordinal = segment->tablet_schema()->field_index(root_field);
652
0
    if (ordinal < 0) {
653
0
        return Status::InvalidArgument("Column '{}' not found in tablet schema for nested query",
654
0
                                       root_field);
655
0
    }
656
0
    const ColumnId column_id = static_cast<ColumnId>(ordinal);
657
658
0
    std::shared_ptr<segment_v2::ColumnReader> column_reader;
659
0
    RETURN_IF_ERROR(segment->get_column_reader(segment->tablet_schema()->column(column_id),
660
0
                                               &column_reader,
661
0
                                               index_exec_ctx->column_iter_opts().stats));
662
0
    auto* variant_reader = dynamic_cast<segment_v2::VariantColumnReader*>(column_reader.get());
663
0
    if (variant_reader == nullptr) {
664
0
        return Status::InvalidArgument("Column '{}' is not VARIANT for nested query", root_field);
665
0
    }
666
667
0
    std::string array_path;
668
0
    if (dot_pos == std::string::npos) {
669
0
        array_path = std::string(segment_v2::kRootNestedGroupPath);
670
0
    } else {
671
0
        array_path = nested_clause.nested_path.substr(dot_pos + 1);
672
0
    }
673
674
0
    auto [found, group_chain, _] = variant_reader->collect_nested_group_chain(array_path);
675
0
    if (!found || group_chain.empty()) {
676
0
        return Status::OK();
677
0
    }
678
679
    // Use the read provider for element counting and bitmap mapping.
680
0
    auto read_provider = segment_v2::create_nested_group_read_provider();
681
0
    if (!read_provider || !read_provider->should_enable_nested_group_read_path()) {
682
0
        return Status::NotSupported(
683
0
                "NestedGroup search is an enterprise capability, not available in this build");
684
0
    }
685
686
0
    auto& leaf_group = group_chain.back();
687
0
    uint64_t total_elements = 0;
688
0
    RETURN_IF_ERROR(read_provider->get_total_elements(index_exec_ctx->column_iter_opts(),
689
0
                                                      leaf_group, &total_elements));
690
0
    if (total_elements == 0) {
691
0
        return Status::OK();
692
0
    }
693
694
    // 3. Evaluate inner query
695
0
    std::string default_operator = "or";
696
0
    if (search_param.__isset.default_operator && !search_param.default_operator.empty()) {
697
0
        default_operator = search_param.default_operator;
698
0
    }
699
0
    int32_t minimum_should_match = -1;
700
0
    if (search_param.__isset.minimum_should_match) {
701
0
        minimum_should_match = search_param.minimum_should_match;
702
0
    }
703
704
0
    query_v2::QueryPtr inner_query;
705
0
    std::string inner_binding_key;
706
0
    RETURN_IF_ERROR(build_query_recursive(nested_clause.children[0], context, resolver,
707
0
                                          &inner_query, &inner_binding_key, default_operator,
708
0
                                          minimum_should_match));
709
0
    if (inner_query == nullptr) {
710
0
        return Status::OK();
711
0
    }
712
713
0
    if (total_elements > std::numeric_limits<uint32_t>::max()) {
714
0
        return Status::InvalidArgument("nested element_count exceeds uint32_t max");
715
0
    }
716
717
0
    ResolverNullBitmapAdapter null_resolver(resolver);
718
0
    query_v2::QueryExecutionContext exec_ctx = build_query_execution_context(
719
0
            static_cast<uint32_t>(total_elements), resolver, &null_resolver);
720
721
0
    auto weight = inner_query->weight(false);
722
0
    if (!weight) {
723
0
        return Status::OK();
724
0
    }
725
0
    auto scorer = weight->scorer(exec_ctx, inner_binding_key);
726
0
    if (!scorer) {
727
0
        return Status::OK();
728
0
    }
729
730
0
    roaring::Roaring element_bitmap;
731
0
    uint32_t doc = scorer->doc();
732
0
    while (doc != query_v2::TERMINATED) {
733
0
        element_bitmap.add(doc);
734
0
        doc = scorer->advance();
735
0
    }
736
737
0
    if (scorer->has_null_bitmap(exec_ctx.null_resolver)) {
738
0
        const auto* bitmap = scorer->get_null_bitmap(exec_ctx.null_resolver);
739
0
        if (bitmap != nullptr && !bitmap->isEmpty()) {
740
0
            element_bitmap -= *bitmap;
741
0
        }
742
0
    }
743
744
    // 4. Map element-level hits back to row-level hits through NestedGroup chain.
745
0
    if (result_bitmap == nullptr) {
746
0
        result_bitmap = std::make_shared<roaring::Roaring>();
747
0
    }
748
0
    roaring::Roaring parent_bitmap;
749
0
    RETURN_IF_ERROR(read_provider->map_elements_to_parent_ords(
750
0
            group_chain, index_exec_ctx->column_iter_opts(), element_bitmap, &parent_bitmap));
751
0
    *result_bitmap = std::move(parent_bitmap);
752
0
    return Status::OK();
753
0
}
754
755
// Aligned with FE QsClauseType enum - uses enum.name() as clause_type
756
FunctionSearch::ClauseTypeCategory FunctionSearch::get_clause_type_category(
757
7.22k
        const std::string& clause_type) const {
758
7.22k
    if (clause_type == "AND" || clause_type == "OR" || clause_type == "NOT" ||
759
7.22k
        clause_type == "OCCUR_BOOLEAN" || clause_type == "NESTED") {
760
146
        return ClauseTypeCategory::COMPOUND;
761
7.07k
    } else if (clause_type == "TERM" || clause_type == "PREFIX" || clause_type == "WILDCARD" ||
762
7.07k
               clause_type == "REGEXP" || clause_type == "RANGE" || clause_type == "LIST" ||
763
7.07k
               clause_type == "EXACT") {
764
        // Non-tokenized queries: exact matching, pattern matching, range, list operations
765
6.67k
        return ClauseTypeCategory::NON_TOKENIZED;
766
6.67k
    } else if (clause_type == "PHRASE" || clause_type == "MATCH" || clause_type == "ANY" ||
767
440
               clause_type == "ALL") {
768
        // Tokenized queries: phrase search, full-text search, multi-value matching
769
        // Note: ANY and ALL require tokenization of their input values
770
440
        return ClauseTypeCategory::TOKENIZED;
771
18.4E
    } else {
772
        // Default to NON_TOKENIZED for unknown types
773
18.4E
        LOG(WARNING) << "Unknown clause type '" << clause_type
774
18.4E
                     << "', defaulting to NON_TOKENIZED category";
775
18.4E
        return ClauseTypeCategory::NON_TOKENIZED;
776
18.4E
    }
777
7.22k
}
778
779
// Analyze query type for a specific field in the search clause
780
InvertedIndexQueryType FunctionSearch::analyze_field_query_type(const std::string& field_name,
781
5.28k
                                                                const TSearchClause& clause) const {
782
5.28k
    const std::string& clause_type = clause.clause_type;
783
5.28k
    ClauseTypeCategory category = get_clause_type_category(clause_type);
784
785
    // Handle leaf queries - use direct mapping
786
5.28k
    if (category != ClauseTypeCategory::COMPOUND) {
787
        // Check if this clause targets the specific field
788
5.14k
        if (clause.field_name == field_name) {
789
            // Use direct mapping from clause_type to InvertedIndexQueryType
790
163
            return clause_type_to_query_type(clause_type);
791
163
        }
792
5.14k
    }
793
794
    // Handle boolean queries - recursively analyze children
795
5.11k
    if (!clause.children.empty()) {
796
5.09k
        for (const auto& child_clause : clause.children) {
797
            // Recursively analyze each child
798
5.09k
            InvertedIndexQueryType child_type = analyze_field_query_type(field_name, child_clause);
799
            // If this child targets the field (not default EQUAL_QUERY), return its query type
800
5.09k
            if (child_type != InvertedIndexQueryType::UNKNOWN_QUERY) {
801
124
                return child_type;
802
124
            }
803
5.09k
        }
804
132
    }
805
806
    // If no children target this field, return UNKNOWN_QUERY as default
807
4.99k
    return InvertedIndexQueryType::UNKNOWN_QUERY;
808
5.11k
}
809
810
// Map clause_type string to InvertedIndexQueryType
811
InvertedIndexQueryType FunctionSearch::clause_type_to_query_type(
812
2.15k
        const std::string& clause_type) const {
813
    // Use static map for better performance and maintainability
814
2.15k
    static const std::unordered_map<std::string, InvertedIndexQueryType> clause_type_map = {
815
            // Boolean operations
816
2.15k
            {"AND", InvertedIndexQueryType::BOOLEAN_QUERY},
817
2.15k
            {"OR", InvertedIndexQueryType::BOOLEAN_QUERY},
818
2.15k
            {"NOT", InvertedIndexQueryType::BOOLEAN_QUERY},
819
2.15k
            {"OCCUR_BOOLEAN", InvertedIndexQueryType::BOOLEAN_QUERY},
820
2.15k
            {"NESTED", InvertedIndexQueryType::BOOLEAN_QUERY},
821
822
            // Non-tokenized queries (exact matching, pattern matching)
823
2.15k
            {"TERM", InvertedIndexQueryType::EQUAL_QUERY},
824
2.15k
            {"PREFIX", InvertedIndexQueryType::MATCH_PHRASE_PREFIX_QUERY},
825
2.15k
            {"WILDCARD", InvertedIndexQueryType::WILDCARD_QUERY},
826
2.15k
            {"REGEXP", InvertedIndexQueryType::MATCH_REGEXP_QUERY},
827
2.15k
            {"RANGE", InvertedIndexQueryType::RANGE_QUERY},
828
2.15k
            {"LIST", InvertedIndexQueryType::LIST_QUERY},
829
830
            // Tokenized queries (full-text search, phrase search)
831
2.15k
            {"PHRASE", InvertedIndexQueryType::MATCH_PHRASE_QUERY},
832
2.15k
            {"MATCH", InvertedIndexQueryType::MATCH_ANY_QUERY},
833
2.15k
            {"ANY", InvertedIndexQueryType::MATCH_ANY_QUERY},
834
2.15k
            {"ALL", InvertedIndexQueryType::MATCH_ALL_QUERY},
835
836
            // Exact match without tokenization
837
2.15k
            {"EXACT", InvertedIndexQueryType::EQUAL_QUERY},
838
2.15k
    };
839
840
2.15k
    auto it = clause_type_map.find(clause_type);
841
2.15k
    if (it != clause_type_map.end()) {
842
2.15k
        return it->second;
843
2.15k
    }
844
845
    // Unknown clause type
846
2.15k
    LOG(WARNING) << "Unknown clause type '" << clause_type << "', defaulting to EQUAL_QUERY";
847
4
    return InvertedIndexQueryType::EQUAL_QUERY;
848
2.15k
}
849
850
// Map Thrift TSearchOccur to query_v2::Occur
851
883
static query_v2::Occur map_thrift_occur(TSearchOccur::type thrift_occur) {
852
883
    switch (thrift_occur) {
853
309
    case TSearchOccur::MUST:
854
309
        return query_v2::Occur::MUST;
855
511
    case TSearchOccur::SHOULD:
856
511
        return query_v2::Occur::SHOULD;
857
64
    case TSearchOccur::MUST_NOT:
858
64
        return query_v2::Occur::MUST_NOT;
859
0
    default:
860
0
        return query_v2::Occur::MUST;
861
883
    }
862
883
}
863
864
Status FunctionSearch::build_query_recursive(const TSearchClause& clause,
865
                                             const std::shared_ptr<IndexQueryContext>& context,
866
                                             FieldReaderResolver& resolver,
867
                                             inverted_index::query_v2::QueryPtr* out,
868
                                             std::string* binding_key,
869
                                             const std::string& default_operator,
870
2.73k
                                             int32_t minimum_should_match) const {
871
2.73k
    DCHECK(out != nullptr);
872
2.73k
    *out = nullptr;
873
2.77k
    if (binding_key) {
874
2.77k
        binding_key->clear();
875
2.77k
    }
876
877
2.73k
    const std::string& clause_type = clause.clause_type;
878
879
    // Handle MATCH_ALL_DOCS - matches all documents in the segment
880
2.73k
    if (clause_type == "MATCH_ALL_DOCS") {
881
42
        *out = std::make_shared<query_v2::AllQuery>();
882
42
        return Status::OK();
883
42
    }
884
885
    // Handle OCCUR_BOOLEAN - Lucene-style boolean query with MUST/SHOULD/MUST_NOT
886
2.69k
    if (clause_type == "OCCUR_BOOLEAN") {
887
426
        auto builder = segment_v2::inverted_index::query_v2::create_occur_boolean_query_builder();
888
889
        // Set minimum_should_match if specified
890
426
        if (clause.__isset.minimum_should_match) {
891
419
            builder->set_minimum_number_should_match(clause.minimum_should_match);
892
419
        }
893
894
433
        if (clause.__isset.children) {
895
885
            for (const auto& child_clause : clause.children) {
896
885
                query_v2::QueryPtr child_query;
897
885
                std::string child_binding_key;
898
885
                RETURN_IF_ERROR(build_query_recursive(child_clause, context, resolver, &child_query,
899
885
                                                      &child_binding_key, default_operator,
900
885
                                                      minimum_should_match));
901
902
                // Determine occur type from child clause
903
884
                query_v2::Occur occur = query_v2::Occur::MUST; // default
904
884
                if (child_clause.__isset.occur) {
905
883
                    occur = map_thrift_occur(child_clause.occur);
906
883
                }
907
908
884
                builder->add(child_query, occur, std::move(child_binding_key));
909
884
            }
910
433
        }
911
912
425
        *out = builder->build();
913
425
        return Status::OK();
914
426
    }
915
916
2.26k
    if (clause_type == "NESTED") {
917
1
        return Status::InvalidArgument("NESTED clause must be evaluated at top level");
918
1
    }
919
920
    // Handle standard boolean operators (AND/OR/NOT)
921
2.26k
    if (clause_type == "AND" || clause_type == "OR" || clause_type == "NOT") {
922
363
        query_v2::OperatorType op = query_v2::OperatorType::OP_AND;
923
363
        if (clause_type == "OR") {
924
199
            op = query_v2::OperatorType::OP_OR;
925
199
        } else if (clause_type == "NOT") {
926
88
            op = query_v2::OperatorType::OP_NOT;
927
88
        }
928
929
363
        auto builder = create_operator_boolean_query_builder(op);
930
363
        if (clause.__isset.children) {
931
776
            for (const auto& child_clause : clause.children) {
932
776
                query_v2::QueryPtr child_query;
933
776
                std::string child_binding_key;
934
776
                RETURN_IF_ERROR(build_query_recursive(child_clause, context, resolver, &child_query,
935
776
                                                      &child_binding_key, default_operator,
936
776
                                                      minimum_should_match));
937
                // Add all children including empty BitSetQuery
938
                // BooleanQuery will handle the logic:
939
                // - AND with empty bitmap → result is empty
940
                // - OR with empty bitmap → empty bitmap is ignored by OR logic
941
                // - NOT with empty bitmap → NOT(empty) = all rows (handled by BooleanQuery)
942
775
                builder->add(child_query, std::move(child_binding_key));
943
775
            }
944
362
        }
945
946
362
        *out = builder->build();
947
362
        return Status::OK();
948
363
    }
949
950
1.90k
    return build_leaf_query(clause, context, resolver, out, binding_key, default_operator,
951
1.90k
                            minimum_should_match);
952
2.26k
}
953
954
Status FunctionSearch::build_leaf_query(const TSearchClause& clause,
955
                                        const std::shared_ptr<IndexQueryContext>& context,
956
                                        FieldReaderResolver& resolver,
957
                                        inverted_index::query_v2::QueryPtr* out,
958
                                        std::string* binding_key,
959
                                        const std::string& default_operator,
960
1.97k
                                        int32_t minimum_should_match) const {
961
1.97k
    DCHECK(out != nullptr);
962
1.97k
    *out = nullptr;
963
1.97k
    if (binding_key) {
964
1.97k
        binding_key->clear();
965
1.97k
    }
966
967
1.97k
    if (!clause.__isset.field_name || !clause.__isset.value) {
968
0
        return Status::InvalidArgument("search clause missing field_name or value");
969
0
    }
970
971
1.97k
    const std::string& field_name = clause.field_name;
972
1.97k
    const std::string& value = clause.value;
973
1.97k
    const std::string& clause_type = clause.clause_type;
974
975
1.97k
    auto query_type = clause_type_to_query_type(clause_type);
976
    // TERM, WILDCARD, PREFIX, and REGEXP in search DSL operate on individual index terms
977
    // (like Lucene TermQuery, WildcardQuery, PrefixQuery, RegexpQuery).
978
    // Override to MATCH_ANY_QUERY so select_best_reader() prefers the FULLTEXT reader
979
    // when multiple indexes exist on the same column (one tokenized, one untokenized).
980
    // Without this, these queries would select the untokenized index and try to match
981
    // patterns like "h*llo" against full strings ("hello world") instead of individual
982
    // tokens ("hello"), returning empty results.
983
    // EXACT must remain EQUAL_QUERY to prefer the untokenized STRING_TYPE reader.
984
    //
985
    // Safe for single-index columns: select_best_reader() has a single-reader fast path
986
    // that returns the only reader directly, bypassing the query_type preference logic.
987
1.97k
    if (clause_type == "TERM" || clause_type == "WILDCARD" || clause_type == "PREFIX" ||
988
1.97k
        clause_type == "REGEXP") {
989
1.47k
        query_type = InvertedIndexQueryType::MATCH_ANY_QUERY;
990
1.47k
    }
991
992
1.97k
    FieldReaderBinding binding;
993
1.97k
    RETURN_IF_ERROR(resolver.resolve(field_name, query_type, &binding));
994
995
    // Check if binding is empty (variant subcolumn not found in this segment)
996
1.95k
    if (binding.lucene_reader == nullptr) {
997
3
        LOG(INFO) << "search: No inverted index for field '" << field_name
998
3
                  << "' in this segment, clause_type='" << clause_type
999
3
                  << "', query_type=" << static_cast<int>(query_type) << ", returning no matches";
1000
        // Variant subcolumn doesn't exist - create empty BitSetQuery (no matches)
1001
3
        *out = std::make_shared<query_v2::BitSetQuery>(roaring::Roaring());
1002
3
        if (binding_key) {
1003
3
            binding_key->clear();
1004
3
        }
1005
3
        return Status::OK();
1006
3
    }
1007
1008
1.94k
    if (binding_key) {
1009
1.93k
        *binding_key = binding.binding_key;
1010
1.93k
    }
1011
1012
1.94k
    FunctionSearch::ClauseTypeCategory category = get_clause_type_category(clause_type);
1013
1.94k
    std::wstring field_wstr = binding.stored_field_wstr;
1014
1.94k
    std::wstring value_wstr = StringHelper::to_wstring(value);
1015
1016
1.94k
    auto make_term_query = [&](const std::wstring& term) -> query_v2::QueryPtr {
1017
1.92k
        return std::make_shared<query_v2::TermQuery>(context, field_wstr, term);
1018
1.92k
    };
1019
1020
1.94k
    if (clause_type == "TERM") {
1021
1.35k
        bool should_analyze =
1022
1.35k
                inverted_index::InvertedIndexAnalyzer::should_analyzer(binding.index_properties);
1023
1.35k
        if (should_analyze) {
1024
1.05k
            if (binding.index_properties.empty()) {
1025
0
                LOG(WARNING) << "search: analyzer required but index properties empty for field '"
1026
0
                             << field_name << "'";
1027
0
                *out = make_term_query(value_wstr);
1028
0
                return Status::OK();
1029
0
            }
1030
1031
1.05k
            std::vector<TermInfo> term_infos =
1032
1.05k
                    inverted_index::InvertedIndexAnalyzer::get_analyse_result(
1033
1.05k
                            value, binding.index_properties);
1034
1.05k
            if (term_infos.empty()) {
1035
0
                LOG(WARNING) << "search: No terms found after tokenization for TERM query, field="
1036
0
                             << field_name << ", value='" << value
1037
0
                             << "', returning empty BitSetQuery";
1038
0
                *out = std::make_shared<query_v2::BitSetQuery>(roaring::Roaring());
1039
0
                return Status::OK();
1040
0
            }
1041
1042
1.05k
            if (term_infos.size() == 1) {
1043
1.05k
                std::wstring term_wstr = StringHelper::to_wstring(term_infos[0].get_single_term());
1044
1.05k
                *out = make_term_query(term_wstr);
1045
1.05k
                return Status::OK();
1046
1.05k
            }
1047
1048
            // When minimum_should_match is specified, use OccurBooleanQuery
1049
            // ES behavior: msm only applies to SHOULD clauses
1050
1
            if (minimum_should_match > 0) {
1051
0
                auto builder =
1052
0
                        segment_v2::inverted_index::query_v2::create_occur_boolean_query_builder();
1053
0
                builder->set_minimum_number_should_match(minimum_should_match);
1054
0
                query_v2::Occur occur = (default_operator == "and") ? query_v2::Occur::MUST
1055
0
                                                                    : query_v2::Occur::SHOULD;
1056
0
                for (const auto& term_info : term_infos) {
1057
0
                    std::wstring term_wstr = StringHelper::to_wstring(term_info.get_single_term());
1058
0
                    builder->add(make_term_query(term_wstr), occur);
1059
0
                }
1060
0
                *out = builder->build();
1061
0
                return Status::OK();
1062
0
            }
1063
1064
            // Use default_operator to determine how to combine tokenized terms
1065
1
            query_v2::OperatorType op_type = (default_operator == "and")
1066
1
                                                     ? query_v2::OperatorType::OP_AND
1067
1
                                                     : query_v2::OperatorType::OP_OR;
1068
1
            auto builder = create_operator_boolean_query_builder(op_type);
1069
9
            for (const auto& term_info : term_infos) {
1070
9
                std::wstring term_wstr = StringHelper::to_wstring(term_info.get_single_term());
1071
9
                builder->add(make_term_query(term_wstr), binding.binding_key);
1072
9
            }
1073
1074
1
            *out = builder->build();
1075
1
            return Status::OK();
1076
1
        }
1077
1078
305
        *out = make_term_query(value_wstr);
1079
305
        return Status::OK();
1080
1.35k
    }
1081
1082
592
    if (category == FunctionSearch::ClauseTypeCategory::TOKENIZED) {
1083
413
        if (clause_type == "PHRASE") {
1084
130
            bool should_analyze = inverted_index::InvertedIndexAnalyzer::should_analyzer(
1085
130
                    binding.index_properties);
1086
130
            if (!should_analyze) {
1087
16
                VLOG_DEBUG << "search: PHRASE on non-tokenized field '" << field_name
1088
0
                           << "', falling back to TERM";
1089
16
                *out = make_term_query(value_wstr);
1090
16
                return Status::OK();
1091
16
            }
1092
1093
114
            if (binding.index_properties.empty()) {
1094
0
                LOG(WARNING) << "search: analyzer required but index properties empty for PHRASE "
1095
0
                                "query on field '"
1096
0
                             << field_name << "'";
1097
0
                *out = make_term_query(value_wstr);
1098
0
                return Status::OK();
1099
0
            }
1100
1101
114
            std::vector<TermInfo> term_infos =
1102
114
                    inverted_index::InvertedIndexAnalyzer::get_analyse_result(
1103
114
                            value, binding.index_properties);
1104
114
            if (term_infos.empty()) {
1105
9
                LOG(WARNING) << "search: No terms found after tokenization for PHRASE query, field="
1106
9
                             << field_name << ", value='" << value
1107
9
                             << "', returning empty BitSetQuery";
1108
9
                *out = std::make_shared<query_v2::BitSetQuery>(roaring::Roaring());
1109
9
                return Status::OK();
1110
9
            }
1111
1112
105
            std::vector<TermInfo> phrase_term_infos =
1113
105
                    QueryHelper::build_phrase_term_infos(term_infos);
1114
105
            if (phrase_term_infos.size() == 1) {
1115
62
                const auto& term_info = phrase_term_infos[0];
1116
62
                if (term_info.is_single_term()) {
1117
62
                    std::wstring term_wstr = StringHelper::to_wstring(term_info.get_single_term());
1118
62
                    *out = std::make_shared<query_v2::TermQuery>(context, field_wstr, term_wstr);
1119
62
                } else {
1120
0
                    auto builder =
1121
0
                            create_operator_boolean_query_builder(query_v2::OperatorType::OP_OR);
1122
0
                    for (const auto& term : term_info.get_multi_terms()) {
1123
0
                        std::wstring term_wstr = StringHelper::to_wstring(term);
1124
0
                        builder->add(make_term_query(term_wstr), binding.binding_key);
1125
0
                    }
1126
0
                    *out = builder->build();
1127
0
                }
1128
62
            } else {
1129
43
                if (QueryHelper::is_simple_phrase(phrase_term_infos)) {
1130
21
                    *out = std::make_shared<query_v2::PhraseQuery>(context, field_wstr,
1131
21
                                                                   phrase_term_infos);
1132
22
                } else {
1133
22
                    *out = std::make_shared<query_v2::MultiPhraseQuery>(context, field_wstr,
1134
22
                                                                        phrase_term_infos);
1135
22
                }
1136
43
            }
1137
1138
105
            return Status::OK();
1139
114
        }
1140
283
        if (clause_type == "MATCH") {
1141
0
            VLOG_DEBUG << "search: MATCH clause not implemented, fallback to TERM";
1142
0
            *out = make_term_query(value_wstr);
1143
0
            return Status::OK();
1144
0
        }
1145
1146
285
        if (clause_type == "ANY" || clause_type == "ALL") {
1147
285
            bool should_analyze = inverted_index::InvertedIndexAnalyzer::should_analyzer(
1148
285
                    binding.index_properties);
1149
285
            if (!should_analyze) {
1150
1
                *out = make_term_query(value_wstr);
1151
1
                return Status::OK();
1152
1
            }
1153
1154
284
            if (binding.index_properties.empty()) {
1155
0
                LOG(WARNING) << "search: index properties empty for tokenized clause '"
1156
0
                             << clause_type << "' field=" << field_name;
1157
0
                *out = make_term_query(value_wstr);
1158
0
                return Status::OK();
1159
0
            }
1160
1161
284
            std::vector<TermInfo> term_infos =
1162
284
                    inverted_index::InvertedIndexAnalyzer::get_analyse_result(
1163
284
                            value, binding.index_properties);
1164
284
            if (term_infos.empty()) {
1165
0
                LOG(WARNING) << "search: tokenization yielded no terms for clause '" << clause_type
1166
0
                             << "', field=" << field_name << ", returning empty BitSetQuery";
1167
0
                *out = std::make_shared<query_v2::BitSetQuery>(roaring::Roaring());
1168
0
                return Status::OK();
1169
0
            }
1170
1171
284
            query_v2::OperatorType bool_type = query_v2::OperatorType::OP_OR;
1172
284
            if (clause_type == "ALL") {
1173
182
                bool_type = query_v2::OperatorType::OP_AND;
1174
182
            }
1175
1176
284
            if (term_infos.size() == 1) {
1177
98
                std::wstring term_wstr = StringHelper::to_wstring(term_infos[0].get_single_term());
1178
98
                *out = make_term_query(term_wstr);
1179
98
                return Status::OK();
1180
98
            }
1181
1182
186
            auto builder = create_operator_boolean_query_builder(bool_type);
1183
389
            for (const auto& term_info : term_infos) {
1184
389
                std::wstring term_wstr = StringHelper::to_wstring(term_info.get_single_term());
1185
389
                builder->add(make_term_query(term_wstr), binding.binding_key);
1186
389
            }
1187
186
            *out = builder->build();
1188
186
            return Status::OK();
1189
284
        }
1190
1191
        // Default tokenized clause fallback
1192
18.4E
        *out = make_term_query(value_wstr);
1193
18.4E
        return Status::OK();
1194
283
    }
1195
1196
181
    if (category == FunctionSearch::ClauseTypeCategory::NON_TOKENIZED) {
1197
181
        if (clause_type == "EXACT") {
1198
            // EXACT match: exact string matching without tokenization
1199
            // Note: EXACT prefers untokenized index (STRING_TYPE) which doesn't support lowercase
1200
            // If only tokenized index exists, EXACT may return empty results because
1201
            // tokenized indexes store individual tokens, not complete strings
1202
82
            *out = make_term_query(value_wstr);
1203
82
            VLOG_DEBUG << "search: EXACT clause processed, field=" << field_name << ", value='"
1204
0
                       << value << "'";
1205
82
            return Status::OK();
1206
82
        }
1207
99
        if (clause_type == "PREFIX") {
1208
            // Apply lowercase only if:
1209
            // 1. There's a parser/analyzer (otherwise lower_case has no effect on indexing)
1210
            // 2. lower_case is explicitly set to "true"
1211
39
            bool has_parser = inverted_index::InvertedIndexAnalyzer::should_analyzer(
1212
39
                    binding.index_properties);
1213
39
            std::string lowercase_setting =
1214
39
                    get_parser_lowercase_from_properties(binding.index_properties);
1215
39
            bool should_lowercase = has_parser && (lowercase_setting == INVERTED_INDEX_PARSER_TRUE);
1216
39
            std::string pattern = should_lowercase ? to_lower(value) : value;
1217
39
            *out = std::make_shared<query_v2::WildcardQuery>(context, field_wstr, pattern);
1218
39
            VLOG_DEBUG << "search: PREFIX clause processed, field=" << field_name << ", pattern='"
1219
0
                       << pattern << "' (original='" << value << "', has_parser=" << has_parser
1220
0
                       << ", lower_case=" << lowercase_setting << ")";
1221
39
            return Status::OK();
1222
39
        }
1223
1224
60
        if (clause_type == "WILDCARD") {
1225
            // Standalone wildcard "*" matches all non-null values for this field
1226
            // Consistent with ES query_string behavior where field:* becomes FieldExistsQuery
1227
27
            if (value == "*") {
1228
0
                *out = std::make_shared<query_v2::AllQuery>(field_wstr, true);
1229
0
                VLOG_DEBUG << "search: WILDCARD '*' converted to AllQuery(nullable=true), field="
1230
0
                           << field_name;
1231
0
                return Status::OK();
1232
0
            }
1233
            // Apply lowercase only if:
1234
            // 1. There's a parser/analyzer (otherwise lower_case has no effect on indexing)
1235
            // 2. lower_case is explicitly set to "true"
1236
27
            bool has_parser = inverted_index::InvertedIndexAnalyzer::should_analyzer(
1237
27
                    binding.index_properties);
1238
27
            std::string lowercase_setting =
1239
27
                    get_parser_lowercase_from_properties(binding.index_properties);
1240
27
            bool should_lowercase = has_parser && (lowercase_setting == INVERTED_INDEX_PARSER_TRUE);
1241
27
            std::string pattern = should_lowercase ? to_lower(value) : value;
1242
27
            *out = std::make_shared<query_v2::WildcardQuery>(context, field_wstr, pattern);
1243
27
            VLOG_DEBUG << "search: WILDCARD clause processed, field=" << field_name << ", pattern='"
1244
0
                       << pattern << "' (original='" << value << "', has_parser=" << has_parser
1245
0
                       << ", lower_case=" << lowercase_setting << ")";
1246
27
            return Status::OK();
1247
27
        }
1248
1249
33
        if (clause_type == "REGEXP") {
1250
            // ES-compatible: regex patterns are NOT lowercased (case-sensitive matching)
1251
            // This matches ES query_string behavior where regex patterns bypass analysis
1252
29
            *out = std::make_shared<query_v2::RegexpQuery>(context, field_wstr, value);
1253
29
            VLOG_DEBUG << "search: REGEXP clause processed, field=" << field_name << ", pattern='"
1254
0
                       << value << "'";
1255
29
            return Status::OK();
1256
29
        }
1257
1258
4
        if (clause_type == "RANGE" || clause_type == "LIST") {
1259
4
            VLOG_DEBUG << "search: clause type '" << clause_type
1260
0
                       << "' not implemented, fallback to TERM";
1261
4
        }
1262
4
        *out = make_term_query(value_wstr);
1263
4
        return Status::OK();
1264
33
    }
1265
1266
18.4E
    LOG(WARNING) << "search: Unexpected clause type '" << clause_type << "', using TERM fallback";
1267
18.4E
    *out = make_term_query(value_wstr);
1268
18.4E
    return Status::OK();
1269
179
}
1270
1271
8
void register_function_search(SimpleFunctionFactory& factory) {
1272
8
    factory.register_function<FunctionSearch>();
1273
8
}
1274
1275
} // namespace doris