This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 7df132022a9 branch-4.2: [fix](be) Preserve BM25 statistics through 
CLucene compaction #69313 (#70887)
7df132022a9 is described below

commit 7df132022a938e3821000702072a05defbfbcd42
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Wed Dec 2 11:04:36 2026 +0800

    branch-4.2: [fix](be) Preserve BM25 statistics through CLucene compaction 
#69313 (#70887)
    
    Cherry-picked from #69313
    
    Co-authored-by: arthur.xqw <[email protected]>
---
 be/src/storage/compaction/compaction.cpp           |  21 +++++
 .../clucene/compaction/index_compaction_test.cpp   |  92 ++++++++++++++----
 contrib/clucene                                    |   2 +-
 .../test_bm25_compaction_statistics.groovy         | 104 +++++++++++++++++++++
 4 files changed, 200 insertions(+), 19 deletions(-)

diff --git a/be/src/storage/compaction/compaction.cpp 
b/be/src/storage/compaction/compaction.cpp
index 41148d56b12..bf434bc6e99 100644
--- a/be/src/storage/compaction/compaction.cpp
+++ b/be/src/storage/compaction/compaction.cpp
@@ -65,6 +65,8 @@
 #include "storage/index/index_file_reader.h"
 #include "storage/index/index_file_writer.h"
 #include "storage/index/index_fs_directory.h"
+#include "storage/index/inverted/analysis/analyzer/analyzer.h"
+#include "storage/index/inverted/analysis/inverted_index_parser.h"
 #include "storage/index/inverted/clucene/inverted_index_compaction.h"
 #include "storage/index/inverted/common/inverted_index_desc.h"
 #include "storage/index/inverted/reader/collection_statistics.h"
@@ -1614,6 +1616,25 @@ void 
Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
             continue;
         }
 
+        // A norms-bearing index without term frequencies cannot reconstruct 
its exact
+        // token count after rows are removed or split across destination 
segments.
+        // Byte norms are lossy (for example, length 41 decodes as 40), so 
rebuild from
+        // the raw column. CLucene compaction is selected per column: a 
sibling index
+        // must not re-enable native merging for this column later in this 
loop.
+        const auto column_indexes = 
_cur_tablet_schema->inverted_indexs(col_unique_id);
+        const bool needs_norms_rebuild =
+                std::ranges::any_of(column_indexes, [](const TabletIndex* 
column_index) {
+                    return 
segment_v2::inverted_index::InvertedIndexAnalyzer::should_analyzer(
+                                   column_index->properties()) &&
+                           should_write_index_norms(*column_index) &&
+                           get_parser_phrase_support_string_from_properties(
+                                   column_index->properties()) !=
+                                   INVERTED_INDEX_PARSER_PHRASE_SUPPORT_YES;
+                });
+        if (needs_norms_rebuild) {
+            continue;
+        }
+
         // if index properties are different, index compaction maybe needs to 
be skipped.
         bool is_continue = false;
         std::optional<std::map<std::string, std::string>> first_properties;
diff --git 
a/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp 
b/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
index c9b70770326..1adf7570078 100644
--- 
a/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
+++ 
b/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
@@ -18,6 +18,7 @@
 #include <gmock/gmock.h>
 
 #include <iterator>
+#include <set>
 
 #include "storage/index/index_writer.h"
 #include 
"storage/index/inverted/clucene/compaction/util/index_compaction_utils.h"
@@ -92,7 +93,7 @@ protected:
     IndexCompactionTest() = default;
     ~IndexCompactionTest() override = default;
 
