Coverage Report

Created: 2026-03-25 23:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment_iterator.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 "storage/segment/segment_iterator.h"
19
20
#include <assert.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/Opcodes_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <algorithm>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <cstdint>
29
#include <memory>
30
#include <numeric>
31
#include <set>
32
#include <unordered_map>
33
#include <utility>
34
#include <vector>
35
36
#include "cloud/config.h"
37
#include "common/compiler_util.h" // IWYU pragma: keep
38
#include "common/config.h"
39
#include "common/consts.h"
40
#include "common/exception.h"
41
#include "common/logging.h"
42
#include "common/metrics/doris_metrics.h"
43
#include "common/object_pool.h"
44
#include "common/status.h"
45
#include "core/assert_cast.h"
46
#include "core/block/column_with_type_and_name.h"
47
#include "core/column/column.h"
48
#include "core/column/column_const.h"
49
#include "core/column/column_nothing.h"
50
#include "core/column/column_nullable.h"
51
#include "core/column/column_string.h"
52
#include "core/column/column_variant.h"
53
#include "core/column/column_vector.h"
54
#include "core/data_type/data_type.h"
55
#include "core/data_type/data_type_factory.hpp"
56
#include "core/data_type/data_type_number.h"
57
#include "core/data_type/define_primitive_type.h"
58
#include "core/field.h"
59
#include "core/string_ref.h"
60
#include "core/typeid_cast.h"
61
#include "core/types.h"
62
#include "exprs/function/array/function_array_index.h"
63
#include "exprs/vexpr.h"
64
#include "exprs/vexpr_context.h"
65
#include "exprs/virtual_slot_ref.h"
66
#include "exprs/vliteral.h"
67
#include "exprs/vslot_ref.h"
68
#include "io/cache/cached_remote_file_reader.h"
69
#include "io/fs/file_reader.h"
70
#include "io/io_common.h"
71
#include "runtime/query_context.h"
72
#include "runtime/runtime_predicate.h"
73
#include "runtime/runtime_state.h"
74
#include "runtime/thread_context.h"
75
#include "storage/compaction/collection_similarity.h"
76
#include "storage/field.h"
77
#include "storage/id_manager.h"
78
#include "storage/index/ann/ann_index.h"
79
#include "storage/index/ann/ann_index_iterator.h"
80
#include "storage/index/ann/ann_index_reader.h"
81
#include "storage/index/ann/ann_topn_runtime.h"
82
#include "storage/index/index_file_reader.h"
83
#include "storage/index/index_iterator.h"
84
#include "storage/index/index_query_context.h"
85
#include "storage/index/index_reader_helper.h"
86
#include "storage/index/indexed_column_reader.h"
87
#include "storage/index/inverted/inverted_index_reader.h"
88
#include "storage/index/ordinal_page_index.h"
89
#include "storage/index/primary_key_index.h"
90
#include "storage/index/short_key_index.h"
91
#include "storage/iterators.h"
92
#include "storage/olap_common.h"
93
#include "storage/predicate/bloom_filter_predicate.h"
94
#include "storage/predicate/column_predicate.h"
95
#include "storage/predicate/like_column_predicate.h"
96
#include "storage/schema.h"
97
#include "storage/segment/column_reader.h"
98
#include "storage/segment/column_reader_cache.h"
99
#include "storage/segment/condition_cache.h"
100
#include "storage/segment/row_ranges.h"
101
#include "storage/segment/segment.h"
102
#include "storage/segment/segment_prefetcher.h"
103
#include "storage/segment/variant/variant_column_reader.h"
104
#include "storage/segment/virtual_column_iterator.h"
105
#include "storage/tablet/tablet_schema.h"
106
#include "storage/types.h"
107
#include "storage/utils.h"
108
#include "util/concurrency_stats.h"
109
#include "util/defer_op.h"
110
#include "util/simd/bits.h"
111
112
namespace doris {
113
using namespace ErrorCode;
114
namespace segment_v2 {
115
116
#include "common/compile_check_begin.h"
117
118
5.63k
SegmentIterator::~SegmentIterator() = default;
119
120
5.63k
void SegmentIterator::_init_row_bitmap_by_condition_cache() {
121
    // Only dispose need column predicate and expr cal in condition cache
122
5.63k
    if (!_col_predicates.empty() ||
123
5.63k
        (_enable_common_expr_pushdown && !_remaining_conjunct_roots.empty())) {
124
0
        if (_opts.condition_cache_digest) {
125
0
            auto* condition_cache = ConditionCache::instance();
126
0
            ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
127
0
                                               _opts.condition_cache_digest);
128
129
            // Increment search count when digest != 0
130
0
            DorisMetrics::instance()->condition_cache_search_count->increment(1);
131
132
0
            ConditionCacheHandle handle;
133
0
            _find_condition_cache = condition_cache->lookup(cache_key, &handle);
134
135
            // Increment hit count if cache lookup is successful
136
0
            if (_find_condition_cache) {
137
0
                DorisMetrics::instance()->condition_cache_hit_count->increment(1);
138
0
                if (_opts.runtime_state) {
139
0
                    VLOG_DEBUG << "Condition cache hit, query id: "
140
0
                               << print_id(_opts.runtime_state->query_id())
141
0
                               << ", segment id: " << _segment->id()
142
0
                               << ", cache digest: " << _opts.condition_cache_digest
143
0
                               << ", rowset id: " << _opts.rowset_id.to_string();
144
0
                }
145
0
            }
146
147
0
            auto num_rows = _segment->num_rows();
148
0
            if (_find_condition_cache) {
149
0
                const auto& filter_result = *(handle.get_filter_result());
150
0
                int64_t filtered_blocks = 0;
151
0
                for (int i = 0; i < filter_result.size(); i++) {
152
0
                    if (!filter_result[i]) {
153
0
                        _row_bitmap.removeRange(
154
0
                                i * CONDITION_CACHE_OFFSET,
155
0
                                i * CONDITION_CACHE_OFFSET + CONDITION_CACHE_OFFSET);
156
0
                        filtered_blocks++;
157
0
                    }
158
0
                }
159
                // Record condition_cache hit segment number
160
0
                _opts.stats->condition_cache_hit_seg_nums++;
161
                // Record rows filtered by condition cache hit
162
0
                _opts.stats->condition_cache_filtered_rows +=
163
0
                        filtered_blocks * SegmentIterator::CONDITION_CACHE_OFFSET;
164
0
            } else {
165
0
                _condition_cache = std::make_shared<std::vector<bool>>(
166
0
                        num_rows / CONDITION_CACHE_OFFSET + 1, false);
167
0
            }
168
0
        }
169
5.63k
    } else {
170
5.63k
        _opts.condition_cache_digest = 0;
171
5.63k
    }
172
5.63k
}
173
174
// A fast range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
175
// Example:
176
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
177
//   output ranges: [0,2), [4,8), [10,11), [15,20) (when max_range_size=10)
178
//   output ranges: [0,2), [4,7), [7,8), [10,11), [15,18), [18,20) (when max_range_size=3)
179
class SegmentIterator::BitmapRangeIterator {
180
public:
181
0
    BitmapRangeIterator() = default;
182
5.63k
    virtual ~BitmapRangeIterator() = default;
183
184
5.63k
    explicit BitmapRangeIterator(const roaring::Roaring& bitmap) {
185
5.63k
        roaring_init_iterator(&bitmap.roaring, &_iter);
186
5.63k
    }
187
188
0
    bool has_more_range() const { return !_eof; }
189
190
12.1k
    [[nodiscard]] static uint32_t get_batch_size() { return kBatchSize; }
191
192
    // read next range into [*from, *to) whose size <= max_range_size.
193
    // return false when there is no more range.
194
0
    virtual bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) {
195
0
        if (_eof) {
196
0
            return false;
197
0
        }
198
199
0
        *from = _buf[_buf_pos];
200
0
        uint32_t range_size = 0;
201
0
        uint32_t expect_val = _buf[_buf_pos]; // this initial value just make first batch valid
202
203
        // if array is contiguous sequence then the following conditions need to be met :
204
        // a_0: x
205
        // a_1: x+1
206
        // a_2: x+2
207
        // ...
208
        // a_p: x+p
209
        // so we can just use (a_p-a_0)-p to check conditions
210
        // and should notice the previous batch needs to be continuous with the current batch
211
0
        while (!_eof && range_size + _buf_size - _buf_pos <= max_range_size &&
212
0
               expect_val == _buf[_buf_pos] &&
213
0
               _buf[_buf_size - 1] - _buf[_buf_pos] == _buf_size - 1 - _buf_pos) {
214
0
            range_size += _buf_size - _buf_pos;
215
0
            expect_val = _buf[_buf_size - 1] + 1;
216
0
            _read_next_batch();
217
0
        }
218
219
        // promise remain range not will reach next batch
220
0
        if (!_eof && range_size < max_range_size && expect_val == _buf[_buf_pos]) {
221
0
            do {
222
0
                _buf_pos++;
223
0
                range_size++;
224
0
            } while (range_size < max_range_size && _buf[_buf_pos] == _buf[_buf_pos - 1] + 1);
225
0
        }
226
0
        *to = *from + range_size;
227
0
        return true;
228
0
    }
229
230
    // read batch_size of rowids from roaring bitmap into buf array
231
23.1k
    virtual uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) {
232
23.1k
        return roaring::api::roaring_read_uint32_iterator(&_iter, buf, batch_size);
233
23.1k
    }
234
235
private:
236
0
    void _read_next_batch() {
237
0
        _buf_pos = 0;
238
0
        _buf_size = roaring::api::roaring_read_uint32_iterator(&_iter, _buf, kBatchSize);
239
0
        _eof = (_buf_size == 0);
240
0
    }
241
242
    static const uint32_t kBatchSize = 256;
243
    roaring::api::roaring_uint32_iterator_t _iter;
244
    uint32_t _buf[kBatchSize];
245
    uint32_t _buf_pos = 0;
246
    uint32_t _buf_size = 0;
247
    bool _eof = false;
248
};
249
250
// A backward range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
251
// Example:
252
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
253
//   output ranges: , [15,20), [10,11), [4,8), [0,2) (when max_range_size=10)
254
//   output ranges: [17,20), [15,17), [10,11), [5,8), [4, 5), [0,2) (when max_range_size=3)
255
class SegmentIterator::BackwardBitmapRangeIterator : public SegmentIterator::BitmapRangeIterator {
256
public:
257
0
    explicit BackwardBitmapRangeIterator(const roaring::Roaring& bitmap) {
258
0
        roaring_init_iterator_last(&bitmap.roaring, &_riter);
259
0
        _rowid_count = cast_set<uint32_t>(roaring_bitmap_get_cardinality(&bitmap.roaring));
260
0
        _rowid_left = _rowid_count;
261
0
    }
262
263
0
    bool has_more_range() const { return !_riter.has_value; }
264
265
    // read next range into [*from, *to) whose size <= max_range_size.
266
    // return false when there is no more range.
267
0
    bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) override {
268
0
        if (!_riter.has_value) {
269
0
            return false;
270
0
        }
271
272
0
        uint32_t range_size = 0;
273
0
        *to = _riter.current_value + 1;
274
275
0
        do {
276
0
            *from = _riter.current_value;
277
0
            range_size++;
278
0
            roaring_previous_uint32_iterator(&_riter);
279
0
        } while (range_size < max_range_size && _riter.has_value &&
280
0
                 _riter.current_value + 1 == *from);
281
282
0
        return true;
283
0
    }
284
    /**
285
     * Reads a batch of row IDs from a roaring bitmap, starting from the end and moving backwards.
286
     * This function retrieves the last `batch_size` row IDs from the bitmap and stores them in the provided buffer.
287
     * It updates the internal state to track how many row IDs are left to read in subsequent calls.
288
     *
289
     * The row IDs are read in reverse order, but stored in the buffer maintaining their original order in the bitmap.
290
     *
291
     * Example:
292
     *   input bitmap: [0 1 4 5 6 7 10 15 16 17 18 19]
293
     *   If the bitmap has 12 elements and batch_size is set to 5, the function will first read [15, 16, 17, 18, 19]
294
     *   into the buffer, leaving 7 elements left. In the next call with batch_size 5, it will read [4, 5, 6, 7, 10].
295
     *
296
     */
297
0
    uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) override {
298
0
        if (!_riter.has_value || _rowid_left == 0) {
299
0
            return 0;
300
0
        }
301
302
0
        if (_rowid_count <= batch_size) {
303
0
            roaring_bitmap_to_uint32_array(_riter.parent,
304
0
                                           buf); // Fill 'buf' with '_rowid_count' elements.
305
0
            uint32_t num_read = _rowid_left;     // Save the number of row IDs read.
306
0
            _rowid_left = 0;                     // No row IDs left after this operation.
307
0
            return num_read;                     // Return the number of row IDs read.
308
0
        }
309
310
0
        uint32_t read_size = std::min(batch_size, _rowid_left);
311
0
        uint32_t num_read = 0; // Counter for the number of row IDs read.
312
313
        // Read row IDs into the buffer in reverse order.
314
0
        while (num_read < read_size && _riter.has_value) {
315
0
            buf[read_size - num_read - 1] = _riter.current_value;
316
0
            num_read++;
317
0
            _rowid_left--; // Decrement the count of remaining row IDs.
318
0
            roaring_previous_uint32_iterator(&_riter);
319
0
        }
320
321
        // Return the actual number of row IDs read.
322
0
        return num_read;
323
0
    }
324
325
private:
326
    roaring::api::roaring_uint32_iterator_t _riter;
327
    uint32_t _rowid_count;
328
    uint32_t _rowid_left;
329
};
330
331
SegmentIterator::SegmentIterator(std::shared_ptr<Segment> segment, SchemaSPtr schema)
332
5.63k
        : _segment(std::move(segment)),
333
5.63k
          _schema(schema),
334
5.63k
          _column_iterators(_schema->num_columns()),
335
5.63k
          _index_iterators(_schema->num_columns()),
336
5.63k
          _cur_rowid(0),
337
5.63k
          _lazy_materialization_read(false),
338
5.63k
          _lazy_inited(false),
339
5.63k
          _inited(false),
340
5.63k
          _pool(new ObjectPool) {}
341
342
11.1k
Status SegmentIterator::init(const StorageReadOptions& opts) {
343
11.1k
    auto status = _init_impl(opts);
344
11.1k
    if (!status.ok()) {
345
0
        _segment->update_healthy_status(status);
346
0
    }
347
11.1k
    return status;
348
11.1k
}
349
350
11.1k
Status SegmentIterator::_init_impl(const StorageReadOptions& opts) {
351
    // get file handle from file descriptor of segment
352
11.1k
    if (_inited) {
353
5.49k
        return Status::OK();
354
5.49k
    }
355
5.63k
    _opts = opts;
356
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_timer_ns);
357
5.63k
    _inited = true;
358
5.63k
    _file_reader = _segment->_file_reader;
359
5.63k
    _col_predicates.clear();
360
361
5.63k
    for (const auto& predicate : opts.column_predicates) {
362
0
        if (!_segment->can_apply_predicate_safely(predicate->column_id(), *_schema,
363
0
                                                  _opts.target_cast_type_for_variants, _opts)) {
364
0
            continue;
365
0
        }
366
0
        _col_predicates.emplace_back(predicate);
367
0
    }
368
5.63k
    _tablet_id = opts.tablet_id;
369
    // Read options will not change, so that just resize here
370
5.63k
    _block_rowids.resize(_opts.block_row_max);
371
372
5.63k
    _remaining_conjunct_roots = opts.remaining_conjunct_roots;
373
374
5.63k
    if (_schema->rowid_col_idx() > 0) {
375
0
        _record_rowids = true;
376
0
    }
377
378
5.63k
    _virtual_column_exprs = _opts.virtual_column_exprs;
379
5.63k
    _vir_cid_to_idx_in_block = _opts.vir_cid_to_idx_in_block;
380
5.63k
    _score_runtime = _opts.score_runtime;
381
5.63k
    _ann_topn_runtime = _opts.ann_topn_runtime;
382
383
5.63k
    if (opts.output_columns != nullptr) {
384
1.29k
        _output_columns = *(opts.output_columns);
385
1.29k
    }
386
387
5.63k
    _storage_name_and_type.resize(_schema->columns().size());
388
5.63k
    auto storage_format = _opts.tablet_schema->get_inverted_index_storage_format();
389
34.2k
    for (int i = 0; i < _schema->columns().size(); ++i) {
390
28.6k
        const StorageField* col = _schema->column(i);
391
28.6k
        if (col) {
392
12.6k
            auto storage_type = _segment->get_data_type_of(col->get_desc(), _opts);
393
12.6k
            if (storage_type == nullptr) {
394
0
                storage_type = DataTypeFactory::instance().create_data_type(col->get_desc(),
395
0
                                                                            col->is_nullable());
396
0
            }
397
            // Currently, when writing a lucene index, the field of the document is column_name, and the column name is
398
            // bound to the index field. Since version 1.2, the data file storage has been changed from column_name to
399
            // column_unique_id, allowing the column name to be changed. Due to current limitations, previous inverted
400
            // index data cannot be used after Doris changes the column name. Column names also support Unicode
401
            // characters, which may cause other problems with indexing in non-ASCII characters.
402
            // After consideration, it was decided to change the field name from column_name to column_unique_id in
403
            // format V2, while format V1 continues to use column_name.
404
12.6k
            std::string field_name;
405
12.6k
            if (storage_format == InvertedIndexStorageFormatPB::V1) {
406
9.98k
                field_name = col->name();
407
9.98k
            } else {
408
2.68k
                if (col->is_extracted_column()) {
409
                    // variant sub col
410
                    // field_name format: parent_unique_id.sub_col_name
411
0
                    field_name = std::to_string(col->parent_unique_id()) + "." + col->name();
412
2.68k
                } else {
413
2.68k
                    field_name = std::to_string(col->unique_id());
414
2.68k
                }
415
2.68k
            }
416
12.6k
            _storage_name_and_type[i] = std::make_pair(field_name, storage_type);
417
12.6k
            if (int32_t uid = col->get_unique_id(); !_variant_sparse_column_cache.contains(uid)) {
418
12.6k
                DCHECK(uid >= 0);
419
12.6k
                _variant_sparse_column_cache.emplace(uid,
420
12.6k
                                                     std::make_unique<PathToBinaryColumnCache>());
421
12.6k
            }
422
12.6k
        }
423
28.6k
    }
424
425
5.63k
    RETURN_IF_ERROR(init_iterators());
426
427
5.63k
    RETURN_IF_ERROR(_construct_compound_expr_context());
428
5.63k
    _enable_common_expr_pushdown = !_common_expr_ctxs_push_down.empty();
429
5.63k
    VLOG_DEBUG << fmt::format(
430
0
            "Segment iterator init, virtual_column_exprs size: {}, "
431
0
            "_vir_cid_to_idx_in_block size: {}, common_expr_pushdown size: {}",
432
0
            _opts.virtual_column_exprs.size(), _opts.vir_cid_to_idx_in_block.size(),
433
0
            _common_expr_ctxs_push_down.size());
434
5.63k
    _initialize_predicate_results();
435
5.63k
    return Status::OK();
436
5.63k
}
437
438
5.63k
void SegmentIterator::_initialize_predicate_results() {
439
    // Initialize from _col_predicates
440
5.63k
    for (auto pred : _col_predicates) {
441
0
        int cid = pred->column_id();
442
0
        _column_predicate_index_exec_status[cid][pred] = false;
443
0
    }
444
445
5.63k
    _calculate_expr_in_remaining_conjunct_root();
446
5.63k
}
447
448
5.63k
Status SegmentIterator::init_iterators() {
449
5.63k
    RETURN_IF_ERROR(_init_return_column_iterators());
450
5.63k
    RETURN_IF_ERROR(_init_index_iterators());
451
5.63k
    return Status::OK();
452
5.63k
}
453
454
23.1k
Status SegmentIterator::_lazy_init(Block* block) {
455
23.1k
    if (_lazy_inited) {
456
17.4k
        return Status::OK();
457
17.4k
    }
458
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->block_init_ns);
459
5.63k
    DorisMetrics::instance()->segment_read_total->increment(1);
460
5.63k
    _row_bitmap.addRange(0, _segment->num_rows());
461
5.63k
    _init_row_bitmap_by_condition_cache();
462
463
    // z-order can not use prefix index
464
5.63k
    if (_segment->_tablet_schema->sort_type() != SortType::ZORDER &&
465
5.63k
        _segment->_tablet_schema->cluster_key_uids().empty()) {
466
5.63k
        RETURN_IF_ERROR(_get_row_ranges_by_keys());
467
5.63k
    }
468
5.63k
    RETURN_IF_ERROR(_get_row_ranges_by_column_conditions());
