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

airborne12 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 7eef244a412 [improvement](be) Cut the cost around ICU's break iterator 
in the icu tokenizer (#70267)
7eef244a412 is described below

commit 7eef244a412e711ad3d54fe844c9217e7b14b0eb
Author: Jack <[email protected]>
AuthorDate: Sun Nov 22 11:27:41 2026 +0800

    [improvement](be) Cut the cost around ICU's break iterator in the icu 
tokenizer (#70267)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: #70266 (depends on)
    
    Problem Summary: Cut the per-character work around ICU's break iterator
    in the icu tokenizer: about 2.1x as fast on mixed text and 1.5x on
    Chinese and Japanese, with the same tokens.
---
 .../index/inverted/analysis/analyzer/analyzer.cpp  |  18 +-
 .../tokenizer/icu/break_iterator_wrapper.cpp       |  89 +----
 .../tokenizer/icu/break_iterator_wrapper.h         |  60 +++-
 .../tokenizer/icu/composite_break_iterator.cpp     |  58 +---
 .../tokenizer/icu/composite_break_iterator.h       |  44 ++-
 .../tokenizer/icu/default_icu_tokenizer_config.cpp |   6 +-
 .../tokenizer/icu/default_icu_tokenizer_config.h   |   7 +-
 .../analysis/tokenizer/icu/icu_char_table.cpp      |  79 +++++
 .../analysis/tokenizer/icu/icu_char_table.h        |  79 +++++
 .../inverted/analysis/tokenizer/icu/icu_common.h   |  10 -
 .../analysis/tokenizer/icu/icu_tokenizer.cpp       | 200 +++++++++--
 .../analysis/tokenizer/icu/icu_tokenizer.h         |  52 ++-
 .../analysis/tokenizer/icu/icu_tokenizer_config.h  |   1 -
 .../analysis/tokenizer/icu/icu_tokenizer_factory.h |   9 +-
 .../analysis/tokenizer/icu/script_iterator.cpp     | 119 +++----
 .../analysis/tokenizer/icu/script_iterator.h       |  29 +-
 .../analysis/tokenizer/icu_char_table_test.cpp     | 124 +++++++
 .../analysis/tokenizer/icu_tokenizer_test.cpp      | 372 +++++++++++++++++++++
 18 files changed, 1051 insertions(+), 305 deletions(-)

diff --git a/be/src/storage/index/inverted/analysis/analyzer/analyzer.cpp 
b/be/src/storage/index/inverted/analysis/analyzer/analyzer.cpp
index ef7b1eefdc5..7540e5e5cd7 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/analyzer.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/analyzer.cpp
@@ -30,7 +30,6 @@
 #include 
"storage/index/inverted/analysis/char_filter/char_replace_char_filter_factory.h"
 #include "storage/index/inverted/analysis/gram/gram_scheme.h"
 #include "storage/index/inverted/analysis/token_filter/lower_case_filter.h"
-#include 
"storage/index/inverted/analysis/token_filter/lower_case_filter_factory.h"
 #include 
"storage/index/inverted/analysis/tokenizer/basic/basic_tokenizer_factory.h"
 #include "storage/index/inverted/analysis/tokenizer/byte_classifier.h"
 #include 
"storage/index/inverted/analysis/tokenizer/english/english_tokenizer.h"
@@ -173,16 +172,6 @@ bool builtin_lowercase(const std::string& lower_case, bool 
parser_default) {
     return parser_default;
 }
 
-// `tokenizer`, followed by the lowercase filter when `lowercase`.
-TextAnalyzerPtr tokenizer_chain(TokenizerFactoryPtr tokenizer, bool lowercase) 
{
-    std::vector<TokenFilterFactoryPtr> token_filters;
-    if (lowercase) {
-        token_filters.push_back(std::make_shared<LowerCaseFilterFactory>());
-    }
-    return std::make_shared<ChainAnalyzer>(std::vector<CharFilterFactoryPtr> 
{},
-                                           std::move(tokenizer), 
std::move(token_filters));
-}
-
 // The builtin parsers lowercase by default, except chinese; stop_words only 
applies to the
 // standard tokenizer.
 TextAnalyzerPtr build_builtin_analyzer(InvertedIndexParserType parser_type,
@@ -207,8 +196,11 @@ TextAnalyzerPtr 
build_builtin_analyzer(InvertedIndexParserType parser_type,
                 std::vector<TokenFilterFactoryPtr> {});
     }
     if (parser_type == InvertedIndexParserType::PARSER_ICU) {
-        return tokenizer_chain(std::make_shared<ICUTokenizerFactory>(),
-                               builtin_lowercase(lower_case, true));
+        // The tokenizer lowercases its own terms as the lowercase filter did.
+        return std::make_shared<ChainAnalyzer>(
+                std::vector<CharFilterFactoryPtr> {},
+                
std::make_shared<ICUTokenizerFactory>(builtin_lowercase(lower_case, true)),
+                std::vector<TokenFilterFactoryPtr> {});
     }
     if (parser_type == InvertedIndexParserType::PARSER_BASIC) {
         // The tokenizer lowercases its own tokens, which are all a lowercase 
filter would change.
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.cpp
 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.cpp
index ba42a1bda65..eef695a89c0 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.cpp
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.cpp
@@ -17,91 +17,28 @@
 
 #include 
"storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.h"
 
-#include <unicode/unistr.h>
-
-#include <mutex>
-#include <string>
-
-#include "storage/index/inverted/analysis/tokenizer/icu/icu_common.h"
-#include "storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h"
+#include "common/check.h"
 
 namespace doris::segment_v2::inverted_index {
 
-icu::UnicodeSet BreakIteratorWrapper::EMOJI_RK;
-icu::UnicodeSet BreakIteratorWrapper::EMOJI;
-
-BreakIteratorWrapper::BreakIteratorWrapper(icu::BreakIterator* rbbi) : 
rbbi_(rbbi) {}
-
-void BreakIteratorWrapper::initialize() {
-    static std::once_flag once_flag;
-    std::call_once(once_flag, []() {
-        UErrorCode status = U_ZERO_ERROR;
-        EMOJI_RK.applyPattern("[*#0-9©®™〰〽]", status);
-        if (U_FAILURE(status)) {
-            std::string error_msg = "EMOJI RK failed to initialize: ";
-            error_msg += u_errorName(status);
-            throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, 
error_msg);
-        }
-        EMOJI.applyPattern("[[:Emoji:][:Extended_Pictographic:]]", status);
-        if (U_FAILURE(status)) {
-            std::string error_msg = "EMOJI failed to initialize: ";
-            error_msg += u_errorName(status);
-            throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, 
error_msg);
-        }
-    });
-}
-
-int32_t BreakIteratorWrapper::next() {
-    int32_t current = rbbi_->current();
-    int32_t next = rbbi_->next();
-    status_ = calc_status(current, next);
-    return next;
-}
-
-int32_t BreakIteratorWrapper::calc_status(int32_t current, int32_t next) {
-    if (next != UBRK_DONE && is_emoji(current, next)) {
-        return ICUTokenizerConfig::EMOJI_SEQUENCE_STATUS;
-    } else {
-        return rbbi_->getRuleStatus();
-    }
-}
+BreakIteratorWrapper::BreakIteratorWrapper(icu::BreakIterator* rbbi)
+        : table_(ICUCharTable::instance()), rbbi_(rbbi) {}
 
-bool BreakIteratorWrapper::is_emoji(int32_t current, int32_t next) {
-    int32_t begin = start_ + current;
-    int32_t end = start_ + next;
-    UChar32 codepoint = 0;
-    U16_GET(text_, 0, begin, end, codepoint);
-    if (EMOJI.contains(codepoint)) {
-        if (EMOJI_RK.contains(codepoint)) {
-            int32_t trailer = begin + U16_LENGTH(codepoint);
-            return trailer < end && (text_[trailer] == 0xFE0F || 
text_[trailer] == 0x20E3);
-        } else {
-            return true;
-        }
-    }
-    return false;
-}
-
-void BreakIteratorWrapper::set_text(const UChar* text, int32_t start, int32_t 
length) {
+void BreakIteratorWrapper::set_text(UText* utext, const UChar* text, int32_t 
start,
+                                    int32_t length) {
     text_ = text;
     start_ = start;
 
+    // Neither fails: `utext` is a valid UText that needs no allocation, and 
the range lies in the
+    // text.
     UErrorCode status = U_ZERO_ERROR;
-    UTextPtr utext(utext_openUChars(nullptr, text + start, length, &status));
-    if (U_FAILURE(status)) {
-        std::string error_msg = "Failed to create UText: ";
-        error_msg += u_errorName(status);
-        throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, error_msg);
-    }
-
-    rbbi_->setText(utext.get(), status);
-    if (U_FAILURE(status)) {
-        std::string error_msg = "Failed to set text: ";
-        error_msg += u_errorName(status);
-        throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, error_msg);
-    }
+    utext_openUChars(utext, text + start, length, &status);
+    rbbi_->setText(utext, status);
+    DORIS_CHECK(U_SUCCESS(status));
 
+    // setText() moved the iterator to the first boundary.
+    position_ = 0;
     status_ = UBRK_WORD_NONE;
 }
 
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.h
index 1f8558449e0..b32ec5bdb9d 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.h
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/break_iterator_wrapper.h
@@ -19,36 +19,74 @@
 
 #include <unicode/umachine.h>
 #include <unicode/utext.h>
+#include <unicode/utf16.h>
 
 #include <memory>
-#include <unordered_set>
 
+#include "common/compiler_util.h"
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h"
 #include "storage/index/inverted/analysis/tokenizer/icu/icu_common.h"
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h"
 
 namespace doris::segment_v2::inverted_index {
 
+// A break iterator of one script, whose rule status after next() is 
EMOJI_SEQUENCE_STATUS when
+// the text from the previous boundary starts with an emoji. next() runs for 
every boundary of the
+// value, so it is inline and keeps the previous boundary itself instead of 
asking the iterator.
 class BreakIteratorWrapper {
 public:
-    BreakIteratorWrapper(icu::BreakIterator* rbbi);
+    explicit BreakIteratorWrapper(icu::BreakIterator* rbbi);
     ~BreakIteratorWrapper() = default;
 
-    void initialize();
-    int32_t current() { return rbbi_->current(); }
     int32_t get_rule_status() const { return status_; }
-    int32_t next();
-    int32_t calc_status(int32_t current, int32_t next);
-    bool is_emoji(int32_t current, int32_t next);
-    void set_text(const UChar* text, int32_t start, int32_t length);
+
+    // The next boundary in the range, or UBRK_DONE after the last one. Forced 
inline into
+    // CompositeBreakIterator::next(), its one caller.
+    ALWAYS_INLINE int32_t next() {
+        const int32_t next = rbbi_->next();
+        if (next != UBRK_DONE && is_emoji(position_, next)) {
+            status_ = ICUTokenizerConfig::EMOJI_SEQUENCE_STATUS;
+        } else {
+            status_ = rbbi_->getRuleStatus();
+        }
+        if (next != UBRK_DONE) {
+            position_ = next;
+        }
+        return next;
+    }
+
+    // Breaks [start, start + length) of `text` from now on. `utext` is 
reopened over that range
+    // and may be reopened again right after: the iterator keeps a shallow 
clone of it, so one
+    // UText serves every iterator of a stream and none is allocated per range.
+    void set_text(UText* utext, const UChar* text, int32_t start, int32_t 
length);
 
 private:
-    static icu::UnicodeSet EMOJI_RK;
-    static icu::UnicodeSet EMOJI;
+    // Whether the text [current, next) of the range starts with an emoji. "#" 
alone is no emoji,
+    // "#" U+FE0F U+20E3 is. Forced inline: the compiler kept it out of line, 
a call for every
+    // boundary.
+    ALWAYS_INLINE bool is_emoji(int32_t current, int32_t next) const {
+        int32_t begin = start_ + current;
+        const int32_t end = start_ + next;
+        UChar32 codepoint = 0;
+        U16_GET(text_, 0, begin, end, codepoint);
+        if (!table_.is_emoji(codepoint)) {
+            return false;
+        }
+        if (table_.is_emoji_rk(codepoint)) {
+            const int32_t trailer = begin + U16_LENGTH(codepoint);
+            return trailer < end && (text_[trailer] == 0xFE0F || 
text_[trailer] == 0x20E3);
+        }
+        return true;
+    }
 
+    const ICUCharTable& table_;
     BreakIteratorPtr rbbi_;
     const UChar* text_ = nullptr;
     int32_t start_ = 0;
+    // The last boundary, relative to the range: what the iterator's current() 
would say.
+    int32_t position_ = 0;
     int32_t status_ = UBRK_WORD_NONE;
 };
 using BreakIteratorWrapperPtr = std::unique_ptr<BreakIteratorWrapper>;
 
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.cpp
 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.cpp
index 9c55eea6080..2e8f8aa2a5c 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.cpp
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.cpp
@@ -17,67 +17,41 @@
 
 #include 
"storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h"
 
-#include <unicode/unistr.h>
+#include <unicode/uchar.h>
 
 #include <memory>
+#include <utility>
 
 namespace doris::segment_v2::inverted_index {
 
-CompositeBreakIterator::CompositeBreakIterator(const ICUTokenizerConfigPtr& 
config)
-        : config_(config) {
-    scriptIterator_ = std::make_unique<ScriptIterator>(config->combine_cj());
+CompositeBreakIterator::CompositeBreakIterator(ICUTokenizerConfigPtr config)
+        : config_(std::move(config)) {
     word_breakers_.resize(u_getIntPropertyMaxValue(UCHAR_SCRIPT) + 1);
 }
 
-void CompositeBreakIterator::initialize() {
-    scriptIterator_->initialize();
-}
-
-int32_t CompositeBreakIterator::next() {
-    int32_t next = rbbi_->next();
-    while (next == UBRK_DONE && scriptIterator_->next()) {
-        rbbi_ = get_break_iterator(scriptIterator_->get_script_code());
-        rbbi_->set_text(text_, scriptIterator_->get_script_start(),
-                        scriptIterator_->get_script_limit() - 
scriptIterator_->get_script_start());
-        next = rbbi_->next();
-    }
-    return (next == UBRK_DONE) ? UBRK_DONE : next + 
scriptIterator_->get_script_start();
-}
-
-int32_t CompositeBreakIterator::current() {
-    int32_t current = rbbi_->current();
-    return (current == UBRK_DONE) ? UBRK_DONE : current + 
scriptIterator_->get_script_start();
-}
-
-int32_t CompositeBreakIterator::get_rule_status() {
-    return rbbi_->get_rule_status();
-}
-
-int32_t CompositeBreakIterator::get_script_code() {
-    return scriptIterator_->get_script_code();
-}
-
 void CompositeBreakIterator::set_text(const UChar* text, int32_t start, 
int32_t length) {
     text_ = text;
-    scriptIterator_->set_text(text_, start, length);
-    if (scriptIterator_->next()) {
-        rbbi_ = get_break_iterator(scriptIterator_->get_script_code());
-        rbbi_->set_text(text_, scriptIterator_->get_script_start(),
-                        scriptIterator_->get_script_limit() - 
scriptIterator_->get_script_start());
+    scriptIterator_.set_text(text_, start, length);
+    if (scriptIterator_.next()) {
+        set_run_text();
     } else {
         rbbi_ = get_break_iterator(USCRIPT_COMMON);
-        rbbi_->set_text(text_, 0, 0);
+        rbbi_->set_text(&utext_, text_, 0, 0);
     }
 }
 
+void CompositeBreakIterator::set_run_text() {
+    rbbi_ = get_break_iterator(scriptIterator_.get_script_code());
+    rbbi_->set_text(&utext_, text_, scriptIterator_.get_script_start(),
+                    scriptIterator_.get_script_limit() - 
scriptIterator_.get_script_start());
+}
+
 BreakIteratorWrapper* CompositeBreakIterator::get_break_iterator(int32_t 
scriptCode) {
     if (!word_breakers_[scriptCode]) {
-        auto wordBreak =
+        word_breakers_[scriptCode] =
                 
std::make_unique<BreakIteratorWrapper>(config_->get_break_iterator(scriptCode));
-        wordBreak->initialize();
-        word_breakers_[scriptCode].swap(wordBreak);
     }
     return word_breakers_[scriptCode].get();
 }
 
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h
 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h
index e0da4d08995..d6b6b2b5a20 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h
@@ -18,7 +18,6 @@
 #pragma once
 
 #include <unicode/umachine.h>
-#include <unicode/unistr.h>
 #include <unicode/utext.h>
 
 #include <memory>
@@ -31,28 +30,51 @@
 
 namespace doris::segment_v2::inverted_index {
 
+// The boundaries of a text, each script run broken by the iterator of its 
script. The iterators
+// and the UText they read through are kept from one text to the next. The 
boundary after the end
+// of a run is the start of the next run, so a word never spans two runs: in 
"abc" followed by two
+// Han characters, "abc" ends where the Han characters start.
 class CompositeBreakIterator {
 public:
-    CompositeBreakIterator(const ICUTokenizerConfigPtr& config);
-    ~CompositeBreakIterator() = default;
-
-    void initialize();
-    int32_t next();
-    int32_t current();
-    int32_t get_rule_status();
-    int32_t get_script_code();
+    explicit CompositeBreakIterator(ICUTokenizerConfigPtr config);
+    ~CompositeBreakIterator() { utext_close(&utext_); }
+
+    CompositeBreakIterator(const CompositeBreakIterator&) = delete;
+    CompositeBreakIterator& operator=(const CompositeBreakIterator&) = delete;
+
+    // The next boundary of the text, or UBRK_DONE after the last one; the 
first boundary, 0, is
+    // never returned.
+    int32_t next() {
+        // One call of the inline BreakIteratorWrapper::next(), which the 
compiler then inlines.
+        for (;;) {
+            const int32_t next = rbbi_->next();
+            if (next != UBRK_DONE) {
+                return next + scriptIterator_.get_script_start();
+            }
+            if (!scriptIterator_.next()) {
+                return UBRK_DONE;
+            }
+            set_run_text();
+        }
+    }
+    // The rule status of the boundary next() returned: 0 when the text before 
it is no word.
+    int32_t get_rule_status() const { return rbbi_->get_rule_status(); }
+    int32_t get_script_code() const { return 
scriptIterator_.get_script_code(); }
     void set_text(const UChar* text, int32_t start, int32_t length);
 
 private:
     BreakIteratorWrapper* get_break_iterator(int32_t scriptCode);
+    // Points the iterator of the current script run at the run.
+    void set_run_text();
 
     const UChar* text_ = nullptr;
 
     ICUTokenizerConfigPtr config_;
     std::vector<BreakIteratorWrapperPtr> word_breakers_;
     BreakIteratorWrapper* rbbi_ = nullptr;
-    ScriptIteratorPtr scriptIterator_;
+    ScriptIterator scriptIterator_;
+    UText utext_ = UTEXT_INITIALIZER;
 };
 using CompositeBreakIteratorPtr = std::unique_ptr<CompositeBreakIterator>;
 
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.cpp
 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.cpp
index 9962960c129..4037342cb2f 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.cpp
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.cpp
@@ -30,10 +30,8 @@ BreakIteratorPtr 
DefaultICUTokenizerConfig::cjk_break_iterator_;
 BreakIteratorPtr DefaultICUTokenizerConfig::default_break_iterator_;
 BreakIteratorPtr DefaultICUTokenizerConfig::myanmar_syllable_iterator_;
 
-DefaultICUTokenizerConfig::DefaultICUTokenizerConfig(bool cjk_as_words, bool 
myanmar_as_words) {
-    cjk_as_words_ = cjk_as_words;
-    myanmar_as_words_ = myanmar_as_words;
-}
+DefaultICUTokenizerConfig::DefaultICUTokenizerConfig(bool myanmar_as_words)
+        : myanmar_as_words_(myanmar_as_words) {}
 
 void DefaultICUTokenizerConfig::initialize(const std::string& dictPath) {
     static std::atomic<bool> initialized_(false);
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.h
 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.h
index 0d5dd130716..1fca97612f7 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.h
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.h
@@ -21,13 +21,15 @@
 
 namespace doris::segment_v2::inverted_index {
 
+// The break iterators of the scripts. Han, Hiragana and Katakana arrive as 
one script, JAPANESE
+// (ICUCharTable::script_of()), which the root locale's dictionary-based word 
iterator breaks into
+// words.
 class DefaultICUTokenizerConfig : public ICUTokenizerConfig {
 public:
-    DefaultICUTokenizerConfig(bool cjkAsWords, bool myanmarAsWords);
+    explicit DefaultICUTokenizerConfig(bool myanmar_as_words);
     ~DefaultICUTokenizerConfig() override = default;
 
     void initialize(const std::string& dictPath) override;
-    bool combine_cj() override { return cjk_as_words_; }
     icu::BreakIterator* get_break_iterator(int32_t script) override;
 
 private:
@@ -37,7 +39,6 @@ private:
     static BreakIteratorPtr default_break_iterator_;
     static BreakIteratorPtr myanmar_syllable_iterator_;
 
-    bool cjk_as_words_ = false;
     bool myanmar_as_words_ = false;
 };
 
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.cpp 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.cpp
new file mode 100644
index 00000000000..c4e831b4282
--- /dev/null
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.cpp
@@ -0,0 +1,79 @@
+// 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.
+
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h"
+
+#include <unicode/uchar.h>
+#include <unicode/unistr.h>
+#include <unicode/uscript.h>
+
+#include "common/check.h"
+
+namespace doris::segment_v2::inverted_index {
+
+const ICUCharTable& ICUCharTable::instance() {
+    static const ICUCharTable table;
+    return table;
+}
+
+int32_t ICUCharTable::script_of(UChar32 c) {
+    UErrorCode status = U_ZERO_ERROR;
+    const int32_t script = uscript_getScript(c, &status);
+    // Fails only for a value that is no code point, and UTF-16 decodes to 
none.
+    DORIS_CHECK(U_SUCCESS(status));
+    if (script == USCRIPT_HAN || script == USCRIPT_HIRAGANA || script == 
USCRIPT_KATAKANA) {
+        return USCRIPT_JAPANESE;
+    }
+    if (c >= 0xFF10 && c <= 0xFF19) {
+        return USCRIPT_LATIN;
+    }
+    return script;
+}
+
+bool ICUCharTable::combining_mark_of(UChar32 c) {
+    const auto type = static_cast<UCharCategory>(u_charType(c));
+    return type == U_COMBINING_SPACING_MARK || type == U_NON_SPACING_MARK ||
+           type == U_ENCLOSING_MARK;
+}
+
+ICUCharTable::ICUCharTable() {
+    UErrorCode status = U_ZERO_ERROR;
+    
emoji_set.applyPattern(icu::UnicodeString::fromUTF8("[[:Emoji:][:Extended_Pictographic:]]"),
+                           status);
+    DORIS_CHECK(U_SUCCESS(status));
+    emoji_rk_set.applyPattern(icu::UnicodeString::fromUTF8("[*#0-9©®™〰〽]"), 
status);
+    DORIS_CHECK(U_SUCCESS(status));
+    // Frozen sets answer contains() from several threads at once.
+    emoji_set.freeze();
+    emoji_rk_set.freeze();
+
+    for (UChar32 c = 0; c < kBmpEnd; ++c) {
+        scripts[c] = static_cast<int16_t>(script_of(c));
+        const uint64_t bit = uint64_t {1} << (c & 63);
+        if (combining_mark_of(c)) {
+            combining_marks[c >> 6] |= bit;
+        }
+        if (emoji_set.contains(c)) {
+            emoji[c >> 6] |= bit;
+        }
+        if (emoji_rk_set.contains(c)) {
+            emoji_rk[c >> 6] |= bit;
+        }
+    }
+}
+
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h
new file mode 100644
index 00000000000..eed2b0796d9
--- /dev/null
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h
@@ -0,0 +1,79 @@
+// 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.
+
+#pragma once
+
+#include <unicode/umachine.h>
+#include <unicode/uniset.h>
+
+#include <array>
+#include <cstdint>
+
+namespace doris::segment_v2::inverted_index {
+
+// The character properties the icu tokenizer asks for: the script of every 
character, whether a
+// character is a combining mark, and whether a token starts with an emoji. 
ICU answers each with a
+// call into its property tries or a UnicodeSet; for the BMP, where nearly all 
text lies, the
+// answers are read from tables built once from those same calls, and only a 
supplementary code
+// point still asks ICU. E.g. the script of U+4E2D, a Han character, is 
scripts[0x4E2D], JAPANESE,
+// and that of U+20000, a supplementary Han character, is script_of(0x20000), 
also JAPANESE.
+//
+// Built at first use and read-only afterwards, so every stream of every 
thread shares it.
+struct ICUCharTable {
+    static constexpr UChar32 kBmpEnd = 0x10000;
+    using Bits = std::array<uint64_t, kBmpEnd / 64>;
+
+    // script_of() of each BMP code point.
+    std::array<int16_t, kBmpEnd> scripts {};
+    // One bit per BMP code point c, bit c % 64 of word c / 64: whether 
combining_mark_of(c),
+    // whether emoji_set has c, whether emoji_rk_set has c.
+    Bits combining_marks {};
+    Bits emoji {};
+    Bits emoji_rk {};
+    // [[:Emoji:][:Extended_Pictographic:]], what can make an emoji token.
+    icu::UnicodeSet emoji_set;
+    // The emoji that are text by default: an emoji token only when U+FE0F 
(emoji presentation) or
+    // U+20E3 (keycap) follows, as in "#" U+FE0F U+20E3; "#" or "1" alone is 
no emoji.
+    icu::UnicodeSet emoji_rk_set;
+
+    static const ICUCharTable& instance();
+
+    // The script the tokenizer groups `c` by: ICU's script, except that Han, 
Hiragana and Katakana
+    // are all JAPANESE, so that the CJK dictionary breaks a run of mixed 
Chinese and Japanese
+    // whole, and the full-width digits U+FF10..U+FF19 are LATIN.
+    static int32_t script_of(UChar32 c);
+    // A spacing, non-spacing or enclosing mark, which joins the script run 
before it.
+    static bool combining_mark_of(UChar32 c);
+
+    int32_t script(UChar32 c) const { return c < kBmpEnd ? scripts[c] : 
script_of(c); }
+    bool is_combining_mark(UChar32 c) const {
+        return c < kBmpEnd ? has(combining_marks, c) : combining_mark_of(c);
+    }
+    bool is_emoji(UChar32 c) const { return c < kBmpEnd ? has(emoji, c) : 
emoji_set.contains(c); }
+    bool is_emoji_rk(UChar32 c) const {
+        return c < kBmpEnd ? has(emoji_rk, c) : emoji_rk_set.contains(c);
+    }
+
+private:
+    // Fills the table in place, inside the static of instance(): 152 KB is 
too much for the stack
+    // of the thread that happens to use it first.
+    ICUCharTable();
+
+    static bool has(const Bits& bits, UChar32 c) { return ((bits[c >> 6] >> (c 
& 63)) & 1) != 0; }
+};
+
+} // namespace doris::segment_v2::inverted_index
diff --git a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_common.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_common.h
index 55b5496cc98..2aeb5b82abc 100644
--- a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_common.h
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_common.h
@@ -34,14 +34,4 @@ namespace doris::segment_v2::inverted_index {
 
 using BreakIteratorPtr = std::unique_ptr<icu::BreakIterator>;
 
-struct UTextDeleter {
-    void operator()(UText* utext) const {
-        if (utext != nullptr) {
-            utext_close(utext);
-        }
-    }
-};
-
-using UTextPtr = std::unique_ptr<UText, UTextDeleter>;
-
 } // namespace doris::segment_v2::inverted_index
\ No newline at end of file
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.cpp 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.cpp
index 9c4c9324827..787de5b4fa7 100644
--- a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.cpp
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.cpp
@@ -17,71 +17,203 @@
 
 #include "storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h"
 
+#include <simdutf.h>
+#include <unicode/ucasemap.h>
+#include <unicode/ustring.h>
 #include <unicode/utf16.h>
 
 #include <algorithm>
 #include <memory>
 #include <string>
 
+#include "common/check.h"
 #include "common/exception.h"
 #include "common/logging.h"
 #include "storage/index/inverted/analysis/common/rune.h"
 #include "storage/index/inverted/analysis/scratch.h"
+#include "storage/index/inverted/analysis/token_batch.h"
+#include "storage/index/inverted/analysis/tokenizer/byte_classifier.h"
 #include "util/utf8_check.h"
 
 namespace doris::segment_v2::inverted_index {
 
-ICUTokenizer::ICUTokenizer() {
-    config_ = std::make_shared<DefaultICUTokenizerConfig>(true, true);
+namespace {
+
+// The case map LowerCaseFilter lowercases with. "" is the root locale 
whatever the process default
+// is, so "I" becomes "i" even under a Turkish default, where it would become 
"ı". ICU lowercases
+// with a const map, so every stream shares one.
+const UCaseMap* icu_root_case_map() {
+    static const UCaseMap* const case_map = [] {
+        UErrorCode status = U_ZERO_ERROR;
+        const UCaseMap* map = ucasemap_open("", 0, &status);
+        DORIS_CHECK(U_SUCCESS(status));
+        return map;
+    }();
+    return case_map;
+}
+
+// Writes the UTF-8 of `length` UTF-16 units and returns the end of it. The 
units pair every
+// surrogate: invalid UTF-8 became U+FFFD, not an unpaired surrogate, and a 
term is never cut
+// inside a pair.
+char* encode_icu_term(const UChar* units, int32_t length, char* out) {
+    for (int32_t i = 0; i < length; ++i) {
+        const UChar c = units[i];
+        if (c < 0x80) {
+            *out++ = static_cast<char>(c);
+        } else if (c < 0x800) {
+            *out++ = static_cast<char>(0xC0 | (c >> 6));
+            *out++ = static_cast<char>(0x80 | (c & 0x3F));
+        } else if (!U16_IS_SURROGATE(c)) {
+            *out++ = static_cast<char>(0xE0 | (c >> 12));
+            *out++ = static_cast<char>(0x80 | ((c >> 6) & 0x3F));
+            *out++ = static_cast<char>(0x80 | (c & 0x3F));
+        } else {
+            DCHECK(U16_IS_SURROGATE_LEAD(c) && i + 1 < length && 
U16_IS_TRAIL(units[i + 1]));
+            const UChar32 code_point = U16_GET_SUPPLEMENTARY(c, units[++i]);
+            *out++ = static_cast<char>(0xF0 | (code_point >> 18));
+            *out++ = static_cast<char>(0x80 | ((code_point >> 12) & 0x3F));
+            *out++ = static_cast<char>(0x80 | ((code_point >> 6) & 0x3F));
+            *out++ = static_cast<char>(0x80 | (code_point & 0x3F));
+        }
+    }
+    return out;
+}
+
+} // namespace
+
+ICUTokenizer::ICUTokenizer(bool lowercase) : _lowercase(lowercase) {
+    config_ = 
std::make_shared<DefaultICUTokenizerConfig>(/*myanmar_as_words=*/true);
     breaker_ = std::make_unique<CompositeBreakIterator>(config_);
 }
 
 void ICUTokenizer::initialize(const std::string& dictPath) {
     config_->initialize(dictPath);
-    breaker_->initialize();
 }
 
-bool ICUTokenizer::next_token(TokenRef& token) {
-    int32_t start = breaker_->current();
-    DCHECK_NE(start, UBRK_DONE);
-
-    int32_t end = breaker_->next();
-    while (end != UBRK_DONE && breaker_->get_rule_status() == 0) {
-        start = end;
-        end = breaker_->next();
+void ICUTokenizer::reset(std::string_view text) {
+    // No token until the value is bound, so a stream whose reset() threw 
makes none.
+    _exhausted = true;
+    _ascii = simdutf::validate_ascii(text.data(), text.size());
+    // Malformed bytes become replacement characters and the rest of the value 
is still indexed;
+    // strict mode rejects them.
+    if (_strict_utf8 && !_ascii && !validate_utf8(text.data(), text.size())) {
+        throw Exception(ErrorCode::INVALID_ARGUMENT, "ICU tokenizer input is 
not valid UTF-8");
+    }
+    if (static_cast<size_t>(buffer_.getCapacity()) * sizeof(UChar) >
+        ANALYZER_SCRATCH_HIGH_WATER_BYTES) {
+        buffer_ = icu::UnicodeString();
     }
+    // A value has at most as many UTF-16 units as UTF-8 bytes: a unit takes 
at least one byte,
+    // and a U+FFFD at least one invalid byte.
+    const auto size = static_cast<int32_t>(text.size());
+    UChar* units = buffer_.getBuffer(size);
+    DORIS_CHECK(units != nullptr);
+    int32_t length = size;
+    if (_ascii) {
+        std::ranges::transform(text, units,
+                               [](char c) { return 
static_cast<UChar>(static_cast<uint8_t>(c)); });
+    } else {
+        // Valid UTF-8 has one UTF-16 form, which simdutf writes; it returns 0 
for invalid UTF-8,
+        // and a value that is not ASCII is not empty.
+        length = static_cast<int32_t>(
+                simdutf::convert_utf8_to_utf16(text.data(), text.size(), 
units));
+        if (length == 0) {
+            // What UnicodeString::fromUTF8() does: one U+FFFD for each 
maximal invalid
+            // subsequence, e.g. "a\xE4\xB8b" becomes "a\uFFFDb".
+            UErrorCode status = U_ZERO_ERROR;
+            u_strFromUTF8WithSub(units, buffer_.getCapacity(), &length, 
text.data(), size, 0xFFFD,
+                                 nullptr, &status);
+            DORIS_CHECK(U_SUCCESS(status));
+        }
+    }
+    buffer_.releaseBuffer(length);
+    _text = text;
+    _units = buffer_.getBuffer();
+    _position = 0;
+    breaker_->set_text(_units, 0, length);
+    _exhausted = false;
+}
 
-    if (end == UBRK_DONE) {
-        return false;
+bool ICUTokenizer::next_batch(TokenBatch& batch) {
+    batch.clear();
+    while (!_exhausted && batch.size() < kBatchTokens) {
+        const int32_t end = breaker_->next();
+        if (end == UBRK_DONE) {
+            _exhausted = true;
+        } else {
+            // A boundary of rule status 0 ends no word: in "a, b" the text ", 
" is no token.
+            if (breaker_->get_rule_status() != 0) {
+                push_term(batch, _position, end);
+            }
+            _position = end;
+        }
     }
+    return batch.size() != 0;
+}
 
-    utf8Str_.clear();
+void ICUTokenizer::push_term(TokenBatch& batch, int32_t start, int32_t end) {
+    DCHECK_LT(start, end);
+    const UChar* units = _units + start;
     int32_t length = std::min(end - start, MAX_WORD_LEN);
-    if (length < end - start && length > 0 && U16_IS_LEAD(buffer_.charAt(start 
+ length - 1)) &&
-        U16_IS_TRAIL(buffer_.charAt(start + length))) {
+    if (length < end - start && U16_IS_LEAD(units[length - 1]) && 
U16_IS_TRAIL(units[length])) {
         --length;
     }
-    buffer_.tempSubString(start, length).toUTF8String(utf8Str_);
-    token = {.data = utf8Str_.data(),
-             .size = static_cast<uint32_t>(utf8Str_.size()),
-             .position_increment = 1};
-    return true;
+    if (_ascii) {
+        const std::string_view term = _text.substr(start, length);
+        if (!_lowercase || std::ranges::none_of(term, [](char c) {
+                return is_ascii_upper(static_cast<uint8_t>(c));
+            })) {
+            batch.push(term, 1);
+            return;
+        }
+        char* lowered = batch.allocate_term(term.size());
+        std::ranges::transform(term, lowered, [](char c) { return 
ascii_lower(c); });
+        batch.push({lowered, term.size()}, 1);
+        return;
+    }
+    // The length of the UTF-8, and what lowercasing the term takes.
+    size_t utf8_length = 0;
+    bool ascii = true;
+    bool caseless = true;
+    for (int32_t i = 0; i < length; ++i) {
+        const UChar c = units[i];
+        ascii &= c < 0x80;
+        caseless &= c >= 0x3000 && c <= 0x9FFF;
+        // 1 byte below U+0080, 2 below U+0800, 3 above; a surrogate pair 
takes 2 + 2 bytes.
+        utf8_length += 1 + static_cast<size_t>(c >= 0x80) +
+                       static_cast<size_t>(c >= 0x800 && !U16_IS_SURROGATE(c));
+    }
+    if (_lowercase && !ascii && !caseless) {
+        utf8Str_.resize(utf8_length);
+        encode_icu_term(units, length, utf8Str_.data());
+        push_lowered(batch);
+        return;
+    }
+    char* term = batch.allocate_term(utf8_length);
+    encode_icu_term(units, length, term);
+    if (_lowercase && ascii) {
+        std::transform(term, term + utf8_length, term, [](char c) { return 
ascii_lower(c); });
+    }
+    batch.push({term, utf8_length}, 1);
 }
 
-void ICUTokenizer::on_reset(std::string_view text) {
-    release_oversized_scratch(utf8Str_);
-    // Malformed bytes become replacement characters and the rest of the value 
is still indexed;
-    // strict mode rejects them.
-    if (_strict_utf8 && !text.empty() && !validate_utf8(text.data(), 
text.size())) {
-        throw Exception(ErrorCode::INVALID_ARGUMENT, "ICU tokenizer input is 
not valid UTF-8");
-    }
-    buffer_ = icu::UnicodeString::fromUTF8(
-            icu::StringPiece(text.data(), static_cast<int32_t>(text.size())));
-    if (!buffer_.isEmpty() && buffer_.isBogus()) {
-        throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR,
-                        "Failed to convert UTF-8 string to UnicodeString.");
+void ICUTokenizer::push_lowered(TokenBatch& batch) {
+    DCHECK(validate_utf8(utf8Str_.data(), utf8Str_.size()));
+    const auto size = static_cast<int32_t>(utf8Str_.size());
+    char* lowered = batch.allocate_term(utf8Str_.size());
+    UErrorCode status = U_ZERO_ERROR;
+    int32_t length = ucasemap_utf8ToLower(icu_root_case_map(), lowered, size, 
utf8Str_.data(), size,
+                                          &status);
+    // The lowercase is longer, as for İ (U+0130, 2 bytes), which becomes 
U+0069 U+0307 (3
+    // bytes); ICU said how long.
+    if (status == U_BUFFER_OVERFLOW_ERROR) {
+        lowered = batch.allocate_term(static_cast<size_t>(length));
+        status = U_ZERO_ERROR;
+        length = ucasemap_utf8ToLower(icu_root_case_map(), lowered, length, 
utf8Str_.data(), size,
+                                      &status);
     }
-    breaker_->set_text(buffer_.getBuffer(), 0, buffer_.length());
+    DORIS_CHECK(U_SUCCESS(status));
+    batch.push({lowered, static_cast<size_t>(length)}, 1);
 }
 
 } // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h
index ab5841b820c..a2126ae75ca 100644
--- a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h
@@ -17,12 +17,15 @@
 
 #pragma once
 
+#include <unicode/umachine.h>
 #include <unicode/unistr.h>
 
+#include <cstddef>
+#include <cstdint>
 #include <string>
 #include <string_view>
 
-#include "storage/index/inverted/analysis/per_token_stream.h"
+#include "storage/index/inverted/analysis/text_token_stream.h"
 #include 
"storage/index/inverted/analysis/tokenizer/icu/composite_break_iterator.h"
 #include 
"storage/index/inverted/analysis/tokenizer/icu/default_icu_tokenizer_config.h"
 #include "storage/index/inverted/analysis/tokenizer/icu/icu_common.h"
@@ -30,29 +33,56 @@
 namespace doris::segment_v2::inverted_index {
 
 // The words of the value by ICU's per-script break rules, at most 
MAX_WORD_LEN UTF-16 code units
-// each.
-class ICUTokenizer final : public PerTokenTokenizer {
+// each: a longer word is cut there, one unit earlier when the cut would split 
a surrogate pair,
+// and the rest of it is dropped. The value is read as UTF-16, invalid UTF-8 
replaced by U+FFFD as
+// UnicodeString::fromUTF8() replaces it; in strict mode it throws instead.
+//
+// With `lowercase`, which only the builtin icu parser asks for, every term is 
what LowerCaseFilter
+// made of it: an ASCII term lowercased byte by byte, a term of only 
U+3000..U+9FFF (CJK
+// punctuation, kana, ideographs, which have no case) left as it is, and any 
other term lowercased
+// by ICU's root-locale case mapping, which may lengthen it: "İstanbul" 
becomes "i" U+0307
+// "stanbul".
+//
+// A term of an ASCII value is a view of the value; any other term is encoded 
from the UTF-16 copy
+// straight into the batch.
+class ICUTokenizer final : public TextTokenizer {
 public:
-    ICUTokenizer();
+    explicit ICUTokenizer(bool lowercase = false);
 
     void initialize(const std::string& dictPath);
 
+    void reset(std::string_view text) override;
+    bool next_batch(TokenBatch& batch) override;
+
     // Strict: invalid UTF-8 throws instead of becoming U+FFFD.
     void set_strict_utf8(bool strict) override { _strict_utf8 = strict; }
 
-    // The UTF-16 copy of the value and the scratch of one word.
+    // The UTF-16 copy of the value, released above the high water mark, and 
the scratch of a term
+    // ICU lowercases, which the term limit bounds to 765 bytes.
     size_t reserved_bytes() const override {
         return static_cast<size_t>(buffer_.getCapacity()) * sizeof(UChar) + 
utf8Str_.capacity();
     }
 
-protected:
-    void on_reset(std::string_view text) override;
-    bool next_token(TokenRef& token) override;
-
 private:
-    std::string utf8Str_;
-    icu::UnicodeString buffer_;
+    // The term of the word [start, end) of the UTF-16 copy.
+    void push_term(TokenBatch& batch, int32_t start, int32_t end);
+    // The root-locale lowercase of utf8Str_.
+    void push_lowered(TokenBatch& batch);
+
+    const bool _lowercase;
     bool _strict_utf8 = false;
+    // No value is bound, or the last word was handed out.
+    bool _exhausted = true;
+    // The last boundary the breaker returned, where the next word may start.
+    int32_t _position = 0;
+    // The value, and whether it is ASCII: then the UTF-8 of every term is the 
value's bytes at the
+    // offsets of its UTF-16 units.
+    std::string_view _text;
+    bool _ascii = false;
+    // The UTF-16 copy of the value, and its units.
+    icu::UnicodeString buffer_;
+    const UChar* _units = nullptr;
+    std::string utf8Str_;
 
     ICUTokenizerConfigPtr config_;
     CompositeBreakIteratorPtr breaker_;
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h
index 9f64f07a836..58306749952 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_config.h
@@ -28,7 +28,6 @@ public:
 
     virtual void initialize(const std::string& dictPath) = 0;
     virtual icu::BreakIterator* get_break_iterator(int32_t script) = 0;
-    virtual bool combine_cj() = 0;
 
     static const int32_t EMOJI_SEQUENCE_STATUS = 299;
 };
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_factory.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_factory.h
index e87ccc259fb..befbc16a1cb 100644
--- 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_factory.h
+++ 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_factory.h
@@ -23,18 +23,23 @@
 
 namespace doris::segment_v2::inverted_index {
 
+// The custom icu_tokenizer, and with `lowercase` the builtin icu parser, 
whose tokenizer
+// lowercases its own terms.
 class ICUTokenizerFactory : public TokenizerFactory {
 public:
-    ICUTokenizerFactory() = default;
+    explicit ICUTokenizerFactory(bool lowercase = false) : 
_lowercase(lowercase) {}
     ~ICUTokenizerFactory() override = default;
 
     void initialize(const Settings& settings) override {}
 
     std::unique_ptr<TextTokenizer> create() const override {
-        auto tokenizer = std::make_unique<ICUTokenizer>();
+        auto tokenizer = std::make_unique<ICUTokenizer>(_lowercase);
         tokenizer->initialize(config::inverted_index_dict_path + "/icu");
         return tokenizer;
     }
+
+private:
+    const bool _lowercase;
 };
 
 } // namespace doris::segment_v2::inverted_index
\ No newline at end of file
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.cpp 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.cpp
index c34ace10695..ac82b84e903 100644
--- a/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.cpp
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.cpp
@@ -17,31 +17,26 @@
 
 #include "storage/index/inverted/analysis/tokenizer/icu/script_iterator.h"
 
-#include <unicode/unistr.h>
+#include <unicode/utf16.h>
 
-#include <mutex>
-#include <string>
+#include <cstring>
 
 namespace doris::segment_v2::inverted_index {
 
-std::vector<int32_t> ScriptIterator::k_basic_latin(128);
-
-ScriptIterator::ScriptIterator(bool combine_cj) : combine_cj_(combine_cj) {}
-
-void ScriptIterator::initialize() {
-    static std::once_flag once_flag;
-    std::call_once(once_flag, []() {
-        UErrorCode status = U_ZERO_ERROR;
-        for (int32_t i = 0; i < 128; i++) {
-            k_basic_latin[i] = uscript_getScript(i, &status);
-            if (U_FAILURE(status)) {
-                std::string error_msg = "Get script failed: ";
-                error_msg += u_errorName(status);
-                throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, 
error_msg);
-            }
+int32_t ScriptIterator::skip_ascii(const UChar* text, int32_t index, int32_t 
limit) {
+    // 8 units, 16 bytes, at a time: none may have a bit above 0x7F.
+    constexpr uint64_t kNotAscii = 0xFF80FF80FF80FF80ULL;
+    while (index + 8 <= limit) {
+        uint64_t low = 0;
+        uint64_t high = 0;
+        std::memcpy(&low, text + index, sizeof(low));
+        std::memcpy(&high, text + index + 4, sizeof(high));
+        if (((low | high) & kNotAscii) != 0) {
+            break;
         }
-        return k_basic_latin;
-    });
+        index += 8;
+    }
+    return index;
 }
 
 bool ScriptIterator::next() {
@@ -49,24 +44,44 @@ bool ScriptIterator::next() {
         return false;
     }
 
-    script_code_ = USCRIPT_COMMON;
     script_start_ = script_limit_;
-
-    while (index_ < limit_) {
-        UChar32 ch = 0;
-        U16_GET(text_, start_, index_, limit_, ch);
-        int32_t script = get_script(ch);
-        if (is_same_script(script_code_, script, ch) || is_combining_mark(ch)) 
{
-            index_ += U16_LENGTH(ch);
-            if (script_code_ <= USCRIPT_INHERITED && script > 
USCRIPT_INHERITED) {
-                script_code_ = script;
+    // The loop visits every character of the value, on locals: stores to 
members would make the
+    // compiler reload the others on every character.
+    const ICUCharTable& table = table_;
+    const UChar* const text = text_;
+    const int32_t start = start_;
+    const int32_t limit = limit_;
+    int32_t index = index_;
+    int32_t code = USCRIPT_COMMON;
+    while (index < limit) {
+        if (code == USCRIPT_LATIN) {
+            index = skip_ascii(text, index, limit);
+            if (index == limit) {
+                break;
             }
-        } else {
+        }
+        UChar32 ch = 0;
+        U16_GET(text, start, index, limit, ch);
+        const int32_t script = table.script(ch);
+        // `|`, not `||`: in "the cat" a Latin run alternates letters and 
Common spaces, and the
+        // short-circuit form mispredicted at every space. Only two real 
scripts that differ ask
+        // ICU, and the answer ends the run unless the script extensions of 
the character name the
+        // run's script: e.g. an Arabic-Indic digit, of the Arabic script, 
joins a Thaana run.
+        const bool joins =
+                (script == code) | (code <= USCRIPT_INHERITED) | (script <= 
USCRIPT_INHERITED);
+        if (!joins && !uscript_hasScript(ch, static_cast<UScriptCode>(code)) &&
+            !table.is_combining_mark(ch)) {
             break;
         }
+        index += U16_LENGTH(ch);
+        if (code <= USCRIPT_INHERITED && script > USCRIPT_INHERITED) {
+            code = script;
+        }
     }
 
-    script_limit_ = index_;
+    index_ = index;
+    script_limit_ = index;
+    script_code_ = code;
     return true;
 }
 
@@ -80,42 +95,4 @@ void ScriptIterator::set_text(const UChar* text, int32_t 
start, int32_t length)
     script_code_ = USCRIPT_INVALID_CODE;
 }
 
-int32_t ScriptIterator::get_script(UChar32 codepoint) const {
-    if (0 <= codepoint && codepoint < 128) {
-        return k_basic_latin[codepoint];
-    } else {
-        UErrorCode err = U_ZERO_ERROR;
-        int32_t script = uscript_getScript(codepoint, &err);
-        if (U_FAILURE(err)) {
-            std::string error_msg = "Get Script error: ";
-            error_msg += u_errorName(err);
-            error_msg += ", script: " + std::to_string(script);
-            throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR, 
error_msg);
-        }
-        if (combine_cj_) {
-            if (script == USCRIPT_HAN || script == USCRIPT_HIRAGANA || script 
== USCRIPT_KATAKANA) {
-                return USCRIPT_JAPANESE;
-            } else if (codepoint >= 0xFF10 && codepoint <= 0xFF19) {
-                return USCRIPT_LATIN;
-            } else {
-                return script;
-            }
-        } else {
-            return script;
-        }
-    }
-}
-
-bool ScriptIterator::is_same_script(int32_t current_script, int32_t script, 
UChar32 codepoint) {
-    return (current_script == script) || (current_script <= USCRIPT_INHERITED) 
||
-           (script <= USCRIPT_INHERITED) ||
-           uscript_hasScript(codepoint, (UScriptCode)current_script);
-}
-
-bool ScriptIterator::is_combining_mark(UChar32 codepoint) {
-    auto type = (UCharCategory)u_charType(codepoint);
-    return (type == U_COMBINING_SPACING_MARK || type == U_NON_SPACING_MARK ||
-            type == U_ENCLOSING_MARK);
-}
-
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.h 
b/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.h
index 3eb66ed82f2..e1cb3c406d2 100644
--- a/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.h
+++ b/be/src/storage/index/inverted/analysis/tokenizer/icu/script_iterator.h
@@ -18,21 +18,20 @@
 #pragma once
 
 #include <unicode/umachine.h>
-#include <unicode/utext.h>
+#include <unicode/uscript.h>
 
-#include <memory>
-#include <vector>
+#include <cstdint>
 
-#include "storage/index/inverted/analysis/tokenizer/icu/icu_common.h"
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h"
 
 namespace doris::segment_v2::inverted_index {
 
+// The runs of one script in a UTF-16 text, by ICUCharTable::script(): 
characters of the Common
+// and Inherited scripts and combining marks join the run they are in, and a 
character joins a run
+// of another script when its script extensions name that script.
 class ScriptIterator {
 public:
-    ScriptIterator(bool combine_cj);
-    ~ScriptIterator() = default;
-
-    void initialize();
+    ScriptIterator() : table_(ICUCharTable::instance()) {}
 
     int32_t get_script_start() const { return script_start_; }
     int32_t get_script_limit() const { return script_limit_; }
@@ -42,11 +41,12 @@ public:
     void set_text(const UChar* text, int32_t start, int32_t length);
 
 private:
-    int32_t get_script(UChar32 codepoint) const;
-    static bool is_same_script(int32_t current_script, int32_t script, UChar32 
codepoint);
-    static bool is_combining_mark(UChar32 codepoint);
+    // The end of the ASCII units from `index`, a block of 8 at a time, so up 
to 7 short of it. A
+    // Latin run takes every ASCII character, all of which are Latin or 
Common, so it may jump over
+    // them: an ASCII value is one run.
+    static int32_t skip_ascii(const UChar* text, int32_t index, int32_t limit);
 
-    static std::vector<int32_t> k_basic_latin;
+    const ICUCharTable& table_;
 
     const UChar* text_ = nullptr;
     int32_t start_ = 0;
@@ -56,9 +56,6 @@ private:
     int32_t script_start_ = 0;
     int32_t script_limit_ = 0;
     int32_t script_code_ = USCRIPT_INVALID_CODE;
-
-    bool combine_cj_ = false;
 };
-using ScriptIteratorPtr = std::unique_ptr<ScriptIterator>;
 
-} // namespace doris::segment_v2::inverted_index
\ No newline at end of file
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/test/storage/index/inverted/analysis/tokenizer/icu_char_table_test.cpp 
b/be/test/storage/index/inverted/analysis/tokenizer/icu_char_table_test.cpp
new file mode 100644
index 00000000000..c35b3050660
--- /dev/null
+++ b/be/test/storage/index/inverted/analysis/tokenizer/icu_char_table_test.cpp
@@ -0,0 +1,124 @@
+// 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.
+
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_char_table.h"
+
+#include <gtest/gtest.h>
+#include <unicode/uchar.h>
+#include <unicode/uniset.h>
+#include <unicode/unistr.h>
+#include <unicode/uscript.h>
+
+#include <cstdint>
+
+namespace doris::segment_v2::inverted_index {
+namespace {
+
+// What ScriptIterator asked ICU for each character before the table: the 
script of an ASCII
+// character as ICU gives it, and of any other with Han, Hiragana and Katakana 
as JAPANESE and the
+// full-width digits as LATIN.
+int32_t icu_script(UChar32 c) {
+    UErrorCode status = U_ZERO_ERROR;
+    const int32_t script = uscript_getScript(c, &status);
+    EXPECT_TRUE(U_SUCCESS(status)) << c;
+    if (c < 128) {
+        return script;
+    }
+    if (script == USCRIPT_HAN || script == USCRIPT_HIRAGANA || script == 
USCRIPT_KATAKANA) {
+        return USCRIPT_JAPANESE;
+    }
+    if (c >= 0xFF10 && c <= 0xFF19) {
+        return USCRIPT_LATIN;
+    }
+    return script;
+}
+
+bool icu_combining_mark(UChar32 c) {
+    const auto type = static_cast<UCharCategory>(u_charType(c));
+    return type == U_COMBINING_SPACING_MARK || type == U_NON_SPACING_MARK ||
+           type == U_ENCLOSING_MARK;
+}
+
+// A set from the pattern BreakIteratorWrapper built its emoji sets from 
before the table.
+icu::UnicodeSet pattern_set(const char* pattern) {
+    UErrorCode status = U_ZERO_ERROR;
+    icu::UnicodeSet set(icu::UnicodeString::fromUTF8(pattern), status);
+    EXPECT_TRUE(U_SUCCESS(status)) << pattern;
+    return set;
+}
+
+bool has(const ICUCharTable::Bits& bits, UChar32 c) {
+    return ((bits[c >> 6] >> (c & 63)) & 1) != 0;
+}
+
+TEST(ICUCharTableTest, HoldsWhatICUAnswersForEveryBmpCodePoint) {
+    const ICUCharTable& table = ICUCharTable::instance();
+    const icu::UnicodeSet emoji = 
pattern_set("[[:Emoji:][:Extended_Pictographic:]]");
+    const icu::UnicodeSet emoji_rk = pattern_set("[*#0-9©®™〰〽]");
+    for (UChar32 c = 0; c < ICUCharTable::kBmpEnd; ++c) {
+        ASSERT_EQ(table.scripts[c], icu_script(c)) << c;
+        ASSERT_EQ(has(table.combining_marks, c), icu_combining_mark(c)) << c;
+        ASSERT_EQ(has(table.emoji, c), emoji.contains(c)) << c;
+        ASSERT_EQ(has(table.emoji_rk, c), emoji_rk.contains(c)) << c;
+    }
+}
+
+// The lookups read the tables for the BMP and ask ICU for the supplementary 
planes.
+TEST(ICUCharTableTest, LooksUpWhatICUAnswersForEveryCodePoint) {
+    const ICUCharTable& table = ICUCharTable::instance();
+    const icu::UnicodeSet emoji = 
pattern_set("[[:Emoji:][:Extended_Pictographic:]]");
+    const icu::UnicodeSet emoji_rk = pattern_set("[*#0-9©®™〰〽]");
+    for (UChar32 c = 0; c <= 0x10FFFF; ++c) {
+        ASSERT_EQ(table.script(c), icu_script(c)) << c;
+        ASSERT_EQ(table.is_combining_mark(c), icu_combining_mark(c)) << c;
+        ASSERT_EQ(table.is_emoji(c), emoji.contains(c)) << c;
+        ASSERT_EQ(table.is_emoji_rk(c), emoji_rk.contains(c)) << c;
+    }
+}
+
+// Why ScriptIterator may jump over ASCII in a Latin run: every ASCII 
character joins it.
+TEST(ICUCharTableTest, EveryASCIICharacterIsLatinOrCommon) {
+    const ICUCharTable& table = ICUCharTable::instance();
+    for (UChar32 c = 0; c < 128; ++c) {
+        const bool letter = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
+        EXPECT_EQ(table.script(c), letter ? USCRIPT_LATIN : USCRIPT_COMMON) << 
c;
+        EXPECT_FALSE(table.is_combining_mark(c)) << c;
+    }
+}
+
+TEST(ICUCharTableTest, GroupsChineseAndJapaneseAsOneScript) {
+    const ICUCharTable& table = ICUCharTable::instance();
+    EXPECT_EQ(table.script(U'中'), USCRIPT_JAPANESE);
+    EXPECT_EQ(table.script(U'あ'), USCRIPT_JAPANESE);
+    EXPECT_EQ(table.script(U'カ'), USCRIPT_JAPANESE);
+    EXPECT_EQ(table.script(0x20000), USCRIPT_JAPANESE);
+    EXPECT_EQ(table.script(U'한'), USCRIPT_HANGUL);
+    EXPECT_EQ(table.script(U'a'), USCRIPT_LATIN);
+    EXPECT_EQ(table.script(U'0'), USCRIPT_LATIN);
+    EXPECT_EQ(table.script(U'A'), USCRIPT_LATIN);
+    EXPECT_EQ(table.script(U'1'), USCRIPT_COMMON);
+    EXPECT_EQ(table.script(0x0301), USCRIPT_INHERITED);
+    EXPECT_TRUE(table.is_combining_mark(0x0301));
+    EXPECT_TRUE(table.is_emoji(0x1F600));
+    EXPECT_TRUE(table.is_emoji(U'#'));
+    EXPECT_TRUE(table.is_emoji_rk(U'#'));
+    EXPECT_FALSE(table.is_emoji_rk(0x1F600));
+    EXPECT_FALSE(table.is_emoji(U'a'));
+}
+
+} // namespace
+} // namespace doris::segment_v2::inverted_index
diff --git 
a/be/test/storage/index/inverted/analysis/tokenizer/icu_tokenizer_test.cpp 
b/be/test/storage/index/inverted/analysis/tokenizer/icu_tokenizer_test.cpp
new file mode 100644
index 00000000000..d30f6167e33
--- /dev/null
+++ b/be/test/storage/index/inverted/analysis/tokenizer/icu_tokenizer_test.cpp
@@ -0,0 +1,372 @@
+// 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.
+
+#include "storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer.h"
+
+#include <gtest/gtest.h>
+#include <unicode/locid.h>
+#include <unicode/unistr.h>
+#include <unicode/utf8.h>
+
+#include <memory>
+#include <random>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "common/config.h"
+#include "common/exception.h"
+#include "storage/index/inverted/analysis/analyzer/analyzer.h"
+#include "storage/index/inverted/analysis/text_stream_contract.h"
+#include "storage/index/inverted/analysis/token_batch.h"
+#include "storage/index/inverted/analysis/token_filter/lower_case_filter.h"
+#include 
"storage/index/inverted/analysis/tokenizer/icu/icu_tokenizer_factory.h"
+#include "util/defer_op.h"
+
+namespace doris::segment_v2::inverted_index {
+namespace {
+
+// The rule files of the source tree.
+class ICUTokenizerStreamTest : public testing::Test {
+protected:
+    void SetUp() override {
+        _saved_dict_path = config::inverted_index_dict_path;
+        config::inverted_index_dict_path = "./be/dict";
+    }
+
+    void TearDown() override { config::inverted_index_dict_path = 
_saved_dict_path; }
+
+private:
+    std::string _saved_dict_path;
+};
+
+// The builtin icu parser as production builds it.
+TextAnalyzerPtr icu_analyzer(bool lowercase) {
+    return 
InvertedIndexAnalyzer::create_builtin_analyzer(InvertedIndexParserType::PARSER_ICU,
 "",
+                                                          lowercase ? "true" : 
"false", "");
+}
+
+// The custom icu_tokenizer, and with `lowercase` the tokenizer of the builtin 
parser.
+std::unique_ptr<TextTokenStream> icu_tokenizer(bool lowercase) {
+    return ICUTokenizerFactory(lowercase).create();
+}
+
+// What the builtin parser was before its tokenizer lowercased: the custom 
tokenizer followed by
+// LowerCaseFilter.
+std::unique_ptr<TextTokenStream> icu_with_lower_case_filter() {
+    auto filter = std::make_unique<LowerCaseFilter>(icu_tokenizer(false));
+    filter->initialize();
+    return filter;
+}
+
+// The tokens of `text`, or that it threw.
+struct Outcome {
+    bool threw = false;
+    std::vector<CollectedToken> tokens;
+};
+
+Outcome read(TextTokenStream& stream, std::string_view text) {
+    try {
+        return {.threw = false, .tokens = collect_checked(stream, text)};
+    } catch (const Exception&) {
+        return {.threw = true, .tokens = {}};
+    }
+}
+
+// Values with every kind of term: ASCII, CJK, cased letters that ICU 
lowercases (some to longer
+// strings), supplementary letters, emoji, invalid bytes, and words long 
enough for the 255 cut.
+std::string random_value(std::mt19937_64& random) {
+    static const std::vector<std::string> kPieces = {"a",
+                                                     "B",
+                                                     "z9",
+                                                     "I",
+                                                     "İ",
+                                                     "ı",
+                                                     "Σ",
+                                                     "ΣΑΣ",
+                                                     "Ω",
+                                                     "ẞ",
+                                                     "ß",
+                                                     "Dž",
+                                                     "Ⱥ",
+                                                     "K",
+                                                     "É",
+                                                     "é",
+                                                     "Я",
+                                                     " ",
+                                                     ".",
+                                                     ",",
+                                                     "'",
+                                                     "-",
+                                                     "\n",
+                                                     "3",
+                                                     "1.5",
+                                                     "12",
+                                                     "AB",
+                                                     "中",
+                                                     "文",
+                                                     "國",
+                                                     "々",
+                                                     "ー",
+                                                     "ひら",
+                                                     "カタ",
+                                                     "カタ",
+                                                     "한국",
+                                                     "ภาษาไทย",
+                                                     "العربية",
+                                                     "עברית",
+                                                     "हिन्दी",
+                                                     "\u0301",
+                                                     "\u200D",
+                                                     "\uFE0F",
+                                                     "\u20E3",
+                                                     "\U0001F600",
+                                                     "#\uFE0F\u20E3",
+                                                     "©",
+                                                     
"\U0001F469\u200D\u2764\uFE0F\u200D\U0001F469",
+                                                     "\U0001F1FA\U0001F1F8",
+                                                     "\U00020000",
+                                                     "\U0001D400",
+                                                     "\U00010400",
+                                                     "\U00010428",
+                                                     "\xC0\x80",
+                                                     "\xED\xA0\x80",
+                                                     "\xF4\x90\x80\x80",
+                                                     "\xFF",
+                                                     "\x80",
+                                                     "\xC3",
+                                                     "\xE4\xB8"};
+    const size_t size = random() % 400;
+    std::string value;
+    if (random() % 4 == 0) {
+        for (size_t i = 0; i < size; ++i) {
+            value.push_back(static_cast<char>(random()));
+        }
+        return value;
+    }
+    while (value.size() < size) {
+        const std::string& piece = kPieces[random() % kPieces.size()];
+        const size_t repeat = random() % 8 == 0 ? random() % 300 : 1;
+        for (size_t i = 0; i < repeat; ++i) {
+            value += piece;
+        }
+    }
+    return value;
+}
+
+TEST_F(ICUTokenizerStreamTest, LowercasesAsTheLowerCaseFilterDid) {
+    for (bool strict : {false, true}) {
+        SCOPED_TRACE(strict);
+        auto candidate = icu_tokenizer(true);
+        auto oracle = icu_with_lower_case_filter();
+        candidate->set_strict_utf8(strict);
+        oracle->set_strict_utf8(strict);
+        std::mt19937_64 random(20261104 + strict);
+        for (int round = 0; round < 3000; ++round) {
+            const std::string value = random_value(random);
+            const Outcome expected = read(*oracle, value);
+            const Outcome actual = read(*candidate, value);
+            ASSERT_EQ(actual.threw, expected.threw) << value;
+            ASSERT_EQ(actual.tokens, expected.tokens) << value;
+            // A writer drops a stream that threw.
+            if (expected.threw) {
+                candidate = icu_tokenizer(true);
+                oracle = icu_with_lower_case_filter();
+                candidate->set_strict_utf8(strict);
+                oracle->set_strict_utf8(strict);
+            }
+        }
+    }
+}
+
+TEST_F(ICUTokenizerStreamTest, LowercasesEachKindOfTerm) {
+    const TextAnalyzerPtr lower = icu_analyzer(true);
+    // ASCII, byte by byte.
+    EXPECT_EQ(collect_terms(*lower, "Hello WORLD"), (std::vector<std::string> 
{"hello", "world"}));
+    // ICU's root-locale mapping, which ends a Greek word with a final sigma 
(U+03C2) and may
+    // lengthen a term: İ (2 bytes) becomes i and U+0307 (3 bytes), Ⱥ (2 
bytes) becomes ⱥ (3 bytes).
+    EXPECT_EQ(collect_terms(*lower, "ÀÉÎ Džungla ΣΑΣ ΟΔΟΣ Ⱥ"),
+              (std::vector<std::string> {"àéî", "džungla", "σας", "οδος", 
"ⱥ"}));
+    EXPECT_EQ(collect_terms(*lower, "ISTANBUL İstanbul DİYARBAKIR"),
+              (std::vector<std::string> {"istanbul", "i\u0307stanbul", 
"di\u0307yarbakir"}));
+    // An ASCII term of a value that is not ASCII.
+    EXPECT_EQ(collect_terms(*lower, "ABC İ"), (std::vector<std::string> 
{"abc", "i\u0307"}));
+    // Full-width letters have case; half-width kana, Hangul and CJK have none.
+    EXPECT_EQ(collect_terms(*lower, "ABC カタカナ 한국어 中文 カタカナ"),
+              (std::vector<std::string> {"abc", "カタカナ", "한국어", "中文", "カタカナ"}));
+    // The custom tokenizer and the builtin parser with lower_case=false keep 
the case.
+    EXPECT_EQ(collect_terms(*icu_tokenizer(false), "Hello WORLD İ"),
+              (std::vector<std::string> {"Hello", "WORLD", "İ"}));
+    EXPECT_EQ(collect_terms(*icu_analyzer(false), "Hello WORLD İ"),
+              (std::vector<std::string> {"Hello", "WORLD", "İ"}));
+}
+
+// The tokenizer skips the case mapping for a term of only these code points.
+TEST_F(ICUTokenizerStreamTest, CJKPunctuationKanaAndIdeographsHaveNoCase) {
+    for (UChar32 c = 0x3000; c <= 0x9FFF; ++c) {
+        char bytes[U8_MAX_LENGTH];
+        int32_t length = 0;
+        U8_APPEND_UNSAFE(bytes, length, c);
+        std::string lowered(bytes, length);
+        unicode_lower(lowered);
+        ASSERT_EQ(lowered, std::string(bytes, length)) << c;
+    }
+}
+
+TEST_F(ICUTokenizerStreamTest, KeepsItsOutputUnderATurkishDefaultLocale) {
+    const std::vector<std::string> values = {"I İ ı i",
+                                             "ISTANBUL İstanbul istanbul 
ıstanbul",
+                                             "TITLE Iİıi DİYARBAKIR",
+                                             "ΣΑΣ ΟΔΟΣ",
+                                             "Džungla DŽUNGLA",
+                                             "KELVIN Kelvin Ⱥ Ⱦ",
+                                             "İ\u0307 I\u0307 J\u0301"};
+    std::vector<std::vector<CollectedToken>> root;
+    for (const std::string& value : values) {
+        root.push_back(collect_checked(*icu_analyzer(true), value));
+    }
+    EXPECT_EQ(terms_of(root[0]), (std::vector<std::string> {"i", "i\u0307", 
"ı", "i"}));
+
+    const icu::Locale saved = icu::Locale::getDefault();
+    Defer restore {[&] {
+        UErrorCode status = U_ZERO_ERROR;
+        icu::Locale::setDefault(saved, status);
+    }};
+    UErrorCode status = U_ZERO_ERROR;
+    icu::Locale::setDefault(icu::Locale("tr"), status);
+    ASSERT_TRUE(U_SUCCESS(status));
+    // The default took effect: ICU's default-locale lowercase of I is now the 
dotless ı.
+    icu::UnicodeString probe = icu::UnicodeString::fromUTF8("I");
+    ASSERT_EQ(probe.toLower(), icu::UnicodeString::fromUTF8("ı"));
+    for (size_t i = 0; i < values.size(); ++i) {
+        EXPECT_EQ(collect_checked(*icu_analyzer(true), values[i]), root[i]) << 
values[i];
+    }
+}
+
+TEST_F(ICUTokenizerStreamTest, AReusedStreamMakesWhatANewStreamMakes) {
+    std::string long_value;
+    while (long_value.size() < 12000) {
+        long_value += "word Ärger 中文 カタカナ ไทย 😀 ";
+    }
+    const std::vector<std::string> values = {
+            "Hello World",
+            "中文分词测试",
+            "ひらがなとカタカナ",
+            "ภาษาไทยง่าย",
+            "مرحبا بالعالم",
+            "한국어 형태소",
+            "\U0001F4A9 \U0001F469\u200D\u2764\uFE0F\u200D\U0001F469 
#\uFE0F\u20E3 3\uFE0F\u20E3",
+            "Mixed 中文 English ひらがな ไทย 123 😀 İstanbul",
+            "bad \xFF\xFE bytes \xC3 end \xE4\xB8",
+            "",
+            long_value};
+    for (bool lowercase : {true, false}) {
+        SCOPED_TRACE(lowercase);
+        expect_text_stream_contract([lowercase] { return 
icu_tokenizer(lowercase); }, values);
+        const TextAnalyzerPtr analyzer = icu_analyzer(lowercase);
+        expect_text_stream_contract([&] { return analyzer->create_stream(); }, 
values);
+    }
+}
+
+TEST_F(ICUTokenizerStreamTest, StrictModeThrowsWhereLenientModeReplaces) {
+    for (bool lowercase : {true, false}) {
+        SCOPED_TRACE(lowercase);
+        // Lenient: \xFF becomes U+FFFD, which is no word.
+        EXPECT_EQ(collect_terms(*icu_tokenizer(lowercase),
+                                "ab\xFF"
+                                "cd"),
+                  (std::vector<std::string> {"ab", "cd"}));
+
+        auto strict = icu_tokenizer(lowercase);
+        strict->set_strict_utf8(true);
+        try {
+            strict->reset(
+                    "ab\xFF"
+                    "cd");
+            FAIL() << "invalid UTF-8 did not throw";
+        } catch (const Exception& e) {
+            EXPECT_EQ(e.code(), ErrorCode::INVALID_ARGUMENT);
+        }
+        // No token after a reset that threw, and the next value reads as 
usual.
+        TokenBatch batch;
+        EXPECT_FALSE(strict->next_batch(batch));
+        EXPECT_EQ(collect_terms(*strict, "Ab 中文"),
+                  (std::vector<std::string> {lowercase ? "ab" : "Ab", "中文"}));
+    }
+}
+
+// U+1D400 MATHEMATICAL BOLD CAPITAL A is a letter of the Common script, so it 
stays in the Latin
+// word before it, as two UTF-16 units.
+TEST_F(ICUTokenizerStreamTest, 
CutsAWordAt255UnitsWithoutSplittingASurrogatePair) {
+    const std::string bold_a = "\U0001D400";
+    auto repeat = [](const std::string& unit, size_t count) {
+        std::string out;
+        for (size_t i = 0; i < count; ++i) {
+            out += unit;
+        }
+        return out;
+    };
+    const auto custom = [](const std::string& text) {
+        return collect_terms(*icu_tokenizer(false), text);
+    };
+    // 254 + 2 units: cut at 255 would split the pair, so the word is cut at 
254.
+    EXPECT_EQ(custom(repeat("a", 254) + bold_a), (std::vector<std::string> 
{repeat("a", 254)}));
+    EXPECT_EQ(custom(repeat("a", 253) + bold_a),
+              (std::vector<std::string> {repeat("a", 253) + bold_a}));
+    EXPECT_EQ(custom(repeat("a", 255) + bold_a), (std::vector<std::string> 
{repeat("a", 255)}));
+    EXPECT_EQ(custom(repeat(bold_a, 128)), (std::vector<std::string> 
{repeat(bold_a, 127)}));
+    EXPECT_EQ(custom(repeat(bold_a, 127) + "a"),
+              (std::vector<std::string> {repeat(bold_a, 127) + "a"}));
+    // The rest of a cut word is dropped.
+    EXPECT_EQ(custom("x " + repeat("a", 300) + " y"),
+              (std::vector<std::string> {"x", repeat("a", 255), "y"}));
+    EXPECT_EQ(custom(repeat("a", 254) + bold_a + " next"),
+              (std::vector<std::string> {repeat("a", 254), "next"}));
+
+    const auto lower = [](const std::string& text) {
+        return collect_terms(*icu_tokenizer(true), text);
+    };
+    EXPECT_EQ(lower(repeat("A", 254) + bold_a + "B"),
+              (std::vector<std::string> {repeat("a", 254)}));
+    EXPECT_EQ(lower(repeat("A", 253) + bold_a + "B"),
+              (std::vector<std::string> {repeat("a", 253) + bold_a}));
+    // Deseret capital letters, lowercased to Deseret small letters, both 
supplementary.
+    EXPECT_EQ(lower(repeat("\U00010400", 128)),
+              (std::vector<std::string> {repeat("\U00010428", 127)}));
+}
+
+TEST_F(ICUTokenizerStreamTest, ReleasesItsCopyOfALongValue) {
+    auto stream = icu_tokenizer(true);
+    auto& tokenizer = dynamic_cast<ICUTokenizer&>(*stream);
+    std::string long_value;
+    while (long_value.size() < 2 * 1024 * 1024) {
+        long_value += "word İstanbul 中文 ";
+    }
+    const auto member_bytes = [&] {
+        return static_cast<size_t>(tokenizer.buffer_.getCapacity()) * 
sizeof(UChar) +
+               tokenizer.utf8Str_.capacity();
+    };
+    collect_checked(tokenizer, long_value);
+    EXPECT_EQ(tokenizer.reserved_bytes(), member_bytes());
+    EXPECT_GT(tokenizer.reserved_bytes(), 1024 * 1024);
+    collect_checked(tokenizer, "short İ");
+    EXPECT_EQ(tokenizer.reserved_bytes(), member_bytes());
+    EXPECT_LE(tokenizer.reserved_bytes(), ANALYZER_SCRATCH_HIGH_WATER_BYTES);
+}
+
+} // namespace
+} // namespace doris::segment_v2::inverted_index


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

Reply via email to