Coverage Report

Created: 2025-12-28 00:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/olap/collection_statistics.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 "collection_statistics.h"
19
20
#include "common/exception.h"
21
#include "olap/rowset/rowset.h"
22
#include "olap/rowset/rowset_reader.h"
23
#include "olap/rowset/segment_v2/index_file_reader.h"
24
#include "olap/rowset/segment_v2/index_reader_helper.h"
25
#include "olap/rowset/segment_v2/inverted_index/analyzer/analyzer.h"
26
#include "olap/rowset/segment_v2/inverted_index/util/string_helper.h"
27
#include "vec/exprs/vexpr.h"
28
#include "vec/exprs/vexpr_context.h"
29
#include "vec/exprs/vliteral.h"
30
#include "vec/exprs/vslot_ref.h"
31
32
namespace doris {
33
#include "common/compile_check_begin.h"
34
35
Status CollectionStatistics::collect(
36
        RuntimeState* state, const std::vector<RowSetSplits>& rs_splits,
37
        const TabletSchemaSPtr& tablet_schema,
38
10
        const vectorized::VExprContextSPtrs& common_expr_ctxs_push_down) {
39
10
    std::unordered_map<std::wstring, CollectInfo> collect_infos;
40
10
    RETURN_IF_ERROR(
41
10
            extract_collect_info(state, common_expr_ctxs_push_down, tablet_schema, &collect_infos));
42
43
10
    for (const auto& rs_split : rs_splits) {
44
5
        const auto& rs_reader = rs_split.rs_reader;
45
5
        auto rowset = rs_reader->rowset();
46
5
        auto rowset_meta = rowset->rowset_meta();
47
48
5
        auto num_segments = rowset->num_segments();
49
7
        for (int32_t seg_id = 0; seg_id < num_segments; ++seg_id) {
50
2
            auto seg_path = DORIS_TRY(rowset->segment_path(seg_id));
51
2
            auto status = process_segment(seg_path, rowset_meta->fs(), tablet_schema.get(),
52
2
                                          collect_infos);
53
2
            if (!status.ok()) {
54
0
                if (status.code() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND ||
55
0
                    status.code() == ErrorCode::INVERTED_INDEX_BYPASS) {
56
0
                    LOG(ERROR) << "Index statistics collection failed: " << status.to_string();
57
0
                } else {
58
0
                    return status;
59
0
                }
60
0
            }
61
2
        }
62
5
    }
63
64
10
#ifndef NDEBUG
65
10
    LOG(INFO) << "term_num_docs: " << _total_num_docs;
66
10
    for (const auto& [ws_field_name, num_tokens] : _total_num_tokens) {
67
0
        LOG(INFO) << "field_name: " << StringHelper::to_string(ws_field_name)
68
0
                  << ", num_tokens: " << num_tokens;
69
0
        for (const auto& [term, doc_freq] : _term_doc_freqs.at(ws_field_name)) {
70
0
            LOG(INFO) << "term: " << StringHelper::to_string(term) << ", doc_freq: " << doc_freq;
71
0
        }
72
0
    }
73
10
    LOG(INFO) << "--------------------------------";
74
10
#endif
75
76
10
    return Status::OK();
77
10
}
78
79
14
vectorized::VSlotRef* find_slot_ref(const vectorized::VExprSPtr& expr) {
80
14
    if (!expr) return nullptr;
81
13
    auto cur = vectorized::VExpr::expr_without_cast(expr);
82
13
    if (cur->node_type() == TExprNodeType::SLOT_REF) {
83
12
        return static_cast<vectorized::VSlotRef*>(cur.get());
84
12
    }
85
1
    for (auto& ch : cur->children()) {
86
1
        if (auto* s = find_slot_ref(ch)) return s;
87
1
    }
88
0
    return nullptr;
89
1
}
90
91
Status handle_match_pred(RuntimeState* state, const TabletSchemaSPtr& tablet_schema,
92
                         const vectorized::VExprSPtr& expr,
93
9
                         std::unordered_map<std::wstring, CollectInfo>* collect_infos) {
94
9
    auto* left_slot_ref = find_slot_ref(expr->children()[0]);
95
9
    if (left_slot_ref == nullptr) {
96
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
97
0
                "Index statistics collection failed: Cannot find slot reference in match predicate "
98
0
                "left expression");
99
0
    }
100
9
    auto* right_literal = static_cast<vectorized::VLiteral*>(expr->children()[1].get());
101
9
    DCHECK(right_literal != nullptr);
102
103
9
    const auto* sd = state->desc_tbl().get_slot_descriptor(left_slot_ref->slot_id());
104
9
    if (sd == nullptr) {
105
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
106
0
                "Index statistics collection failed: Cannot find slot descriptor for slot_id={}",
107
0
                left_slot_ref->slot_id());
108
0
    }
109
9
    int32_t col_idx = tablet_schema->field_index(left_slot_ref->column_name());
110
9
    if (col_idx == -1) {
111
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
112
0
                "Index statistics collection failed: Cannot find column index for column={}",
113
0
                left_slot_ref->column_name());
114
0
    }