469
5.63k
    RETURN_IF_ERROR(_vec_init_lazy_materialization());
470
    // Remove rows that have been marked deleted
471
5.63k
    if (_opts.delete_bitmap.count(segment_id()) > 0 &&
472
5.63k
        _opts.delete_bitmap.at(segment_id()) != nullptr) {
473
25
        size_t pre_size = _row_bitmap.cardinality();
474
25
        _row_bitmap -= *(_opts.delete_bitmap.at(segment_id()));
475
25
        _opts.stats->rows_del_by_bitmap += (pre_size - _row_bitmap.cardinality());
476
25
        VLOG_DEBUG << "read on segment: " << segment_id() << ", delete bitmap cardinality: "
477
0
                   << _opts.delete_bitmap.at(segment_id())->cardinality() << ", "
478
0
                   << _opts.stats->rows_del_by_bitmap << " rows deleted by bitmap";
479
25
    }
480
481
5.63k
    if (!_opts.row_ranges.is_empty()) {
482
0
        _row_bitmap &= RowRanges::ranges_to_roaring(_opts.row_ranges);
483
0
    }
484
485
5.63k
    _prepare_score_column_materialization();
486
487
5.63k
    RETURN_IF_ERROR(_apply_ann_topn_predicate());
488
489
5.63k
    if (_opts.read_orderby_key_reverse) {
490
0
        _range_iter.reset(new BackwardBitmapRangeIterator(_row_bitmap));
491
5.63k
    } else {
492
5.63k
        _range_iter.reset(new BitmapRangeIterator(_row_bitmap));
493
5.63k
    }
494
495
    // If the row bitmap size is smaller than block_row_max, there's no need to reserve that many column rows.
496
5.63k
    auto nrows_reserve_limit = std::min(_row_bitmap.cardinality(), uint64_t(_opts.block_row_max));
497
5.63k
    if (_lazy_materialization_read || _opts.record_rowids || _is_need_expr_eval) {
498
894
        _block_rowids.resize(_opts.block_row_max);
499
894
    }
500
5.63k
    _current_return_columns.resize(_schema->columns().size());
501
502
5.63k
    _vec_init_char_column_id(block);
503
18.3k
    for (size_t i = 0; i < _schema->column_ids().size(); i++) {
504
12.6k
        ColumnId cid = _schema->column_ids()[i];
505
12.6k
        const auto* column_desc = _schema->column(cid);
506
12.6k
        if (_is_pred_column[cid]) {
507
467
            auto storage_column_type = _storage_name_and_type[cid].second;
508
            // Char type is special , since char type's computational datatype is same with string,
509
            // both are DataTypeString, but DataTypeString only return FieldType::OLAP_FIELD_TYPE_STRING
510
            // in get_storage_field_type.
511
467
            RETURN_IF_CATCH_EXCEPTION(
512
                    // Here, cid will not go out of bounds
513
                    // because the size of _current_return_columns equals _schema->tablet_columns().size()
514
467
                    _current_return_columns[cid] = Schema::get_predicate_column_ptr(
515
467
                            _is_char_type[cid] ? FieldType::OLAP_FIELD_TYPE_CHAR
516
467
                                               : storage_column_type->get_storage_field_type(),
517
467
                            storage_column_type->is_nullable(), _opts.io_ctx.reader_type));
518
467
            _current_return_columns[cid]->set_rowset_segment_id(
519
467
                    {_segment->rowset_id(), _segment->id()});
520
467
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
521
12.2k
        } else if (i >= block->columns()) {
522
            // This column needs to be scanned, but doesn't need to be returned upward. (delete sign)
523
            // if i >= block->columns means the column and not the pred_column means `column i` is
524
            // a delete condition column. but the column is not effective in the segment. so we just
525
            // create a column to hold the data.
526
            // a. origin data -> b. delete condition -> c. new load data
527
            // the segment of c do not effective delete condition, but it still need read the column
528
            // to match the schema.
529
            // TODO: skip read the not effective delete column to speed up segment read.
530
0
            _current_return_columns[cid] = Schema::get_data_type_ptr(*column_desc)->create_column();
531
0
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
532
0
        }
533
12.6k
    }
534
535
    // Additional deleted filter condition will be materialized column be at the end of the block,
536
    // after _output_column_by_sel_idx  will be erase, we not need to filter it,
537
    // so erase it from _columns_to_filter in the first next_batch.
538
    // Eg:
539
    //      `delete from table where a = 10;`
540
    //      `select b from table;`
541
    // a column only effective in segment iterator, the block from query engine only contain the b column,
542
    // so no need to filter a column by expr.
543
5.63k
    for (auto it = _columns_to_filter.begin(); it != _columns_to_filter.end();) {
544
0
        if (*it >= block->columns()) {
545
0
            it = _columns_to_filter.erase(it);
546
0
        } else {
547
0
            ++it;
548
0
        }
549
0
    }
550
551
5.63k
    _lazy_inited = true;
552
553
5.63k
    _init_segment_prefetchers();
554
555
5.63k
    return Status::OK();
556
5.63k
}
557
558
5.63k
void SegmentIterator::_init_segment_prefetchers() {
559
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_segment_prefetchers_timer_ns);
560
5.63k
    if (!config::is_cloud_mode()) {
561
5.63k
        return;
562
5.63k
    }
563
0
    static std::vector<ReaderType> supported_reader_types {
564
0
            ReaderType::READER_QUERY, ReaderType::READER_BASE_COMPACTION,
565
0
            ReaderType::READER_CUMULATIVE_COMPACTION, ReaderType::READER_FULL_COMPACTION};
566
0
    if (std::ranges::none_of(supported_reader_types,
567
0
                             [&](ReaderType t) { return _opts.io_ctx.reader_type == t; })) {
568
0
        return;
569
0
    }
570
    // Initialize segment prefetcher for predicate and non-predicate columns
571
0
    bool is_query = (_opts.io_ctx.reader_type == ReaderType::READER_QUERY);
572
0
    bool enable_prefetch = is_query ? config::enable_query_segment_file_cache_prefetch
573
0
                                    : config::enable_compaction_segment_file_cache_prefetch;
574
0
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
575
0
            "[verbose] SegmentIterator _init_segment_prefetchers, is_query={}, enable_prefetch={}, "
576
0
            "_row_bitmap.isEmpty()={}, row_bitmap.cardinality()={}, tablet={}, rowset={}, "
577
0
            "segment={}, predicate_column_ids={}, common_expr_column_ids={}",
578
0
            is_query, enable_prefetch, _row_bitmap.isEmpty(), _row_bitmap.cardinality(),
579
0
            _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
580
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_common_expr_column_ids, ","));
581
0
    if (enable_prefetch && !_row_bitmap.isEmpty()) {
582
0
        int window_size =
583
0
                1 + (is_query ? config::query_segment_file_cache_prefetch_block_size
584
0
                              : config::compaction_segment_file_cache_prefetch_block_size);
585
0
        LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
586
0
                "[verbose] SegmentIterator prefetch config: window_size={}", window_size);
587
0
        if (window_size > 0 &&
588
0
            !_column_iterators.empty()) { // ensure init_iterators has been called
589
0
            SegmentPrefetcherConfig prefetch_config(window_size,
590
0
                                                    config::file_cache_each_block_size);
591
0
            for (auto cid : _schema->column_ids()) {
592
0
                auto& column_iter = _column_iterators[cid];
593
0
                if (column_iter == nullptr) {
594
0
                    continue;
595
0
                }
596
0
                const auto* tablet_column = _schema->column(cid);
597
0
                SegmentPrefetchParams params {
598
0
                        .config = prefetch_config,
599
0
                        .read_options = _opts,
600
0
                };
601
0
                LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
602
0
                        "[verbose] SegmentIterator init_segment_prefetchers, "
603
0
                        "tablet={}, rowset={}, segment={}, column_id={}, col_name={}, type={}",
604
0
                        _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(), cid,
605
0
                        tablet_column->name(), tablet_column->type());
606
0
                Status st = column_iter->init_prefetcher(params);
607
0
                if (!st.ok()) {
608
0
                    LOG_IF(WARNING, config::enable_segment_prefetch_verbose_log) << fmt::format(
609
0
                            "[verbose] failed to init prefetcher for column_id={}, "
610
0
                            "tablet={}, rowset={}, segment={}, error={}",
611
0
                            cid, _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
612
0
                            st.to_string());
613
0
                }
614
0
            }
615
616
            // for compaction, it's guaranteed that all rows are read, so we can prefetch all data blocks
617
0
            PrefetcherInitMethod init_method = (is_query && _row_bitmap.cardinality() < num_rows())
618
0
                                                       ? PrefetcherInitMethod::FROM_ROWIDS
619
0
                                                       : PrefetcherInitMethod::ALL_DATA_BLOCKS;
620
0
            std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>> prefetchers;
621
0
            for (const auto& column_iter : _column_iterators) {
622
0
                if (column_iter != nullptr) {
623
0
                    column_iter->collect_prefetchers(prefetchers, init_method);
624
0
                }
625
0
            }
626
0
            for (auto& [method, prefetcher_vec] : prefetchers) {
627
0
                if (method == PrefetcherInitMethod::ALL_DATA_BLOCKS) {
628
0
                    for (auto* prefetcher : prefetcher_vec) {
629
0
                        prefetcher->build_all_data_blocks();
630
0
                    }
631
0
                } else if (method == PrefetcherInitMethod::FROM_ROWIDS && !prefetcher_vec.empty()) {
632
0
                    SegmentPrefetcher::build_blocks_by_rowids(_row_bitmap, prefetcher_vec);
633
0
                }
634
0
            }
635
0
        }
636
0
    }
637
0
}
638
639
5.63k
Status SegmentIterator::_get_row_ranges_by_keys() {
640
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_keys_ns);
641
5.63k
    DorisMetrics::instance()->segment_row_total->increment(num_rows());
642
643
    // fast path for empty segment or empty key ranges
644
5.63k
    if (_row_bitmap.isEmpty() || _opts.key_ranges.empty()) {
645
5.63k
        return Status::OK();
646
5.63k
    }
647
648
    // Read & seek key columns is a waste of time when no key column in _schema
649
0
    if (std::none_of(
650
0
                _schema->columns().begin(), _schema->columns().end(), [&](const StorageField* col) {
651
0
                    return col && _opts.tablet_schema->column_by_uid(col->unique_id()).is_key();
652
0
                })) {
653
0
        return Status::OK();
654
0
    }
655
656
0
    RowRanges result_ranges;
657
0
    for (auto& key_range : _opts.key_ranges) {
658
0
        rowid_t lower_rowid = 0;
659
0
        rowid_t upper_rowid = num_rows();
660
0
        RETURN_IF_ERROR(_prepare_seek(key_range));
661
0
        if (key_range.upper_key != nullptr) {
662
            // If client want to read upper_bound, the include_upper is true. So we
663
            // should get the first ordinal at which key is larger than upper_bound.
664
            // So we call _lookup_ordinal with include_upper's negate
665
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.upper_key, !key_range.include_upper,
666
0
                                            num_rows(), &upper_rowid));
667
0
        }
668
0
        if (upper_rowid > 0 && key_range.lower_key != nullptr) {
669
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.lower_key, key_range.include_lower,
670
0
                                            upper_rowid, &lower_rowid));
671
0
        }
672
0
        auto row_range = RowRanges::create_single(lower_rowid, upper_rowid);
673
0
        RowRanges::ranges_union(result_ranges, row_range, &result_ranges);
674
0
    }
675
0
    size_t pre_size = _row_bitmap.cardinality();
676
0
    _row_bitmap &= RowRanges::ranges_to_roaring(result_ranges);
677
0
    _opts.stats->rows_key_range_filtered += (pre_size - _row_bitmap.cardinality());
678
679
0
    return Status::OK();
680
0
}
681
682
// Set up environment for the following seek.
683
0
Status SegmentIterator::_prepare_seek(const StorageReadOptions::KeyRange& key_range) {
684
0
    std::vector<const StorageField*> key_fields;
685
0
    std::set<uint32_t> column_set;
686
0
    if (key_range.lower_key != nullptr) {
687
0
        for (auto cid : key_range.lower_key->schema()->column_ids()) {
688
0
            column_set.emplace(cid);
689
0
            key_fields.emplace_back(key_range.lower_key->column_schema(cid));
690
0
        }
691
0
    }
692
0
    if (key_range.upper_key != nullptr) {
693
0
        for (auto cid : key_range.upper_key->schema()->column_ids()) {
694
0
            if (column_set.count(cid) == 0) {
695
0
                key_fields.emplace_back(key_range.upper_key->column_schema(cid));
696
0
                column_set.emplace(cid);
697
0
            }
698
0
        }
699
0
    }
700
0
    if (!_seek_schema) {
701
        // Schema constructors accept a vector of TabletColumnPtr. Convert
702
        // StorageField pointers to TabletColumnPtr by copying their descriptors.
703
0
        std::vector<TabletColumnPtr> cols;
704
0
        cols.reserve(key_fields.size());
705
0
        for (const StorageField* f : key_fields) {
706
0
            cols.emplace_back(std::make_shared<TabletColumn>(f->get_desc()));
707
0
        }
708
0
        _seek_schema = std::make_unique<Schema>(cols, cols.size());
709
0
    }
710
    // todo(wb) need refactor here, when using pk to search, _seek_block is useless
711
0
    if (_seek_block.size() == 0) {
712
0
        _seek_block.resize(_seek_schema->num_column_ids());
713
0
        int i = 0;
714
0
        for (auto cid : _seek_schema->column_ids()) {
715
0
            auto column_desc = _seek_schema->column(cid);
716
0
            _seek_block[i] = Schema::get_column_by_field(*column_desc);
717
0
            i++;
718
0
        }
719
0
    }
720
721
    // create used column iterator
722
0
    for (auto cid : _seek_schema->column_ids()) {
723
0
        if (_column_iterators[cid] == nullptr) {
724
            // TODO: Do we need this?
725
0
            if (_virtual_column_exprs.contains(cid)) {
726
0
                _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
727
0
                continue;
728
0
            }
729
730
0
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
731
0
                                                          &_column_iterators[cid], &_opts,
732
0
                                                          &_variant_sparse_column_cache));
733
0
            ColumnIteratorOptions iter_opts {
734
0
                    .use_page_cache = _opts.use_page_cache,
735
0
                    .file_reader = _file_reader.get(),
736
0
                    .stats = _opts.stats,
737
0
                    .io_ctx = _opts.io_ctx,
738
0
            };
739
0
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
740
0
        }
741
0
    }
742
743
0
    return Status::OK();
744
0
}
745
746
5.63k
Status SegmentIterator::_get_row_ranges_by_column_conditions() {
747
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_column_conditions_ns);
748
5.63k
    if (_row_bitmap.isEmpty()) {
749
0
        return Status::OK();
750
0
    }
751
752
5.63k
    {
753
5.63k
        if (_opts.runtime_state &&
754
5.63k
            _opts.runtime_state->query_options().enable_inverted_index_query &&
755
5.63k
            (has_index_in_iterators() || !_common_expr_ctxs_push_down.empty())) {
756
0
            SCOPED_RAW_TIMER(&_opts.stats->inverted_index_filter_timer);
757
0
            size_t input_rows = _row_bitmap.cardinality();
758
            // Only apply column-level inverted index if we have iterators
759
0
            if (has_index_in_iterators()) {
760
0
                RETURN_IF_ERROR(_apply_inverted_index());
761
0
            }
762
            // Always apply expr-level index (e.g., search expressions) if we have common_expr_pushdown
763
            // This allows search expressions with variant subcolumns to be evaluated even when
764
            // the segment doesn't have all subcolumns
765
0
            RETURN_IF_ERROR(_apply_index_expr());
766
0
            for (auto it = _common_expr_ctxs_push_down.begin();
767
0
                 it != _common_expr_ctxs_push_down.end();) {
768
0
                if ((*it)->all_expr_inverted_index_evaluated()) {
769
0
                    const auto* result = (*it)->get_index_context()->get_index_result_for_expr(
770
0
                            (*it)->root().get());
771
0
                    if (result != nullptr) {
772
0
                        _row_bitmap &= *result->get_data_bitmap();
773
0
                        auto root = (*it)->root();
774
0
                        auto iter_find = std::find(_remaining_conjunct_roots.begin(),
775
0
                                                   _remaining_conjunct_roots.end(), root);
776
0
                        if (iter_find != _remaining_conjunct_roots.end()) {
777
0
                            _remaining_conjunct_roots.erase(iter_find);
778
0
                        }
779
0
                        it = _common_expr_ctxs_push_down.erase(it);
780
0
                    }
781
0
                } else {
782
0
                    ++it;
783
0
                }
784
0
            }
785
0
            _opts.condition_cache_digest =
786
0
                    _common_expr_ctxs_push_down.empty() ? 0 : _opts.condition_cache_digest;
787
0
            _opts.stats->rows_inverted_index_filtered += (input_rows - _row_bitmap.cardinality());
788
0
            for (auto cid : _schema->column_ids()) {
789
0
                bool result_true = _check_all_conditions_passed_inverted_index_for_column(cid);
790
0
                if (result_true) {
791
0
                    _need_read_data_indices[cid] = false;
792
0
                }
793
0
            }
794
0
        }
795
5.63k
    }
796
797
5.63k
    DBUG_EXECUTE_IF("segment_iterator.inverted_index.filtered_rows", {
798
5.63k
        LOG(INFO) << "Debug Point: segment_iterator.inverted_index.filtered_rows: "
799
5.63k
                  << _opts.stats->rows_inverted_index_filtered;
800
5.63k
        auto filtered_rows = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
801
5.63k
                "segment_iterator.inverted_index.filtered_rows", "filtered_rows", -1);
802
5.63k
        if (filtered_rows != _opts.stats->rows_inverted_index_filtered) {
803
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
804
5.63k
                    "filtered_rows: {} not equal to expected: {}",
805
5.63k
                    _opts.stats->rows_inverted_index_filtered, filtered_rows);
806
5.63k
        }
807
5.63k
    })
808
809
5.63k
    DBUG_EXECUTE_IF("segment_iterator.apply_inverted_index", {
810
5.63k
        LOG(INFO) << "Debug Point: segment_iterator.apply_inverted_index";
811
5.63k
        if (!_common_expr_ctxs_push_down.empty() || !_col_predicates.empty()) {
812
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
813
5.63k
                    "it is failed to apply inverted index, common_expr_ctxs_push_down: {}, "
814
5.63k
                    "col_predicates: {}",
815
5.63k
                    _common_expr_ctxs_push_down.size(), _col_predicates.size());
816
5.63k
        }
817
5.63k
    })
818
819
5.63k
    if (!_row_bitmap.isEmpty() &&
820
5.63k
        (!_opts.topn_filter_source_node_ids.empty() || !_opts.col_id_to_predicates.empty() ||
821
5.63k
         _opts.delete_condition_predicates->num_of_column_predicate() > 0)) {
822
467
        RowRanges condition_row_ranges = RowRanges::create_single(_segment->num_rows());
823
467
        RETURN_IF_ERROR(_get_row_ranges_from_conditions(&condition_row_ranges));
824
467
        size_t pre_size = _row_bitmap.cardinality();
825
467
        _row_bitmap &= RowRanges::ranges_to_roaring(condition_row_ranges);
826
467
        _opts.stats->rows_conditions_filtered += (pre_size - _row_bitmap.cardinality());
827
467
    }
828
829
5.63k
    DBUG_EXECUTE_IF("bloom_filter_must_filter_data", {
830
5.63k
        if (_opts.stats->rows_bf_filtered == 0) {
831
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
832
5.63k
                    "Bloom filter did not filter the data.");
833
5.63k
        }
834
5.63k
    })
835
836
    // TODO(hkp): calculate filter rate to decide whether to
837
    // use zone map/bloom filter/secondary index or not.
838
5.63k
    return Status::OK();