-    void _build_tablet() {
+    void _build_tablet(bool support_phrase = true) {
         // tablet_schema
         TabletSchemaPB schema_pb;
         schema_pb.set_keys_type(KeysType::DUP_KEYS);
@@ -104,6 +105,10 @@ protected:
                                                "v1_index", 1, "STRING", "v1");
         std::map<std::string, std::string> properties;
         properties.emplace(INVERTED_INDEX_PARSER_KEY, 
INVERTED_INDEX_PARSER_UNICODE);
+        // Native compaction needs stored frequencies for this norms-bearing 
index.
+        properties.emplace(INVERTED_INDEX_PARSER_PHRASE_SUPPORT_KEY,
+                           support_phrase ? 
INVERTED_INDEX_PARSER_PHRASE_SUPPORT_YES
+                                          : 
INVERTED_INDEX_PARSER_PHRASE_SUPPORT_NO);
         IndexCompactionUtils::construct_column(schema_pb.add_column(), 
schema_pb.add_index(), 10002,
                                                "v2_index", 2, "STRING", "v2", 
properties);
         IndexCompactionUtils::construct_column(schema_pb.add_column(), 
schema_pb.add_index(), 10003,
@@ -577,6 +582,15 @@ protected:
         EXPECT_TRUE(_tablet->init().ok());
     }
 
+    static void _check_wiki_native_columns(const RowsetWriterContext& ctx) {
+        // Phrase-enabled analyzed columns and untokenized columns merge 
natively.
+        // The phrase-disabled groups (5-8, 13-16, 21-24, 29-32) rebuild their 
norms.
+        // Selection precedes row filtering, so this also holds when every row 
is deleted.
+        const std::set<int32_t> native_columns = {0,  1,  2,  3,  4,  9,  10, 
11, 12, 17, 18,
+                                                  19, 20, 25, 26, 27, 28, 33, 
34, 35, 36};
+        EXPECT_EQ(ctx.columns_to_do_index_compaction, native_columns);
+    }
+
     void _run_normal_wiki_test(bool with_delete = false, const std::string& 
delete_pred = "",
                                int64_t max_rows_per_segment = 100000,
                                int output_rowset_segment_number = 1) {
@@ -623,17 +637,11 @@ protected:
             if (keys_type == KeysType::UNIQUE_KEYS) {
                 
EXPECT_EQ(compaction._cur_tablet_schema->inverted_indexes().size(),
                           _tablet_schema->num_columns() - 1);
-                EXPECT_EQ(ctx.columns_to_do_index_compaction.size(),
-                          _tablet_schema->num_columns() - 1);
             } else {
                 
EXPECT_EQ(compaction._cur_tablet_schema->inverted_indexes().size(),
                           _tablet_schema->num_columns());
-                EXPECT_EQ(ctx.columns_to_do_index_compaction.size(), 
_tablet_schema->num_columns());
             }
-            EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(0));
-            EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(1));
-            EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(2));
-            EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(3));
+            _check_wiki_native_columns(ctx);
             EXPECT_EQ(compaction._output_rowset->num_segments(), 
output_rowset_segment_number)
                     << compaction._output_rowset->num_segments();
         };
@@ -882,6 +890,62 @@ TEST_F(IndexCompactionTest, tes_write_index_normally) {
     IndexCompactionUtils::check_meta_and_file(output_rowset_normal, 
_tablet_schema, query_map);
 }
 
+TEST_F(IndexCompactionTest, test_phrase_disabled_index_rebuilds_from_column) {
+    _build_tablet(false);
+    
ASSERT_TRUE(io::global_local_filesystem()->delete_directory(_tablet->tablet_path()).ok());
+    
ASSERT_TRUE(io::global_local_filesystem()->create_directory(_tablet->tablet_path()).ok());
+    const std::vector<std::string> data_files = {
+            _current_dir + "/be/test/storage/index/inverted/data/data1.csv",
+            _current_dir + "/be/test/storage/index/inverted/data/data2.csv"};
+    std::vector<RowsetSharedPtr> rowsets(data_files.size());
+    auto check_indexes = [](const int32_t& size) { EXPECT_EQ(size, 4); };
+    IndexCompactionUtils::build_rowsets<IndexCompactionUtils::DataRow>(
+            _data_dir, _tablet_schema, _tablet, _engine_ref, rowsets, 
data_files, _inc_id,
+            check_indexes);
+
+    auto check_native_columns = [](const BaseCompaction& compaction,
+                                   const RowsetWriterContext& ctx) {
+        // The untokenized column still merges natively; the Unicode column 
must rebuild.
+        EXPECT_EQ(ctx.columns_to_do_index_compaction, (std::set<int32_t> {1}));
+        EXPECT_EQ(compaction._output_rowset->num_segments(), 1);
+    };
+    RowsetSharedPtr output_rowset_index;
+    auto st = IndexCompactionUtils::do_compaction(rowsets, _engine_ref, 
_tablet, true,
+                                                  output_rowset_index, 
check_native_columns);
+    ASSERT_TRUE(st.ok()) << st.to_string();
+
+    auto check_raw_rebuild = [](const BaseCompaction& compaction, const 
RowsetWriterContext& ctx) {
+        EXPECT_TRUE(ctx.columns_to_do_index_compaction.empty());
+        EXPECT_EQ(compaction._output_rowset->num_segments(), 1);
+    };
+    RowsetSharedPtr output_rowset_normal;
+    st = IndexCompactionUtils::do_compaction(rowsets, _engine_ref, _tablet, 
false,
+                                             output_rowset_normal, 
check_raw_rebuild);
+    ASSERT_TRUE(st.ok()) << st.to_string();
+
+    const auto& index_path = output_rowset_index->segment_path(0);
+    ASSERT_TRUE(index_path.has_value()) << index_path.error();
+    auto index_reader = IndexCompactionUtils::init_index_file_reader(
+            output_rowset_index, index_path.value(),
+            _tablet_schema->get_inverted_index_storage_format());
+    const auto& normal_path = output_rowset_normal->segment_path(0);
+    ASSERT_TRUE(normal_path.has_value()) << normal_path.error();
+    auto normal_reader = IndexCompactionUtils::init_index_file_reader(
+            output_rowset_normal, normal_path.value(),
+            _tablet_schema->get_inverted_index_storage_format());
+    auto index_dir = index_reader->_open(10002, "");
+    ASSERT_TRUE(index_dir.has_value()) << index_dir.error();
+    auto normal_dir = normal_reader->_open(10002, "");
+    ASSERT_TRUE(normal_dir.has_value()) << normal_dir.error();
+    st = IndexCompactionUtils::check_idx_file_correctness(index_dir->get(), 
normal_dir->get());
+    EXPECT_TRUE(st.ok()) << st.to_string();
+
+    const std::map<int, QueryData> query_map = {
+            {2, {{"musicstream.com", "http", "https", "null"}, {191, 799, 
1201, 0}}}};
+    IndexCompactionUtils::check_meta_and_file(output_rowset_index, 
_tablet_schema, query_map);
+    IndexCompactionUtils::check_meta_and_file(output_rowset_normal, 
_tablet_schema, query_map);
+}
+
 TEST_F(IndexCompactionTest, test_col_unique_ids_empty) {
     _build_tablet();
     // clear column unique id in tablet index 10001 and rebuild tablet_schema
@@ -1490,11 +1554,7 @@ TEST_F(IndexCompactionTest, 
tes_wikipedia_dup_v2_with_total_delete) {
                                      const RowsetWriterContext& ctx) {
         EXPECT_EQ(compaction._cur_tablet_schema->inverted_indexes().size(),
                   _tablet_schema->num_columns());
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.size() == 
_tablet_schema->num_columns());
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(0));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(1));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(2));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(3));
+        _check_wiki_native_columns(ctx);
         EXPECT_TRUE(compaction._output_rowset->num_segments() == 0);
     };
 