115
116
9
    const auto& column = tablet_schema->column(col_idx);
117
9
    auto index_metas = tablet_schema->inverted_indexs(sd->col_unique_id(), column.suffix_path());
118
#ifndef BE_TEST
119
    if (index_metas.empty()) {
120
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
121
                "Index statistics collection failed: Score query is not supported without inverted "
122
                "index for column={}",
123
                left_slot_ref->column_name());
124
    }
125
#endif
126
127
9
    auto format_options = vectorized::DataTypeSerDe::get_default_format_options();
128
9
    format_options.timezone = &state->timezone_obj();
129
9
    for (const auto* index_meta : index_metas) {
130
0
        if (!InvertedIndexAnalyzer::should_analyzer(index_meta->properties())) {
131
0
            continue;
132
0
        }
133
0
        if (!segment_v2::IndexReaderHelper::is_need_similarity_score(expr->op(), index_meta)) {
134
0
            continue;
135
0
        }
136
137
0
        auto term_infos = InvertedIndexAnalyzer::get_analyse_result(
138
0
                right_literal->value(format_options), index_meta->properties());
139
140
0
        std::string field_name = std::to_string(index_meta->col_unique_ids()[0]);
141
0
        if (!column.suffix_path().empty()) {
142
0
            field_name += "." + column.suffix_path();
143
0
        }
144
0
        std::wstring ws_field_name = StringHelper::to_wstring(field_name);
145
0
        auto iter = collect_infos->find(ws_field_name);
146
0
        if (iter == collect_infos->end()) {
147
0
            CollectInfo collect_info;
148
0
            collect_info.term_infos.insert(term_infos.begin(), term_infos.end());
149
0
            collect_info.index_meta = index_meta;
150
0
            (*collect_infos)[ws_field_name] = std::move(collect_info);
151
0
        } else {
152
0
            iter->second.term_infos.insert(term_infos.begin(), term_infos.end());
153
0
        }
154
0
    }
155
9
    return Status::OK();
156
9
}
157
158
Status CollectionStatistics::extract_collect_info(
159
        RuntimeState* state, const vectorized::VExprContextSPtrs& common_expr_ctxs_push_down,
160
        const TabletSchemaSPtr& tablet_schema,
161
10
        std::unordered_map<std::wstring, CollectInfo>* collect_infos) {
162
10
    for (const auto& root_expr_ctx : common_expr_ctxs_push_down) {
163
10
        const auto& root_expr = root_expr_ctx->root();
164
10
        if (root_expr == nullptr) {
165
0
            continue;
166
0
        }
167
168
10
        std::stack<vectorized::VExprSPtr> stack;
169
10
        stack.emplace(root_expr);
170
171
24
        while (!stack.empty()) {
172
14
            const auto& expr = stack.top();
173
14
            stack.pop();
174
175
14
            if (expr->node_type() == TExprNodeType::MATCH_PRED) {
176
9
                RETURN_IF_ERROR(handle_match_pred(state, tablet_schema, expr, collect_infos));
177
9
            }
178
179
14
            const auto& children = expr->children();
180
37
            for (int32_t i = static_cast<int32_t>(children.size()) - 1; i >= 0; --i) {
181
23
                if (!children[i]->children().empty()) {
182
4
                    stack.emplace(children[i]);
183
4
                }
184
23
            }
185
14
        }
186
10
    }
187
10
    return Status::OK();
188
10
}
189
190
Status CollectionStatistics::process_segment(
191
        const std::string& seg_path, const io::FileSystemSPtr& fs,
192
        const TabletSchema* tablet_schema,
193
2
        const std::unordered_map<std::wstring, CollectInfo>& collect_infos) {
194
2
    auto idx_file_reader = std::make_unique<IndexFileReader>(
195
2
            fs, std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path)},
196
2
            tablet_schema->get_inverted_index_storage_format());
197
2
    RETURN_IF_ERROR(idx_file_reader->init());
198
199
2
    int32_t total_seg_num_docs = 0;