839
5.63k
}
840
841
0
bool SegmentIterator::_column_has_ann_index(int32_t cid) {
842
0
    bool has_ann_index = _index_iterators[cid] != nullptr &&
843
0
                         _index_iterators[cid]->get_reader(AnnIndexReaderType::ANN);
844
845
0
    return has_ann_index;
846
0
}
847
848
5.63k
Status SegmentIterator::_apply_ann_topn_predicate() {
849
5.63k
    if (_ann_topn_runtime == nullptr) {
850
5.63k
        return Status::OK();
851
5.63k
    }
852
853
0
    VLOG_DEBUG << fmt::format("Try apply ann topn: {}", _ann_topn_runtime->debug_string());
854
0
    size_t src_col_idx = _ann_topn_runtime->get_src_column_idx();
855
0
    ColumnId src_cid = _schema->column_id(src_col_idx);
856
0
    IndexIterator* ann_index_iterator = _index_iterators[src_cid].get();
857
0
    bool has_ann_index = _column_has_ann_index(src_cid);
858
0
    bool has_common_expr_push_down = !_common_expr_ctxs_push_down.empty();
859
0
    bool has_column_predicate = std::any_of(_is_pred_column.begin(), _is_pred_column.end(),
860
0
                                            [](bool is_pred) { return is_pred; });
861
0
    if (!has_ann_index || has_common_expr_push_down || has_column_predicate) {
862
0
        VLOG_DEBUG << fmt::format(
863
0
                "Ann topn can not be evaluated by ann index, has_ann_index: {}, "
864
0
                "has_common_expr_push_down: {}, has_column_predicate: {}",
865
0
                has_ann_index, has_common_expr_push_down, has_column_predicate);
866
        // Disable index-only scan on ann indexed column.
867
0
        _need_read_data_indices[src_cid] = true;
868
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
869
0
        return Status::OK();
870
0
    }
871
872
    // Process asc & desc according to the type of metric
873
0
    auto index_reader = ann_index_iterator->get_reader(AnnIndexReaderType::ANN);
874
0
    auto ann_index_reader = dynamic_cast<AnnIndexReader*>(index_reader.get());
875
0
    DCHECK(ann_index_reader != nullptr);
876
0
    if (ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
877
0
        if (_ann_topn_runtime->is_asc()) {
878
0
            VLOG_DEBUG << fmt::format(
879
0
                    "Asc topn for inner product can not be evaluated by ann index");
880
            // Disable index-only scan on ann indexed column.
881
0
            _need_read_data_indices[src_cid] = true;
882
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
883
0
            return Status::OK();
884
0
        }
885
0
    } else {
886
0
        if (!_ann_topn_runtime->is_asc()) {
887
0
            VLOG_DEBUG << fmt::format("Desc topn for l2/cosine can not be evaluated by ann index");
888
            // Disable index-only scan on ann indexed column.
889
0
            _need_read_data_indices[src_cid] = true;
890
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
891
0
            return Status::OK();
892
0
        }
893
0
    }
894
895
0
    if (ann_index_reader->get_metric_type() != _ann_topn_runtime->get_metric_type()) {
896
0
        VLOG_DEBUG << fmt::format(
897
0
                "Ann topn metric type {} not match index metric type {}, can not be evaluated by "
898
0
                "ann index",
899
0
                metric_to_string(_ann_topn_runtime->get_metric_type()),
900
0
                metric_to_string(ann_index_reader->get_metric_type()));
901
        // Disable index-only scan on ann indexed column.
902
0
        _need_read_data_indices[src_cid] = true;
903
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
904
0
        return Status::OK();
905
0
    }
906
907
0
    size_t pre_size = _row_bitmap.cardinality();
908
0
    size_t rows_of_segment = _segment->num_rows();
909
0
    if (static_cast<double>(pre_size) < static_cast<double>(rows_of_segment) * 0.3) {
910
0
        VLOG_DEBUG << fmt::format(
911
0
                "Ann topn predicate input rows {} < 30% of segment rows {}, will not use ann index "
912
0
                "to "
913
0
                "filter",
914
0
                pre_size, rows_of_segment);
915
        // Disable index-only scan on ann indexed column.
916
0
        _need_read_data_indices[src_cid] = true;
917
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
918
0
        return Status::OK();
919
0
    }
920
0
    IColumn::MutablePtr result_column;
921
0
    std::unique_ptr<std::vector<uint64_t>> result_row_ids;
922
0
    segment_v2::AnnIndexStats ann_index_stats;
923
924
    // Try to load ANN index before search
925
0
    auto ann_index_iterator_casted =
926
0
            dynamic_cast<segment_v2::AnnIndexIterator*>(ann_index_iterator);
927
0
    if (ann_index_iterator_casted == nullptr) {
928
0
        VLOG_DEBUG << "Failed to cast index iterator to AnnIndexIterator, fallback to brute force";
929
0
        _need_read_data_indices[src_cid] = true;
930
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
931
0
        return Status::OK();
932
0
    }
933
934
    // Track load index timing
935
0
    {
936
0
        SCOPED_TIMER(&(ann_index_stats.load_index_costs_ns));
937
0
        if (!ann_index_iterator_casted->try_load_index()) {
938
0
            VLOG_DEBUG << "Failed to load ANN index, fallback to brute force search";
939
0
            _need_read_data_indices[src_cid] = true;
940
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
941
0
            return Status::OK();
942
0
        }
943
0
        double load_costs_ms =
944
0
                static_cast<double>(ann_index_stats.load_index_costs_ns.value()) / 1000000.0;
945
0
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
946
0
                static_cast<int64_t>(load_costs_ms));
947
0
    }
948
949
0
    RETURN_IF_ERROR(_ann_topn_runtime->evaluate_vector_ann_search(
950
0
            ann_index_iterator_casted, &_row_bitmap, rows_of_segment, result_column, result_row_ids,
951
0
            ann_index_stats));
952
953
0
    VLOG_DEBUG << fmt::format("Ann topn filtered {} - {} = {} rows", pre_size,
954
0
                              _row_bitmap.cardinality(), pre_size - _row_bitmap.cardinality());
955
956
0
    int64_t rows_filterd = pre_size - _row_bitmap.cardinality();
957
0
    _opts.stats->rows_ann_index_topn_filtered += rows_filterd;
958
0
    _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
959
0
    _opts.stats->ann_topn_search_ns += ann_index_stats.search_costs_ns.value();
960
0
    _opts.stats->ann_index_topn_engine_search_ns += ann_index_stats.engine_search_ns.value();
961
0
    _opts.stats->ann_index_topn_result_process_ns +=
962
0
            ann_index_stats.result_process_costs_ns.value();
963
0
    _opts.stats->ann_index_topn_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
964
0
    _opts.stats->ann_index_topn_engine_prepare_ns += ann_index_stats.engine_prepare_ns.value();
965
0
    _opts.stats->ann_index_topn_search_cnt += 1;
966
0
    const size_t dst_col_idx = _ann_topn_runtime->get_dest_column_idx();
967
0
    ColumnIterator* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
968
0
    DCHECK(column_iter != nullptr);
969
0
    VirtualColumnIterator* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
970
0
    DCHECK(virtual_column_iter != nullptr);
971
0
    VLOG_DEBUG << fmt::format(
972
0
            "Virtual column iterator, column_idx {}, is materialized with {} rows", dst_col_idx,
973
0
            result_row_ids->size());
974
    // reference count of result_column should be 1, so move will not issue any data copy.
975
0
    virtual_column_iter->prepare_materialization(std::move(result_column),
976
0
                                                 std::move(result_row_ids));
977
978
0
    _need_read_data_indices[src_cid] = false;
979
0
    VLOG_DEBUG << fmt::format(
980
0
            "Enable ANN index-only scan for src column cid {} (skip reading data pages)", src_cid);
981
982
0
    return Status::OK();
983
0
}
984
985
467
Status SegmentIterator::_get_row_ranges_from_conditions(RowRanges* condition_row_ranges) {
986
467
    std::set<int32_t> cids;
987
467
    for (auto& entry : _opts.col_id_to_predicates) {
988
0
        cids.insert(entry.first);
989
0
    }
990
991
467
    {
992
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_dict_ns);
993
        /// Low cardinality optimization is currently not very stable, so to prevent data corruption,
994
        /// we are temporarily disabling its use in data compaction.
995
        // TODO: enable it in not only ReaderTyper::READER_QUERY but also other reader types.
996
467
        if (_opts.io_ctx.reader_type == ReaderType::READER_QUERY) {
997
0
            RowRanges dict_row_ranges = RowRanges::create_single(num_rows());
998
0
            for (auto cid : cids) {
999
0
                if (!_segment->can_apply_predicate_safely(
1000
0
                            cid, *_schema, _opts.target_cast_type_for_variants, _opts)) {
1001
0
                    continue;
1002
0
                }
1003
0
                DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1004
0
                RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_dict(
1005
0
                        _opts.col_id_to_predicates.at(cid).get(), &dict_row_ranges));
1006
1007
0
                if (dict_row_ranges.is_empty()) {
1008
0
                    break;
1009
0
                }
1010
0
            }
1011
1012
0
            if (dict_row_ranges.is_empty()) {
1013
0
                RowRanges::ranges_intersection(*condition_row_ranges, dict_row_ranges,
1014
0
                                               condition_row_ranges);
1015
0
                _opts.stats->segment_dict_filtered++;
1016
0
                _opts.stats->filtered_segment_number++;
1017
0
                return Status::OK();
1018
0
            }
1019
0
        }
1020
467
    }
1021
1022
467
    size_t pre_size = 0;
1023
467
    {
1024
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_bf_ns);
1025
        // first filter data by bloom filter index
1026
        // bloom filter index only use CondColumn
1027
467
        RowRanges bf_row_ranges = RowRanges::create_single(num_rows());
1028
467
        for (auto& cid : cids) {
1029
0
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1030
0
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1031
0
                                                      _opts.target_cast_type_for_variants, _opts)) {
1032
0
                continue;
1033
0
            }
1034
            // get row ranges by bf index of this column,
1035
0
            RowRanges column_bf_row_ranges = RowRanges::create_single(num_rows());
1036
0
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_bloom_filter(
1037
0
                    _opts.col_id_to_predicates.at(cid).get(), &column_bf_row_ranges));
1038
0
            RowRanges::ranges_intersection(bf_row_ranges, column_bf_row_ranges, &bf_row_ranges);
1039
0
        }
1040
1041
467
        pre_size = condition_row_ranges->count();
1042
467
        RowRanges::ranges_intersection(*condition_row_ranges, bf_row_ranges, condition_row_ranges);
1043
467
        _opts.stats->rows_bf_filtered += (pre_size - condition_row_ranges->count());
1044
467
    }
1045
1046
0
    {
1047
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_zonemap_ns);
1048
467
        RowRanges zone_map_row_ranges = RowRanges::create_single(num_rows());
1049
        // second filter data by zone map
1050
467
        for (const auto& cid : cids) {
1051
0
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1052
0
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1053
0
                                                      _opts.target_cast_type_for_variants, _opts)) {
1054
0
                continue;
1055
0
            }
1056
            // do not check zonemap if predicate does not support zonemap
1057
0
            if (!_opts.col_id_to_predicates.at(cid)->support_zonemap()) {
1058
0
                VLOG_DEBUG << "skip zonemap for column " << cid;
1059
0
                continue;
1060
0
            }
1061
            // get row ranges by zone map of this column,
1062
0
            RowRanges column_row_ranges = RowRanges::create_single(num_rows());
1063
0
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_zone_map(
1064
0
                    _opts.col_id_to_predicates.at(cid).get(),
1065
0
                    _opts.del_predicates_for_zone_map.count(cid) > 0
1066
0
                            ? &(_opts.del_predicates_for_zone_map.at(cid))
1067
0
                            : nullptr,
1068
0
                    &column_row_ranges));
1069
            // intersect different columns's row ranges to get final row ranges by zone map
1070
0
            RowRanges::ranges_intersection(zone_map_row_ranges, column_row_ranges,
1071
0
                                           &zone_map_row_ranges);
1072
0
        }
1073
1074
467
        pre_size = condition_row_ranges->count();
1075
467
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1076
467
                                       condition_row_ranges);
1077
1078
467
        size_t pre_size2 = condition_row_ranges->count();
1079
467
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1080
467
                                       condition_row_ranges);
1081
467
        _opts.stats->rows_stats_rp_filtered += (pre_size2 - condition_row_ranges->count());
1082
467
        _opts.stats->rows_stats_filtered += (pre_size - condition_row_ranges->count());
1083
467
    }
1084
1085
0
    return Status::OK();
1086
467
}
1087
1088
0
bool SegmentIterator::_is_literal_node(const TExprNodeType::type& node_type) {
1089
0
    switch (node_type) {
1090
0
    case TExprNodeType::BOOL_LITERAL:
1091
0
    case TExprNodeType::INT_LITERAL:
1092
0
    case TExprNodeType::LARGE_INT_LITERAL:
1093
0
    case TExprNodeType::FLOAT_LITERAL:
1094
0
    case TExprNodeType::DECIMAL_LITERAL:
1095
0
    case TExprNodeType::STRING_LITERAL:
1096
0
    case TExprNodeType::DATE_LITERAL:
1097
0
    case TExprNodeType::TIMEV2_LITERAL:
1098
0
        return true;
1099
0
    default:
1100
0
        return false;
1101
0
    }
1102
0
}
1103
1104
0
Status SegmentIterator::_extract_common_expr_columns(const VExprSPtr& expr) {
1105
0
    auto& children = expr->children();
1106
0
    for (int i = 0; i < children.size(); ++i) {
1107
0
        RETURN_IF_ERROR(_extract_common_expr_columns(children[i]));
1108
0
    }
1109
1110
0
    auto node_type = expr->node_type();
1111
0
    if (node_type == TExprNodeType::SLOT_REF) {
1112
0
        auto slot_expr = std::dynamic_pointer_cast<doris::VSlotRef>(expr);
1113
0
        _is_common_expr_column[_schema->column_id(slot_expr->column_id())] = true;
1114
0
        _common_expr_columns.insert(_schema->column_id(slot_expr->column_id()));
1115
0
    } else if (node_type == TExprNodeType::VIRTUAL_SLOT_REF) {
1116
0
        std::shared_ptr<VirtualSlotRef> virtual_slot_ref =
1117
0
                std::dynamic_pointer_cast<VirtualSlotRef>(expr);
1118
0
        RETURN_IF_ERROR(_extract_common_expr_columns(virtual_slot_ref->get_virtual_column_expr()));
1119
0
    }
1120
1121
0
    return Status::OK();
1122
0
}
1123
1124
0
bool SegmentIterator::_check_apply_by_inverted_index(std::shared_ptr<ColumnPredicate> pred) {
1125
0
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_inverted_index_query) {
1126
0
        return false;
1127
0
    }
1128
0
    auto pred_column_id = pred->column_id();
1129
0
    if (_index_iterators[pred_column_id] == nullptr) {
1130
        //this column without inverted index
1131
0
        return false;
1132
0
    }
1133
1134
0
    if (_inverted_index_not_support_pred_type(pred->type())) {
1135
0
        return false;
1136
0
    }
1137
1138
0
    if (pred->type() == PredicateType::IN_LIST || pred->type() == PredicateType::NOT_IN_LIST) {
1139
        // in_list or not_in_list predicate produced by runtime filter
1140
0
        if (pred->is_runtime_filter()) {
1141
0
            return false;
1142
0
        }
1143
0
    }
1144
1145
    // UNTOKENIZED strings exceed ignore_above, they are written as null, causing range query errors
1146
0
    if (PredicateTypeTraits::is_range(pred->type()) &&
1147
0
        !IndexReaderHelper::has_bkd_index(_index_iterators[pred_column_id].get())) {
1148
0
        return false;
1149
0
    }
1150
1151
    // Function filter no apply inverted index
1152
0
    if (dynamic_cast<LikeColumnPredicate<TYPE_CHAR>*>(pred.get()) != nullptr ||
1153
0
        dynamic_cast<LikeColumnPredicate<TYPE_STRING>*>(pred.get()) != nullptr) {
1154
0
        return false;
1155
0
    }
1156
1157
0
    bool handle_by_fulltext = _column_has_fulltext_index(pred_column_id);
1158
0
    if (handle_by_fulltext) {
1159
        // when predicate is leafNode of andNode,
1160
        // can apply 'match query' and 'equal query' and 'list query' for fulltext index.
1161
0
        return pred->type() == PredicateType::MATCH || pred->type() == PredicateType::IS_NULL ||
1162
0
               pred->type() == PredicateType::IS_NOT_NULL ||
1163
0
               PredicateTypeTraits::is_equal_or_list(pred->type());
1164
0
    }
1165
1166
0
    return true;
1167
0
}
1168
1169
// TODO: optimization when all expr can not evaluate by inverted/ann index,
1170
0
Status SegmentIterator::_apply_index_expr() {
1171
0
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1172
0
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1173
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1174
0
                continue;
1175
0
            } else {
1176
                // other code is not to be handled, we should just break
1177
0
                LOG(WARNING) << "failed to evaluate inverted index for expr_ctx: "
1178
0
                             << expr_ctx->root()->debug_string()
1179
0
                             << ", error msg: " << st.to_string();
1180
0
                return st;
1181
0
            }
1182
0
        }
1183
0
    }
1184
1185
    // Evaluate inverted index for virtual column MATCH expressions (projections).
1186
    // Unlike common exprs which filter rows, these only compute index result bitmaps
1187
    // for later materialization via fast_execute().
1188
0
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
1189
0
        if (expr_ctx->get_index_context() == nullptr) {
1190
0
            continue;
1191
0
        }
1192
0
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1193
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1194
0
                continue;
1195
0
            } else {
1196
0
                LOG(WARNING) << "failed to evaluate inverted index for virtual column expr: "
1197
0
                             << expr_ctx->root()->debug_string()
1198
0
                             << ", error msg: " << st.to_string();
1199
0
                return st;
1200
0
            }
1201
0
        }
1202
0
    }
1203
1204
    // Apply ann range search
1205
0
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1206
0
        segment_v2::AnnIndexStats ann_index_stats;
1207
0
        size_t origin_rows = _row_bitmap.cardinality();
1208
0
        RETURN_IF_ERROR(expr_ctx->evaluate_ann_range_search(
1209
0
                _index_iterators, _schema->column_ids(), _column_iterators,
1210
0
                _common_expr_to_slotref_map, _row_bitmap, ann_index_stats));
1211
0
        _opts.stats->rows_ann_index_range_filtered += (origin_rows - _row_bitmap.cardinality());
1212
0
        _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
1213
0
        _opts.stats->ann_index_range_search_ns += ann_index_stats.search_costs_ns.value();
1214
0
        _opts.stats->ann_range_engine_search_ns += ann_index_stats.engine_search_ns.value();
1215
0
        _opts.stats->ann_range_result_convert_ns += ann_index_stats.result_process_costs_ns.value();
1216
0
        _opts.stats->ann_range_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
1217
0
        _opts.stats->ann_range_pre_process_ns += ann_index_stats.engine_prepare_ns.value();
1218
0
        _opts.stats->ann_fall_back_brute_force_cnt += ann_index_stats.fall_back_brute_force_cnt;
1219
0
    }
1220
1221
0
    for (auto it = _common_expr_ctxs_push_down.begin(); it != _common_expr_ctxs_push_down.end();) {
1222
0
        if ((*it)->root()->ann_range_search_executedd()) {
1223
0
            _opts.stats->ann_index_range_search_cnt++;
1224
0
            it = _common_expr_ctxs_push_down.erase(it);
1225
0
        } else {
1226
0
            ++it;
1227
0
        }
1228
0
    }
1229
    // TODO:Do we need to remove these expr root from _remaining_conjunct_roots?
1230
1231
0
    return Status::OK();
1232
0
}
1233
1234
0
bool SegmentIterator::_downgrade_without_index(Status res, bool need_remaining) {
1235
0
    bool is_fallback =
1236
0
            _opts.runtime_state->query_options().enable_fallback_on_missing_inverted_index;
1237
0
    if ((res.code() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND && is_fallback) ||
1238
0
        res.code() == ErrorCode::INVERTED_INDEX_BYPASS ||
1239
0
        res.code() == ErrorCode::INVERTED_INDEX_EVALUATE_SKIPPED ||
1240
0
        (res.code() == ErrorCode::INVERTED_INDEX_NO_TERMS && need_remaining) ||
1241
0
        res.code() == ErrorCode::INVERTED_INDEX_FILE_CORRUPTED) {
1242
        // 1. INVERTED_INDEX_FILE_NOT_FOUND means index file has not been built,
1243
        //    usually occurs when creating a new index, queries can be downgraded
1244
        //    without index.
1245
        // 2. INVERTED_INDEX_BYPASS means the hit of condition by index
1246
        //    has reached the optimal limit, downgrade without index query can
1247
        //    improve query performance.
1248
        // 3. INVERTED_INDEX_EVALUATE_SKIPPED means the inverted index is not
1249
        //    suitable for executing this predicate, skipped it and filter data
1250
        //    by function later.
1251
        // 4. INVERTED_INDEX_NO_TERMS means the column has fulltext index,
1252
        //    but the column condition value no terms in specified parser,
1253
        //    such as: where A = '' and B = ','
1254
        //    the predicate of A and B need downgrade without index query.
1255
        // 5. INVERTED_INDEX_FILE_CORRUPTED means the index file is corrupted,
1256
        //    such as when index segment files are not generated
1257
        // above case can downgrade without index query
1258
0
        _opts.stats->inverted_index_downgrade_count++;
1259
0
        if (!res.is<ErrorCode::INVERTED_INDEX_BYPASS>()) {
1260
0
            LOG(INFO) << "will downgrade without index to evaluate predicate, because of res: "
1261
0
                      << res;
1262
0
        } else {
1263
0
            VLOG_DEBUG << "will downgrade without index to evaluate predicate, because of res: "
1264
0
                       << res;
1265
0
        }
1266
0
        return true;
1267
0
    }
1268
0
    return false;
1269
0
}
1270
1271
0
bool SegmentIterator::_column_has_fulltext_index(int32_t cid) {
1272
0
    bool has_fulltext_index =
1273
0
            _index_iterators[cid] != nullptr &&
1274
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::FULLTEXT) &&
1275
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::STRING_TYPE) == nullptr;
1276
1277
0
    return has_fulltext_index;
