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 e6eb5f08123 [improvement](be) Match the ik dictionaries through a flat
trie (#70268)
e6eb5f08123 is described below
commit e6eb5f08123dbce9bc67b62f4601ef5f0a9c11aa
Author: Jack <[email protected]>
AuthorDate: Sun Nov 22 18:27:10 2026 +0800
[improvement](be) Match the ik dictionaries through a flat trie (#70268)
### What problem does this PR solve?
Issue Number: None
Related PR: #70267 (depends on)
Problem Summary: Match the ik dictionaries through a flat trie: about
1.8x as fast, dictionary memory from 64 MB to 6 MB, the same tokens.
---
.../inverted/analysis/analyzer/ik/IKTokenizer.cpp | 67 +--
.../inverted/analysis/analyzer/ik/IKTokenizer.h | 17 +-
.../analysis/analyzer/ik/core/AnalyzeContext.cpp | 124 ++----
.../analysis/analyzer/ik/core/AnalyzeContext.h | 85 +++-
.../analysis/analyzer/ik/core/CJKSegmenter.cpp | 47 +-
.../analysis/analyzer/ik/core/CJKSegmenter.h | 12 +-
.../analyzer/ik/core/CN_QuantifierSegmenter.cpp | 11 +-
.../analyzer/ik/core/CN_QuantifierSegmenter.h | 8 +-
.../analysis/analyzer/ik/core/CharacterUtil.cpp | 65 ++-
.../analysis/analyzer/ik/core/CharacterUtil.h | 40 +-
.../analysis/analyzer/ik/core/IKSegmenter.cpp | 60 ++-
.../analysis/analyzer/ik/core/IKSegmenter.h | 20 +-
.../inverted/analysis/analyzer/ik/core/Lexeme.cpp | 14 -
.../inverted/analysis/analyzer/ik/core/Lexeme.h | 12 +-
.../analysis/analyzer/ik/core/QuickSortSet.cpp | 16 +-
.../analysis/analyzer/ik/core/QuickSortSet.h | 4 +-
.../analysis/analyzer/ik/dic/DictSegment.cpp | 106 ++---
.../analysis/analyzer/ik/dic/DictSegment.h | 47 +-
.../analysis/analyzer/ik/dic/Dictionary.cpp | 93 ++--
.../inverted/analysis/analyzer/ik/dic/Dictionary.h | 69 ++-
.../inverted/analysis/analyzer/ik/dic/FlatDict.h | 161 +++++++
.../index/inverted/analysis/analyzer/ik/dic/Hit.h | 18 +-
.../inverted/analysis/analyzer/ik_anayzer_test.cpp | 72 ++-
.../analysis/analyzer/ik_flat_dict_test.cpp | 482 +++++++++++++++++++++
.../inverted/analysis/component_stream_test.cpp | 15 +-
25 files changed, 1229 insertions(+), 436 deletions(-)
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.cpp
index 4427ca6a369..540ed055e78 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.cpp
@@ -19,6 +19,7 @@
#include <unicode/utf8.h>
+#include <cstring>
#include <utility>
#include "common/exception.h"
@@ -30,31 +31,30 @@ namespace doris::segment_v2 {
namespace {
-// Folds the word rune by rune as CharacterUtil::regularizeString() does,
except that an invalid
-// byte sequence is kept as it is and decoding goes on after it.
-void regularize_strictly(std::string& token, bool lowercase) {
- const auto length = static_cast<int32_t>(token.size());
- std::string normalized;
- normalized.reserve(token.size());
+// Folds the word rune by rune as CharacterUtil::regularizeInPlace() does,
except that an invalid
+// byte sequence is kept as it is and decoding goes on after it; returns the
new size. In place: a
+// valid rune is written back in at most the bytes it was read from, so with
`lowercase` AB
+// (EF BC A1 42) becomes ab in its first two bytes, and an invalid sequence is
copied as it is.
+size_t regularize_strictly(char* data, size_t size, bool lowercase) {
+ const auto length = static_cast<int32_t>(size);
+ int32_t out = 0;
int32_t offset = 0;
while (offset < length) {
const int32_t source_start = offset;
UChar32 codepoint;
- U8_NEXT(token.c_str(), offset, length, codepoint);
+ U8_NEXT(data, offset, length, codepoint);
if (codepoint < 0) {
- normalized.append(token, source_start, offset - source_start);
+ std::memmove(data + out, data + source_start, offset -
source_start);
+ out += offset - source_start;
continue;
}
UChar32 regularized = CharacterUtil::regularize(codepoint, false);
if (lowercase && regularized >= 'A' && regularized <= 'Z') {
regularized += 'a' - 'A';
}
- char encoded[U8_MAX_LENGTH];
- int32_t encoded_length = 0;
- U8_APPEND_UNSAFE(encoded, encoded_length, regularized);
- normalized.append(encoded, encoded_length);
+ U8_APPEND_UNSAFE(data, out, regularized);
}
- token = std::move(normalized);
+ return static_cast<size_t>(out);
}
} // namespace
@@ -67,33 +67,37 @@ IKTokenizer::IKTokenizer(std::shared_ptr<Configuration>
config, bool lowercase)
}
bool IKTokenizer::next_token(inverted_index::TokenRef& token) {
- if (buffer_index_ >= tokens_.size()) {
+ if (next_word_ >= words_.size()) {
return false;
}
- std::string& text = tokens_[buffer_index_++];
+ const Word& word = words_[next_word_++];
+ char* text = words_bytes_.data() + word.offset;
// full-width to half-width, and lowercase
- if (strict_utf8_) {
- regularize_strictly(text, lowercase_);
- } else {
- CharacterUtil::regularizeString(text, lowercase_);
- }
- size_t size = text.size();
+ size_t size = strict_utf8_ ? regularize_strictly(text, word.size,
lowercase_)
+ : CharacterUtil::regularizeInPlace(text,
word.size, lowercase_);
if (size > static_cast<size_t>(inverted_index::MAX_WORD_LEN)) {
- size = inverted_index::utf8_prefix_at_most(text,
inverted_index::MAX_WORD_LEN).first;
+ size = inverted_index::utf8_prefix_at_most({text, size},
inverted_index::MAX_WORD_LEN)
+ .first;
}
- token = {.data = text.data(), .size = static_cast<uint32_t>(size),
.position_increment = 1};
+ token = {.data = text, .size = static_cast<uint32_t>(size),
.position_increment = 1};
return true;
}
void IKTokenizer::on_reset(std::string_view text) {
- buffer_index_ = 0;
- tokens_.clear();
- inverted_index::release_oversized_scratch(tokens_);
+ next_word_ = 0;
+ words_.clear();
+ words_bytes_.clear();
+ inverted_index::release_oversized_scratch(words_);
+ inverted_index::release_oversized_scratch(words_bytes_);
try {
ik_segmenter_->reset(text);
Lexeme lexeme;
- while (ik_segmenter_->next(lexeme)) {
- tokens_.push_back(lexeme.getText());
+ std::string_view word;
+ while (ik_segmenter_->next(lexeme, word)) {
+ Word& entry = words_.emplace_back();
+ entry.offset = words_bytes_.size();
+ entry.size = word.size();
+ words_bytes_.append(word);
}
} catch (const Exception&) {
throw;
@@ -105,11 +109,8 @@ void IKTokenizer::on_reset(std::string_view text) {
}
size_t IKTokenizer::reserved_bytes() const {
- size_t bytes = tokens_.capacity() * sizeof(std::string) +
ik_segmenter_->reserved_bytes();
- for (const std::string& text : tokens_) {
- bytes += text.capacity();
- }
- return bytes;
+ return words_.capacity() * sizeof(Word) + words_bytes_.capacity() +
+ ik_segmenter_->reserved_bytes();
}
} // namespace doris::segment_v2
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.h
index f92cc25e3aa..d6eaca06ea5 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/IKTokenizer.h
@@ -17,6 +17,7 @@
#pragma once
+#include <cstddef>
#include <memory>
#include <string>
#include <string_view>
@@ -30,8 +31,13 @@ namespace doris::segment_v2 {
// The words IK segments the value into, full-width forms folded to half-width
and, with
// `lowercase`, ASCII lowercased; at most MAX_WORD_LEN bytes each, cut on a
rune boundary.
+//
+// reset() segments the whole value, so that a value IK cannot decode throws
there, and keeps the
+// words back to back in one buffer reused from value to value; next_token()
folds each word in
+// place, which never makes it longer.
class IKTokenizer final : public inverted_index::PerTokenTokenizer {
public:
+ // The dictionaries must be loaded.
IKTokenizer(std::shared_ptr<Configuration> config, bool lowercase);
// Strict: folds rune by rune and keeps an invalid byte sequence as it is.
@@ -45,8 +51,15 @@ protected:
bool next_token(inverted_index::TokenRef& token) override;
private:
- size_t buffer_index_ {0};
- std::vector<std::string> tokens_;
+ // A word of the current value: words_bytes_[offset, offset + size).
+ struct Word {
+ size_t offset;
+ size_t size;
+ };
+
+ size_t next_word_ {0};
+ std::string words_bytes_;
+ std::vector<Word> words_;
std::shared_ptr<Configuration> config_;
std::unique_ptr<IKSegmenter> ik_segmenter_;
const bool lowercase_;
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.cpp
index 0bb4dca4ee1..eb9ee38e80e 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.cpp
@@ -20,12 +20,14 @@
#include <algorithm>
#include <cstring>
#include <string>
+#include <utility>
#include "common/exception.h"
namespace doris::segment_v2 {
-AnalyzeContext::AnalyzeContext(Arena& arena, std::shared_ptr<Configuration>
config)
+AnalyzeContext::AnalyzeContext(Arena& arena, std::shared_ptr<Configuration>
config,
+ const Dictionary& dictionary)
: segment_buff_(),
typed_runes_(),
buffer_offset_(0),
@@ -35,8 +37,8 @@ AnalyzeContext::AnalyzeContext(Arena& arena,
std::shared_ptr<Configuration> conf
buffer_locker_(0),
org_lexemes_(arena),
path_map_(),
- results_(),
- config_(config) {
+ config_(std::move(config)),
+ dictionary_(dictionary) {
segment_buff_.resize(BUFF_SIZE);
typed_runes_.reserve(BUFF_SIZE);
}
@@ -66,7 +68,8 @@ void AnalyzeContext::reset() {
}
path_map_.clear();
- results_ = std::queue<Lexeme>();
+ results_.clear();
+ results_head_ = 0;
}
size_t AnalyzeContext::fillBuffer(inverted_index::TextCursor& cursor) {
@@ -134,9 +137,9 @@ void AnalyzeContext::compound(Lexeme& lexeme) {
if (!config_->isUseSmart()) {
return;
}
- if (!results_.empty()) {
+ if (hasResult()) {
if (Lexeme::Type::Arabic == lexeme.getType()) {
- auto& nextLexeme = results_.front();
+ const Lexeme& nextLexeme = results_[results_head_];
bool appendOk = false;
if (Lexeme::Type::CNum == nextLexeme.getType()) {
appendOk = lexeme.append(nextLexeme, Lexeme::Type::CNum);
@@ -144,113 +147,44 @@ void AnalyzeContext::compound(Lexeme& lexeme) {
appendOk = lexeme.append(nextLexeme, Lexeme::Type::CQuan);
}
if (appendOk) {
- results_.pop();
+ ++results_head_;
}
}
- if (Lexeme::Type::CNum == lexeme.getType() && !results_.empty()) {
- auto nextLexeme = results_.front();
+ if (Lexeme::Type::CNum == lexeme.getType() && hasResult()) {
+ const Lexeme& nextLexeme = results_[results_head_];
bool appendOk = false;
if (Lexeme::Type::Count == nextLexeme.getType()) {
appendOk = lexeme.append(nextLexeme, Lexeme::Type::CQuan);
}
if (appendOk) {
- results_.pop();
+ ++results_head_;
}
}
}
- return;
-}
-
-bool AnalyzeContext::moveCursor() {
- if (cursor_ < typed_runes_.size() - 1) {
- cursor_++;
- return true;
- }
- return false;
-}
-
-void AnalyzeContext::initCursor() {
- cursor_ = 0;
-}
-
-bool AnalyzeContext::isBufferConsumed() const {
- return cursor_ == typed_runes_.size() - 1;
-}
-
-bool AnalyzeContext::needRefillBuffer() const {
- return available_ == BUFF_SIZE && !isBufferLocked() && cursor_ <
typed_runes_.size() - 1 &&
- cursor_ > typed_runes_.size() - BUFF_EXHAUST_CRITICAL;
}
void AnalyzeContext::markBufferOffset() {
buffer_offset_ += typed_runes_[cursor_].getNextBytePosition();
}
-void AnalyzeContext::lockBuffer(SegmenterType type) {
- switch (type) {
- case SegmenterType::CJK_SEGMENTER:
- buffer_locker_ |= CJK_SEGMENTER_FLAG;
- break;
- case SegmenterType::CN_QUANTIFIER:
- buffer_locker_ |= CN_QUANTIFIER_FLAG;
- break;
- case SegmenterType::LETTER_SEGMENTER:
- buffer_locker_ |= LETTER_SEGMENTER_FLAG;
- break;
- case SegmenterType::SURROGATE_PAIR_SEGMENTER:
- buffer_locker_ |= SURROGATE_PAIR_SEGMENTER_FLAG;
- break;
- }
-}
-
-void AnalyzeContext::unlockBuffer(SegmenterType type) {
- switch (type) {
- case SegmenterType::CJK_SEGMENTER:
- buffer_locker_ &= ~CJK_SEGMENTER_FLAG;
- break;
- case SegmenterType::CN_QUANTIFIER:
- buffer_locker_ &= ~CN_QUANTIFIER_FLAG;
- break;
- case SegmenterType::LETTER_SEGMENTER:
- buffer_locker_ &= ~LETTER_SEGMENTER_FLAG;
- break;
- case SegmenterType::SURROGATE_PAIR_SEGMENTER:
- buffer_locker_ &= ~SURROGATE_PAIR_SEGMENTER_FLAG;
- break;
- }
-}
-
-bool AnalyzeContext::isBufferLocked() const {
- return buffer_locker_ != 0;
-}
-
bool AnalyzeContext::getNextLexeme(Lexeme& lexeme) {
- if (results_.empty()) {
- return false;
- }
- auto result = results_.front();
- results_.pop();
- auto* dictionary = Dictionary::getSingleton();
- while (true) {
+ while (hasResult()) {
+ Lexeme result = results_[results_head_++];
compound(result);
- if (dictionary->isStopWord(typed_runes_, result.getCharBegin(),
result.getCharLength())) {
- if (results_.empty()) {
- return false;
- }
- result = results_.front();
- results_.pop();
- } else {
- result.setText(std::string(segment_buff_.data() +
result.getByteBegin(),
- result.getByteLength()));
- break;
+ if (!dictionary_.isStopWord(typed_runes_, result.getCharBegin(),
result.getCharLength())) {
+ lexeme = result;
+ return true;
}
}
- lexeme = std::move(result);
- return true;
+ return false;
}
void AnalyzeContext::outputToResult() {
+ // The lexemes of the previous window are all read before the next window
is analyzed.
+ DCHECK(!hasResult());
+ results_.clear();
+ results_head_ = 0;
for (size_t index = 0; index <= cursor_;) {
if (typed_runes_[index].char_type == CharacterUtil::CharType::USELESS)
{
index++;
@@ -263,7 +197,7 @@ void AnalyzeContext::outputToResult() {
if (pathIter != path_map_.end()) {
auto& path = pathIter->second;
while (auto lexeme = path->pollFirst()) {
- results_.push(*lexeme);
+ results_.push_back(*lexeme);
index = lexeme->getCharEnd() + 1;
auto next_lexeme = path->peekFirst();
if (next_lexeme) {
@@ -286,11 +220,11 @@ void AnalyzeContext::outputToResult() {
void AnalyzeContext::outputSingleCJK(size_t index) {
if (typed_runes_[index].char_type == CharacterUtil::CharType::CHINESE ||
typed_runes_[index].char_type == CharacterUtil::CharType::OTHER_CJK) {
- results_.emplace(buffer_offset_, typed_runes_[index].offset,
typed_runes_[index].len,
- typed_runes_[index].char_type ==
CharacterUtil::CharType::CHINESE
- ? Lexeme::Type::CNChar
- : Lexeme::Type::OtherCJK,
- index, index);
+ results_.emplace_back(buffer_offset_, typed_runes_[index].offset,
typed_runes_[index].len,
+ typed_runes_[index].char_type ==
CharacterUtil::CharType::CHINESE
+ ? Lexeme::Type::CNChar
+ : Lexeme::Type::OtherCJK,
+ index, index);
}
}
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.h
index 7dc60cdc926..927c5b1261e 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.h
@@ -19,13 +19,10 @@
#include <parallel_hashmap/phmap.h>
-#include <list>
-#include <map>
#include <memory>
-#include <optional>
-#include <queue>
-#include <set>
#include <string>
+#include <string_view>
+#include <vector>
#include "common/logging.h"
#include "core/arena.h"
@@ -66,12 +63,17 @@ private:
QuickSortSet org_lexemes_;
// LexemePath position index table
phmap::flat_hash_map<size_t, LexemePath*> path_map_;
- // Final tokenization result set
- std::queue<Lexeme> results_;
+ // The final lexemes of the window, which outputToResult() fills and
getNextLexeme() reads
+ // from results_head_ on; reused from window to window and value to value.
+ std::vector<Lexeme> results_;
+ size_t results_head_ {0};
// Tokenizer configuration
std::shared_ptr<Configuration> config_;
+ // The loaded dictionaries, for the stop words.
+ const Dictionary& dictionary_;
void outputSingleCJK(size_t index);
void compound(Lexeme& lexeme);
+ bool hasResult() const { return results_head_ < results_.size(); }
public:
enum class SegmenterType {
@@ -81,7 +83,8 @@ public:
SURROGATE_PAIR_SEGMENTER
};
const CharacterUtil::TypedRuneArray& getTypedRuneArray() const { return
typed_runes_; }
- explicit AnalyzeContext(Arena& arena, std::shared_ptr<Configuration>
config);
+ AnalyzeContext(Arena& arena, std::shared_ptr<Configuration> config,
+ const Dictionary& dictionary);
virtual ~AnalyzeContext();
void reset();
@@ -92,24 +95,72 @@ public:
size_t getLastUselessCharNum() const { return last_useless_char_num_; }
size_t fillBuffer(inverted_index::TextCursor& cursor);
- // The read window and the runes decoded from it, both sized by BUFF_SIZE.
+ // The read window, the runes decoded from it and the window's final
lexemes, all bounded by
+ // BUFF_SIZE.
size_t reserved_bytes() const {
return segment_buff_.capacity() +
- typed_runes_.capacity() * sizeof(CharacterUtil::TypedRune);
+ typed_runes_.capacity() * sizeof(CharacterUtil::TypedRune) +
+ results_.capacity() * sizeof(Lexeme);
+ }
+ // The cursor and lock helpers below run several times per character, from
every segmenter,
+ // so they are defined here, where the segmenters can inline them.
+ bool moveCursor() {
+ if (cursor_ < typed_runes_.size() - 1) {
+ cursor_++;
+ return true;
+ }
+ return false;
+ }
+ void initCursor() { cursor_ = 0; }
+ bool isBufferConsumed() const { return cursor_ == typed_runes_.size() - 1;
}
+ bool needRefillBuffer() const {
+ return available_ == BUFF_SIZE && !isBufferLocked() && cursor_ <
typed_runes_.size() - 1 &&
+ cursor_ > typed_runes_.size() - BUFF_EXHAUST_CRITICAL;
}
- bool moveCursor();
- void initCursor();
- bool isBufferConsumed() const;
- bool needRefillBuffer() const;
void markBufferOffset();
- void lockBuffer(SegmenterType type);
- void unlockBuffer(SegmenterType type);
- bool isBufferLocked() const;
+ void lockBuffer(SegmenterType type) {
+ switch (type) {
+ case SegmenterType::CJK_SEGMENTER:
+ buffer_locker_ |= CJK_SEGMENTER_FLAG;
+ break;
+ case SegmenterType::CN_QUANTIFIER:
+ buffer_locker_ |= CN_QUANTIFIER_FLAG;
+ break;
+ case SegmenterType::LETTER_SEGMENTER:
+ buffer_locker_ |= LETTER_SEGMENTER_FLAG;
+ break;
+ case SegmenterType::SURROGATE_PAIR_SEGMENTER:
+ buffer_locker_ |= SURROGATE_PAIR_SEGMENTER_FLAG;
+ break;
+ }
+ }
+ void unlockBuffer(SegmenterType type) {
+ switch (type) {
+ case SegmenterType::CJK_SEGMENTER:
+ buffer_locker_ &= ~CJK_SEGMENTER_FLAG;
+ break;
+ case SegmenterType::CN_QUANTIFIER:
+ buffer_locker_ &= ~CN_QUANTIFIER_FLAG;
+ break;
+ case SegmenterType::LETTER_SEGMENTER:
+ buffer_locker_ &= ~LETTER_SEGMENTER_FLAG;
+ break;
+ case SegmenterType::SURROGATE_PAIR_SEGMENTER:
+ buffer_locker_ &= ~SURROGATE_PAIR_SEGMENTER_FLAG;
+ break;
+ }
+ }
+ bool isBufferLocked() const { return buffer_locker_ != 0; }
void addLexeme(Lexeme& lexeme);
void addLexemePath(LexemePath* path);
+ // The next final lexeme of the window that is no stop word, or false once
there is none.
bool getNextLexeme(Lexeme& lexeme);
+ // The bytes of a lexeme of the current window; valid until the window is
refilled.
+ std::string_view getText(const Lexeme& lexeme) const {
+ return {segment_buff_.data() + lexeme.getByteBegin(),
lexeme.getByteLength()};
+ }
QuickSortSet* getOrgLexemes() { return &org_lexemes_; }
void outputToResult();
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.cpp
index 11227ce4b25..e18a6ccc771 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.cpp
@@ -19,39 +19,32 @@
namespace doris::segment_v2 {
-CJKSegmenter::CJKSegmenter() = default;
+CJKSegmenter::CJKSegmenter(const Dictionary& dictionary) :
dictionary_(dictionary) {}
void CJKSegmenter::analyze(AnalyzeContext& context) {
if (context.getCurrentCharType() != CharacterUtil::CharType::USELESS) {
- // Prioritize processing the prefixes that have already been matched
- if (!tmp_hits_.empty()) {
- auto it = tmp_hits_.begin();
- while (it != tmp_hits_.end()) {
- Hit& hit = *it;
-
Dictionary::getSingleton()->matchWithHit(context.getTypedRuneArray(),
- context.getCursor(),
hit);
- if (hit.isMatch()) {
- Lexeme newLexeme(context.getBufferOffset(),
hit.getByteBegin(),
- hit.getByteEnd() - hit.getByteBegin(),
Lexeme::Type::CNWord,
- hit.getCharBegin(), hit.getCharEnd());
- context.addLexeme(newLexeme);
-
- if (!hit.isPrefix()) {
- it = tmp_hits_.erase(it);
- } else {
- ++it;
- }
- } else if (hit.isUnmatch()) {
- // Hit is not a word, remove
- it = tmp_hits_.erase(it);
- } else {
- ++it;
- }
+ // Prioritize processing the prefixes that have already been matched.
A hit that is still
+ // a prefix moves down to the next kept slot, so the kept hits stay in
their order: in
+ // ABCD, four Han characters, the hits at D started at A, B and C; BCD
leads to no word
+ // and is dropped, and the hits from A and C stay first and second.
+ size_t kept = 0;
+ for (Hit& hit : tmp_hits_) {
+ dictionary_.matchWithHit(context.getTypedRuneArray(),
context.getCursor(), hit);
+ if (hit.isMatch()) {
+ Lexeme newLexeme(context.getBufferOffset(), hit.getByteBegin(),
+ hit.getByteEnd() - hit.getByteBegin(),
Lexeme::Type::CNWord,
+ hit.getCharBegin(), hit.getCharEnd());
+ context.addLexeme(newLexeme);
+ }
+ // A hit that is no longer a prefix, a word that ends here or no
word, is dropped.
+ if (hit.isPrefix()) {
+ tmp_hits_[kept++] = hit;
}
}
+ tmp_hits_.resize(kept);
// Perform a single-character match at the current pointer position.
- auto singleCharHit = Dictionary::getSingleton()->matchInMainDict(
- context.getTypedRuneArray(), context.getCursor(), 1);
+ auto singleCharHit =
+ dictionary_.matchInMainDict(context.getTypedRuneArray(),
context.getCursor(), 1);
if (singleCharHit.isMatch()) {
Lexeme newLexeme(context.getBufferOffset(),
context.getCurrentCharOffset(),
context.getCurrentCharLen(), Lexeme::Type::CNChar,
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.h
index 4b11c70f5ff..8bf742ecd6e 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.h
@@ -17,9 +17,7 @@
#pragma once
-#include <list>
-#include <memory>
-#include <string>
+#include <vector>
#include "storage/index/inverted/analysis/analyzer/ik/core/AnalyzeContext.h"
#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
@@ -27,14 +25,16 @@
namespace doris::segment_v2 {
-class CJKSegmenter : public ISegmenter {
+class CJKSegmenter final : public ISegmenter {
private:
static constexpr AnalyzeContext::SegmenterType SEGMENTER_TYPE =
AnalyzeContext::SegmenterType::CJK_SEGMENTER;
- std::list<Hit> tmp_hits_;
+ const Dictionary& dictionary_;
+ // The prefixes matched so far, oldest first.
+ std::vector<Hit> tmp_hits_;
public:
- CJKSegmenter();
+ explicit CJKSegmenter(const Dictionary& dictionary);
void analyze(AnalyzeContext& context) override;
void reset() override;
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.cpp
index a1b38ab1241..7a1be1bee29 100644
---
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.cpp
+++
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.cpp
@@ -30,7 +30,8 @@ const std::unordered_set<char32_t>
CN_QuantifierSegmenter::CHINESE_NUMBER_CHARS
return chars;
}();
-CN_QuantifierSegmenter::CN_QuantifierSegmenter() : number_start_(-1),
number_end_(-1) {}
+CN_QuantifierSegmenter::CN_QuantifierSegmenter(const Dictionary& dictionary)
+ : dictionary_(dictionary), number_start_(-1), number_end_(-1) {}
void CN_QuantifierSegmenter::analyze(AnalyzeContext& context) {
// Handle Chinese numerals
@@ -38,7 +39,7 @@ void CN_QuantifierSegmenter::analyze(AnalyzeContext& context)
{
// Handle Chinese measure words
processCount(context);
- if (number_start_ == -1 && number_end_ == -1 && count_hits_.empty()) {
+ if (isIdle()) {
context.unlockBuffer(CN_QuantifierSegmenter::SEGMENTER_TYPE);
} else {
context.lockBuffer(CN_QuantifierSegmenter::SEGMENTER_TYPE);
@@ -94,7 +95,7 @@ void CN_QuantifierSegmenter::processCount(AnalyzeContext&
context) {
if (!count_hits_.empty()) {
auto it = count_hits_.begin();
while (it != count_hits_.end()) {
- Dictionary::getSingleton()->matchWithHit(typedRuneArray,
it->getCharEnd(), *it);
+ dictionary_.matchWithHit(typedRuneArray, it->getCharEnd(),
*it);
if (it->isMatch()) {
Lexeme newLexeme(context.getBufferOffset(),
it->getByteBegin(),
it->getByteEnd() - it->getByteBegin(),
Lexeme::Type::Count,
@@ -126,8 +127,8 @@ void CN_QuantifierSegmenter::processCount(AnalyzeContext&
context) {
if (shouldMatchSingleChar || !count_hits_.empty()) {
// Perform a single-character match at the current pointer
position.
- auto singleCharHit =
Dictionary::getSingleton()->matchInQuantifierDict(
- typedRuneArray, context.getCursor(), 1);
+ auto singleCharHit =
+ dictionary_.matchInQuantifierDict(typedRuneArray,
context.getCursor(), 1);
if (singleCharHit.isMatch()) {
Lexeme newLexeme(context.getBufferOffset(),
context.getCurrentCharOffset(),
context.getCurrentCharLen(),
Lexeme::Type::Count,
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.h
index e1ff04bb7a1..150ba165026 100644
---
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.h
+++
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.h
@@ -25,18 +25,21 @@
#include "storage/index/inverted/analysis/analyzer/ik/core/ISegmenter.h"
namespace doris::segment_v2 {
-class CN_QuantifierSegmenter : public ISegmenter {
+class CN_QuantifierSegmenter final : public ISegmenter {
public:
static constexpr AnalyzeContext::SegmenterType SEGMENTER_TYPE =
AnalyzeContext::SegmenterType::CN_QUANTIFIER;
static const std::u32string CHINESE_NUMBERS;
static const std::unordered_set<char32_t> CHINESE_NUMBER_CHARS;
- CN_QuantifierSegmenter();
+ explicit CN_QuantifierSegmenter(const Dictionary& dictionary);
~CN_QuantifierSegmenter() override = default;
void analyze(AnalyzeContext& context) override;
void reset() override;
+ // No numeral and no quantifier in progress: analyze() then only releases
the lock on a
+ // character that is not Chinese.
+ bool isIdle() const { return number_start_ == -1 && number_end_ == -1 &&
count_hits_.empty(); }
private:
void processCNumber(AnalyzeContext& context);
@@ -44,6 +47,7 @@ private:
bool needCountScan(AnalyzeContext& context);
void outputNumLexeme(AnalyzeContext& context);
+ const Dictionary& dictionary_;
int number_start_;
int number_end_;
std::vector<Hit> count_hits_;
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.cpp
index 1d93bae6542..e76b21b3485 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.cpp
@@ -19,7 +19,13 @@
namespace doris::segment_v2 {
-CharacterUtil::CharType CharacterUtil::identifyCharType(int32_t rune) {
+CharacterUtil::BmpCharTypes::BmpCharTypes() {
+ for (int32_t rune = 0; rune < kSize; ++rune) {
+ types[rune] = static_cast<uint8_t>(identifyCharTypeByBlock(rune));
+ }
+}
+
+CharacterUtil::CharType CharacterUtil::identifyCharTypeByBlock(int32_t rune) {
if (rune >= '0' && rune <= '9') {
return CharType::ARABIC;
}
@@ -93,45 +99,62 @@ void CharacterUtil::decodeStringToRunes(char* str, size_t
length, TypedRuneArray
if (runeStr.len == 1 && use_lowercase && str[byte_pos] >= 'A' &&
str[byte_pos] <= 'Z') {
str[byte_pos] += 32;
}
- typed_runes.emplace_back(runeStr.rune, byte_pos, runeStr.len,
typed_runes.size(), 1);
-
- typed_runes.back().regularize(use_lowercase);
+ // The rune is regularized before its type is taken, as
TypedRune::regularize() does.
+
typed_runes.emplace_back(regularize(static_cast<int32_t>(runeStr.rune),
use_lowercase),
+ byte_pos, runeStr.len, typed_runes.size(), 1);
byte_pos += runeStr.len;
}
}
-void CharacterUtil::regularizeString(std::string& input, bool use_lowercase) {
- std::string temp;
- size_t len = input.size();
- temp.reserve(len);
- for (size_t i = 0; i < len;) {
- unsigned char c = input[i];
- if ((c & 0xF0) == 0xE0 && i + 2 < len) {
- int rune = ((c & 0x0F) << 12) | ((input[i + 1] & 0x3F) << 6) |
(input[i + 2] & 0x3F);
+size_t CharacterUtil::regularizeInPlace(char* data, size_t length, bool
use_lowercase) {
+ // U+3000 is E3 80 80 and U+FF01 to U+FF5E are EF BC 81 to EF BD 9E, so
only a three-byte group
+ // led by E3 or EF can fold, and with `use_lowercase` an ASCII capital
lower; a word without
+ // them comes back byte for byte. The Han characters U+6570 U+636E U+5E93
are E6 95 B0 E6 8D AE
+ // E5 BA 93 and stay as they are, SQL (EF BC B3 ...) and Doris go the full
way.
+ bool may_change = false;
+ for (size_t i = 0; i < length; ++i) {
+ const auto byte = static_cast<uint8_t>(data[i]);
+ if (byte == 0xE3 || byte == 0xEF || (use_lowercase && byte >= 'A' &&
byte <= 'Z')) {
+ may_change = true;
+ break;
+ }
+ }
+ if (!may_change) {
+ return length;
+ }
+ // Never longer than what it reads, so the folded bytes can go where the
word was: a group
+ // that folds writes one byte for three, every other byte writes itself.
+ size_t out = 0;
+ for (size_t i = 0; i < length;) {
+ const auto c = static_cast<unsigned char>(data[i]);
+ if ((c & 0xF0) == 0xE0 && i + 2 < length) {
+ const char second = data[i + 1];
+ const char third = data[i + 2];
+ int rune = ((c & 0x0F) << 12) | ((second & 0x3F) << 6) | (third &
0x3F);
if (rune == 0x3000) {
- temp += ' ';
+ data[out++] = ' ';
} else if (rune >= 0xFF01 && rune <= 0xFF5E) {
char half = static_cast<char>(rune - 0xFEE0);
if (use_lowercase && half >= 'A' && half <= 'Z') {
half += 32;
}
- temp += half;
+ data[out++] = half;
} else {
- temp += input[i];
- temp += input[i + 1];
- temp += input[i + 2];
+ data[out++] = static_cast<char>(c);
+ data[out++] = second;
+ data[out++] = third;
}
i += 3;
} else {
- char ch = input[i];
+ char ch = data[i];
if (use_lowercase && ch >= 'A' && ch <= 'Z') {
ch += 32;
}
- temp += ch;
+ data[out++] = ch;
i += 1;
}
}
- input = std::move(temp);
+ return out;
}
-} // namespace doris::segment_v2
\ No newline at end of file
+} // namespace doris::segment_v2
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h
index 5d7760c6d2f..c75586df7d7 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h
@@ -19,6 +19,7 @@
#include <unicode/uchar.h>
+#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -76,7 +77,18 @@ public:
using TypedRuneArray = std::vector<TypedRune>;
- static CharType identifyCharType(int32_t rune);
+ // The type of `rune`: identifyCharTypeByBlock(), read from a table for
the first plane, where
+ // nearly every character of a text is.
+ static CharType identifyCharType(int32_t rune) {
+ if (rune >= 0 && rune < BmpCharTypes::kSize) {
+ return static_cast<CharType>(BmpCharTypes::instance().types[rune]);
+ }
+ return identifyCharTypeByBlock(rune);
+ }
+
+ // The type of `rune` by its ASCII class or Unicode block: a binary search
of ICU's blocks for
+ // anything but an ASCII digit or letter.
+ static CharType identifyCharTypeByBlock(int32_t rune);
static void decodeStringToRunes(char* str, size_t length, TypedRuneArray&
typed_runes,
bool use_lowercase);
@@ -88,7 +100,31 @@ public:
static void regularizeCharInfo(TypedRune& type_rune, bool use_lowercase);
- static void regularizeString(std::string& input, bool use_lowercase =
true);
+ // Folds U+3000 to a space and U+FF01 to U+FF5E to ASCII, and with
`use_lowercase` lowercases
+ // ASCII capitals, in place; returns the new length, which is at most
`length`. A lead byte
+ // from E0 to EF takes the next two bytes whatever they are, so E3 C0 80
folds to a space too.
+ static size_t regularizeInPlace(char* data, size_t length, bool
use_lowercase);
+
+ // regularizeInPlace() of `input`.
+ static void regularizeString(std::string& input, bool use_lowercase =
true) {
+ input.resize(regularizeInPlace(input.data(), input.size(),
use_lowercase));
+ }
+
+private:
+ // identifyCharTypeByBlock() of every first-plane character, built in
place on first use, so
+ // that its 64 KiB never land on a small stack.
+ struct BmpCharTypes {
+ static constexpr int32_t kSize = 0x10000;
+
+ BmpCharTypes();
+
+ static const BmpCharTypes& instance() {
+ static const BmpCharTypes kInstance;
+ return kInstance;
+ }
+
+ std::array<uint8_t, kSize> types;
+ };
};
} // namespace doris::segment_v2
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.cpp
index dade6edf73e..754e281f026 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.cpp
@@ -17,25 +17,46 @@
#include "storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.h"
+#include <utility>
+
namespace doris::segment_v2 {
IKSegmenter::IKSegmenter(std::shared_ptr<Configuration> config)
- : arena_(),
- config_(config),
- context_(std::make_unique<AnalyzeContext>(arena_, config_)),
- segmenters_(loadSegmenters()),
- arbitrator_(IKArbitrator(arena_)) {}
+ : config_(std::move(config)),
+ dictionary_(*Dictionary::getSingleton()),
+ context_(std::make_unique<AnalyzeContext>(arena_, config_,
dictionary_)),
+ quantifier_segmenter_(dictionary_),
+ cjk_segmenter_(dictionary_),
+ arbitrator_(arena_) {}
-std::vector<std::unique_ptr<ISegmenter>> IKSegmenter::loadSegmenters() {
- std::vector<std::unique_ptr<ISegmenter>> segmenters;
- segmenters.push_back(std::make_unique<LetterSegmenter>());
- segmenters.push_back(std::make_unique<CN_QuantifierSegmenter>());
- segmenters.push_back(std::make_unique<CJKSegmenter>());
- segmenters.push_back(std::make_unique<SurrogatePairSegmenter>());
- return segmenters;
+void IKSegmenter::analyzeCurrentChar() {
+ const CharacterUtil::CharType type = context_->getCurrentCharType();
+ letter_segmenter_.analyze(*context_);
+ // An idle quantifier segmenter does nothing on a character that is not
Chinese but release
+ // its lock, which it may still hold from the end of the previous window:
say a window ends
+ // in U+4E09, the Chinese numeral three, and the next one starts with "a",
then only the
+ // release of the lock is left to do.
+ if (type == CharacterUtil::CharType::CHINESE ||
!quantifier_segmenter_.isIdle()) {
+ quantifier_segmenter_.analyze(*context_);
+ } else {
+ context_->unlockBuffer(CN_QuantifierSegmenter::SEGMENTER_TYPE);
+ }
+ cjk_segmenter_.analyze(*context_);
+ // The surrogate pair segmenter only makes a lexeme of a surrogate pair
character. It never
+ // locks the buffer, so there is no lock to release on any other character.
+ if (type == CharacterUtil::CharType::SURROGATE) {
+ surrogate_pair_segmenter_.analyze(*context_);
+ }
}
-bool IKSegmenter::next(Lexeme& lexeme) {
+void IKSegmenter::resetSegmenters() {
+ letter_segmenter_.reset();
+ quantifier_segmenter_.reset();
+ cjk_segmenter_.reset();
+ surrogate_pair_segmenter_.reset();
+}
+
+bool IKSegmenter::next(Lexeme& lexeme, std::string_view& text) {
while (!context_->getNextLexeme(lexeme)) {
// Read data from the reader and fill the buffer
auto available = static_cast<int32_t>(context_->fillBuffer(input_));
@@ -45,32 +66,27 @@ bool IKSegmenter::next(Lexeme& lexeme) {
} else {
context_->initCursor();
do {
- for (const auto& segmenter : segmenters_) {
- segmenter->analyze(*context_);
- }
+ analyzeCurrentChar();
// The buffer is nearly read, new characters need to be read
in.
if (context_->needRefillBuffer()) {
break;
}
} while (context_->moveCursor());
- for (const auto& segmenter : segmenters_) {
- segmenter->reset();
- }
+ resetSegmenters();
}
arbitrator_.process(*context_, config_->isUseSmart());
context_->outputToResult();
context_->markBufferOffset();
arena_.clear();
}
+ text = context_->getText(lexeme);
return true;
}
void IKSegmenter::reset(std::string_view text) {
input_.reset(text);
context_->reset();
- for (const auto& segmenter : segmenters_) {
- segmenter->reset();
- }
+ resetSegmenters();
}
size_t IKSegmenter::getLastUselessCharNum() {
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.h
index 8aa7fee96af..43bf6489ca1 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/IKSegmenter.h
@@ -17,10 +17,8 @@
#pragma once
-#include <iostream>
#include <memory>
#include <string_view>
-#include <vector>
#include "core/arena.h"
#include "storage/index/inverted/analysis/analyzer/ik/cfg/Configuration.h"
@@ -28,27 +26,37 @@
#include "storage/index/inverted/analysis/analyzer/ik/core/CJKSegmenter.h"
#include
"storage/index/inverted/analysis/analyzer/ik/core/CN_QuantifierSegmenter.h"
#include "storage/index/inverted/analysis/analyzer/ik/core/IKArbitrator.h"
-#include "storage/index/inverted/analysis/analyzer/ik/core/ISegmenter.h"
#include "storage/index/inverted/analysis/analyzer/ik/core/LetterSegmenter.h"
#include
"storage/index/inverted/analysis/analyzer/ik/core/SurrogatePairSegmenter.h"
namespace doris::segment_v2 {
class IKSegmenter {
public:
+ // The dictionaries must be loaded: the segmenter takes the loaded
Dictionary once, here.
IKSegmenter(std::shared_ptr<Configuration> config);
- bool next(Lexeme& lexeme);
+ // The next lexeme of the value, or false once it is exhausted. `text`
views the lexeme's bytes
+ // in the window and stays valid until the next call.
+ bool next(Lexeme& lexeme, std::string_view& text);
void reset(std::string_view text);
size_t getLastUselessCharNum();
// The arena of the current window and the window itself.
size_t reserved_bytes() const { return arena_.size() +
context_->reserved_bytes(); }
private:
- std::vector<std::unique_ptr<ISegmenter>> loadSegmenters();
+ // Runs the segmenters on the character at the cursor, in the order
letter, quantifier, CJK,
+ // surrogate pair.
+ void analyzeCurrentChar();
+ void resetSegmenters();
+
Arena arena_;
inverted_index::TextCursor input_;
std::shared_ptr<Configuration> config_;
+ const Dictionary& dictionary_;
std::unique_ptr<AnalyzeContext> context_;
- std::vector<std::unique_ptr<ISegmenter>> segmenters_;
+ LetterSegmenter letter_segmenter_;
+ CN_QuantifierSegmenter quantifier_segmenter_;
+ CJKSegmenter cjk_segmenter_;
+ SurrogatePairSegmenter surrogate_pair_segmenter_;
IKArbitrator arbitrator_;
};
} // namespace doris::segment_v2
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.cpp
index fcbfa34b534..423baadf8cf 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.cpp
@@ -35,14 +35,6 @@ void Lexeme::setLength(size_t length) {
this->byte_length_ = length;
}
-void Lexeme::setText(std::string&& text) {
- if (text.empty()) {
- this->text_.clear();
- return;
- }
- this->text_ = std::move(text);
-}
-
bool Lexeme::append(const Lexeme& other, Type new_type) {
if (this->getByteEndPosition() == other.getByteBeginPosition()) {
byte_length_ += other.getByteLength();
@@ -53,12 +45,6 @@ bool Lexeme::append(const Lexeme& other, Type new_type) {
return false;
}
-std::string Lexeme::toString() const {
- std::ostringstream oss;
- oss << getByteBeginPosition() << '-' << getByteEndPosition() << " : " <<
text_;
- return oss.str();
-}
-
bool Lexeme::operator==(const Lexeme& other) const noexcept {
return offset_ == other.offset_ && byte_begin_ == other.byte_begin_ &&
byte_length_ == other.byte_length_;
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.h
index 659f9415a97..8bb3a6c45fa 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/Lexeme.h
@@ -17,15 +17,17 @@
#pragma once
+#include <cstddef>
#include <memory>
-#include <sstream>
#include <stdexcept>
-#include <string>
#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
namespace doris::segment_v2 {
+// A word candidate: where it is in the window and what kind it is. Its text
is the window's bytes
+// it spans, which AnalyzeContext::getText() views; a lexeme carries no
string, so the arbitration
+// copies and moves it as plain data.
class Lexeme {
public:
enum class Type {
@@ -65,7 +67,6 @@ public:
byte_length_ = 0;
char_begin_ = 0;
char_end_ = 0;
- text_.clear();
type_ = Type::Unknown;
}
bool append(const Lexeme& other, Type newType);
@@ -76,7 +77,6 @@ public:
size_t getByteLength() const noexcept { return byte_length_; }
size_t getCharLength() const noexcept { return char_end_ - char_begin_ +
1; }
Type getType() const noexcept { return type_; }
- std::string getText() noexcept { return std::move(text_); }
size_t getCharEnd() const noexcept { return char_end_; }
size_t getByteBeginPosition() const noexcept { return offset_ +
byte_begin_; }
@@ -84,9 +84,6 @@ public:
void setLength(size_t length);
void setType(Type type) noexcept { this->type_ = type; }
- void setText(std::string&& text);
-
- std::string toString() const;
bool operator==(const Lexeme& other) const noexcept;
bool operator<(const Lexeme& other) const noexcept;
@@ -97,7 +94,6 @@ private:
size_t byte_length_; // Lexeme length
size_t char_begin_; // Lexeme character start
size_t char_end_; // Lexeme character end
- std::string text_; // UTF-8 text
Type type_; // Lexeme type
};
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.cpp
index ed28a210a9d..447d7318767 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.cpp
@@ -42,13 +42,13 @@ void QuickSortSet::clear() {
bool QuickSortSet::addLexeme(Lexeme& lexeme) {
Cell* new_cell = nullptr;
if (cell_size_ == 0) {
- new_cell = allocateCell(std::move(lexeme));
+ new_cell = allocateCell(lexeme);
head_ = tail_ = new_cell;
cell_size_++;
return true;
}
if (lexeme < tail_->lexeme_) {
- new_cell = allocateCell(std::move(lexeme));
+ new_cell = allocateCell(lexeme);
tail_->next_ = new_cell;
new_cell->prev_ = tail_;
tail_ = new_cell;
@@ -56,7 +56,7 @@ bool QuickSortSet::addLexeme(Lexeme& lexeme) {
return true;
}
if (head_->lexeme_ < lexeme) {
- new_cell = allocateCell(std::move(lexeme));
+ new_cell = allocateCell(lexeme);
head_->prev_ = new_cell;
new_cell->next_ = head_;
head_ = new_cell;
@@ -75,7 +75,7 @@ bool QuickSortSet::addLexeme(Lexeme& lexeme) {
if (index && index->lexeme_ == lexeme) {
return false;
}
- new_cell = allocateCell(std::move(lexeme));
+ new_cell = allocateCell(lexeme);
new_cell->prev_ = index;
if (auto next = index->next_) {
new_cell->next_ = next;
@@ -93,7 +93,7 @@ const Lexeme* QuickSortSet::peekFirst() const {
std::optional<Lexeme> QuickSortSet::pollFirst() {
if (!head_) return std::nullopt;
Cell* old_head = head_;
- Lexeme result = std::move(old_head->getLexeme());
+ Lexeme result = old_head->getLexeme();
head_ = head_->next_;
if (head_)
@@ -113,7 +113,7 @@ const Lexeme* QuickSortSet::peekLast() const {
std::optional<Lexeme> QuickSortSet::pollLast() {
if (!tail_) return std::nullopt;
Cell* old_tail = tail_;
- Lexeme result = std::move(old_tail->getLexeme());
+ Lexeme result = old_tail->getLexeme();
tail_ = tail_->prev_;
if (tail_)
@@ -134,9 +134,9 @@ size_t QuickSortSet::getPathEnd() const {
return tail_ ? tail_->lexeme_.getByteBegin() +
tail_->lexeme_.getByteLength() : 0;
}
-Cell* QuickSortSet::allocateCell(Lexeme&& lexeme) {
+Cell* QuickSortSet::allocateCell(const Lexeme& lexeme) {
Cell* cell = arena_.alloc<Cell>();
- return new (cell) Cell(std::move(lexeme));
+ return new (cell) Cell(lexeme);
}
void QuickSortSet::deallocateCell(Cell* cell) {
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.h
index 04d44bccc5e..94adc5c96b9 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/core/QuickSortSet.h
@@ -27,7 +27,7 @@ namespace doris::segment_v2 {
class Cell {
public:
Cell() = default;
- explicit Cell(Lexeme&& lexeme) : lexeme_(std::move(lexeme)) {}
+ explicit Cell(const Lexeme& lexeme) : lexeme_(lexeme) {}
~Cell() = default;
bool operator<(const Cell& other) const { return lexeme_ < other.lexeme_;
};
@@ -80,7 +80,7 @@ public:
const Cell* getHead() const { return head_; }
private:
- Cell* allocateCell(Lexeme&& lexeme);
+ Cell* allocateCell(const Lexeme& lexeme);
void deallocateCell(Cell* cell);
};
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.cpp
index 8da2eda5751..1b06ef89047 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.cpp
@@ -17,70 +17,76 @@
#include "storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h"
+#include <algorithm>
+#include <limits>
+#include <string>
+
+#include "common/check.h"
+#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h"
+
namespace doris::segment_v2 {
+// Here rather than in a FlatDict.cpp of its own: the trie is what it is built
from, and a new
+// source would move the Storage target's unity batches.
+FlatDict::FlatDict(const DictSegment& root) {
+ // `order` lists the segments in the order they are numbered; a segment's
children are
+ // appended when it is numbered, so they get the next free numbers, all in
a row.
+ std::vector<const DictSegment*> order {&root};
+ std::vector<const DictSegment*> children;
+ for (size_t i = 0; i < order.size(); ++i) {
+ const DictSegment& segment = *order[i];
+ children.clear();
+ segment.forEachChild([&children](const DictSegment& child) {
children.push_back(&child); });
+ std::ranges::sort(children, [](const DictSegment* lhs, const
DictSegment* rhs) {
+ return lhs->keyChar() < rhs->keyChar();
+ });
+ // Every number fits child_begin, and every child count the 31 bits it
has.
+ DORIS_CHECK(order.size() + children.size() <=
std::numeric_limits<uint32_t>::max() / 2);
+ Node node;
+ node.key = segment.keyChar();
+ node.child_begin = static_cast<uint32_t>(order.size());
+ node.child_count = static_cast<uint32_t>(children.size());
+ node.word_end = segment.isWordEnd() ? 1 : 0;
+ nodes_.push_back(node);
+ order.insert(order.end(), children.begin(), children.end());
+ }
+ nodes_.shrink_to_fit();
+
+ root_children_.assign(kDirectKeys, kNoNode);
+ const Node& root_node = nodes_[kNoNode];
+ for (uint32_t c = root_node.child_begin; c < root_node.child_begin +
root_node.child_count;
+ ++c) {
+ if (nodes_[c].key >= 0 && nodes_[c].key < kDirectKeys) {
+ root_children_[nodes_[c].key] = c;
+ }
+ }
+}
+
DictSegment::DictSegment(int32_t key_char) : key_char_(key_char) {
children_array_.reserve(ARRAY_LENGTH_LIMIT);
+ live_count_.fetch_add(1, std::memory_order_relaxed);
}
-bool DictSegment::hasNextNode() const {
- return store_size_ > 0;
+DictSegment::~DictSegment() {
+ live_count_.fetch_sub(1, std::memory_order_relaxed);
}
-Hit DictSegment::match(const CharacterUtil::TypedRuneArray& typed_runes,
size_t unicode_offset,
- size_t length) {
- Hit search_hit;
- search_hit.setByteBegin(typed_runes[unicode_offset].offset);
- search_hit.setCharBegin(unicode_offset);
- match(typed_runes, unicode_offset, length, search_hit);
- return search_hit;
+bool DictSegment::hasNextNode() const {
+ return store_size_ > 0;
}
-void DictSegment::match(const CharacterUtil::TypedRuneArray& typed_runes,
size_t unicode_offset,
- size_t length, Hit& search_hit) {
- search_hit.setUnmatch();
-
- if (!typed_runes.empty() && unicode_offset < typed_runes.size()) {
- search_hit.setByteEnd(typed_runes[unicode_offset].offset +
- typed_runes[unicode_offset].getByteLength());
- search_hit.setCharEnd(unicode_offset);
- }
-
- length = (length == 0 || unicode_offset + length > typed_runes.size())
- ? typed_runes.size() - unicode_offset
- : length;
-
- int32_t ch = typed_runes[unicode_offset].getChar();
- DictSegment* ds = nullptr;
+const DictSegment* DictSegment::findChild(int32_t key_char) const {
if (store_size_ <= ARRAY_LENGTH_LIMIT) {
- for (size_t i = 0; i < store_size_ && i < children_array_.size(); i++)
{
- if (children_array_[i]->key_char_ == ch) {
- ds = children_array_[i].get();
- break;
- }
- }
- } else {
- auto it = children_map_.find(ch);
- if (it != children_map_.end()) {
- ds = it->second.get();
- } else {
- return;
- }
- }
-
- if (ds) {
- if (length == 1) {
- if (ds->is_word_end_) {
- search_hit.setMatch();
- }
- if (ds->hasNextNode()) {
- search_hit.setPrefix();
- search_hit.setMatchedDictSegment(ds);
+ for (size_t i = 0; i < store_size_; ++i) {
+ if (children_array_[i]->key_char_ == key_char) {
+ return children_array_[i].get();
}
- } else if (length > 1) {
- ds->match(typed_runes, unicode_offset + 1, length - 1, search_hit);
}
+ return nullptr;
}
+ const auto it = children_map_.find(key_char);
+ return it == children_map_.end() ? nullptr : it->second.get();
}
void DictSegment::fillSegment(const char* text) {
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h
index 653b9c297e7..bd7a03632f3 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h
@@ -19,21 +19,23 @@
#include <parallel_hashmap/phmap.h>
-#include <algorithm>
-#include <array>
-#include <cassert>
+#include <atomic>
+#include <cstddef>
+#include <cstdint>
#include <memory>
-#include <unordered_map>
#include <vector>
-#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
-#include "storage/index/inverted/analysis/analyzer/ik/dic/Hit.h"
-
namespace doris::segment_v2 {
-class DictSegment : public std::enable_shared_from_this<DictSegment> {
+// The trie a dictionary file is loaded into, one segment per character of its
words. It only
+// exists while the dictionary loads: FlatDict copies it into flat arrays,
which the analysis
+// reads, and the tree is freed then.
+class DictSegment {
private:
static constexpr size_t ARRAY_LENGTH_LIMIT = 3;
+ // The segments that exist, for the test that a loaded Dictionary keeps
none.
+ static inline std::atomic<size_t> live_count_ {0};
+
int32_t key_char_;
std::vector<std::unique_ptr<DictSegment>> children_array_;
phmap::flat_hash_map<int32_t, std::unique_ptr<DictSegment>> children_map_;
@@ -44,18 +46,33 @@ private:
public:
explicit DictSegment(int32_t key_char);
- ~DictSegment() = default;
+ ~DictSegment();
DictSegment(const DictSegment&) = delete;
DictSegment& operator=(const DictSegment&) = delete;
- DictSegment(DictSegment&&) noexcept = default;
- DictSegment& operator=(DictSegment&&) noexcept = default;
+ static size_t liveCount() { return
live_count_.load(std::memory_order_relaxed); }
+
+ int32_t keyChar() const { return key_char_; }
+ bool isWordEnd() const { return is_word_end_; }
bool hasNextNode() const;
- Hit match(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
- size_t length);
- void match(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
- size_t length, Hit& search_hit);
+ size_t childCount() const { return store_size_; }
+ // The child for `key_char`, or nullptr.
+ const DictSegment* findChild(int32_t key_char) const;
+ // Calls `visitor` with each child, in no particular order.
+ template <typename Visitor>
+ void forEachChild(Visitor&& visitor) const {
+ if (store_size_ <= ARRAY_LENGTH_LIMIT) {
+ for (size_t i = 0; i < store_size_; ++i) {
+ visitor(*children_array_[i]);
+ }
+ } else {
+ for (const auto& [key, child] : children_map_) {
+ visitor(*child);
+ }
+ }
+ }
+
void fillSegment(const char* text);
};
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.cpp
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.cpp
index cc806f18316..23da3d310d3 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.cpp
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.cpp
@@ -17,14 +17,18 @@
#include "storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h"
+#include <fstream>
+
+#include "storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h"
+
namespace doris::segment_v2 {
Dictionary::Dictionary(const Configuration& cfg, bool use_ext_dict)
- : main_dict_(std::make_unique<DictSegment>(0)),
- quantifier_dict_(std::make_unique<DictSegment>(0)),
- stop_words_(std::make_unique<DictSegment>(0)),
- config_(std::make_unique<Configuration>(cfg)),
- load_ext_dict_(use_ext_dict) {}
+ : config_(std::make_unique<Configuration>(cfg)),
+ load_ext_dict_(use_ext_dict),
+ main_dict_(loadMainDict()),
+ quantifier_dict_(loadQuantifierDict()),
+ stop_words_(loadStopWordDict()) {}
void Dictionary::loadDictFile(DictSegment* dict, const std::string& file_path,
bool critical,
const std::string& dict_name) {
@@ -44,16 +48,17 @@ void Dictionary::loadDictFile(DictSegment* dict, const
std::string& file_path, b
}
}
-void Dictionary::loadMainDict() {
+FlatDict Dictionary::loadMainDict() const {
try {
- loadDictFile(main_dict_.get(), config_->getDictPath() + "/" +
config_->getMainDictFile(),
- true, "Main Dict");
+ DictSegment main_dict(0);
+ loadDictFile(&main_dict, config_->getDictPath() + "/" +
config_->getMainDictFile(), true,
+ "Main Dict");
// Load extension dictionaries - can fail
if (load_ext_dict_) {
for (const auto& extDict : config_->getExtDictFiles()) {
try {
- loadDictFile(main_dict_.get(), config_->getDictPath() +
"/" + extDict, false,
+ loadDictFile(&main_dict, config_->getDictPath() + "/" +
extDict, false,
"Extra Dict");
} catch (const Exception& e) {
// Extension dictionary loading failure is logged but
doesn't affect main functionality
@@ -62,23 +67,24 @@ void Dictionary::loadMainDict() {
}
}
}
+ return FlatDict(main_dict);
} catch (const Exception& e) {
LOG(ERROR) << "Failed to load main dictionary: " << e.what();
throw;
}
}
-void Dictionary::loadStopWordDict() {
+FlatDict Dictionary::loadStopWordDict() const {
try {
- loadDictFile(stop_words_.get(),
- config_->getDictPath() + "/" +
config_->getStopWordDictFile(), false,
- "Stopword");
+ DictSegment stop_words(0);
+ loadDictFile(&stop_words, config_->getDictPath() + "/" +
config_->getStopWordDictFile(),
+ false, "Stopword");
// Load extension stopword dictionaries
if (load_ext_dict_) {
for (const auto& extDict : config_->getExtStopWordDictFiles()) {
try {
- loadDictFile(stop_words_.get(), config_->getDictPath() +
"/" + extDict, false,
+ loadDictFile(&stop_words, config_->getDictPath() + "/" +
extDict, false,
"Extra Stopword");
} catch (const Exception& e) {
// Extension stopword loading failure is just logged
@@ -87,6 +93,7 @@ void Dictionary::loadStopWordDict() {
}
}
}
+ return FlatDict(stop_words);
} catch (const std::exception& e) {
// Catch any other unexpected exceptions
LOG(ERROR) << "Unexpected error loading stopword dictionary: " <<
e.what();
@@ -94,11 +101,13 @@ void Dictionary::loadStopWordDict() {
}
}
-void Dictionary::loadQuantifierDict() {
+FlatDict Dictionary::loadQuantifierDict() const {
try {
- loadDictFile(quantifier_dict_.get(),
+ DictSegment quantifier_dict(0);
+ loadDictFile(&quantifier_dict,
config_->getDictPath() + "/" +
config_->getQuantifierDictFile(), true,
"Quantifier");
+ return FlatDict(quantifier_dict);
} catch (const Exception& e) {
LOG(ERROR) << "Failed to load quantifier dictionary: " << e.what();
throw;
@@ -113,11 +122,9 @@ void Dictionary::initial(const Configuration& cfg, bool
useExtDict) {
if (singleton_.load(std::memory_order_relaxed) != nullptr) {
return;
}
- std::unique_ptr<Dictionary> dictionary(new Dictionary(cfg, useExtDict));
+ std::unique_ptr<Dictionary> dictionary;
try {
- dictionary->loadMainDict();
- dictionary->loadQuantifierDict();
- dictionary->loadStopWordDict();
+ dictionary.reset(new Dictionary(cfg, useExtDict));
} catch (const Exception& e) {
LOG(ERROR) << "Dictionary loading failed: " << e.what();
throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR,
@@ -126,50 +133,4 @@ void Dictionary::initial(const Configuration& cfg, bool
useExtDict) {
singleton_.store(dictionary.release(), std::memory_order_release);
}
-Hit Dictionary::matchInMainDict(const CharacterUtil::TypedRuneArray&
typed_runes,
- size_t unicode_offset, size_t length) {
- Hit result = main_dict_->match(typed_runes, unicode_offset, length);
-
- if (!result.isUnmatch()) {
- result.setByteBegin(typed_runes[unicode_offset].offset);
- result.setCharBegin(unicode_offset);
- result.setByteEnd(typed_runes[unicode_offset + length -
1].getNextBytePosition());
- result.setCharEnd(unicode_offset + length);
- }
- return result;
-}
-
-Hit Dictionary::matchInQuantifierDict(const CharacterUtil::TypedRuneArray&
typed_runes,
- size_t unicode_offset, size_t length) {
- Hit result = quantifier_dict_->match(typed_runes, unicode_offset, length);
-
- if (!result.isUnmatch()) {
- result.setByteBegin(typed_runes[unicode_offset].offset);
- result.setCharBegin(unicode_offset);
- result.setByteEnd(typed_runes[unicode_offset + length -
1].getNextBytePosition());
- result.setCharEnd(unicode_offset + length);
- }
- return result;
-}
-
-void Dictionary::matchWithHit(const CharacterUtil::TypedRuneArray& typed_runes,
- size_t current_index, Hit& hit) {
- if (auto* matchedSegment = hit.getMatchedDictSegment()) {
- matchedSegment->match(typed_runes, current_index, 1, hit);
- return;
- }
- hit.setUnmatch();
-}
-
-bool Dictionary::isStopWord(const CharacterUtil::TypedRuneArray& typed_runes,
size_t unicode_offset,
- size_t length) {
- if (typed_runes.empty() || unicode_offset >= typed_runes.size()) {
- return false;
- }
-
- Hit result = stop_words_->match(typed_runes, unicode_offset, length);
-
- return result.isMatch();
-}
-
} // namespace doris::segment_v2
diff --git
a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h
index 50a09a3a5b2..d70c38134b2 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h
@@ -18,20 +18,25 @@
#pragma once
#include <atomic>
-#include <fstream>
#include <memory>
#include <mutex>
#include <string>
-#include <vector>
#include "common/exception.h"
#include "common/logging.h"
#include "storage/index/inverted/analysis/analyzer/ik/cfg/Configuration.h"
#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
-#include "storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h"
#include "storage/index/inverted/analysis/analyzer/ik/dic/Hit.h"
namespace doris::segment_v2 {
+
+class DictSegment;
+
+// The main, quantifier and stop word dictionaries, loaded once per process.
Each file is loaded
+// into a DictSegment trie, copied into a FlatDict and freed, so a loaded
Dictionary keeps only the
+// flat copies. A segmenter is given the loaded Dictionary when it is made and
reads it through
+// that reference: the per-character path never goes through getSingleton().
class Dictionary {
private:
// Published only after every dictionary has loaded, so a failed load
leaves nothing behind and
@@ -42,12 +47,13 @@ private:
static std::atomic<Dictionary*> singleton_;
static std::mutex init_mutex_;
- // Dictionary segment mappings
- std::unique_ptr<DictSegment> main_dict_;
- std::unique_ptr<DictSegment> quantifier_dict_;
- std::unique_ptr<DictSegment> stop_words_;
std::unique_ptr<Configuration> config_;
bool load_ext_dict_;
+ // Built in this order by the constructor, after config_ and
load_ext_dict_.
+ FlatDict main_dict_;
+ FlatDict quantifier_dict_;
+ FlatDict stop_words_;
+
class Cleanup {
public:
~Cleanup() { delete Dictionary::singleton_.exchange(nullptr); }
@@ -59,14 +65,16 @@ private:
static const std::string PATH_DIC_QUANTIFIER;
static const std::string PATH_DIC_STOP;
+ // Loads every dictionary; throws when one of the three files cannot be
read, while a missing
+ // extension file is only logged.
explicit Dictionary(const Configuration& cfg, bool use_ext_dict = false);
- void loadMainDict();
- void loadStopWordDict();
- void loadQuantifierDict();
+ FlatDict loadMainDict() const;
+ FlatDict loadStopWordDict() const;
+ FlatDict loadQuantifierDict() const;
- void loadDictFile(DictSegment* dict, const std::string& file_path, bool
critical,
- const std::string& dict_name);
+ static void loadDictFile(DictSegment* dict, const std::string& file_path,
bool critical,
+ const std::string& dict_name);
Dictionary(const Dictionary&) = delete;
Dictionary& operator=(const Dictionary&) = delete;
@@ -94,16 +102,43 @@ public:
Configuration* getConfiguration() const { return config_.get(); }
+ // A hit of the `length` characters from `unicode_offset`; a match or a
prefix spans them,
+ // which makes its char end unicode_offset + length, one past the last of
them: a character
+ // matched alone at index 5 ends at 6. The CJK segmenter gives that end to
the lexeme of the
+ // character and the quantifier segmenter continues the hit from it, and
both decide tokens.
Hit matchInMainDict(const CharacterUtil::TypedRuneArray& typed_runes,
size_t unicode_offset,
- size_t length);
+ size_t length) const {
+ return spanHit(main_dict_.match(typed_runes, unicode_offset, length),
typed_runes,
+ unicode_offset, length);
+ }
Hit matchInQuantifierDict(const CharacterUtil::TypedRuneArray& typed_runes,
- size_t unicode_offset, size_t length);
+ size_t unicode_offset, size_t length) const {
+ return spanHit(quantifier_dict_.match(typed_runes, unicode_offset,
length), typed_runes,
+ unicode_offset, length);
+ }
+ // Continues a prefix `hit` with the character at `current_index`, after
which the hit's char
+ // end is `current_index` itself.
void matchWithHit(const CharacterUtil::TypedRuneArray& typed_runes, size_t
current_index,
- Hit& hit);
+ Hit& hit) const {
+ DCHECK(hit.getMatchedDict() != nullptr);
+ hit.getMatchedDict()->match(typed_runes, current_index, 1,
hit.getMatchedNode(), hit);
+ }
bool isStopWord(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
- size_t length);
+ size_t length) const {
+ return stop_words_.isWord(typed_runes, unicode_offset, length);
+ }
- void printStats() const;
+private:
+ static Hit spanHit(Hit result, const CharacterUtil::TypedRuneArray&
typed_runes,
+ size_t unicode_offset, size_t length) {
+ if (!result.isUnmatch()) {
+ result.setByteBegin(typed_runes[unicode_offset].offset);
+ result.setCharBegin(unicode_offset);
+ result.setByteEnd(typed_runes[unicode_offset + length -
1].getNextBytePosition());
+ result.setCharEnd(unicode_offset + length);
+ }
+ return result;
+ }
};
inline std::atomic<Dictionary*> Dictionary::singleton_ {nullptr};
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h
new file mode 100644
index 00000000000..106e0f399bc
--- /dev/null
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h
@@ -0,0 +1,161 @@
+// 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 <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+#include "common/logging.h"
+#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/Hit.h"
+
+namespace doris::segment_v2 {
+
+class DictSegment;
+
+// A dictionary as the analysis reads it: a read-only copy of a DictSegment
trie in one array,
+// built once the dictionary file is loaded, after which the tree is freed. A
lookup is an array
+// probe or a scan of adjacent nodes instead of a hash lookup behind a pointer
per character.
+//
+// Node 0 is the root and the other nodes are numbered breadth first, so the
children of a node are
+// consecutive nodes, in increasing key; the root's children are also found
through a table indexed
+// by the first-plane character. Say the words are A, AB, ABC and C, each
letter a character and
+// A < C: the root's children are node 1 (A) and node 2 (C), node 1's only
child is node 3 (B)
+// and node 3's is node 4 (C); nodes 1 to 4 end a word, nodes 2 and 4 have no
child, and the
+// table maps A to 1 and C to 2.
+class FlatDict {
+public:
+ // The root, which is nobody's child, also stands for no node.
+ static constexpr uint32_t kNoNode = 0;
+
+ // Copies the trie under `root`; defined in DictSegment.cpp.
+ explicit FlatDict(const DictSegment& root);
+ FlatDict(FlatDict&&) noexcept = default;
+ FlatDict& operator=(FlatDict&&) noexcept = default;
+ FlatDict(const FlatDict&) = delete;
+ FlatDict& operator=(const FlatDict&) = delete;
+
+ // The child of `node` for `key`, or kNoNode. A node of up to
kLinearChildren children is
+ // scanned, one of more is searched by bisection.
+ uint32_t child(uint32_t node, int32_t key) const {
+ if (node == kNoNode && key >= 0 && key < kDirectKeys) {
+ return root_children_[key];
+ }
+ const Node& parent = nodes_[node];
+ const Node* const first = nodes_.data() + parent.child_begin;
+ const Node* const last = first + parent.child_count;
+ if (parent.child_count <= kLinearChildren) {
+ for (const Node* it = first; it != last; ++it) {
+ if (it->key == key) {
+ return static_cast<uint32_t>(it - nodes_.data());
+ }
+ }
+ return kNoNode;
+ }
+ const Node* const it = std::lower_bound(
+ first, last, key,
+ [](const Node& entry, int32_t value) { return entry.key <
value; });
+ return it != last && it->key == key ? static_cast<uint32_t>(it -
nodes_.data()) : kNoNode;
+ }
+
+ bool isWordEnd(uint32_t node) const { return nodes_[node].word_end != 0; }
+ bool hasChildren(uint32_t node) const { return nodes_[node].child_count !=
0; }
+
+ // Walks `length` characters from `unicode_offset` (all that are left when
`length` is 0 or
+ // more than are left) down from `node`, as the pointer trie's match did.
`hit` ends unmatched
+ // at the first character without a child, with that character's end;
otherwise the last
+ // character's node decides: it is a match if a word ends there and a
prefix, which the next
+ // character continues from, if it has children. Say the words are AB and
ABC, each letter a
+ // character, and the text is ABC: from the root, A is a prefix only; from
its node, B is a
+ // match and a prefix; from that one, C is a match only.
+ void match(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
+ size_t length, uint32_t node, Hit& hit) const {
+ DCHECK_LT(unicode_offset, typed_runes.size());
+ if (length == 0 || unicode_offset + length > typed_runes.size()) {
+ length = typed_runes.size() - unicode_offset;
+ }
+ while (true) {
+ const CharacterUtil::TypedRune& rune = typed_runes[unicode_offset];
+ hit.setUnmatch();
+ hit.setByteEnd(rune.offset + rune.getByteLength());
+ hit.setCharEnd(unicode_offset);
+ node = child(node, rune.getChar());
+ if (node == kNoNode) {
+ return;
+ }
+ if (length == 1) {
+ if (isWordEnd(node)) {
+ hit.setMatch();
+ }
+ if (hasChildren(node)) {
+ hit.setPrefix();
+ hit.setMatchedNode(this, node);
+ }
+ return;
+ }
+ ++unicode_offset;
+ --length;
+ }
+ }
+
+ // match() from the root, with the hit starting at `unicode_offset`.
+ Hit match(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
+ size_t length) const {
+ Hit hit;
+ hit.setByteBegin(typed_runes[unicode_offset].offset);
+ hit.setCharBegin(unicode_offset);
+ match(typed_runes, unicode_offset, length, kNoNode, hit);
+ return hit;
+ }
+
+ // Whether the characters match() walks are a word: match(...).isMatch()
without the hit.
+ bool isWord(const CharacterUtil::TypedRuneArray& typed_runes, size_t
unicode_offset,
+ size_t length) const {
+ DCHECK_LT(unicode_offset, typed_runes.size());
+ if (length == 0 || unicode_offset + length > typed_runes.size()) {
+ length = typed_runes.size() - unicode_offset;
+ }
+ uint32_t node = kNoNode;
+ for (size_t i = unicode_offset; i < unicode_offset + length; ++i) {
+ node = child(node, typed_runes[i].getChar());
+ if (node == kNoNode) {
+ return false;
+ }
+ }
+ return isWordEnd(node);
+ }
+
+private:
+ // The characters below this have a slot of their own in the root's table.
+ static constexpr int32_t kDirectKeys = 0x10000;
+ static constexpr uint32_t kLinearChildren = 8;
+
+ struct Node {
+ int32_t key;
+ uint32_t child_begin;
+ uint32_t child_count : 31;
+ uint32_t word_end : 1;
+ };
+
+ std::vector<uint32_t> root_children_;
+ std::vector<Node> nodes_;
+};
+
+} // namespace doris::segment_v2
diff --git a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Hit.h
b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Hit.h
index 8084eb8a90e..0a0c244e8a4 100644
--- a/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Hit.h
+++ b/be/src/storage/index/inverted/analysis/analyzer/ik/dic/Hit.h
@@ -17,11 +17,12 @@
#pragma once
-#include <memory>
+#include <cstddef>
+#include <cstdint>
namespace doris::segment_v2 {
-class DictSegment;
+class FlatDict;
class Hit {
private:
@@ -30,7 +31,10 @@ private:
static const int PREFIX = 0x00000010;
int hitState_ {UNMATCH};
- DictSegment* matchedDictSegment_;
+ // The dictionary node the characters matched so far lead to, which the
next character
+ // continues from; set while the hit is a prefix.
+ const FlatDict* matchedDict_ {nullptr};
+ uint32_t matchedNode_ {0};
size_t byteBegin_ {0};
size_t byteEnd_ {0};
size_t charBegin_ {0};
@@ -48,8 +52,12 @@ public:
bool isUnmatch() const { return hitState_ == UNMATCH; }
void setUnmatch() { hitState_ = UNMATCH; }
- DictSegment* getMatchedDictSegment() const { return matchedDictSegment_; }
- void setMatchedDictSegment(DictSegment* segment) { matchedDictSegment_ =
segment; }
+ const FlatDict* getMatchedDict() const { return matchedDict_; }
+ uint32_t getMatchedNode() const { return matchedNode_; }
+ void setMatchedNode(const FlatDict* dict, uint32_t node) {
+ matchedDict_ = dict;
+ matchedNode_ = node;
+ }
size_t getByteBegin() const { return byteBegin_; }
void setByteBegin(size_t pos) { byteBegin_ = pos; }
diff --git
a/be/test/storage/index/inverted/analysis/analyzer/ik_anayzer_test.cpp
b/be/test/storage/index/inverted/analysis/analyzer/ik_anayzer_test.cpp
index 874e1d7e9fc..6992ad3587a 100644
--- a/be/test/storage/index/inverted/analysis/analyzer/ik_anayzer_test.cpp
+++ b/be/test/storage/index/inverted/analysis/analyzer/ik_anayzer_test.cpp
@@ -21,6 +21,9 @@
#include <limits>
#include <memory>
#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
#include "CLucene.h" // IWYU pragma: keep
#include "common/config.h"
@@ -85,8 +88,9 @@ protected:
segmenter.reset(s);
Lexeme lexeme;
- while (segmenter.next(lexeme)) {
- tokenInfos.emplace_back(lexeme.getText(), lexeme.getType());
+ std::string_view text;
+ while (segmenter.next(lexeme, text)) {
+ tokenInfos.emplace_back(std::string(text), lexeme.getType());
}
}
@@ -773,6 +777,66 @@ TEST_F(IKTokenizerTest, TestCNQuantifierSegmenter) {
<< "'U+5E74' should be COUNT type";
}
+// lower_case only applies to the words IK hands out: the window lowercases an
ASCII capital in
+// place before it segments, so "Hello" comes out as "hello" either way, while
the full-width ABC
+// stays in the window as it is and only folds to ASCII when its word is
handed out, to "ABC" with
+// lower_case false and to "abc" with lower_case true.
+TEST_F(IKTokenizerTest, TestLowerCaseOnlyAppliesToTheWords) {
+ for (const bool smart : {true, false}) {
+ SCOPED_TRACE(smart);
+ IKTokenizer keep_case(ik_config(smart), false);
+ EXPECT_EQ(inverted_index::collect_terms(keep_case, "Hello ABC"),
+ (std::vector<std::string> {"hello", "ABC"}));
+ IKTokenizer lowercase(ik_config(smart), true);
+ EXPECT_EQ(inverted_index::collect_terms(lowercase, "Hello ABC"),
+ (std::vector<std::string> {"hello", "abc"}));
+ }
+}
+
+// A character on the 4096-byte window boundary, at every misalignment, after
ASCII words: the
+// window ends before a character it cannot hold whole and refills at a space
within its last 100
+// characters, so the next window starts with the cut character and no word is
split or lost. é is
+// no word character and only ends the word before it; U+4E2D (a Han
character) and 😀 are words
+// of their own.
+TEST_F(IKTokenizerTest, TestCharacterAcrossTheWindowAtEveryOffset) {
+ constexpr std::string_view kFiller = "lorem ipsum dolor sit amet
consectetur ";
+ for (const bool smart : {true, false}) {
+ IKTokenizer tokenizer(ik_config(smart), true);
+ for (const std::string_view character : {"é", "中", "😀"}) {
+ for (size_t start = 4096 - 8; start <= 4096 + 4; ++start) {
+ std::string text;
+ while (text.size() < start) {
+ text += kFiller;
+ }
+ text.resize(start);
+ std::vector<std::string> expected;
+ std::istringstream words(text);
+ for (std::string word; words >> word;) {
+ expected.push_back(word);
+ }
+ if (character != "é") {
+ expected.emplace_back(character);
+ }
+ expected.emplace_back("tail");
+ expected.emplace_back("words");
+ text += character;
+ text += " tail words";
+ EXPECT_EQ(inverted_index::collect_terms(tokenizer, text),
expected)
+ << smart << " " << character << " at " << start;
+ }
+ }
+ }
+}
+
+// A value whose last character is cut short throws, even after words IK could
segment: the Han
+// characters U+4F60 U+597D and the first two bytes of U+4E2D. The stream
reads the next value as
+// if nothing happened.
+TEST_F(IKTokenizerTest, TestUndecodableTailThrows) {
+ IKTokenizer tokenizer(ik_config(true), true);
+ EXPECT_THROW(tokenizer.reset("你好\xE4\xB8"), Exception);
+ EXPECT_EQ(inverted_index::collect_terms(tokenizer, "你好"),
std::vector<std::string> {"你好"});
+}
+
// Test the exception handling capabilities of the IKTokenizer and
AnalyzeContext. The value is a
// string, so a failure comes from bytes IK cannot decode, not from a reader.
TEST_F(IKTokenizerTest, TestExceptionHandling) {
@@ -798,10 +862,10 @@ TEST_F(IKTokenizerTest, TestExceptionHandling) {
// PART 2: Test AnalyzeContext::fillBuffer exception handling
{
- // Create AnalyzeContext
+ // Create AnalyzeContext, with the dictionaries PART 1 loaded
std::shared_ptr<Configuration> config =
std::make_shared<Configuration>();
Arena arena {};
- AnalyzeContext context(arena, config);
+ AnalyzeContext context(arena, config, *Dictionary::getSingleton());
// Test case 1: bytes that decode to no character
inverted_index::TextCursor cut_short;
diff --git
a/be/test/storage/index/inverted/analysis/analyzer/ik_flat_dict_test.cpp
b/be/test/storage/index/inverted/analysis/analyzer/ik_flat_dict_test.cpp
new file mode 100644
index 00000000000..c705ccb8c11
--- /dev/null
+++ b/be/test/storage/index/inverted/analysis/analyzer/ik_flat_dict_test.cpp
@@ -0,0 +1,482 @@
+// 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 <gtest/gtest.h>
+#include <unicode/utf8.h>
+
+#include <cstdint>
+#include <fstream>
+#include <initializer_list>
+#include <memory>
+#include <ostream>
+#include <random>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "common/exception.h"
+#include "storage/index/inverted/analysis/analyzer/ik/IKTokenizer.h"
+#include "storage/index/inverted/analysis/analyzer/ik/cfg/Configuration.h"
+#include "storage/index/inverted/analysis/analyzer/ik/core/CharacterUtil.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/DictSegment.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/Dictionary.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/FlatDict.h"
+#include "storage/index/inverted/analysis/analyzer/ik/dic/Hit.h"
+#include "storage/index/inverted/analysis/text_stream_contract.h"
+#include "util/defer_op.h"
+
+namespace doris::segment_v2 {
+namespace {
+
+using TypedRune = CharacterUtil::TypedRune;
+using TypedRuneArray = CharacterUtil::TypedRuneArray;
+
+constexpr std::string_view kDictDir = "./be/dict/ik";
+
+// A hit as DictSegment::match() made it before the trie was flattened: the
reference the flat
+// dictionary is held to.
+struct ReferenceHit {
+ bool match = false;
+ bool prefix = false;
+ const DictSegment* matched = nullptr;
+ size_t byte_begin = 0;
+ size_t byte_end = 0;
+ size_t char_begin = 0;
+ size_t char_end = 0;
+};
+
+// DictSegment::match(typed_runes, unicode_offset, length, hit) of the pointer
trie, as it was.
+void reference_match(const DictSegment& segment, const TypedRuneArray&
typed_runes,
+ size_t unicode_offset, size_t length, ReferenceHit& hit) {
+ hit.match = false;
+ hit.prefix = false;
+ if (!typed_runes.empty() && unicode_offset < typed_runes.size()) {
+ hit.byte_end =
+ typed_runes[unicode_offset].offset +
typed_runes[unicode_offset].getByteLength();
+ hit.char_end = unicode_offset;
+ }
+ length = (length == 0 || unicode_offset + length > typed_runes.size())
+ ? typed_runes.size() - unicode_offset
+ : length;
+ const DictSegment* ds =
segment.findChild(typed_runes[unicode_offset].getChar());
+ if (ds != nullptr) {
+ if (length == 1) {
+ hit.match = ds->isWordEnd();
+ if (ds->hasNextNode()) {
+ hit.prefix = true;
+ hit.matched = ds;
+ }
+ } else if (length > 1) {
+ reference_match(*ds, typed_runes, unicode_offset + 1, length - 1,
hit);
+ }
+ }
+}
+
+ReferenceHit reference_match(const DictSegment& root, const TypedRuneArray&
typed_runes,
+ size_t unicode_offset, size_t length) {
+ ReferenceHit hit;
+ hit.byte_begin = typed_runes[unicode_offset].offset;
+ hit.char_begin = unicode_offset;
+ reference_match(root, typed_runes, unicode_offset, length, hit);
+ return hit;
+}
+
+// Where a comparison is: the input, the walk and the character or length;
formatted only when a
+// comparison fails.
+struct Where {
+ const std::string& input;
+ const char* walk;
+ size_t at;
+};
+
+std::ostream& operator<<(std::ostream& out, const Where& where) {
+ return out << where.input << ", " << where.walk << " " << where.at;
+}
+
+// A prefix leads to the same node: the same key, the same word end and the
same number of
+// children.
+void expect_same_node(const DictSegment& expected, const Hit& actual, const
FlatDict& flat,
+ const Where& where) {
+ ASSERT_EQ(actual.getMatchedDict(), &flat) << where;
+ const uint32_t node = actual.getMatchedNode();
+ ASSERT_EQ(flat.nodes_[node].key, expected.keyChar()) << where;
+ ASSERT_EQ(flat.isWordEnd(node), expected.isWordEnd()) << where;
+ ASSERT_EQ(flat.nodes_[node].child_count, expected.childCount()) << where;
+}
+
+// The same state and ends, and a prefix leads to the same node.
+void expect_same_hit(const ReferenceHit& expected, const Hit& actual, const
FlatDict& flat,
+ const Where& where) {
+ ASSERT_EQ(expected.match, actual.isMatch()) << where;
+ ASSERT_EQ(expected.prefix, actual.isPrefix()) << where;
+ ASSERT_EQ(!expected.match && !expected.prefix, actual.isUnmatch()) <<
where;
+ ASSERT_EQ(expected.byte_begin, actual.getByteBegin()) << where;
+ ASSERT_EQ(expected.byte_end, actual.getByteEnd()) << where;
+ ASSERT_EQ(expected.char_begin, actual.getCharBegin()) << where;
+ ASSERT_EQ(expected.char_end, actual.getCharEnd()) << where;
+ if (expected.prefix) {
+ expect_same_node(*expected.matched, actual, flat, where);
+ }
+}
+
+// The bytes decode_rune reads for `code_point`, four for a 21-bit one from a
four-byte lead too.
+size_t utf8_length_of(int32_t code_point) {
+ if (code_point < 0x80) {
+ return 1;
+ }
+ if (code_point < 0x800) {
+ return 2;
+ }
+ return code_point < 0x10000 ? 3 : 4;
+}
+
+// The runes of `code_points`, as the window holds them: each with its offset
and length in bytes.
+TypedRuneArray runes_of(const std::vector<int32_t>& code_points) {
+ TypedRuneArray runes;
+ size_t offset = 0;
+ for (const int32_t code_point : code_points) {
+ const size_t length = utf8_length_of(code_point);
+ runes.emplace_back(code_point, offset, length, runes.size(), 1);
+ offset += length;
+ }
+ return runes;
+}
+
+std::vector<int32_t> code_points_of(std::string_view word) {
+ CharacterUtil::RuneStrArray decoded;
+ if (!CharacterUtil::decodeString(word.data(), word.size(), decoded)) {
+ return {};
+ }
+ std::vector<int32_t> code_points;
+ for (const auto& rune : decoded) {
+ code_points.push_back(static_cast<int32_t>(rune.rune));
+ }
+ return code_points;
+}
+
+// Every walk the analysis makes over `runes` from `begin`: the hit of one
character continued
+// character by character as a segmenter does, a match of every length from
the root, and the
+// stop word test of every length. Stops at the first difference.
+void expect_same_walks(const DictSegment& root, const FlatDict& flat, const
TypedRuneArray& runes,
+ size_t begin, const std::string& input) {
+ ReferenceHit expected = reference_match(root, runes, begin, 1);
+ Hit actual = flat.match(runes, begin, 1);
+ expect_same_hit(expected, actual, flat,
+ {.input = input, .walk = "first character at", .at =
begin});
+ for (size_t i = begin + 1; i < runes.size() && expected.prefix; ++i) {
+ if (::testing::Test::HasFatalFailure()) {
+ return;
+ }
+ reference_match(*expected.matched, runes, i, 1, expected);
+ flat.match(runes, i, 1, actual.getMatchedNode(), actual);
+ expect_same_hit(expected, actual, flat,
+ {.input = input, .walk = "next character at", .at =
i});
+ }
+ // A length of 0, and lengths beyond the end, mean all that is left.
+ for (size_t length = 0; length <= runes.size() - begin + 1; ++length) {
+ if (::testing::Test::HasFatalFailure()) {
+ return;
+ }
+ const ReferenceHit whole = reference_match(root, runes, begin, length);
+ expect_same_hit(whole, flat.match(runes, begin, length), flat,
+ {.input = input, .walk = "match of length", .at =
length});
+ ASSERT_EQ(whole.match, flat.isWord(runes, begin, length))
+ << Where {.input = input, .walk = "word of length", .at =
length};
+ }
+}
+
+// A trie loaded as Dictionary loads a file.
+std::unique_ptr<DictSegment> load_trie(const std::string& file) {
+ auto root = std::make_unique<DictSegment>(0);
+ Dictionary::loadDictFile(root.get(), std::string(kDictDir) + "/" + file,
true, file);
+ return root;
+}
+
+std::vector<std::string> read_lines(const std::string& file) {
+ std::ifstream in(std::string(kDictDir) + "/" + file);
+ std::vector<std::string> lines;
+ std::string line;
+ while (std::getline(in, line)) {
+ lines.push_back(line);
+ }
+ return lines;
+}
+
+// Every word of a dictionary file, each of its prefixes and each of its
suffixes, against the
+// trie the file was loaded into; the words are also read as the window would
hold them.
+void expect_flat_dictionary_matches_trie(const std::string& file) {
+ SCOPED_TRACE(file);
+ const std::unique_ptr<DictSegment> root = load_trie(file);
+ const FlatDict flat(*root);
+ size_t words = 0;
+ for (const std::string& line : read_lines(file)) {
+ const std::vector<int32_t> code_points = code_points_of(line);
+ if (code_points.empty()) {
+ continue;
+ }
+ ++words;
+ const TypedRuneArray runes = runes_of(code_points);
+ for (size_t begin = 0; begin < runes.size(); ++begin) {
+ expect_same_walks(*root, flat, runes, begin, line);
+ }
+ std::string window = line;
+ TypedRuneArray regularized;
+ CharacterUtil::decodeStringToRunes(window.data(), window.size(),
regularized, true);
+ expect_same_walks(*root, flat, regularized, 0, line);
+ if (::testing::Test::HasFatalFailure()) {
+ return;
+ }
+ }
+ EXPECT_GT(words, 0U);
+}
+
+TEST(IKFlatDictTest, MainDictionaryMatchesItsTrie) {
+ expect_flat_dictionary_matches_trie("main.dic");
+}
+
+TEST(IKFlatDictTest, QuantifierAndStopWordDictionariesMatchTheirTries) {
+ expect_flat_dictionary_matches_trie("quantifier.dic");
+ expect_flat_dictionary_matches_trie("stopword.dic");
+ expect_flat_dictionary_matches_trie("extra_stopword.dic");
+}
+
+// Random strings of characters of the dictionary, ASCII, other first-plane
characters and
+// supplementary ones, from every start, against a trie with every kind of
node: words that start
+// or go on with a supplementary character, which the root's table does not
hold, nodes of more
+// than eight children, which are searched by bisection, and the main
dictionary's words.
+TEST(IKFlatDictTest, RandomStringsMatchTheTrie) {
+ const std::unique_ptr<DictSegment> root = load_trie("main.dic");
+ std::vector<int32_t> pool;
+ for (const char* word : {"\U00020000\U00020001",
"\U00020000\U00020001\U00020002", "\U0001F600",
+ "\U0001F600中", "中\U0001F600", "中\U00020000国",
"\U0010FFFF",
+ "a\U0001F600b", "ab", "abc", "\U000E0001x"}) {
+ root->fillSegment(word);
+ }
+ // Twelve children below U+6D4B and below U+20000, beyond kLinearChildren.
+ for (int32_t i = 0; i < 12; ++i) {
+ std::string word = "测";
+ std::string supplementary = "\U00020000";
+ char encoded[U8_MAX_LENGTH];
+ int32_t length = 0;
+ U8_APPEND_UNSAFE(encoded, length, 0x20010 + i * 7);
+ word.append(encoded, length);
+ supplementary.append(encoded, length);
+ root->fillSegment(word.c_str());
+ root->fillSegment(supplementary.c_str());
+ pool.push_back(0x20010 + i * 7);
+ }
+ const FlatDict flat(*root);
+ const std::vector<std::string> lines = read_lines("main.dic");
+ for (size_t i = 0; i < lines.size(); i += 101) {
+ for (const int32_t code_point : code_points_of(lines[i])) {
+ pool.push_back(code_point);
+ }
+ }
+ for (const int32_t code_point : std::initializer_list<int32_t> {
+ 'a', 'b', 'c', 'x', '1', ' ', 0x3000, 0xFF21, 0x00E9,
0x20000, 0x20001, 0x20002,
+ 0x1F600, 0x10FFFF, 0xE0001, 0x1FFFFF, 0x6D4B, 0x4E2D,
0x56FD}) {
+ pool.push_back(code_point);
+ }
+ std::mt19937 rng(20261104);
+ std::uniform_int_distribution<size_t> pick(0, pool.size() - 1);
+ std::uniform_int_distribution<size_t> size(1, 8);
+ for (int round = 0; round < 20000; ++round) {
+ std::vector<int32_t> code_points(size(rng));
+ for (int32_t& code_point : code_points) {
+ code_point = pool[pick(rng)];
+ }
+ const TypedRuneArray runes = runes_of(code_points);
+ const std::string input = "round " + std::to_string(round);
+ for (size_t begin = 0; begin < runes.size(); ++begin) {
+ expect_same_walks(*root, flat, runes, begin, input);
+ }
+ if (::testing::Test::HasFatalFailure()) {
+ return;
+ }
+ }
+}
+
+// A loaded Dictionary keeps only its flat copies: the tries it loaded the
files into are gone.
+TEST(IKFlatDictTest, LoadedDictionaryKeepsNoTrie) {
+ {
+ const std::unique_ptr<DictSegment> trie = load_trie("quantifier.dic");
+ EXPECT_GT(DictSegment::liveCount(), 300U);
+ }
+ EXPECT_EQ(DictSegment::liveCount(), 0U);
+
+ Dictionary::destroy();
+ Configuration config;
+ config.setDictPath(std::string(kDictDir));
+ Dictionary::initial(config);
+ EXPECT_EQ(DictSegment::liveCount(), 0U);
+
+ // And the copies hold the words: the text's first seven characters, the
PRC's name, are a word
+ // of main.dic, the classifier U+4E2A one of quantifier.dic and "the" a
stop word.
+ const Dictionary& dictionary = *Dictionary::getSingleton();
+ std::string text = "中华人民共和国个the";
+ TypedRuneArray runes;
+ CharacterUtil::decodeStringToRunes(text.data(), text.size(), runes, true);
+ Hit hit = dictionary.matchInMainDict(runes, 0, 1);
+ for (size_t i = 1; i < 7; ++i) {
+ ASSERT_TRUE(hit.isPrefix()) << i;
+ dictionary.matchWithHit(runes, i, hit);
+ }
+ EXPECT_TRUE(hit.isMatch());
+ EXPECT_TRUE(dictionary.matchInQuantifierDict(runes, 7, 1).isMatch());
+ EXPECT_TRUE(dictionary.isStopWord(runes, 8, 3));
+ EXPECT_FALSE(dictionary.isStopWord(runes, 0, 2));
+}
+
+// The tokens of `text` with the singleton taken away, which makes
Dictionary::getSingleton() throw,
+// from a tokenizer made before; the singleton is put back after.
+std::vector<std::string> collect_without_singleton(IKTokenizer& tokenizer,
+ const std::string& text) {
+ Dictionary* const loaded = Dictionary::singleton_.exchange(nullptr);
+ Defer restore {[&] { Dictionary::singleton_.store(loaded); }};
+ EXPECT_THROW(Dictionary::getSingleton(), Exception);
+ std::vector<std::string> terms;
+ EXPECT_NO_THROW(terms = inverted_index::collect_terms(tokenizer, text));
+ return terms;
+}
+
+// A tokenizer reads the Dictionary it was given when it was made: without the
singleton, a value
+// that runs every segmenter (letters, digits, a numeral with a quantifier,
Chinese words, a stop
+// word, full-width forms and a surrogate pair) gives the tokens it gave
before.
+TEST(IKFlatDictTest, SegmenterPathNeverCallsGetSingleton) {
+ auto config = std::make_shared<Configuration>(false, true);
+ config->setDictPath(std::string(kDictDir));
+ Dictionary::initial(*config);
+ const std::string text =
+ "Doris 2023年 三个 中华人民共和国的 SQL92 ABC12 \U0001F600 the 数据库 a-b_c
3.14";
+ for (const bool smart : {false, true}) {
+ auto stream_config = std::make_shared<Configuration>(smart, true);
+ stream_config->setDictPath(std::string(kDictDir));
+ IKTokenizer tokenizer(stream_config, true);
+ const std::vector<std::string> expected =
inverted_index::collect_terms(tokenizer, text);
+ EXPECT_GT(expected.size(), 10U);
+ EXPECT_EQ(collect_without_singleton(tokenizer, text), expected) <<
smart;
+ }
+}
+
+// The bytes of `text`, as hexadecimal pairs.
+std::string hex_of(std::string_view text) {
+ static constexpr char kDigits[] = "0123456789ABCDEF";
+ std::string hex;
+ for (const char c : text) {
+ hex += kDigits[static_cast<uint8_t>(c) >> 4];
+ hex += kDigits[static_cast<uint8_t>(c) & 0xF];
+ hex += ' ';
+ }
+ return hex;
+}
+
+// The original CharacterUtil::regularizeString(), which built a new string
for every word: the
+// reference of the in-place fold and its shortcut.
+std::string reference_regularize(const std::string& input, bool use_lowercase)
{
+ std::string temp;
+ const size_t len = input.size();
+ temp.reserve(len);
+ for (size_t i = 0; i < len;) {
+ const auto c = static_cast<unsigned char>(input[i]);
+ if ((c & 0xF0) == 0xE0 && i + 2 < len) {
+ const int rune =
+ ((c & 0x0F) << 12) | ((input[i + 1] & 0x3F) << 6) |
(input[i + 2] & 0x3F);
+ if (rune == 0x3000) {
+ temp += ' ';
+ } else if (rune >= 0xFF01 && rune <= 0xFF5E) {
+ char half = static_cast<char>(rune - 0xFEE0);
+ if (use_lowercase && half >= 'A' && half <= 'Z') {
+ half += 32;
+ }
+ temp += half;
+ } else {
+ temp += input[i];
+ temp += input[i + 1];
+ temp += input[i + 2];
+ }
+ i += 3;
+ } else {
+ char ch = input[i];
+ if (use_lowercase && ch >= 'A' && ch <= 'Z') {
+ ch += 32;
+ }
+ temp += ch;
+ i += 1;
+ }
+ }
+ return temp;
+}
+
+TEST(IKCharacterUtilTest, CharTypeTableMatchesTheBlockRules) {
+ // decode_rune makes runes of up to 21 bits.
+ size_t mismatches = 0;
+ for (int32_t rune = 0; rune < 0x200000; ++rune) {
+ if (CharacterUtil::identifyCharType(rune) !=
CharacterUtil::identifyCharTypeByBlock(rune)) {
+ ADD_FAILURE_AT(__FILE__, __LINE__) << "rune " << rune;
+ if (++mismatches > 10) {
+ break;
+ }
+ }
+ }
+ EXPECT_EQ(mismatches, 0U);
+ EXPECT_EQ(CharacterUtil::identifyCharType(0x4E2D),
CharacterUtil::CharType::CHINESE);
+ EXPECT_EQ(CharacterUtil::identifyCharType(0x3042),
CharacterUtil::CharType::OTHER_CJK);
+ EXPECT_EQ(CharacterUtil::identifyCharType(0x1F600),
CharacterUtil::CharType::SURROGATE);
+ EXPECT_EQ(CharacterUtil::identifyCharType('7'),
CharacterUtil::CharType::ARABIC);
+ EXPECT_EQ(CharacterUtil::identifyCharType('Q'),
CharacterUtil::CharType::ENGLISH);
+ EXPECT_EQ(CharacterUtil::identifyCharType(0x00E9),
CharacterUtil::CharType::USELESS);
+}
+
+// Random bytes, most of them those the fold looks at: the leads E3 and EF,
the continuation bytes
+// of U+3000 and of U+FF01 to U+FF5E, other leads, and ASCII capitals.
+TEST(IKCharacterUtilTest, RegularizeStringMatchesTheFullFold) {
+ const std::vector<uint8_t> alphabet = {0xE3, 0xEF, 0x80, 0xBC, 0xBD, 0x81,
0x9E, 0x9F, 0xA1,
+ 0xBA, 0xE4, 0xE0, 0xE6, 0xF0, 0xC3,
'A', 'Z', 'M',
+ 'a', 'z', '@', '[', ' ', '0',
0x00, 0xFF};
+ std::mt19937 rng(4096);
+ std::uniform_int_distribution<size_t> pick(0, alphabet.size() - 1);
+ std::uniform_int_distribution<int> any_byte(0, 255);
+ std::uniform_int_distribution<size_t> size(0, 12);
+ std::vector<std::string> inputs = {"",
+ "数据库",
+ "Doris",
+ "SQL",
+ "Hello ABC",
+ "\xE3\x80\x80",
+ "\xEF\xBC",
+ "\xE3",
+ "hi",
+ "\xEF\xBD\x9E\xEF\xBD\x9F"};
+ for (int i = 0; i < 300000; ++i) {
+ std::string input(size(rng), '\0');
+ for (char& c : input) {
+ c = static_cast<char>(i % 4 == 0 ? any_byte(rng) :
alphabet[pick(rng)]);
+ }
+ inputs.push_back(std::move(input));
+ }
+ for (const std::string& input : inputs) {
+ for (const bool use_lowercase : {false, true}) {
+ std::string actual = input;
+ CharacterUtil::regularizeString(actual, use_lowercase);
+ ASSERT_EQ(actual, reference_regularize(input, use_lowercase))
+ << hex_of(input) << "use_lowercase " << use_lowercase;
+ }
+ }
+}
+
+} // namespace
+} // namespace doris::segment_v2
diff --git a/be/test/storage/index/inverted/analysis/component_stream_test.cpp
b/be/test/storage/index/inverted/analysis/component_stream_test.cpp
index da8984885c5..aefa29c0622 100644
--- a/be/test/storage/index/inverted/analysis/component_stream_test.cpp
+++ b/be/test/storage/index/inverted/analysis/component_stream_test.cpp
@@ -359,15 +359,12 @@ TEST(ComponentStreamTest, IKTokenizerReleasesItsWords) {
auto& ik = as<IKTokenizer>(*tokenizer);
expect_released_at_next_row(
*tokenizer, repeat_to("中华人民共和国 ab ", kLongRowBytes), "short",
true, [&] {
- size_t bytes = ik.tokens_.capacity() * sizeof(std::string)
+
- ik.ik_segmenter_->arena_.size() +
-
ik.ik_segmenter_->context_->segment_buff_.capacity() +
-
ik.ik_segmenter_->context_->typed_runes_.capacity() *
- sizeof(CharacterUtil::TypedRune);
- for (const std::string& text : ik.tokens_) {
- bytes += text.capacity();
- }
- return bytes;
+ return ik.words_.capacity() * sizeof(IKTokenizer::Word) +
+ ik.words_bytes_.capacity() +
ik.ik_segmenter_->arena_.size() +
+
ik.ik_segmenter_->context_->segment_buff_.capacity() +
+ ik.ik_segmenter_->context_->typed_runes_.capacity()
*
+ sizeof(CharacterUtil::TypedRune) +
+ ik.ik_segmenter_->context_->results_.capacity() *
sizeof(Lexeme);
});
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]