200
2
    for (const auto& [ws_field_name, collect_info] : collect_infos) {
201
0
#ifdef BE_TEST
202
0
        auto compound_reader = DORIS_TRY(idx_file_reader->open(collect_info.index_meta, nullptr));
203
0
        auto* reader = lucene::index::IndexReader::open(compound_reader.get());
204
0
        auto index_searcher = std::make_shared<lucene::search::IndexSearcher>(reader, true);
205
206
0
        auto* index_reader = index_searcher->getReader();
207
#else
208
        InvertedIndexCacheHandle inverted_index_cache_handle;
209
        auto index_file_key = idx_file_reader->get_index_file_cache_key(collect_info.index_meta);
210
        InvertedIndexSearcherCache::CacheKey searcher_cache_key(index_file_key);
211
        if (!InvertedIndexSearcherCache::instance()->lookup(searcher_cache_key,
212
                                                            &inverted_index_cache_handle)) {
213
            auto compound_reader =
214
                    DORIS_TRY(idx_file_reader->open(collect_info.index_meta, nullptr));
215
            auto* reader = lucene::index::IndexReader::open(compound_reader.get());
216
            size_t reader_size = reader->getTermInfosRAMUsed();
217
            auto index_searcher = std::make_shared<lucene::search::IndexSearcher>(reader, true);
218
            auto* cache_value = new InvertedIndexSearcherCache::CacheValue(
219
                    std::move(index_searcher), reader_size, UnixMillis());
220
            InvertedIndexSearcherCache::instance()->insert(searcher_cache_key, cache_value,
221
                                                           &inverted_index_cache_handle);
222
        }
223
224
        auto searcher_variant = inverted_index_cache_handle.get_index_searcher();
225
        auto index_searcher = std::get<FulltextIndexSearcherPtr>(searcher_variant);
226
        auto* index_reader = index_searcher->getReader();
227
#endif
228
229
0
        total_seg_num_docs = std::max(total_seg_num_docs, index_reader->maxDoc());
230
0
        _total_num_tokens[ws_field_name] +=
231
0
                index_reader->sumTotalTermFreq(ws_field_name.c_str()).value_or(0);
232
233
0
        for (const auto& term_info : collect_info.term_infos) {
234
0
            auto iter = TermIterator::create(nullptr, false, index_reader, ws_field_name,
235
0
                                             term_info.get_single_term());
236
0
            _term_doc_freqs[ws_field_name][iter->term()] += iter->doc_freq();
237
0
        }
238
0
    }
239
2
    _total_num_docs += total_seg_num_docs;
240
2
    return Status::OK();
241
2
}
242
243
uint64_t CollectionStatistics::get_term_doc_freq_by_col(const std::wstring& lucene_col_name,
244
22
                                                        const std::wstring& term) {
245
22
    if (!_term_doc_freqs.contains(lucene_col_name)) {
246
1
        throw Exception(ErrorCode::INVERTED_INDEX_CLUCENE_ERROR,
247
1
                        "Index statistics collection failed: Not such column {}",
248
1
                        StringHelper::to_string(lucene_col_name));
249
1
    }
250
251
21
    if (!_term_doc_freqs[lucene_col_name].contains(term)) {
252
0
        throw Exception(ErrorCode::INVERTED_INDEX_CLUCENE_ERROR,
253
0
                        "Index statistics collection failed: Not such term {}",
254
0
                        StringHelper::to_string(term));
255
0
    }
256
257
21
    return _term_doc_freqs[lucene_col_name][term];
258
21
}
259
260
12
uint64_t CollectionStatistics::get_total_term_cnt_by_col(const std::wstring& lucene_col_name) {
261
12
    if (!_total_num_tokens.contains(lucene_col_name)) {
262
2
        throw Exception(ErrorCode::INVERTED_INDEX_CLUCENE_ERROR,
263
2
                        "Index statistics collection failed: Not such column {}",
264
2
                        StringHelper::to_string(lucene_col_name));
265
2
    }
266
267
10
    return _total_num_tokens[lucene_col_name];
268
12
}
269
270
31
uint64_t CollectionStatistics::get_doc_num() const {
271
31
    if (_total_num_docs == 0) {
272
3
        throw Exception(
273
3
                ErrorCode::INVERTED_INDEX_CLUCENE_ERROR,
274
3
                "Index statistics collection failed: No data available for SimilarityCollector");
275
3
    }
276
277
28
    return _total_num_docs;
278
31
}
279
280
11
float CollectionStatistics::get_or_calculate_avg_dl(const std::wstring& lucene_col_name) {
281
11
    auto iter = _avg_dl_by_col.find(lucene_col_name);
282
11
    if (iter != _avg_dl_by_col.end()) {
283
2
        return iter->second;
284
2
    }
285
286
9
    const uint64_t total_term_cnt = get_total_term_cnt_by_col(lucene_col_name);
287
9
    const uint64_t total_doc_cnt = get_doc_num();
288
9
    float avg_dl = total_doc_cnt > 0 ? float((double)total_term_cnt / (double)total_doc_cnt) : 0.0F;
289
9
    _avg_dl_by_col[lucene_col_name] = avg_dl;
290
9
    return avg_dl;
291
11
}
292
293
float CollectionStatistics::get_or_calculate_idf(const std::wstring& lucene_col_name,
294
21
                                                 const std::wstring& term) {
295
21
    auto iter = _idf_by_col_term.find(lucene_col_name);
296
21
    if (iter != _idf_by_col_term.end()) {
297
12
        auto term_iter = iter->second.find(term);
298
12
        if (term_iter != iter->second.end()) {
299
1
            return term_iter->second;
300
1
        }
301
12
    }
302
303
20
    const uint64_t doc_num = get_doc_num();
304
20
    const uint64_t doc_freq = get_term_doc_freq_by_col(lucene_col_name, term);
305
20
    auto idf = (float)std::log(1 + ((double)doc_num - (double)doc_freq + (double)0.5) /
306
20
                                           ((double)doc_freq + (double)0.5));
307
20
    _idf_by_col_term[lucene_col_name][term] = idf;
308
20
    return idf;
309
21
}
310
311
#include "common/compile_check_end.h"
312
} // namespace doris