1278
0
}
1279
1280
0
inline bool SegmentIterator::_inverted_index_not_support_pred_type(const PredicateType& type) {
1281
0
    return type == PredicateType::BF || type == PredicateType::BITMAP_FILTER;
1282
0
}
1283
1284
Status SegmentIterator::_apply_inverted_index_on_column_predicate(
1285
        std::shared_ptr<ColumnPredicate> pred,
1286
0
        std::vector<std::shared_ptr<ColumnPredicate>>& remaining_predicates, bool* continue_apply) {
1287
0
    if (!_check_apply_by_inverted_index(pred)) {
1288
0
        remaining_predicates.emplace_back(pred);
1289
0
    } else {
1290
0
        bool need_remaining_after_evaluate = _column_has_fulltext_index(pred->column_id()) &&
1291
0
                                             PredicateTypeTraits::is_equal_or_list(pred->type());
1292
0
        Status res =
1293
0
                pred->evaluate(_storage_name_and_type[pred->column_id()],
1294
0
                               _index_iterators[pred->column_id()].get(), num_rows(), &_row_bitmap);
1295
0
        if (!res.ok()) {
1296
0
            if (_downgrade_without_index(res, need_remaining_after_evaluate)) {
1297
0
                remaining_predicates.emplace_back(pred);
1298
0
                return Status::OK();
1299
0
            }
1300
0
            LOG(WARNING) << "failed to evaluate index"
1301
0
                         << ", column predicate type: " << pred->pred_type_string(pred->type())
1302
0
                         << ", error msg: " << res;
1303
0
            return res;
1304
0
        }
1305
1306
0
        if (_row_bitmap.isEmpty()) {
1307
            // all rows have been pruned, no need to process further predicates
1308
0
            *continue_apply = false;
1309
0
        }
1310
1311
0
        if (need_remaining_after_evaluate) {
1312
0
            remaining_predicates.emplace_back(pred);
1313
0
            return Status::OK();
1314
0
        }
1315
0
        if (!pred->is_runtime_filter()) {
1316
0
            _column_predicate_index_exec_status[pred->column_id()][pred] = true;
1317
0
        }
1318
0
    }
1319
0
    return Status::OK();
1320
0
}
1321
1322
43.4k
bool SegmentIterator::_need_read_data(ColumnId cid) {
1323
43.4k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
1324
0
        return true;
1325
0
    }
1326
    // only support DUP_KEYS and UNIQUE_KEYS with MOW
1327
43.4k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
1328
43.4k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
1329
16.3k
            _opts.enable_unique_key_merge_on_write)))) {
1330
12.0k
        return true;
1331
12.0k
    }
1332
    // this is a virtual column, we always need to read data
1333
31.3k
    if (this->_vir_cid_to_idx_in_block.contains(cid)) {
1334
0
        return true;
1335
0
    }
1336
1337
    // if there is a delete predicate, we always need to read data
1338
31.3k
    if (_has_delete_predicate(cid)) {
1339
4.03k
        return true;
1340
4.03k
    }
1341
27.2k
    if (_output_columns.count(-1)) {
1342
        // if _output_columns contains -1, it means that the light
1343
        // weight schema change may not be enabled or other reasons
1344
        // caused the column unique_id not be set, to prevent errors
1345
        // occurring, return true here that column data needs to be read
1346
0
        return true;
1347
0
    }
1348
    // Check the following conditions:
1349
    // 1. If the column represented by the unique ID is an inverted index column (indicated by '_need_read_data_indices.count(unique_id) > 0 && !_need_read_data_indices[unique_id]')
1350
    //    and it's not marked for projection in '_output_columns'.
1351
    // 2. Or, if the column is an inverted index column and it's marked for projection in '_output_columns',
1352
    //    and the operation is a push down of the 'COUNT_ON_INDEX' aggregation function.
1353
    // If any of the above conditions are met, log a debug message indicating that there's no need to read data for the indexed column.
1354
    // Then, return false.
1355
27.2k
    const auto& column = _opts.tablet_schema->column(cid);
1356
    // Different subcolumns may share the same parent_unique_id, so we choose to abandon this optimization.
1357
27.2k
    if (column.is_extracted_column() &&
1358
27.2k
        _opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
1359
1
        return true;
1360
1
    }
1361
27.2k
    int32_t unique_id = column.unique_id();
1362
27.2k
    if (unique_id < 0) {
1363
1
        unique_id = column.parent_unique_id();
1364
1
    }
1365
27.2k
    if ((_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1366
27.2k
         !_output_columns.contains(unique_id)) ||
1367
27.2k
        (_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1368
27.2k
         _output_columns.count(unique_id) == 1 &&
1369
27.2k
         _opts.push_down_agg_type_opt == TPushAggOp::COUNT_ON_INDEX)) {
1370
1
        VLOG_DEBUG << "SegmentIterator no need read data for column: "
1371
0
                   << _opts.tablet_schema->column_by_uid(unique_id).name();
1372
1
        return false;
1373
1
    }
1374
27.2k
    return true;
1375
27.2k
}
1376
1377
0
Status SegmentIterator::_apply_inverted_index() {
1378
0
    std::vector<std::shared_ptr<ColumnPredicate>> remaining_predicates;
1379
0
    std::set<std::shared_ptr<ColumnPredicate>> no_need_to_pass_column_predicate_set;
1380
1381
0
    for (auto pred : _col_predicates) {
1382
0
        if (no_need_to_pass_column_predicate_set.count(pred) > 0) {
1383
0
            continue;
1384
0
        } else {
1385
0
            bool continue_apply = true;
1386
0
            RETURN_IF_ERROR(_apply_inverted_index_on_column_predicate(pred, remaining_predicates,
1387
0
                                                                      &continue_apply));
1388
0
            if (!continue_apply) {
1389
0
                break;
1390
0
            }
1391
0
        }
1392
0
    }
1393
1394
0
    _col_predicates = std::move(remaining_predicates);
1395
0
    return Status::OK();
1396
0
}
1397
1398
/**
1399
 * @brief Checks if all conditions related to a specific column have passed in both
1400
 * `_column_predicate_inverted_index_status` and `_common_expr_inverted_index_status`.
1401
 *
1402
 * This function first checks the conditions in `_column_predicate_inverted_index_status`
1403
 * for the given `ColumnId`. If all conditions pass, it sets `default_return` to `true`.
1404
 * It then checks the conditions in `_common_expr_inverted_index_status` for the same column.
1405
 *
1406
 * The function returns `true` if all conditions in both maps pass. If any condition fails
1407
 * in either map, the function immediately returns `false`. If the column does not exist
1408
 * in one of the maps, the function returns `default_return`.
1409
 *
1410
 * @param cid The ColumnId of the column to check.
1411
 * @param default_return The default value to return if the column is not found in the status maps.
1412
 * @return true if all conditions in both status maps pass, or if the column is not found
1413
 *         and `default_return` is true.
1414
 * @return false if any condition in either status map fails, or if the column is not found
1415
 *         and `default_return` is false.
1416
 */
1417
bool SegmentIterator::_check_all_conditions_passed_inverted_index_for_column(ColumnId cid,
1418
0
                                                                             bool default_return) {
1419
    // If common_expr_pushdown is disabled, we cannot guarantee that all conditions are processed by the inverted index.
1420
    // Consider a scenario where there is a column predicate and an expression involving the same column in the SQL query,
1421
    // such as 'a < 0' and 'abs(a) > 1'. This could potentially lead to errors.
1422
0
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_common_expr_pushdown) {
1423
0
        return false;
1424
0
    }
1425
0
    auto pred_it = _column_predicate_index_exec_status.find(cid);
1426
0
    if (pred_it != _column_predicate_index_exec_status.end()) {
1427
0
        const auto& pred_map = pred_it->second;
1428
0
        bool pred_passed = std::all_of(pred_map.begin(), pred_map.end(),
1429
0
                                       [](const auto& pred_entry) { return pred_entry.second; });
1430
0
        if (!pred_passed) {
1431
0
            return false;
1432
0
        } else {
1433
0
            default_return = true;
1434
0
        }
1435
0
    }
1436
1437
0
    auto expr_it = _common_expr_index_exec_status.find(cid);
1438
0
    if (expr_it != _common_expr_index_exec_status.end()) {
1439
0
        const auto& expr_map = expr_it->second;
1440
0
        return std::all_of(expr_map.begin(), expr_map.end(),
1441
0
                           [](const auto& expr_entry) { return expr_entry.second; });
1442
0
    }
1443
0
    return default_return;
1444
0
}
1445
1446
5.63k
Status SegmentIterator::_init_return_column_iterators() {
1447
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_return_column_iterators_timer_ns);
1448
5.63k
    if (_cur_rowid >= num_rows()) {
1449
0
        return Status::OK();
1450
0
    }
1451
1452
12.6k
    for (auto cid : _schema->column_ids()) {
1453
12.6k
        if (_schema->column(cid)->name() == BeConsts::ROWID_COL) {
1454
0
            _column_iterators[cid].reset(
1455
0
                    new RowIdColumnIterator(_opts.tablet_id, _opts.rowset_id, _segment->id()));
1456
0
            continue;
1457
0
        }
1458
1459
12.6k
        if (_schema->column(cid)->name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1460
0
            auto& id_file_map = _opts.runtime_state->get_id_file_map();
1461
0
            uint32_t file_id = id_file_map->get_file_mapping_id(std::make_shared<FileMapping>(
1462
0
                    _opts.tablet_id, _opts.rowset_id, _segment->id()));
1463
0
            _column_iterators[cid].reset(new RowIdColumnIteratorV2(
1464
0
                    IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id));
1465
0
            continue;
1466
0
        }
1467
1468
12.6k
        if (_schema->column(cid)->name().starts_with(BeConsts::VIRTUAL_COLUMN_PREFIX)) {
1469
0
            _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
1470
0
            continue;
1471
0
        }
1472
1473
12.6k
        std::set<ColumnId> del_cond_id_set;
1474
12.6k
        _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1475
12.6k
        std::vector<bool> tmp_is_pred_column;
1476
12.6k
        tmp_is_pred_column.resize(_schema->columns().size(), false);
1477
12.6k
        for (auto predicate : _col_predicates) {
1478
0
            auto p_cid = predicate->column_id();
1479
0
            tmp_is_pred_column[p_cid] = true;
1480
0
        }
1481
        // handle delete_condition
1482
12.6k
        for (auto d_cid : del_cond_id_set) {
1483
1.32k
            tmp_is_pred_column[d_cid] = true;
1484
1.32k
        }
1485
1486
12.6k
        if (_column_iterators[cid] == nullptr) {
1487
12.6k
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
1488
12.6k
                                                          &_column_iterators[cid], &_opts,
1489
12.6k
                                                          &_variant_sparse_column_cache));
1490
12.6k
            ColumnIteratorOptions iter_opts {
1491
12.6k
                    .use_page_cache = _opts.use_page_cache,
1492
                    // If the col is predicate column, then should read the last page to check
1493
                    // if the column is full dict encoding
1494
12.6k
                    .is_predicate_column = tmp_is_pred_column[cid],
1495
12.6k
                    .file_reader = _file_reader.get(),
1496
12.6k
                    .stats = _opts.stats,
1497
12.6k
                    .io_ctx = _opts.io_ctx,
1498
12.6k
            };
1499
12.6k
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
1500
12.6k
        }
1501
12.6k
    }
1502
1503
5.63k
#ifndef NDEBUG
1504
5.63k
    for (auto pair : _vir_cid_to_idx_in_block) {
1505
0
        ColumnId vir_col_cid = pair.first;
1506
0
        DCHECK(_column_iterators[vir_col_cid] != nullptr)
1507
0
                << "Virtual column iterator for " << vir_col_cid << " should not be null";
1508
0
        ColumnIterator* column_iter = _column_iterators[vir_col_cid].get();
1509
0
        DCHECK(dynamic_cast<VirtualColumnIterator*>(column_iter) != nullptr)
1510
0
                << "Virtual column iterator for " << vir_col_cid
1511
0
                << " should be VirtualColumnIterator";
1512
0
    }
1513
5.63k
#endif
1514
5.63k
    return Status::OK();
1515
5.63k
}
1516
1517
5.63k
Status SegmentIterator::_init_index_iterators() {
1518
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_index_iterators_timer_ns);
1519
5.63k
    if (_cur_rowid >= num_rows()) {
1520
0
        return Status::OK();
1521
0
    }
1522
1523
5.63k
    _index_query_context = std::make_shared<IndexQueryContext>();
1524
5.63k
    _index_query_context->io_ctx = &_opts.io_ctx;
1525
5.63k
    _index_query_context->stats = _opts.stats;
1526
5.63k
    _index_query_context->runtime_state = _opts.runtime_state;
1527
1528
5.63k
    if (_score_runtime) {
1529
0
        _index_query_context->collection_statistics = _opts.collection_statistics;
1530
0
        _index_query_context->collection_similarity = std::make_shared<CollectionSimilarity>();
1531
0
        _index_query_context->query_limit = _score_runtime->get_limit();
1532
0
        _index_query_context->is_asc = _score_runtime->is_asc();
1533
0
    }
1534
1535
    // Inverted index iterators
1536
12.6k
    for (auto cid : _schema->column_ids()) {
1537
        // Use segment’s own index_meta, for compatibility with future indexing needs to default to lowercase.
1538
12.6k
        if (_index_iterators[cid] == nullptr) {
1539
            // In the _opts.tablet_schema, the sub-column type information for the variant is FieldType::OLAP_FIELD_TYPE_VARIANT.
1540
            // This is because the sub-column is created in create_materialized_variant_column.
1541
            // We use this column to locate the metadata for the inverted index, which requires a unique_id and path.
1542
12.6k
            const auto& column = _opts.tablet_schema->column(cid);
1543
12.6k
            std::vector<const TabletIndex*> inverted_indexs;
1544
            // Keep shared_ptr alive to prevent use-after-free when accessing raw pointers
1545
12.6k
            TabletIndexes inverted_indexs_holder;
1546
            // If the column is an extracted column, we need to find the sub-column in the parent column reader.
1547
12.6k
            std::shared_ptr<ColumnReader> column_reader;
1548
12.6k
            if (column.is_extracted_column()) {
1549
0
                if (!_segment->_column_reader_cache->get_column_reader(
1550
0
                            column.parent_unique_id(), &column_reader, _opts.stats) ||
1551
0
                    column_reader == nullptr) {
1552
0
                    continue;
1553
0
                }
1554
0
                auto* variant_reader = assert_cast<VariantColumnReader*>(column_reader.get());
1555
0
                DataTypePtr data_type = _storage_name_and_type[cid].second;
1556
0
                if (data_type != nullptr &&
1557
0
                    data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
1558
0
                    DataTypePtr inferred_type;
1559
0
                    Status st = variant_reader->infer_data_type_for_path(
1560
0
                            &inferred_type, column, _opts, _segment->_column_reader_cache.get());
1561
0
                    if (st.ok() && inferred_type != nullptr) {
1562
0
                        data_type = inferred_type;
1563
0
                    }
1564
0
                }
1565
0
                inverted_indexs_holder =
1566
0
                        variant_reader->find_subcolumn_tablet_indexes(column, data_type);
1567
                // Extract raw pointers from shared_ptr for iteration
1568
0
                for (const auto& index_ptr : inverted_indexs_holder) {
1569
0
                    inverted_indexs.push_back(index_ptr.get());
1570
0
                }
1571
0
            }
1572
            // If the column is not an extracted column, we can directly get the inverted index metadata from the tablet schema.
1573
12.6k
            else {
1574
12.6k
                inverted_indexs = _segment->_tablet_schema->inverted_indexs(column);
1575
12.6k
            }
1576
12.6k
            for (const auto& inverted_index : inverted_indexs) {
1577
2.56k
                RETURN_IF_ERROR(_segment->new_index_iterator(column, inverted_index, _opts,
1578
2.56k
                                                             &_index_iterators[cid]));
1579
2.56k
            }
1580
12.6k
            if (_index_iterators[cid] != nullptr) {
1581
2.55k
                _index_iterators[cid]->set_context(_index_query_context);
1582
2.55k
            }
1583
12.6k
        }
1584
12.6k
    }
1585
1586
    // Ann index iterators
1587
12.6k
    for (auto cid : _schema->column_ids()) {
1588
12.6k
        if (_index_iterators[cid] == nullptr) {
1589
10.1k
            const auto& column = _opts.tablet_schema->column(cid);
1590
10.1k
            const auto* index_meta = _segment->_tablet_schema->ann_index(column);
1591
10.1k
            if (index_meta) {
1592
1
                RETURN_IF_ERROR(_segment->new_index_iterator(column, index_meta, _opts,
1593
1
                                                             &_index_iterators[cid]));
1594
1595
1
                if (_index_iterators[cid] != nullptr) {
1596
1
                    _index_iterators[cid]->set_context(_index_query_context);
1597
1
                }
1598
1
            }
1599
10.1k
        }
1600
12.6k
    }
1601
1602
5.63k
    return Status::OK();