@@ -1563,11 +1623,7 @@ TEST_F(IndexCompactionTest, 
tes_wikipedia_mow_v2_with_total_delete) {
                                      const RowsetWriterContext& ctx) {
         EXPECT_EQ(compaction._cur_tablet_schema->inverted_indexes().size(),
                   _tablet_schema->num_columns() - 1);
-        EXPECT_EQ(ctx.columns_to_do_index_compaction.size(), 
_tablet_schema->num_columns() - 1);
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(0));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(1));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(2));
-        EXPECT_TRUE(ctx.columns_to_do_index_compaction.contains(3));
+        _check_wiki_native_columns(ctx);
         EXPECT_TRUE(compaction._output_rowset->num_segments() == 0);
     };
 
diff --git a/contrib/clucene b/contrib/clucene
index 08d45e541fe..f2864e07f08 160000
--- a/contrib/clucene
+++ b/contrib/clucene
@@ -1 +1 @@
-Subproject commit 08d45e541fef1e48dc4ab00d2d5fde9569b49ee3
+Subproject commit f2864e07f08583b5cc948e87e82294fd0fd5de16
diff --git 
a/regression-test/suites/inverted_index_p0/index_compaction/test_bm25_compaction_statistics.groovy
 
b/regression-test/suites/inverted_index_p0/index_compaction/test_bm25_compaction_statistics.groovy
new file mode 100644
index 00000000000..112435b69cf
--- /dev/null
+++ 
b/regression-test/suites/inverted_index_p0/index_compaction/test_bm25_compaction_statistics.groovy
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Compare compacted indexes with independently rebuilt indexes. Exact scores 
are
+// data-dependent; equivalence avoids pinning the BM25 formula in a golden 
file.
+suite("test_bm25_compaction_statistics", "p0,nonConcurrent") {
+    setBeConfigTemporary(["inverted_index_compaction_enable": "true"]) {
+        for (String format : ["V2", "V3"]) {
+            for (String phrase : ["true", "false"]) {
+                for (String history : ["dup_delete", "mow_light_delete", 
"mow_bitmap_delete",
+                                       "delete_sign", "overwrite"]) {
+                    // Eligibility is tracked per column: either ordering of a 
frequency-bearing
+                    // sibling must still rebuild when another index of that 
column has no frequencies.
+                    def layouts = phrase == "false" && history == "dup_delete" 
?
+                            ["single", "mixed_first", "mixed_last"] : 
["single"]
+                    for (String layout : layouts) {
+                        String prefix = 
"bm25_compaction_${format.toLowerCase()}_${phrase}_${history}_${layout}"
+                        String clean = "${prefix}_clean"
+                        String compacted = "${prefix}_history"
+                        String keyType = history == "dup_delete" ? "DUPLICATE" 
: "UNIQUE"
+                        String mowProperties = history == "dup_delete" ? "" : 
"""
+                            "enable_unique_key_merge_on_write"="true",
+                            "enable_mow_light_delete"="${history == 
'mow_light_delete'}",
+                        """
+                        String indexes = """INDEX body_idx(body) USING INVERTED
+                            PROPERTIES("parser"="english", 
"support_phrase"="${phrase}")"""
+                        if (layout != "single") {
+                            String sibling = """INDEX sibling_idx(body) USING 
INVERTED
+                                PROPERTIES("parser"="unicode", 
"support_phrase"="true")"""
+                            indexes = layout == "mixed_first" ? "${sibling}, 
${indexes}" : "${indexes}, ${sibling}"
+                        }
+                        for (String table : [clean, compacted]) {
+                            sql "DROP TABLE IF EXISTS ${table}"
+                            sql """CREATE TABLE ${table} (
+                                id INT, body TEXT,
+                                ${indexes}
+                            ) ENGINE=OLAP ${keyType} KEY(id)
+                            DISTRIBUTED BY HASH(id) BUCKETS 1
+                            PROPERTIES("replication_num"="1", 
"disable_auto_compaction"="true",
+                                       ${mowProperties}
+                                       
"inverted_index_storage_format"="${format}")"""
+                        }
+                        String visible = "(1, 'alpha'), (2, CONCAT('alpha 
alpha ', REPEAT('omega ', 14)))"
+                        sql "INSERT INTO ${clean} VALUES ${visible}"
+                        // Both source rowsets retain a document and discard a 
long document.
+                        // This exercises posting remapping, not just dropping 
a whole rowset.
+                        for (int batch = 0; batch < 2; ++batch) {
+                            String body = batch == 0 ? "'alpha'" :
+                                "CONCAT('alpha alpha ', REPEAT('omega ', 14))"
+                            String deletedBody = "CONCAT(REPEAT('alpha ', 
240), REPEAT('omega ', 16))"
+                            if (history == "delete_sign") {
+                                sql """INSERT INTO ${compacted}(id, body, 
__DORIS_DELETE_SIGN__)
+                                    VALUES (${batch + 1}, ${body}, 0), 
(${batch + 100}, ${deletedBody}, 1)"""
+                            } else {
+                                sql """INSERT INTO ${compacted} VALUES
+                                    (${batch + 1}, ${body}), (${batch + 100}, 
${deletedBody})"""
+                            }
+                        }
+                        if (history == "overwrite") {
+                            sql "INSERT INTO ${compacted} VALUES (100, 
'omega'), (101, 'omega')"
+                            sql "INSERT INTO ${clean} VALUES (100, 'omega'), 
(101, 'omega')"
+                        } else if (history != "delete_sign") {
+                            sql "DELETE FROM ${compacted} WHERE id >= 100"
+                        }
+                        sql "SYNC"
+                        def visibleRows = sql "SELECT * FROM ${clean} ORDER BY 
id"
+                        assertEquals(visibleRows, sql("SELECT * FROM 
${compacted} ORDER BY id"))
+                        trigger_and_wait_compaction(compacted, "full")
+                        assertEquals(visibleRows, sql("SELECT * FROM 
${compacted} ORDER BY id"))
+                        for (String predicate : ["SEARCH('body:alpha')", "body 
MATCH_ANY 'alpha'"]) {
+                            // MATCH_ANY can return equal scores without 
stored frequencies.
+                            // Compare all hits in that case; TopK among ties 
is unspecified.
+                            def limits = phrase == "false" && predicate == 
"body MATCH_ANY 'alpha'" ?
+                                ["LIMIT 10"] : ["LIMIT 10", "LIMIT 1", "LIMIT 
1 OFFSET 1"]
+                            for (String limit : limits) {
+                                def scored = { String table ->
+                                    sql """SELECT id, ROUND(s, 6) FROM (
+                                        SELECT id, score() AS s FROM ${table} 
WHERE ${predicate}
+                                        ORDER BY s DESC ${limit}) ranked ORDER 
BY id"""
+                                }
+                                assertEquals(scored(clean), scored(compacted),
+                                    "${format}, support_phrase=${phrase}, 
${history}, ${layout}, ${predicate}, ${limit}")
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to