1603
5.63k
}
1604
1605
Status SegmentIterator::_lookup_ordinal(const RowCursor& key, bool is_include, rowid_t upper_bound,
1606
0
                                        rowid_t* rowid) {
1607
0
    if (_segment->_tablet_schema->keys_type() == UNIQUE_KEYS &&
1608
0
        _segment->get_primary_key_index() != nullptr) {
1609
0
        return _lookup_ordinal_from_pk_index(key, is_include, rowid);
1610
0
    }
1611
0
    return _lookup_ordinal_from_sk_index(key, is_include, upper_bound, rowid);
1612
0
}
1613
1614
// look up one key to get its ordinal at which can get data by using short key index.
1615
// 'upper_bound' is defined the max ordinal the function will search.
1616
// We use upper_bound to reduce search times.
1617
// If we find a valid ordinal, it will be set in rowid and with Status::OK()
1618
// If we can not find a valid key in this segment, we will set rowid to upper_bound
1619
// Otherwise return error.
1620
// 1. get [start, end) ordinal through short key index
1621
// 2. binary search to find exact ordinal that match the input condition
1622
// Make is_include template to reduce branch
1623
Status SegmentIterator::_lookup_ordinal_from_sk_index(const RowCursor& key, bool is_include,
1624
0
                                                      rowid_t upper_bound, rowid_t* rowid) {
1625
0
    const ShortKeyIndexDecoder* sk_index_decoder = _segment->get_short_key_index();
1626
0
    DCHECK(sk_index_decoder != nullptr);
1627
1628
0
    std::string index_key;
1629
0
    key.encode_key_with_padding(&index_key, _segment->_tablet_schema->num_short_key_columns(),
1630
0
                                is_include);
1631
1632
0
    const auto& key_col_ids = key.schema()->column_ids();
1633
1634
    // Clone the key once and pad CHAR fields to storage format before the binary search.
1635
    // _seek_block holds storage-format data where CHAR is zero-padded to column length,
1636
    // while RowCursor holds CHAR in compute format (unpadded). Padding once here avoids
1637
    // repeated allocation inside the comparison loop.
1638
0
    RowCursor padded_key = key.clone();
1639
0
    padded_key.pad_char_fields();
1640
1641
0
    ssize_t start_block_id = 0;
1642
0
    auto start_iter = sk_index_decoder->lower_bound(index_key);
1643
0
    if (start_iter.valid()) {
1644
        // Because previous block may contain this key, so we should set rowid to
1645
        // last block's first row.
1646
0
        start_block_id = start_iter.ordinal();
1647
0
        if (start_block_id > 0) {
1648
0
            start_block_id--;
1649
0
        }
1650
0
    } else {
1651
        // When we don't find a valid index item, which means all short key is
1652
        // smaller than input key, this means that this key may exist in the last
1653
        // row block. so we set the rowid to first row of last row block.
1654
0
        start_block_id = sk_index_decoder->num_items() - 1;
1655
0
    }
1656
0
    rowid_t start = cast_set<rowid_t>(start_block_id) * sk_index_decoder->num_rows_per_block();
1657
1658
0
    rowid_t end = upper_bound;
1659
0
    auto end_iter = sk_index_decoder->upper_bound(index_key);
1660
0
    if (end_iter.valid()) {
1661
0
        end = cast_set<rowid_t>(end_iter.ordinal()) * sk_index_decoder->num_rows_per_block();
1662
0
    }
1663
1664
    // binary search to find the exact key
1665
0
    while (start < end) {
1666
0
        rowid_t mid = (start + end) / 2;
1667
0
        RETURN_IF_ERROR(_seek_and_peek(mid));
1668
0
        int cmp = _compare_short_key_with_seek_block(padded_key, key_col_ids);
1669
0
        if (cmp > 0) {
1670
0
            start = mid + 1;
1671
0
        } else if (cmp == 0) {
1672
0
            if (is_include) {
1673
                // lower bound
1674
0
                end = mid;
1675
0
            } else {
1676
                // upper bound
1677
0
                start = mid + 1;
1678
0
            }
1679
0
        } else {
1680
0
            end = mid;
1681
0
        }
1682
0
    }
1683
1684
0
    *rowid = start;
1685
0
    return Status::OK();
1686
0
}
1687
1688
Status SegmentIterator::_lookup_ordinal_from_pk_index(const RowCursor& key, bool is_include,
1689
0
                                                      rowid_t* rowid) {
1690
0
    DCHECK(_segment->_tablet_schema->keys_type() == UNIQUE_KEYS);
1691
0
    const PrimaryKeyIndexReader* pk_index_reader = _segment->get_primary_key_index();
1692
0
    DCHECK(pk_index_reader != nullptr);
1693
1694
0
    std::string index_key;
1695
0
    key.encode_key_with_padding<true>(&index_key, _segment->_tablet_schema->num_key_columns(),
1696
0
                                      is_include);
1697
0
    if (index_key < _segment->min_key()) {
1698
0
        *rowid = 0;
1699
0
        return Status::OK();
1700
0
    } else if (index_key > _segment->max_key()) {
1701
0
        *rowid = num_rows();
1702
0
        return Status::OK();
1703
0
    }
1704
0
    bool exact_match = false;
1705
1706
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1707
0
    RETURN_IF_ERROR(pk_index_reader->new_iterator(&index_iterator, _opts.stats));
1708
1709
0
    Status status = index_iterator->seek_at_or_after(&index_key, &exact_match);
1710
0
    if (UNLIKELY(!status.ok())) {
1711
0
        *rowid = num_rows();
1712
0
        if (status.is<ENTRY_NOT_FOUND>()) {
1713
0
            return Status::OK();
1714
0
        }
1715
0
        return status;
1716
0
    }
1717
0
    *rowid = cast_set<rowid_t>(index_iterator->get_current_ordinal());
1718
1719
    // The sequence column needs to be removed from primary key index when comparing key
1720
0
    bool has_seq_col = _segment->_tablet_schema->has_sequence_col();
1721
    // Used to get key range from primary key index,
1722
    // for mow with cluster key table, we should get key range from short key index.
1723
0
    DCHECK(_segment->_tablet_schema->cluster_key_uids().empty());
1724
1725
    // if full key is exact_match, the primary key without sequence column should also the same
1726
0
    if (has_seq_col && !exact_match) {
1727
0
        size_t seq_col_length =
1728
0
                _segment->_tablet_schema->column(_segment->_tablet_schema->sequence_col_idx())
1729
0
                        .length() +
1730
0
                1;
1731
0
        auto index_type = DataTypeFactory::instance().create_data_type(
1732
0
                _segment->_pk_index_reader->type_info()->type(), 1, 0);
1733
0
        auto index_column = index_type->create_column();
1734
0
        size_t num_to_read = 1;
1735
0
        size_t num_read = num_to_read;
1736
0
        RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1737
0
        DCHECK(num_to_read == num_read);
1738
1739
0
        Slice sought_key =
1740
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1741
0
        Slice sought_key_without_seq =
1742
0
                Slice(sought_key.get_data(), sought_key.get_size() - seq_col_length);
1743
1744
        // compare key
1745
0
        if (Slice(index_key).compare(sought_key_without_seq) == 0) {
1746
0
            exact_match = true;
1747
0
        }
1748
0
    }
1749
1750
    // find the key in primary key index, and the is_include is false, so move
1751
    // to the next row.
1752
0
    if (exact_match && !is_include) {
1753
0
        *rowid += 1;
1754
0
    }
1755
0
    return Status::OK();
1756
0
}
1757
1758
// seek to the row and load that row to _key_cursor
1759
0
Status SegmentIterator::_seek_and_peek(rowid_t rowid) {
1760
0
    {
1761
0
        _opts.stats->block_init_seek_num += 1;
1762
0
        SCOPED_RAW_TIMER(&_opts.stats->block_init_seek_ns);
1763
0
        RETURN_IF_ERROR(_seek_columns(_seek_schema->column_ids(), rowid));
1764
0
    }
1765
0
    size_t num_rows = 1;
1766
1767
    //note(wb) reset _seek_block for memory reuse
1768
    // it is easier to use row based memory layout for clear memory
1769
0
    for (int i = 0; i < _seek_block.size(); i++) {
1770
0
        _seek_block[i]->clear();
1771
0
    }
1772
0
    RETURN_IF_ERROR(_read_columns(_seek_schema->column_ids(), _seek_block, num_rows));
1773
0
    return Status::OK();
1774
0
}
1775
1776
0
Status SegmentIterator::_seek_columns(const std::vector<ColumnId>& column_ids, rowid_t pos) {
1777
0
    for (auto cid : column_ids) {
1778
0
        if (!_need_read_data(cid)) {
1779
0
            continue;
1780
0
        }
1781
0
        RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(pos));
1782
0
    }
1783
0
    return Status::OK();
1784
0
}
1785
1786
/* ---------------------- for vectorization implementation  ---------------------- */
1787
1788
/**
1789
 *  For storage layer data type, can be measured from two perspectives:
1790
 *  1 Whether the type can be read in a fast way(batch read using SIMD)
1791
 *    Such as integer type and float type, this type can be read in SIMD way.
1792
 *    For the type string/bitmap/hll, they can not be read in batch way, so read this type data is slow.
1793
 *   If a type can be read fast, we can try to eliminate Lazy Materialization, because we think for this type, seek cost > read cost.
1794
 *   This is an estimate, if we want more precise cost, statistics collection is necessary(this is a todo).
1795
 *   In short, when returned non-pred columns contains string/hll/bitmap, we using Lazy Materialization.
1796
 *   Otherwise, we disable it.
1797
 *
1798
 *   When Lazy Materialization enable, we need to read column at least two times.
1799
 *   First time to read Pred col, second time to read non-pred.
1800
 *   Here's an interesting question to research, whether read Pred col once is the best plan.
1801
 *   (why not read Pred col twice or more?)
1802
 *
1803
 *   When Lazy Materialization disable, we just need to read once.
1804
 *
1805
 *
1806
 *  2 Whether the predicate type can be evaluate in a fast way(using SIMD to eval pred)
1807
 *    Such as integer type and float type, they can be eval fast.
1808
 *    But for BloomFilter/string/date, they eval slow.
1809
 *    If a type can be eval fast, we use vectorization to eval it.
1810
 *    Otherwise, we use short-circuit to eval it.
1811
 *
1812
 *
1813
 */
1814
1815
// todo(wb) need a UT here
1816
5.63k
Status SegmentIterator::_vec_init_lazy_materialization() {
1817
5.63k
    _is_pred_column.resize(_schema->columns().size(), false);
1818
1819
    // including short/vec/delete pred
1820
5.63k
    std::set<ColumnId> pred_column_ids;
1821
5.63k
    _lazy_materialization_read = false;
1822
1823
5.63k
    std::set<ColumnId> del_cond_id_set;
1824
5.63k
    _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1825
1826
5.63k
    std::set<std::shared_ptr<const ColumnPredicate>> delete_predicate_set {};
1827
5.63k
    _opts.delete_condition_predicates->get_all_column_predicate(delete_predicate_set);
1828
5.63k
    for (auto predicate : delete_predicate_set) {
1829
467
        if (PredicateTypeTraits::is_range(predicate->type())) {
1830
327
            _delete_range_column_ids.push_back(predicate->column_id());
1831
327
        } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
1832
0
            _delete_bloom_filter_column_ids.push_back(predicate->column_id());
1833
0
        }
1834
467
    }
1835
1836
    // Step1: extract columns that can be lazy materialization
1837
5.63k
    if (!_col_predicates.empty() || !del_cond_id_set.empty()) {
1838
467
        std::set<ColumnId> short_cir_pred_col_id_set; // using set for distinct cid
1839
467
        std::set<ColumnId> vec_pred_col_id_set;
1840
1841
467
        for (auto predicate : _col_predicates) {
1842
0
            auto cid = predicate->column_id();
1843
0
            _is_pred_column[cid] = true;
1844
0
            pred_column_ids.insert(cid);
1845
1846
            // check pred using short eval or vec eval
1847
0
            if (_can_evaluated_by_vectorized(predicate)) {
1848
0
                vec_pred_col_id_set.insert(cid);
1849
0
                _pre_eval_block_predicate.push_back(predicate);
1850
0
            } else {
1851
0
                short_cir_pred_col_id_set.insert(cid);
1852
0
                _short_cir_eval_predicate.push_back(predicate);
1853
0
            }
1854
0
            if (predicate->is_runtime_filter()) {
1855
0
                _filter_info_id.push_back(predicate);
1856
0
            }
1857
0
        }
1858
1859
        // handle delete_condition
1860
467
        if (!del_cond_id_set.empty()) {
1861
467
            short_cir_pred_col_id_set.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1862
467
            pred_column_ids.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1863
1864
467
            for (auto cid : del_cond_id_set) {
1865
467
                _is_pred_column[cid] = true;
1866
467
            }
1867
467
        }
1868
1869
467
        _vec_pred_column_ids.assign(vec_pred_col_id_set.cbegin(), vec_pred_col_id_set.cend());
1870
467
        _short_cir_pred_column_ids.assign(short_cir_pred_col_id_set.cbegin(),
1871
467
                                          short_cir_pred_col_id_set.cend());
1872
467
    }
1873
1874
5.63k
    if (!_vec_pred_column_ids.empty()) {
1875
0
        _is_need_vec_eval = true;
1876
0
    }
1877
5.63k
    if (!_short_cir_pred_column_ids.empty()) {
1878
467
        _is_need_short_eval = true;
1879
467
    }
1880
1881
    // ColumnId to column index in block
1882
    // ColumnId will contail all columns in tablet schema, including virtual columns and global rowid column,
1883
5.63k
    _schema_block_id_map.resize(_schema->columns().size(), -1);
1884
    // Use cols read by query to initialize _schema_block_id_map.
1885
    // We need to know the index of each column in the block.
1886
    // There is an assumption here that the columns in the block are in the same order as in the read schema.
1887
    // TODO: A probelm is that, delete condition columns will exist in _schema->column_ids but not in block if
1888
    // delete column is not read by the query.
1889
18.3k
    for (int i = 0; i < _schema->num_column_ids(); i++) {
1890
12.6k
        auto cid = _schema->column_id(i);
1891
12.6k
        _schema_block_id_map[cid] = i;
1892
12.6k
    }
1893
1894
    // Step2: extract columns that can execute expr context
1895
5.63k
    _is_common_expr_column.resize(_schema->columns().size(), false);
1896
5.63k
    if (_enable_common_expr_pushdown && !_remaining_conjunct_roots.empty()) {
1897
0
        for (auto expr : _remaining_conjunct_roots) {
1898
0
            RETURN_IF_ERROR(_extract_common_expr_columns(expr));
1899
0
        }
1900
0
        if (!_common_expr_columns.empty()) {
1901
0
            _is_need_expr_eval = true;
1902
0
            for (auto cid : _schema->column_ids()) {
1903
                // pred column also needs to be filtered by expr, exclude additional delete condition column.
1904
                // if delete condition column not in the block, no filter is needed
1905
                // and will be removed from _columns_to_filter in the first next_batch.
1906
0
                if (_is_common_expr_column[cid] || _is_pred_column[cid]) {
1907
0
                    auto loc = _schema_block_id_map[cid];
1908
0
                    _columns_to_filter.push_back(loc);
1909
0
                }
1910
0
            }
1911
1912
0
            for (auto pair : _vir_cid_to_idx_in_block) {
1913
0
                _columns_to_filter.push_back(cast_set<ColumnId>(pair.second));
1914
0
            }
1915
0
        }
1916
0
    }
1917
1918
    // Step 3: fill non predicate columns and second read column
1919
    // if _schema columns size equal to pred_column_ids size, lazy_materialization_read is false,
1920
    // all columns are lazy materialization columns without non predicte column.
1921
    // If common expr pushdown exists, and expr column is not contained in lazy materialization columns,
1922
    // add to second read column, which will be read after lazy materialization
1923
5.63k
    if (_schema->column_ids().size() > pred_column_ids.size()) {
1924
        // pred_column_ids maybe empty, so that could not set _lazy_materialization_read = true here
1925
        // has to check there is at least one predicate column
1926
12.6k
        for (auto cid : _schema->column_ids()) {
1927
12.6k
            if (!_is_pred_column[cid]) {
1928
12.2k
                if (_is_need_vec_eval || _is_need_short_eval) {
1929
862
                    _lazy_materialization_read = true;
1930
862
                }
1931
12.2k
                if (_is_common_expr_column[cid]) {
1932
0
                    _common_expr_column_ids.push_back(cid);
1933
12.2k
                } else {
1934
12.2k
                    _non_predicate_columns.push_back(cid);
1935
12.2k
                }
1936
12.2k
            }
1937
12.6k
        }
1938
5.57k
    }
1939
1940
    // Step 4: fill first read columns
1941
5.63k
    if (_lazy_materialization_read) {
1942
        // insert pred cid to first_read_columns
1943
410
        for (auto cid : pred_column_ids) {
1944
410
            _predicate_column_ids.push_back(cid);
1945
410
        }
1946
5.22k
    } else if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
1947
16.5k
        for (int i = 0; i < _schema->num_column_ids(); i++) {
1948
11.3k
            auto cid = _schema->column_id(i);
1949
11.3k
            _predicate_column_ids.push_back(cid);
1950
11.3k
        }
1951
5.16k
    } else {
1952
57
        if (_is_need_vec_eval || _is_need_short_eval) {
1953
            // TODO To refactor, because we suppose lazy materialization is better performance.
1954
            // pred exits, but we can eliminate lazy materialization
1955
            // insert pred/non-pred cid to first read columns
1956
57
            std::set<ColumnId> pred_id_set;
1957
57
            pred_id_set.insert(_short_cir_pred_column_ids.begin(),
1958
57
                               _short_cir_pred_column_ids.end());
1959
57
            pred_id_set.insert(_vec_pred_column_ids.begin(), _vec_pred_column_ids.end());
1960
1961
57
            DCHECK(_common_expr_column_ids.empty());
1962
            // _non_predicate_column_ids must be empty. Otherwise _lazy_materialization_read must not false.
1963
114
            for (int i = 0; i < _schema->num_column_ids(); i++) {
1964
57
                auto cid = _schema->column_id(i);
1965
57
                if (pred_id_set.find(cid) != pred_id_set.end()) {
1966
57
                    _predicate_column_ids.push_back(cid);
1967
57
                }
1968
57
            }
1969
57
        } else if (_is_need_expr_eval) {
1970
0
            DCHECK(!_is_need_vec_eval && !_is_need_short_eval);
1971
0
            for (auto cid : _common_expr_columns) {
1972
0
                _predicate_column_ids.push_back(cid);
1973
0
            }
1974
0
        }
1975
57
    }
1976
1977
5.63k
    VLOG_DEBUG << fmt::format(
1978
0
            "Laze materialization init end. "
1979
0
            "lazy_materialization_read: {}, "
1980
0
            "_col_predicates size: {}, "
1981
0
            "_cols_read_by_column_predicate: [{}], "
1982
0
            "_non_predicate_columns: [{}], "
1983
0
            "_cols_read_by_common_expr: [{}], "
1984
0
            "columns_to_filter: [{}], "
1985
0
            "_schema_block_id_map: [{}]",
1986
0
            _lazy_materialization_read, _col_predicates.size(),
1987
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_non_predicate_columns, ","),
1988
0
            fmt::join(_common_expr_column_ids, ","), fmt::join(_columns_to_filter, ","),
1989
0
            fmt::join(_schema_block_id_map, ","));
1990
5.63k
    return Status::OK();
1991
5.63k
}
1992
1993
0
bool SegmentIterator::_can_evaluated_by_vectorized(std::shared_ptr<ColumnPredicate> predicate) {
1994
0
    auto cid = predicate->column_id();
1995
0
    FieldType field_type = _schema->column(cid)->type();
1996
0
    if (field_type == FieldType::OLAP_FIELD_TYPE_VARIANT) {
1997
        // Use variant cast dst type
1998
0
        field_type = _opts.target_cast_type_for_variants[_schema->column(cid)->name()]
1999
0
                             ->get_storage_field_type();
2000
0
    }
2001
0
    switch (predicate->type()) {
2002
0
    case PredicateType::EQ:
2003
0
    case PredicateType::NE:
2004
0
    case PredicateType::LE:
2005
0
    case PredicateType::LT:
2006
0
    case PredicateType::GE:
2007
0
    case PredicateType::GT: {
2008
0
        if (field_type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
2009
0
            field_type == FieldType::OLAP_FIELD_TYPE_CHAR ||
2010
0
            field_type == FieldType::OLAP_FIELD_TYPE_STRING) {
2011
0
            return config::enable_low_cardinality_optimize &&
2012
0
                   _opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2013
0
                   _column_iterators[cid]->is_all_dict_encoding();
2014
0
        } else if (field_type == FieldType::OLAP_FIELD_TYPE_DECIMAL) {
2015
0
            return false;
2016
0
        }
2017
0
        return true;
2018
0
    }
2019
0
    default:
2020
0
        return false;
2021
0
    }
2022
0
}
2023
2024
12.6k
bool SegmentIterator::_has_char_type(const StorageField& column_desc) {
2025
12.6k
    switch (column_desc.type()) {
2026
0
    case FieldType::OLAP_FIELD_TYPE_CHAR:
2027
0
        return true;
2028
2
    case FieldType::OLAP_FIELD_TYPE_ARRAY:
2029
2
        return _has_char_type(*column_desc.get_sub_field(0));
2030
0
    case FieldType::OLAP_FIELD_TYPE_MAP:
2031
0
        return _has_char_type(*column_desc.get_sub_field(0)) ||
2032
0
               _has_char_type(*column_desc.get_sub_field(1));
2033
0
    case FieldType::OLAP_FIELD_TYPE_STRUCT:
2034
0
        for (int idx = 0; idx < column_desc.get_sub_field_count(); ++idx) {
2035
0
            if (_has_char_type(*column_desc.get_sub_field(idx))) {
2036
0
                return true;
2037
0
            }
2038
0
        }
2039
0
        return false;
2040
12.6k
    default:
2041
12.6k
        return false;
2042
12.6k
    }
2043
12.6k
};
2044
2045
5.63k
void SegmentIterator::_vec_init_char_column_id(Block* block) {
2046
5.63k
    if (!_char_type_idx.empty()) {
2047
0
        return;
2048
0
    }
2049
5.63k
    _is_char_type.resize(_schema->columns().size(), false);
2050
18.3k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2051
12.6k
        auto cid = _schema->column_id(i);
2052
12.6k
        const StorageField* column_desc = _schema->column(cid);
2053
2054
        // The additional deleted filter condition will be in the materialized column at the end of the block.
2055
        // After _output_column_by_sel_idx, it will be erased, so we do not need to shrink it.
2056
12.6k
        if (i < block->columns()) {
2057
12.6k
            if (_has_char_type(*column_desc)) {
2058
0
                _char_type_idx.emplace_back(i);
2059
0
            }
2060
12.6k
        }
2061
2062
12.6k
        if (column_desc->type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
2063
0
            _is_char_type[cid] = true;
2064
0
        }
2065
12.6k
    }
2066
5.63k
}
2067
2068
bool SegmentIterator::_prune_column(ColumnId cid, MutableColumnPtr& column, bool fill_defaults,
2069
43.4k
                                    size_t num_of_defaults) {
2070
43.4k
    if (_need_read_data(cid)) {
2071
43.4k
        return false;
2072
43.4k
    }
2073
0
    if (!fill_defaults) {
2074
0
        return true;
2075
0
    }
2076
0
    if (column->is_nullable()) {
2077
0
        auto nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
2078
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(num_of_defaults);
2079
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(num_of_defaults);
2080
0
    } else {
2081
        // assert(column->is_const());
2082
0
        column->insert_many_defaults(num_of_defaults);
2083
0
    }
2084
0
    return true;
2085
0
}
2086
2087
Status SegmentIterator::_read_columns(const std::vector<ColumnId>& column_ids,
2088
0
                                      MutableColumns& column_block, size_t nrows) {
2089
0
    for (auto cid : column_ids) {
2090
0
        auto& column = column_block[cid];
2091
0
        size_t rows_read = nrows;
2092
0
        if (_prune_column(cid, column, true, rows_read)) {
2093
0
            continue;
2094
0
        }
2095
0
        RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2096
0
        if (nrows != rows_read) {
2097
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})", nrows,
2098
0
                                                            rows_read);
2099
0
        }
2100
0
    }
2101
0
    return Status::OK();
2102
0
}
2103
2104
Status SegmentIterator::_init_current_block(Block* block,
2105
                                            std::vector<MutableColumnPtr>& current_columns,
2106
23.1k
                                            uint32_t nrows_read_limit) {
2107
23.1k
    block->clear_column_data(_schema->num_column_ids());
2108
2109
67.5k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2110
44.4k
        auto cid = _schema->column_id(i);
2111
44.4k
        const auto* column_desc = _schema->column(cid);
2112
2113
44.4k
        auto file_column_type = _storage_name_and_type[cid].second;
2114
44.4k
        auto expected_type = Schema::get_data_type_ptr(*column_desc);
2115
44.4k
        if (!_is_pred_column[cid] && !file_column_type->equals(*expected_type)) {
2116
            // The storage layer type is different from schema needed type, so we use storage
2117
            // type to read columns instead of schema type for safety
2118
0
            VLOG_DEBUG << fmt::format(
2119
0
                    "Recreate column with expected type {}, file column type {}, col_name {}, "
2120
0
                    "col_path {}",
2121
0
                    block->get_by_position(i).type->get_name(), file_column_type->get_name(),
2122
0
                    column_desc->name(),
2123
0
                    column_desc->path() == nullptr ? "" : column_desc->path()->get_path());
2124
            // TODO reuse
2125
0
            current_columns[cid] = file_column_type->create_column();
2126
0
            current_columns[cid]->reserve(nrows_read_limit);
2127
44.4k
        } else {
2128
            // the column in block must clear() here to insert new data
2129
44.4k
            if (_is_pred_column[cid] ||
2130
44.4k
                i >= block->columns()) { //todo(wb) maybe we can release it after output block
2131
4.66k
                if (current_columns[cid].get() == nullptr) {
2132
0
                    return Status::InternalError(
2133
0
                            "SegmentIterator meet invalid column, id={}, name={}", cid,
2134
0
                            _schema->column(cid)->name());
2135
0
                }
2136
4.66k
                current_columns[cid]->clear();
2137
39.7k
            } else { // non-predicate column
2138
39.7k
                current_columns[cid] = std::move(*block->get_by_position(i).column).mutate();
2139
39.7k
                current_columns[cid]->reserve(nrows_read_limit);
2140
39.7k
            }
2141
44.4k
        }
2142
44.4k
    }
2143
2144
23.1k
    for (auto entry : _virtual_column_exprs) {
2145
0
        auto cid = entry.first;
2146
0
        current_columns[cid] = ColumnNothing::create(0);
2147
0
        current_columns[cid]->reserve(nrows_read_limit);
2148
0
    }
2149
2150
23.1k
    return Status::OK();
2151
23.1k
}
2152
2153
17.5k
Status SegmentIterator::_output_non_pred_columns(Block* block) {
2154
17.5k
    SCOPED_RAW_TIMER(&_opts.stats->output_col_ns);
2155
17.5k
    VLOG_DEBUG << fmt::format(
2156
0
            "Output non-predicate columns, _non_predicate_columns: [{}], "
2157
0
            "_schema_block_id_map: [{}]",
2158
0
            fmt::join(_non_predicate_columns, ","), fmt::join(_schema_block_id_map, ","));
2159
17.5k
    RETURN_IF_ERROR(_convert_to_expected_type(_non_predicate_columns));
2160
27.5k
    for (auto cid : _non_predicate_columns) {
2161
27.5k
        auto loc = _schema_block_id_map[cid];
2162
        // Whether a delete predicate column gets output depends on how the caller builds
2163
        // the block passed to next_batch(). Both calling paths now build the block with
2164
        // only the output schema (return_columns), so delete predicate columns are skipped:
2165
        //
2166
        // 1) VMergeIterator path: block_reset() builds _block using the output schema
2167
        //    (return_columns only), e.g. block has 2 columns {c1, c2}.
2168
        //    Here loc=2 for delete predicate c3, block->columns()=2, so loc < block->columns()
2169
        //    is false, and c3 is skipped.
2170
        //
2171
        // 2) VUnionIterator path: the caller's block is built with only return_columns
2172
        //    (output schema), e.g. block has 2 columns {c1, c2}.
2173
        //    Here loc=2 for c3, block->columns()=2, so loc < block->columns() is false,
2174
        //    and c3 is skipped — same behavior as the VMergeIterator path.
2175
27.5k
        if (loc < block->columns()) {
2176
27.5k
            bool column_in_block_is_nothing = check_and_get_column<const ColumnNothing>(
2177
27.5k
                    block->get_by_position(loc).column.get());
2178
27.5k
            bool column_is_normal = !_vir_cid_to_idx_in_block.contains(cid);
2179
27.5k
            bool return_column_is_nothing =
2180
27.5k
                    check_and_get_column<const ColumnNothing>(_current_return_columns[cid].get());
2181
27.5k
            VLOG_DEBUG << fmt::format(
2182
0
                    "Cid {} loc {}, column_in_block_is_nothing {}, column_is_normal {}, "
2183
0
                    "return_column_is_nothing {}",
2184
0
                    cid, loc, column_in_block_is_nothing, column_is_normal,
2185
0
                    return_column_is_nothing);
2186
2187
27.5k
            if (column_in_block_is_nothing || column_is_normal) {
2188
27.5k
                block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2189
27.5k
                VLOG_DEBUG << fmt::format(
2190
0
                        "Output non-predicate column, cid: {}, loc: {}, col_name: {}, rows {}", cid,
2191
0
                        loc, _schema->column(cid)->name(),
2192
0
                        block->get_by_position(loc).column->size());
2193
27.5k
            }
2194
            // Means virtual column in block has been materialized(maybe by common expr).
2195
            // so do nothing here.
2196
27.5k
        }
2197
27.5k
    }
2198
17.5k
    return Status::OK();
2199
17.5k
}
2200
2201
/**
2202
 * Reads columns by their index, handling both continuous and discontinuous rowid scenarios.
2203
 *
2204
 * This function is designed to read a specified number of rows (up to nrows_read_limit)
2205
 * from the segment iterator, dealing with both continuous and discontinuous rowid arrays.
2206
 * It operates as follows:
2207
 *
2208
 * 1. Reads a batch of rowids (up to the specified limit), and checks if they are continuous.
2209
 *    Continuous here means that the rowids form an unbroken sequence (e.g., 1, 2, 3, 4...).
2210
 *
2211
 * 2. For each column that needs to be read (identified by _predicate_column_ids):
2212
 *    - If the rowids are continuous, the function uses seek_to_ordinal and next_batch
2213
 *      for efficient reading.
2214
 *    - If the rowids are not continuous, the function processes them in smaller batches
2215
 *      (each of size up to 256). Each batch is checked for internal continuity:
2216
 *        a. If a batch is continuous, uses seek_to_ordinal and next_batch for that batch.
2217
 *        b. If a batch is not continuous, uses read_by_rowids for individual rowids in the batch.
2218
 *
2219
 * This approach optimizes reading performance by leveraging batch processing for continuous
2220
 * rowid sequences and handling discontinuities gracefully in smaller chunks.
2221
 */
2222
23.1k
Status SegmentIterator::_read_columns_by_index(uint32_t nrows_read_limit, uint16_t& nrows_read) {
2223
23.1k
    SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_ns);
2224
2225
23.1k
    nrows_read = (uint16_t)_range_iter->read_batch_rowids(_block_rowids.data(), nrows_read_limit);
2226
23.1k
    bool is_continuous = (nrows_read > 1) &&
2227
23.1k
                         (_block_rowids[nrows_read - 1] - _block_rowids[0] == nrows_read - 1);
2228
23.1k
    VLOG_DEBUG << fmt::format(
2229
0
            "nrows_read from range iterator: {}, is_continus {}, _cols_read_by_column_predicate "
2230
0
            "[{}]",
2231
0
            nrows_read, is_continuous, fmt::join(_predicate_column_ids, ","));
2232
2233
23.1k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2234
0
            "[verbose] SegmentIterator::_read_columns_by_index read {} rowids, continuous: {}, "
2235
0
            "rowids: [{}...{}]",
2236
0
            nrows_read, is_continuous, nrows_read > 0 ? _block_rowids[0] : 0,
2237
0
            nrows_read > 0 ? _block_rowids[nrows_read - 1] : 0);
2238
39.6k
    for (auto cid : _predicate_column_ids) {
2239
39.6k
        auto& column = _current_return_columns[cid];
2240
39.6k
        VLOG_DEBUG << fmt::format("Reading column {}, col_name {}", cid,
2241
0
                                  _schema->column(cid)->name());
2242
39.6k
        if (!_virtual_column_exprs.contains(cid)) {
2243
39.6k
            if (_no_need_read_key_data(cid, column, nrows_read)) {
2244
0
                VLOG_DEBUG << fmt::format("Column {} no need to read.", cid);
2245
0
                continue;
2246
0
            }
2247
39.6k
            if (_prune_column(cid, column, true, nrows_read)) {
2248
0
                VLOG_DEBUG << fmt::format("Column {} is pruned. No need to read data.", cid);
2249
0
                continue;
2250
0
            }
2251
39.6k
            DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2252
39.6k
                auto col_name = _opts.tablet_schema->column(cid).name();
2253
39.6k
                auto debug_col_name =
2254
39.6k
                        DebugPoints::instance()->get_debug_param_or_default<std::string>(
2255
39.6k
                                "segment_iterator._read_columns_by_index", "column_name", "");
2256
39.6k
                if (debug_col_name.empty() && col_name != "__DORIS_DELETE_SIGN__") {
2257
39.6k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2258
39.6k
                            "does not need to read data, {}", col_name);
2259
39.6k
                }
2260
39.6k
                if (debug_col_name.find(col_name) != std::string::npos) {
2261
39.6k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2262
39.6k
                            "does not need to read data, {}", col_name);
2263
39.6k
                }
2264
39.6k
            })
2265
39.6k
        }
2266
2267
39.6k
        if (is_continuous) {
2268
27.5k
            size_t rows_read = nrows_read;
2269
27.5k
            _opts.stats->predicate_column_read_seek_num += 1;
2270
27.5k
            if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2271
0
                SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2272
0
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2273
27.5k
            } else {
2274
27.5k
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2275
27.5k
            }
2276
27.5k
            RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2277
27.5k
            if (rows_read != nrows_read) {
2278
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})",
2279
0
                                                                nrows_read, rows_read);
2280
0
            }
2281
27.5k
        } else {
2282
12.1k
            const uint32_t batch_size = _range_iter->get_batch_size();
2283
12.1k
            uint32_t processed = 0;
2284
13.3k
            while (processed < nrows_read) {
2285
1.19k
                uint32_t current_batch_size = std::min(batch_size, nrows_read - processed);
2286
1.19k
                bool batch_continuous = (current_batch_size > 1) &&
2287
1.19k
                                        (_block_rowids[processed + current_batch_size - 1] -
2288
1.17k
                                                 _block_rowids[processed] ==
2289
1.17k
                                         current_batch_size - 1);
2290
2291
1.19k
                if (batch_continuous) {
2292
0
                    size_t rows_read = current_batch_size;
2293
0
                    _opts.stats->predicate_column_read_seek_num += 1;
2294
0
                    if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2295
0
                        SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2296
0
                        RETURN_IF_ERROR(
2297
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2298
0
                    } else {
2299
0
                        RETURN_IF_ERROR(
2300
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2301
0
                    }
2302
0
                    RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2303
0
                    if (rows_read != current_batch_size) {
2304
0
                        return Status::Error<ErrorCode::INTERNAL_ERROR>(
2305
0
                                "batch nrows({}) != rows_read({})", current_batch_size, rows_read);
2306
0
                    }
2307
1.19k
                } else {
2308
1.19k
                    RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(
2309
1.19k
                            &_block_rowids[processed], current_batch_size, column));
2310
1.19k
                }
2311
1.19k
                processed += current_batch_size;
2312
1.19k
            }
2313
12.1k
        }
2314
39.6k
    }
2315
2316
23.1k
    return Status::OK();
2317
23.1k
}
2318
void SegmentIterator::_replace_version_col_if_needed(const std::vector<ColumnId>& column_ids,
2319
26.1k
                                                     size_t num_rows) {
2320
    // Only the rowset with single version need to replace the version column.
2321
    // Doris can't determine the version before publish_version finished, so
2322
    // we can't write data to __DORIS_VERSION_COL__ in segment writer, the value
2323
    // is 0 by default.
2324
    // So we need to replace the value to real version while reading.
2325
26.1k
    if (_opts.version.first != _opts.version.second) {
2326
9.41k
        return;
2327
9.41k
    }
2328
16.7k
    int32_t version_idx = _schema->version_col_idx();
2329
16.7k
    if (std::ranges::find(column_ids, version_idx) == column_ids.end()) {
2330
16.7k
        return;
2331
16.7k
    }
2332
2333
0
    const auto* column_desc = _schema->column(version_idx);
2334
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2335
0
    DCHECK(_schema->column(version_idx)->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2336
0
    auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2337
0
    for (size_t j = 0; j < num_rows; j++) {
2338
0
        col_ptr->insert_value(_opts.version.second);
2339
0
    }
2340
0
    _current_return_columns[version_idx] = std::move(column);
2341
0
    VLOG_DEBUG << "replaced version column in segment iterator, version_col_idx:" << version_idx;
2342
0
}
2343
2344
uint16_t SegmentIterator::_evaluate_vectorization_predicate(uint16_t* sel_rowid_idx,
2345
4.19k
                                                            uint16_t selected_size) {
2346
4.19k
    SCOPED_RAW_TIMER(&_opts.stats->vec_cond_ns);
2347
4.19k
    bool all_pred_always_true = true;
2348
4.19k
    for (const auto& pred : _pre_eval_block_predicate) {
2349
0
        if (!pred->always_true()) {
2350
0
            all_pred_always_true = false;
2351
0
        } else {
2352
0
            pred->update_filter_info(0, 0, selected_size);
2353
0
        }
2354
0
    }
2355
2356
4.19k
    const uint16_t original_size = selected_size;
2357
    //If all predicates are always_true, then return directly.
2358
4.19k
    if (all_pred_always_true || !_is_need_vec_eval) {
2359
3.91M
        for (uint16_t i = 0; i < original_size; ++i) {
2360
3.90M
            sel_rowid_idx[i] = i;
2361
3.90M
        }
2362
        // All preds are always_true, so return immediately and update the profile statistics here.
2363
4.19k
        _opts.stats->vec_cond_input_rows += original_size;
2364
4.19k
        return original_size;
2365
4.19k
    }
2366
2367
0
    _ret_flags.resize(original_size);
2368
0
    DCHECK(!_pre_eval_block_predicate.empty());
2369
0
    bool is_first = true;
2370
0
    for (auto& pred : _pre_eval_block_predicate) {
2371
0
        if (pred->always_true()) {
2372
0
            continue;
2373
0
        }
2374
0
        auto column_id = pred->column_id();
2375
0
        auto& column = _current_return_columns[column_id];
2376
0
        if (is_first) {
2377
0
            pred->evaluate_vec(*column, original_size, (bool*)_ret_flags.data());
2378
0
            is_first = false;
2379
0
        } else {
2380
0
            pred->evaluate_and_vec(*column, original_size, (bool*)_ret_flags.data());
2381
0
        }
2382
0
    }
2383
2384
0
    uint16_t new_size = 0;
2385
2386
0
    uint16_t sel_pos = 0;
2387
0
    const uint16_t sel_end = sel_pos + selected_size;
2388
0
    static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2389
0
    const uint16_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2390
2391
0
    while (sel_pos < sel_end_simd) {
2392
0
        auto mask = simd::bytes_mask_to_bits_mask(_ret_flags.data() + sel_pos);
2393
0
        if (0 == mask) {
2394
            //pass
2395
0
        } else if (simd::bits_mask_all() == mask) {
2396
0
            for (uint16_t i = 0; i < SIMD_BYTES; i++) {
2397
0
                sel_rowid_idx[new_size++] = sel_pos + i;
2398
0
            }
2399
0
        } else {
2400
0
            simd::iterate_through_bits_mask(
2401
0
                    [&](const int bit_pos) {
2402
0
                        sel_rowid_idx[new_size++] = sel_pos + (uint16_t)bit_pos;
2403
0
                    },
2404
0
                    mask);
2405
0
        }
2406
0
        sel_pos += SIMD_BYTES;
2407
0
    }
2408
2409
0
    for (; sel_pos < sel_end; sel_pos++) {
2410
0
        if (_ret_flags[sel_pos]) {
2411
0
            sel_rowid_idx[new_size++] = sel_pos;
2412
0
        }
2413
0
    }
2414
2415
0
    _opts.stats->vec_cond_input_rows += original_size;
2416
0
    _opts.stats->rows_vec_cond_filtered += original_size - new_size;
2417
0
    return new_size;
2418
4.19k
}
2419
2420
uint16_t SegmentIterator::_evaluate_short_circuit_predicate(uint16_t* vec_sel_rowid_idx,
2421
4.19k
                                                            uint16_t selected_size) {
2422
4.19k
    SCOPED_RAW_TIMER(&_opts.stats->short_cond_ns);
2423
4.19k
    if (!_is_need_short_eval) {
2424
0
        return selected_size;
2425
0
    }
2426
2427
4.19k
    uint16_t original_size = selected_size;
2428
4.19k
    for (auto predicate : _short_cir_eval_predicate) {
2429
0
        auto column_id = predicate->column_id();
2430
0
        auto& short_cir_column = _current_return_columns[column_id];
2431
0
        selected_size = predicate->evaluate(*short_cir_column, vec_sel_rowid_idx, selected_size);
2432
0
    }
2433
2434
4.19k
    _opts.stats->short_circuit_cond_input_rows += original_size;
2435
4.19k
    _opts.stats->rows_short_circuit_cond_filtered += original_size - selected_size;
2436
2437
    // evaluate delete condition
2438
4.19k
    original_size = selected_size;
2439
4.19k
    selected_size = _opts.delete_condition_predicates->evaluate(_current_return_columns,
2440
4.19k
                                                                vec_sel_rowid_idx, selected_size);
2441
4.19k
    _opts.stats->rows_vec_del_cond_filtered += original_size - selected_size;
2442
4.19k
    return selected_size;
2443
4.19k
}
2444
2445
Status SegmentIterator::_read_columns_by_rowids(std::vector<ColumnId>& read_column_ids,
2446
                                                std::vector<rowid_t>& rowid_vector,
2447
                                                uint16_t* sel_rowid_idx, size_t select_size,
2448
                                                MutableColumns* mutable_columns,
2449
3.05k
                                                bool init_condition_cache) {
2450
3.05k
    SCOPED_RAW_TIMER(&_opts.stats->lazy_read_ns);
2451
3.05k
    std::vector<rowid_t> rowids(select_size);
2452
2453
3.05k
    if (init_condition_cache) {
2454
0
        DCHECK(_condition_cache);
2455
0
        auto& condition_cache = *_condition_cache;
2456
0
        for (size_t i = 0; i < select_size; ++i) {
2457
0
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2458
0
            condition_cache[rowids[i] / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2459
0
        }
2460
3.05k
    } else {
2461
2.74M
        for (size_t i = 0; i < select_size; ++i) {
2462
2.74M
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2463
2.74M
        }
2464
3.05k
    }
2465
2466
3.77k
    for (auto cid : read_column_ids) {
2467
3.77k
        auto& colunm = (*mutable_columns)[cid];
2468
3.77k
        if (_no_need_read_key_data(cid, colunm, select_size)) {
2469
0
            continue;
2470
0
        }
2471
3.77k
        if (_prune_column(cid, colunm, true, select_size)) {
2472
0
            continue;
2473
0
        }
2474
2475
3.77k
        DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2476
3.77k
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
2477
3.77k
                    "segment_iterator._read_columns_by_index", "column_name", "");
2478
3.77k
            if (debug_col_name.empty()) {
2479
3.77k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data");
2480
3.77k
            }
2481
3.77k
            auto col_name = _opts.tablet_schema->column(cid).name();
2482
3.77k
            if (debug_col_name.find(col_name) != std::string::npos) {
2483
3.77k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data, {}",
2484
3.77k
                                                                debug_col_name);
2485
3.77k
            }
2486
3.77k
        })
2487
2488
3.77k
        if (_current_return_columns[cid].get() == nullptr) {
2489
0
            return Status::InternalError(
2490
0
                    "SegmentIterator meet invalid column, return columns size {}, cid {}",
2491
0
                    _current_return_columns.size(), cid);
2492
0
        }
2493
3.77k
        RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(rowids.data(), select_size,
2494
3.77k
                                                               _current_return_columns[cid]));
2495
3.77k
    }
2496
2497
3.05k
    return Status::OK();
2498
3.05k
}
2499
2500
23.1k
Status SegmentIterator::next_batch(Block* block) {
2501
    // Replace virtual columns with ColumnNothing at the begining of each next_batch call.
2502
23.1k
    _init_virtual_columns(block);
2503
23.1k
    auto status = [&]() {
2504
23.1k
        RETURN_IF_CATCH_EXCEPTION({
2505
23.1k
            auto res = _next_batch_internal(block);
2506
2507
23.1k
            if (res.is<END_OF_FILE>()) {
2508
                // Since we have a type check at the caller.
2509
                // So a replacement of nothing column with real column is needed.
2510
23.1k
                const auto& idx_to_datatype = _opts.vir_col_idx_to_type;
2511
23.1k
                for (const auto& pair : _vir_cid_to_idx_in_block) {
2512
23.1k
                    size_t idx = pair.second;
2513
23.1k
                    auto type = idx_to_datatype.find(idx)->second;
2514
23.1k
                    block->replace_by_position(idx, type->create_column());
2515
23.1k
                }
2516
2517
23.1k
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2518
23.1k
                    auto* condition_cache = ConditionCache::instance();
2519
23.1k
                    ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
2520
23.1k
                                                       _opts.condition_cache_digest);
2521
23.1k
                    VLOG_DEBUG << "Condition cache insert, query id: "
2522
23.1k
                               << print_id(_opts.runtime_state->query_id())
2523
23.1k
                               << ", rowset id: " << _opts.rowset_id.to_string()
2524
23.1k
                               << ", segment id: " << _segment->id()
2525
23.1k
                               << ", cache digest: " << _opts.condition_cache_digest;
2526
23.1k
                    condition_cache->insert(cache_key, std::move(_condition_cache));
2527
23.1k
                }
2528
23.1k
                return res;
2529
23.1k
            }
2530
2531
23.1k
            RETURN_IF_ERROR(res);
2532
            // reverse block row order if read_orderby_key_reverse is true for key topn
2533
            // it should be processed for all success _next_batch_internal
2534
23.1k
            if (_opts.read_orderby_key_reverse) {
2535
23.1k
                size_t num_rows = block->rows();
2536
23.1k
                if (num_rows == 0) {
2537
23.1k
                    return Status::OK();
2538
23.1k
                }
2539
23.1k
                size_t num_columns = block->columns();
2540
23.1k
                IColumn::Permutation permutation;
2541
23.1k
                for (size_t i = 0; i < num_rows; ++i) permutation.emplace_back(num_rows - 1 - i);
2542
2543
23.1k
                for (size_t i = 0; i < num_columns; ++i)
2544
23.1k
                    block->get_by_position(i).column =
2545
23.1k
                            block->get_by_position(i).column->permute(permutation, num_rows);
2546
23.1k
            }
2547
2548
23.1k
            RETURN_IF_ERROR(block->check_type_and_column());
2549
2550
23.1k
            return Status::OK();
2551
23.1k
        });
2552
23.1k
    }();
2553
2554
    // if rows read by batch is 0, will return end of file, we should not remove segment cache in this situation.
2555
23.1k
    if (!status.ok() && !status.is<END_OF_FILE>()) {
2556
0
        _segment->update_healthy_status(status);
2557
0
    }
2558
23.1k
    return status;
2559
23.1k
}
2560
2561
23.1k
Status SegmentIterator::_convert_to_expected_type(const std::vector<ColumnId>& col_ids) {
2562
40.2k
    for (ColumnId i : col_ids) {
2563
40.2k
        if (!_current_return_columns[i] || _converted_column_ids[i] || _is_pred_column[i]) {
2564
467
            continue;
2565
467
        }
2566
39.7k
        const StorageField* field_type = _schema->column(i);
2567
39.7k
        DataTypePtr expected_type = Schema::get_data_type_ptr(*field_type);
2568
39.7k
        DataTypePtr file_column_type = _storage_name_and_type[i].second;
2569
39.7k
        if (!file_column_type->equals(*expected_type)) {
2570
0
            ColumnPtr expected;
2571
0
            ColumnPtr original = _current_return_columns[i]->assume_mutable()->get_ptr();
2572
0
            RETURN_IF_ERROR(variant_util::cast_column({original, file_column_type, ""},
2573
0
                                                      expected_type, &expected));
2574
0
            _current_return_columns[i] = expected->assume_mutable();
2575
0
            _converted_column_ids[i] = true;
2576
0
            VLOG_DEBUG << fmt::format(
2577
0
                    "Convert {} fom file column type {} to {}, num_rows {}",
2578
0
                    field_type->path() == nullptr ? "" : field_type->path()->get_path(),
2579
0
                    file_column_type->get_name(), expected_type->get_name(),
2580
0
                    _current_return_columns[i]->size());
2581
0
        }
2582
39.7k
    }
2583
23.1k
    return Status::OK();
2584
23.1k
}
2585
2586
Status SegmentIterator::copy_column_data_by_selector(IColumn* input_col_ptr,
2587
                                                     MutableColumnPtr& output_col,
2588
                                                     uint16_t* sel_rowid_idx, uint16_t select_size,
2589
2.83k
                                                     size_t batch_size) {
2590
2.83k
    if (output_col->is_nullable() != input_col_ptr->is_nullable()) {
2591
0
        LOG(WARNING) << "nullable mismatch for output_column: " << output_col->dump_structure()
2592
0
                     << " input_column: " << input_col_ptr->dump_structure()
2593
0
                     << " select_size: " << select_size;
2594
0
        return Status::RuntimeError("copy_column_data_by_selector nullable mismatch");
2595
0
    }
2596
2.83k
    output_col->reserve(select_size);
2597
2.83k
    return input_col_ptr->filter_by_selector(sel_rowid_idx, select_size, output_col.get());
2598
2.83k
}
2599
2600
23.1k
Status SegmentIterator::_next_batch_internal(Block* block) {
2601
23.1k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().segment_iterator_next_batch);
2602
2603
23.1k
    bool is_mem_reuse = block->mem_reuse();
2604
23.1k
    DCHECK(is_mem_reuse);
2605
2606
23.1k
    RETURN_IF_ERROR(_lazy_init(block));
2607
2608
23.1k
    SCOPED_RAW_TIMER(&_opts.stats->block_load_ns);
2609
2610
    // If the row bitmap size is smaller than nrows_read_limit, there's no need to reserve that many column rows.
2611
23.1k
    uint32_t nrows_read_limit =
2612
23.1k
            std::min(cast_set<uint32_t>(_row_bitmap.cardinality()), _opts.block_row_max);
2613
23.1k
    if (_can_opt_topn_reads()) {
2614
0
        nrows_read_limit = std::min(static_cast<uint32_t>(_opts.topn_limit), nrows_read_limit);
2615
0
    }
2616
23.1k
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
2617
23.1k
        if (nrows_read_limit != 1) {
2618
23.1k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
2619
23.1k
                    "topn opt 1 execute failed: nrows_read_limit={}, _opts.topn_limit={}",
2620
23.1k
                    nrows_read_limit, _opts.topn_limit);
2621
23.1k
        }
2622
23.1k
    })
2623
2624
23.1k
    RETURN_IF_ERROR(_init_current_block(block, _current_return_columns, nrows_read_limit));
2625
23.1k
    _converted_column_ids.assign(_schema->columns().size(), false);
2626
2627
23.1k
    _selected_size = 0;
2628
23.1k
    RETURN_IF_ERROR(_read_columns_by_index(nrows_read_limit, _selected_size));
2629
23.1k
    _replace_version_col_if_needed(_predicate_column_ids, _selected_size);
2630
2631
23.1k
    _opts.stats->blocks_load += 1;
2632
23.1k
    _opts.stats->raw_rows_read += _selected_size;
2633
2634
23.1k
    if (_selected_size == 0) {
2635
5.62k
        return _process_eof(block);
2636
5.62k
    }
2637
2638
17.5k
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
2639
4.19k
        _sel_rowid_idx.resize(_selected_size);
2640
2641
4.19k
        if (_is_need_vec_eval || _is_need_short_eval) {
2642
4.19k
            _convert_dict_code_for_predicate_if_necessary();
2643
2644
            // step 1: evaluate vectorization predicate
2645
4.19k
            _selected_size =
2646
4.19k
                    _evaluate_vectorization_predicate(_sel_rowid_idx.data(), _selected_size);
2647
2648
            // step 2: evaluate short circuit predicate
2649
            // todo(wb) research whether need to read short predicate after vectorization evaluation
2650
            //          to reduce cost of read short circuit columns.
2651
            //          In SSB test, it make no difference; So need more scenarios to test
2652
4.19k
            _selected_size =
2653
4.19k
                    _evaluate_short_circuit_predicate(_sel_rowid_idx.data(), _selected_size);
2654
4.19k
            VLOG_DEBUG << fmt::format("After evaluate predicates, selected size: {} ",
2655
0
                                      _selected_size);
2656
4.19k
            if (_selected_size > 0) {
2657
                // step 3.1: output short circuit and predicate column
2658
                // when lazy materialization enables, _predicate_column_ids = distinct(_short_cir_pred_column_ids + _vec_pred_column_ids)
2659
                // see _vec_init_lazy_materialization
2660
                // todo(wb) need to tell input columnids from output columnids
2661
4.04k
                RETURN_IF_ERROR(_output_column_by_sel_idx(block, _predicate_column_ids,
2662
4.04k
                                                          _sel_rowid_idx.data(), _selected_size));
2663
2664
                // step 3.2: read remaining expr column and evaluate it.
2665
4.04k
                if (_is_need_expr_eval) {
2666
                    // The predicate column contains the remaining expr column, no need second read.
2667
0
                    if (_common_expr_column_ids.size() > 0) {
2668
0
                        SCOPED_RAW_TIMER(&_opts.stats->non_predicate_read_ns);
2669
0
                        RETURN_IF_ERROR(_read_columns_by_rowids(
2670
0
                                _common_expr_column_ids, _block_rowids, _sel_rowid_idx.data(),
2671
0
                                _selected_size, &_current_return_columns));
2672
0
                        _replace_version_col_if_needed(_common_expr_column_ids, _selected_size);
2673
0
                        RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2674
0
                    }
2675
2676
0
                    DCHECK(block->columns() > _schema_block_id_map[*_common_expr_columns.begin()]);
2677
0
                    RETURN_IF_ERROR(
2678
0
                            _process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2679
0
                }
2680
4.04k
            } else {
2681
150
                _fill_column_nothing();
2682
150
                if (_is_need_expr_eval) {
2683
0
                    RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2684
0
                }
2685
150
            }
2686
4.19k
        } else if (_is_need_expr_eval) {
2687
0
            DCHECK(!_predicate_column_ids.empty());
2688
0
            RETURN_IF_ERROR(_process_columns(_predicate_column_ids, block));
2689
            // first read all rows are insert block, initialize sel_rowid_idx to all rows.
2690
0
            for (uint16_t i = 0; i < _selected_size; ++i) {
2691
0
                _sel_rowid_idx[i] = i;
2692
0
            }
2693
0
            RETURN_IF_ERROR(_process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2694
0
        }
2695
2696
        // step4: read non_predicate column
2697
4.19k
        if (_selected_size > 0) {
2698
4.04k
            if (!_non_predicate_columns.empty()) {
2699
3.05k
                RETURN_IF_ERROR(_read_columns_by_rowids(
2700
3.05k
                        _non_predicate_columns, _block_rowids, _sel_rowid_idx.data(),
2701
3.05k
                        _selected_size, &_current_return_columns,
2702
3.05k
                        _opts.condition_cache_digest && !_find_condition_cache));
2703
3.05k
                _replace_version_col_if_needed(_non_predicate_columns, _selected_size);
2704
3.05k
            } else {
2705
995
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2706
0
                    auto& condition_cache = *_condition_cache;
2707
0
                    for (size_t i = 0; i < _selected_size; ++i) {
2708
0
                        auto rowid = _block_rowids[_sel_rowid_idx[i]];
2709
0
                        condition_cache[rowid / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2710
0
                    }
2711
0
                }
2712
995
            }
2713
4.04k
        }
2714
4.19k
    }
2715
2716
    // step5: output columns
2717
17.5k
    RETURN_IF_ERROR(_output_non_pred_columns(block));
2718
    // Convert inverted index bitmaps to result columns for virtual column exprs
2719
    // (e.g., MATCH projections). This must run before _materialization_of_virtual_column
2720
    // so that fast_execute() can find the pre-computed result columns.
2721
17.5k
    if (!_virtual_column_exprs.empty()) {
2722
0
        bool use_sel = _is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval;
2723
0
        uint16_t* sel_rowid_idx = use_sel ? _sel_rowid_idx.data() : nullptr;
2724
0
        std::vector<VExprContext*> vir_ctxs;
2725
0
        vir_ctxs.reserve(_virtual_column_exprs.size());
2726
0
        for (auto& [cid, ctx] : _virtual_column_exprs) {
2727
0
            vir_ctxs.push_back(ctx.get());
2728
0
        }
2729
0
        _output_index_result_column(vir_ctxs, sel_rowid_idx, _selected_size, block);
2730
0
    }
2731
17.5k
    RETURN_IF_ERROR(_materialization_of_virtual_column(block));
2732
    // shrink char_type suffix zero data
2733
17.5k
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
2734
17.5k
    return _check_output_block(block);
2735
17.5k
}
2736
2737
0
Status SegmentIterator::_process_columns(const std::vector<ColumnId>& column_ids, Block* block) {
2738
0
    RETURN_IF_ERROR(_convert_to_expected_type(column_ids));
2739
0
    for (auto cid : column_ids) {
2740
0
        auto loc = _schema_block_id_map[cid];
2741
0
        block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2742
0
    }
2743
0
    return Status::OK();
2744
0
}
2745
2746
150
void SegmentIterator::_fill_column_nothing() {
2747
    // If column_predicate filters out all rows, the corresponding column in _current_return_columns[cid] must be a ColumnNothing.
2748
    // Because:
2749
    // 1. Before each batch, _init_return_columns is called to initialize _current_return_columns, and virtual columns in _current_return_columns are initialized as ColumnNothing.
2750
    // 2. When select_size == 0, the read method of VirtualColumnIterator will definitely not be called, so the corresponding Column remains a ColumnNothing
2751
150
    for (const auto pair : _vir_cid_to_idx_in_block) {
2752
0
        auto cid = pair.first;
2753
0
        auto pos = pair.second;
2754
0
        const auto* nothing_col =
2755
0
                check_and_get_column<ColumnNothing>(_current_return_columns[cid].get());
2756
0
        DCHECK(nothing_col != nullptr)
2757
0
                << fmt::format("ColumnNothing expected, but got {}, cid: {}, pos: {}",
2758
0
                               _current_return_columns[cid]->get_name(), cid, pos);
2759
0
        _current_return_columns[cid] = _opts.vir_col_idx_to_type[pos]->create_column();
2760
0
    }
2761
150
}
2762
2763
17.5k
Status SegmentIterator::_check_output_block(Block* block) {
2764
17.5k
#ifndef NDEBUG
2765
17.5k
    size_t rows = block->rows();
2766
17.5k
    size_t idx = 0;
2767
30.5k
    for (const auto& entry : *block) {
2768
30.5k
        if (!entry.column) {
2769
0
            return Status::InternalError(
2770
0
                    "Column in idx {} is null, block columns {}, normal_columns {}, "
2771
0
                    "virtual_columns {}",
2772
0
                    idx, block->columns(), _schema->num_column_ids(), _virtual_column_exprs.size());
2773
30.5k
        } else if (check_and_get_column<ColumnNothing>(entry.column.get())) {
2774
0
            if (rows > 0) {
2775
0
                std::vector<std::string> vcid_to_idx;
2776
0
                for (const auto& pair : _vir_cid_to_idx_in_block) {
2777
0
                    vcid_to_idx.push_back(fmt::format("{}-{}", pair.first, pair.second));
2778
0
                }
2779
0
                std::string vir_cid_to_idx_in_block_msg =
2780
0
                        fmt::format("_vir_cid_to_idx_in_block:[{}]", fmt::join(vcid_to_idx, ","));
2781
0
                return Status::InternalError(
2782
0
                        "Column in idx {} is nothing, block columns {}, normal_columns {}, "
2783
0
                        "vir_cid_to_idx_in_block_msg {}",
2784
0
                        idx, block->columns(), _schema->num_column_ids(),
2785
0
                        vir_cid_to_idx_in_block_msg);
2786
0
            }
2787
30.5k
        } else if (entry.column->size() != rows) {
2788
0
            return Status::InternalError(
2789
0
                    "Unmatched size {}, expected {}, column: {}, type: {}, idx_in_block: {}, "
2790
0
                    "block: {}",
2791
0
                    entry.column->size(), rows, entry.column->get_name(), entry.type->get_name(),
2792
0
                    idx, block->dump_structure());
2793
0
        }
2794
30.5k
        idx++;
2795
30.5k
    }
2796
17.5k
#endif
2797
17.5k
    return Status::OK();
2798
17.5k
}
2799
2800
0
Status SegmentIterator::_process_column_predicate() {
2801
0
    return Status::OK();
2802
0
}
2803
2804
5.62k
Status SegmentIterator::_process_eof(Block* block) {
2805
    // Convert all columns in _current_return_columns to schema column
2806
5.62k
    RETURN_IF_ERROR(_convert_to_expected_type(_schema->column_ids()));
2807
18.0k
    for (int i = 0; i < block->columns(); i++) {
2808
12.4k
        auto cid = _schema->column_id(i);
2809
12.4k
        if (!_is_pred_column[cid]) {
2810
12.1k
            block->replace_by_position(i, std::move(_current_return_columns[cid]));
2811
12.1k
        }
2812
12.4k
    }
2813
5.62k
    block->clear_column_data();
2814
    // clear and release iterators memory footprint in advance
2815
5.62k
    _column_iterators.clear();
2816
5.62k
    _index_iterators.clear();
2817
5.62k
    return Status::EndOfFile("no more data in segment");
2818
5.62k
}
2819
2820
Status SegmentIterator::_process_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
2821
0
                                             Block* block) {
2822
    // Here we just use col0 as row_number indicator. when reach here, we will calculate the predicates first.
2823
    //  then use the result to reduce our data read(that is, expr push down). there's now row in block means the first
2824
    //  column is not in common expr. so it's safe to replace it temporarily to provide correct `selected_size`.
2825
0
    VLOG_DEBUG << fmt::format("Execute common expr. block rows {}, selected size {}", block->rows(),
2826
0
                              _selected_size);
2827
2828
0
    bool need_mock_col = block->rows() != selected_size;
2829
0
    MutableColumnPtr col0;
2830
0
    if (need_mock_col) {
2831
0
        col0 = std::move(*block->get_by_position(0).column).mutate();
2832
0
        block->replace_by_position(
2833
0
                0, block->get_by_position(0).type->create_column_const_with_default_value(
2834
0
                           _selected_size));
2835
0
    }
2836
2837
0
    std::vector<VExprContext*> common_ctxs;
2838
0
    common_ctxs.reserve(_common_expr_ctxs_push_down.size());
2839
0
    for (auto& ctx : _common_expr_ctxs_push_down) {
2840
0
        common_ctxs.push_back(ctx.get());
2841
0
    }
2842
0
    _output_index_result_column(common_ctxs, _sel_rowid_idx.data(), _selected_size, block);
2843
0
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
2844
0
    RETURN_IF_ERROR(_execute_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2845
2846
0
    if (need_mock_col) {
2847
0
        block->replace_by_position(0, std::move(col0));
2848
0
    }
2849
2850
0
    VLOG_DEBUG << fmt::format("Execute common expr end. block rows {}, selected size {}",
2851
0
                              block->rows(), _selected_size);
2852
0
    return Status::OK();
2853
0
}
2854
2855
Status SegmentIterator::_execute_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
2856
0
                                             Block* block) {
2857
0
    SCOPED_RAW_TIMER(&_opts.stats->expr_filter_ns);
2858
0
    DCHECK(!_remaining_conjunct_roots.empty());
2859
0
    DCHECK(block->rows() != 0);
2860
0
    int prev_columns = block->columns();
2861
0
    uint16_t original_size = selected_size;
2862
0
    _opts.stats->expr_cond_input_rows += original_size;
2863
2864
0
    IColumn::Filter filter;
2865
0
    RETURN_IF_ERROR(VExprContext::execute_conjuncts_and_filter_block(
2866
0
            _common_expr_ctxs_push_down, block, _columns_to_filter, prev_columns, filter));
2867
2868
0
    selected_size = _evaluate_common_expr_filter(sel_rowid_idx, selected_size, filter);
2869
0
    _opts.stats->rows_expr_cond_filtered += original_size - selected_size;
2870
0
    return Status::OK();
2871
0
}
2872
2873
uint16_t SegmentIterator::_evaluate_common_expr_filter(uint16_t* sel_rowid_idx,
2874
                                                       uint16_t selected_size,
2875
0
                                                       const IColumn::Filter& filter) {
2876
0
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
2877
0
    if (count == 0) {
2878
0
        return 0;
2879
0
    } else {
2880
0
        const UInt8* filt_pos = filter.data();
2881
2882
0
        uint16_t new_size = 0;
2883
0
        uint32_t sel_pos = 0;
2884
0
        const uint32_t sel_end = selected_size;
2885
0
        static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2886
0
        const uint32_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2887
2888
0
        while (sel_pos < sel_end_simd) {
2889
0
            auto mask = simd::bytes_mask_to_bits_mask(filt_pos + sel_pos);
2890
0
            if (0 == mask) {
2891
                //pass
2892
0
            } else if (simd::bits_mask_all() == mask) {
2893
0
                for (uint32_t i = 0; i < SIMD_BYTES; i++) {
2894
0
                    sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + i];
2895
0
                }
2896
0
            } else {
2897
0
                simd::iterate_through_bits_mask(
2898
0
                        [&](const size_t bit_pos) {
2899
0
                            sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + bit_pos];
2900
0
                        },
2901
0
                        mask);
2902
0
            }
2903
0
            sel_pos += SIMD_BYTES;
2904
0
        }
2905
2906
0
        for (; sel_pos < sel_end; sel_pos++) {
2907
0
            if (filt_pos[sel_pos]) {
2908
0
                sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos];
2909
0
            }
2910
0
        }
2911
0
        return new_size;
2912
0
    }
2913
0
}
2914
2915
void SegmentIterator::_output_index_result_column(const std::vector<VExprContext*>& expr_ctxs,
2916
                                                  uint16_t* sel_rowid_idx, uint16_t select_size,
2917
0
                                                  Block* block) {
2918
0
    SCOPED_RAW_TIMER(&_opts.stats->output_index_result_column_timer);
2919
0
    if (block->rows() == 0) {
2920
0
        return;
2921
0
    }
2922
0
    for (auto* expr_ctx_ptr : expr_ctxs) {
2923
0
        auto index_ctx = expr_ctx_ptr->get_index_context();
2924
0
        if (index_ctx == nullptr) {
2925
0
            continue;
2926
0
        }
2927
0
        for (auto& inverted_index_result_bitmap_for_expr : index_ctx->get_index_result_bitmap()) {
2928
0
            const auto* expr = inverted_index_result_bitmap_for_expr.first;
2929
0
            const auto& result_bitmap = inverted_index_result_bitmap_for_expr.second;
2930
0
            const auto& index_result_bitmap = result_bitmap.get_data_bitmap();
2931
0
            auto index_result_column = ColumnUInt8::create();
2932
0
            ColumnUInt8::Container& vec_match_pred = index_result_column->get_data();
2933
0
            vec_match_pred.resize(block->rows());
2934
0
            std::fill(vec_match_pred.begin(), vec_match_pred.end(), 0);
2935
2936
0
            const auto& null_bitmap = result_bitmap.get_null_bitmap();
2937
0
            bool has_null_bitmap = null_bitmap != nullptr && !null_bitmap->isEmpty();
2938
0
            bool expr_returns_nullable = expr->data_type()->is_nullable();
2939
2940
0
            ColumnUInt8::MutablePtr null_map_column = nullptr;
2941
0
            ColumnUInt8::Container* null_map_data = nullptr;
2942
0
            if (has_null_bitmap && expr_returns_nullable) {
2943
0
                null_map_column = ColumnUInt8::create();
2944
0
                auto& null_map_vec = null_map_column->get_data();
2945
0
                null_map_vec.resize(block->rows());
2946
0
                std::fill(null_map_vec.begin(), null_map_vec.end(), 0);
2947
0
                null_map_data = &null_map_column->get_data();
2948
0
            }
2949
2950
0
            roaring::BulkContext bulk_context;
2951
0
            for (uint32_t i = 0; i < select_size; i++) {
2952
0
                auto rowid = sel_rowid_idx ? _block_rowids[sel_rowid_idx[i]] : _block_rowids[i];
2953
0
                if (index_result_bitmap) {
2954
0
                    vec_match_pred[i] = index_result_bitmap->containsBulk(bulk_context, rowid);
2955
0
                }
2956
0
                if (null_map_data != nullptr && null_bitmap->contains(rowid)) {
2957
0
                    (*null_map_data)[i] = 1;
2958
0
                    vec_match_pred[i] = 0;
2959
0
                }
2960
0
            }
2961
2962
0
            DCHECK(block->rows() == vec_match_pred.size());
2963
2964
0
            if (null_map_column) {
2965
0
                index_ctx->set_index_result_column_for_expr(
2966
0
                        expr, ColumnNullable::create(std::move(index_result_column),
2967
0
                                                     std::move(null_map_column)));
2968
0
            } else {
2969
0
                index_ctx->set_index_result_column_for_expr(expr, std::move(index_result_column));
2970
0
            }
2971
0
        }
2972
0
    }
2973
0
}
2974
2975
4.19k
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary() {
2976
4.19k
    for (auto predicate : _short_cir_eval_predicate) {
2977
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
2978
0
    }
2979
2980
4.19k
    for (auto predicate : _pre_eval_block_predicate) {
2981
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
2982
0
    }
2983
2984
4.19k
    for (auto column_id : _delete_range_column_ids) {
2985
4.05k
        _current_return_columns[column_id].get()->convert_dict_codes_if_necessary();
2986
4.05k
    }
2987
2988
4.19k
    for (auto column_id : _delete_bloom_filter_column_ids) {
2989
0
        _current_return_columns[column_id].get()->initialize_hash_values_for_runtime_filter();
2990
0
    }
2991
4.19k
}
2992
2993
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary_impl(
2994
0
        std::shared_ptr<ColumnPredicate> predicate) {
2995
0
    auto& column = _current_return_columns[predicate->column_id()];
2996
0
    auto* col_ptr = column.get();
2997
2998
0
    if (PredicateTypeTraits::is_range(predicate->type())) {
2999
0
        col_ptr->convert_dict_codes_if_necessary();
3000
0
    } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
3001
0
        col_ptr->initialize_hash_values_for_runtime_filter();
3002
0
    }
3003
0
}
3004
3005
7.19k
Status SegmentIterator::current_block_row_locations(std::vector<RowLocation>* block_row_locations) {
3006
7.19k
    DCHECK(_opts.record_rowids);
3007
7.19k
    DCHECK_GE(_block_rowids.size(), _selected_size);
3008
7.19k
    block_row_locations->resize(_selected_size);
3009
7.19k
    uint32_t sid = segment_id();
3010
7.19k
    if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
3011
4.24M
        for (auto i = 0; i < _selected_size; i++) {
3012
4.23M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[i]);
3013
4.23M
        }
3014
4.46k
    } else {
3015
2.46M
        for (auto i = 0; i < _selected_size; i++) {
3016
2.46M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[_sel_rowid_idx[i]]);
3017
2.46M
        }
3018
2.73k
    }
3019
7.19k
    return Status::OK();
3020
7.19k
}
3021
3022
5.63k
Status SegmentIterator::_construct_compound_expr_context() {
3023
5.63k
    ColumnIteratorOptions iter_opts {
3024
5.63k
            .use_page_cache = _opts.use_page_cache,
3025
5.63k
            .file_reader = _file_reader.get(),
3026
5.63k
            .stats = _opts.stats,
3027
5.63k
            .io_ctx = _opts.io_ctx,
3028
5.63k
    };
3029
5.63k
    auto inverted_index_context = std::make_shared<IndexExecContext>(
3030
5.63k
            _schema->column_ids(), _index_iterators, _storage_name_and_type,
3031
5.63k
            _common_expr_index_exec_status, _score_runtime, _segment.get(), iter_opts);
3032
5.63k
    inverted_index_context->set_index_query_context(_index_query_context);
3033
5.63k
    for (const auto& expr_ctx : _opts.common_expr_ctxs_push_down) {
3034
0
        VExprContextSPtr context;
3035
        // _ann_range_search_runtime will do deep copy.
3036
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3037
0
        context->set_index_context(inverted_index_context);
3038
0
        _common_expr_ctxs_push_down.emplace_back(context);
3039
0
    }
3040
    // Clone virtual column exprs before setting IndexExecContext, because
3041
    // IndexExecContext holds segment-specific index iterator references.
3042
    // Without cloning, shared VExprContext would be overwritten per-segment
3043
    // and could point to the wrong segment's context.
3044
5.63k
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
3045
0
        VExprContextSPtr context;
3046
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3047
0
        context->set_index_context(inverted_index_context);
3048
0
        expr_ctx = context;
3049
0
    }
3050
5.63k
    return Status::OK();
3051
5.63k
}
3052
3053
5.63k
void SegmentIterator::_calculate_expr_in_remaining_conjunct_root() {
3054
5.63k
    for (const auto& root_expr_ctx : _common_expr_ctxs_push_down) {
3055
0
        const auto& root_expr = root_expr_ctx->root();
3056
0
        if (root_expr == nullptr) {
3057
0
            continue;
3058
0
        }
3059
0
        _common_expr_to_slotref_map[root_expr_ctx.get()] = std::unordered_map<ColumnId, VExpr*>();
3060
3061
0
        std::stack<VExprSPtr> stack;
3062
0
        stack.emplace(root_expr);
3063
3064
0
        while (!stack.empty()) {
3065
0
            const auto& expr = stack.top();
3066
0
            stack.pop();
3067
3068
0
            for (const auto& child : expr->children()) {
3069
0
                if (child->is_virtual_slot_ref()) {
3070
                    // Expand virtual slot ref to its underlying expression tree and
3071
                    // collect real slot refs used inside. We still associate those
3072
                    // slot refs with the current parent expr node for inverted index
3073
                    // tracking, just like normal slot refs.
3074
0
                    auto* vir_slot_ref = assert_cast<VirtualSlotRef*>(child.get());
3075
0
                    auto vir_expr = vir_slot_ref->get_virtual_column_expr();
3076
0
                    if (vir_expr) {
3077
0
                        std::stack<VExprSPtr> vir_stack;
3078
0
                        vir_stack.emplace(vir_expr);
3079
3080
0
                        while (!vir_stack.empty()) {
3081
0
                            const auto& vir_node = vir_stack.top();
3082
0
                            vir_stack.pop();
3083
3084
0
                            for (const auto& vir_child : vir_node->children()) {
3085
0
                                if (vir_child->is_slot_ref()) {
3086
0
                                    auto* inner_slot_ref = assert_cast<VSlotRef*>(vir_child.get());
3087
0
                                    _common_expr_index_exec_status[_schema->column_id(
3088
0
                                            inner_slot_ref->column_id())][expr.get()] = false;
3089
0
                                    _common_expr_to_slotref_map[root_expr_ctx.get()]
3090
0
                                                               [inner_slot_ref->column_id()] =
3091
0
                                                                       expr.get();
3092
0
                                }
3093
3094
0
                                if (!vir_child->children().empty()) {
3095
0
                                    vir_stack.emplace(vir_child);
3096
0
                                }
3097
0
                            }
3098
0
                        }
3099
0
                    }
3100
0
                }
3101
                // Example: CAST(v['a'] AS VARCHAR) MATCH 'hello', do not add CAST expr to index tracking.
3102
0
                auto expr_without_cast = VExpr::expr_without_cast(child);
3103
0
                if (expr_without_cast->is_slot_ref() && expr->op() != TExprOpcode::CAST) {
3104
0
                    auto* column_slot_ref = assert_cast<VSlotRef*>(expr_without_cast.get());
3105
0
                    _common_expr_index_exec_status[_schema->column_id(column_slot_ref->column_id())]
3106
0
                                                  [expr.get()] = false;
3107
0
                    _common_expr_to_slotref_map[root_expr_ctx.get()][column_slot_ref->column_id()] =
3108
0
                            expr.get();
3109
0
                }
3110
0
            }
3111
3112
0
            const auto& children = expr->children();
3113
0
            for (int i = cast_set<int>(children.size()) - 1; i >= 0; --i) {
3114
0
                if (!children[i]->children().empty()) {
3115
0
                    stack.emplace(children[i]);
3116
0
                }
3117
0
            }
3118
0
        }
3119
0
    }
3120
5.63k
}
3121
3122
bool SegmentIterator::_no_need_read_key_data(ColumnId cid, MutableColumnPtr& column,
3123
43.4k
                                             size_t nrows_read) {
3124
43.4k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
3125
0
        return false;
3126
0
    }
3127
3128
43.4k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
3129
43.4k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
3130
16.3k
            _opts.enable_unique_key_merge_on_write)))) {
3131
12.0k
        return false;
3132
12.0k
    }
3133
3134
31.3k
    if (_opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
3135
31.3k
        return false;
3136
31.3k
    }
3137
3138
0
    if (!_opts.tablet_schema->column(cid).is_key()) {
3139
0
        return false;
3140
0
    }
3141
3142
0
    if (_has_delete_predicate(cid)) {
3143
0
        return false;
3144
0
    }
3145
3146
0
    if (!_check_all_conditions_passed_inverted_index_for_column(cid)) {
3147
0
        return false;
3148
0
    }
3149
3150
0
    if (column->is_nullable()) {
3151
0
        auto* nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
3152
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(nrows_read);
3153
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(nrows_read);
3154
0
    } else {
3155
0
        column->insert_many_defaults(nrows_read);
3156
0
    }
3157
3158
0
    return true;
3159
0
}
3160
3161
31.3k
bool SegmentIterator::_has_delete_predicate(ColumnId cid) {
3162
31.3k
    std::set<uint32_t> delete_columns_set;
3163
31.3k
    _opts.delete_condition_predicates->get_all_column_ids(delete_columns_set);
3164
31.3k
    return delete_columns_set.contains(cid);
3165
31.3k
}
3166
3167
23.1k
bool SegmentIterator::_can_opt_topn_reads() {
3168
23.1k
    if (_opts.topn_limit <= 0) {
3169
23.1k
        return false;
3170
23.1k
    }
3171
3172
0
    if (_opts.delete_condition_predicates->num_of_column_predicate() > 0) {
3173
0
        return false;
3174
0
    }
3175
3176
0
    bool all_true = std::ranges::all_of(_schema->column_ids(), [this](auto cid) {
3177
0
        if (cid == _opts.tablet_schema->delete_sign_idx()) {
3178
0
            return true;
3179
0
        }
3180
0
        if (_check_all_conditions_passed_inverted_index_for_column(cid, true)) {
3181
0
            return true;
3182
0
        }
3183
0
        return false;
3184
0
    });
3185
3186
0
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
3187
0
        LOG(INFO) << "col_predicates: " << _col_predicates.size() << ", all_true: " << all_true;
3188
0
    })
3189
3190
0
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_2", {
3191
0
        if (all_true) {
3192
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("topn opt 2 execute failed");
3193
0
        }
3194
0
    })
3195
3196
0
    return all_true;
3197
0
}
3198
3199
// Before get next batch. make sure all virtual columns in block has type ColumnNothing.
3200
23.1k
void SegmentIterator::_init_virtual_columns(Block* block) {
3201
23.1k
    for (const auto& pair : _vir_cid_to_idx_in_block) {
3202
0
        auto& col_with_type_and_name = block->get_by_position(pair.second);
3203
0
        col_with_type_and_name.column = ColumnNothing::create(0);
3204
0
        col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3205
0
    }
3206
23.1k
}
3207
3208
17.5k
Status SegmentIterator::_materialization_of_virtual_column(Block* block) {
3209
17.5k
    size_t prev_block_columns = block->columns();
3210
    // Some expr can not process empty block, such as function `element_at`.
3211
    // So materialize virtual column in advance to avoid errors.
3212
17.5k
    if (block->rows() == 0) {
3213
150
        for (const auto& pair : _vir_cid_to_idx_in_block) {
3214
0
            auto& col_with_type_and_name = block->get_by_position(pair.second);
3215
0
            col_with_type_and_name.column = _opts.vir_col_idx_to_type[pair.second]->create_column();
3216
0
            col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3217
0
        }
3218
150
        return Status::OK();
3219
150
    }
3220
3221
17.3k
    for (const auto& cid_and_expr : _virtual_column_exprs) {
3222
0
        auto cid = cid_and_expr.first;
3223
0
        auto column_expr = cid_and_expr.second;
3224
0
        size_t idx_in_block = _vir_cid_to_idx_in_block[cid];
3225
0
        if (block->columns() <= idx_in_block) {
3226
0
            return Status::InternalError(
3227
0
                    "Virtual column index {} is out of range, block columns {}, "
3228
0
                    "virtual columns size {}, virtual column expr {}",
3229
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3230
0
                    column_expr->root()->debug_string());
3231
0
        } else if (block->get_by_position(idx_in_block).column.get() == nullptr) {
3232
0
            return Status::InternalError(
3233
0
                    "Virtual column index {} is null, block columns {}, virtual columns size {}, "
3234
0
                    "virtual column expr {}",
3235
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3236
0
                    column_expr->root()->debug_string());
3237
0
        }
3238
0
        block->shrink_char_type_column_suffix_zero(_char_type_idx);
3239
0
        if (check_and_get_column<const ColumnNothing>(
3240
0
                    block->get_by_position(idx_in_block).column.get())) {
3241
0
            VLOG_DEBUG << fmt::format("Virtual column is doing materialization, cid {}, col idx {}",
3242
0
                                      cid, idx_in_block);
3243
0
            int result_cid = -1;
3244
0
            RETURN_IF_ERROR(column_expr->execute(block, &result_cid));
3245
3246
0
            block->replace_by_position(idx_in_block,
3247
0
                                       std::move(block->get_by_position(result_cid).column));
3248
0
            if (block->get_by_position(idx_in_block).column->size() == 0) {
3249
0
                LOG_WARNING(
3250
0
                        "Result of expr column {} is empty. cid {}, idx_in_block {}, result_cid",
3251
0
                        column_expr->root()->debug_string(), cid, idx_in_block, result_cid);
3252
0
            }
3253
0
        }
3254
0
    }
3255
    // During execution of expr, some columns may be added to the end of the block.
3256
    // Remove them to keep consistent with current block.
3257
17.3k
    block->erase_tail(prev_block_columns);
3258
17.3k
    return Status::OK();
3259
17.3k
}
3260
3261
5.63k
void SegmentIterator::_prepare_score_column_materialization() {
3262
5.63k
    if (_score_runtime == nullptr) {
3263
5.63k
        return;
3264
5.63k
    }
3265
3266
0
    ScoreRangeFilterPtr filter;
3267
0
    if (_score_runtime->has_score_range_filter()) {
3268
0
        const auto& range_info = _score_runtime->get_score_range_info();
3269
0
        filter = std::make_shared<ScoreRangeFilter>(range_info->op, range_info->threshold);
3270
0
    }
3271
3272
0
    IColumn::MutablePtr result_column;
3273
0
    auto result_row_ids = std::make_unique<std::vector<uint64_t>>();
3274
0
    if (_score_runtime->get_limit() > 0 && _col_predicates.empty() &&
3275
0
        _common_expr_ctxs_push_down.empty()) {
3276
0
        OrderType order_type = _score_runtime->is_asc() ? OrderType::ASC : OrderType::DESC;
3277
0
        _index_query_context->collection_similarity->get_topn_bm25_scores(
3278
0
                &_row_bitmap, result_column, result_row_ids, order_type,
3279
0
                _score_runtime->get_limit(), filter);
3280
0
    } else {
3281
0
        _index_query_context->collection_similarity->get_bm25_scores(&_row_bitmap, result_column,
3282
0
                                                                     result_row_ids, filter);
3283
0
    }
3284
0
    const size_t dst_col_idx = _score_runtime->get_dest_column_idx();
3285
0
    auto* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
3286
0
    auto* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
3287
0
    virtual_column_iter->prepare_materialization(std::move(result_column),
3288
0
                                                 std::move(result_row_ids));
3289
0
}
3290
3291
} // namespace segment_v2
3292
} // namespace doris