Skip to content

[feature](inverted-index) Add Japanese (Kuromoji) morphological analyzer - #64667

Open
nishant94 wants to merge 25 commits into
apache:masterfrom
nishant94:feat/kuromoji-japanese-analyzer
Open

[feature](inverted-index) Add Japanese (Kuromoji) morphological analyzer#64667
nishant94 wants to merge 25 commits into
apache:masterfrom
nishant94:feat/kuromoji-japanese-analyzer

Conversation

@nishant94

Copy link
Copy Markdown

What problem does this PR solve?

Issue Number: #64646

Related PR: None

Problem Summary:
Doris has no Japanese-aware tokenizer for the inverted index. Japanese text has no spaces between words, so the existing parsers can't segment it and MATCH / MATCH_PHRASE on Japanese columns end up with poor recall and precision.

This PR adds a built-in kuromoji parser for Japanese, in the same style as the existing Chinese IK analyzer. It's opt-in per column:

 INDEX content_idx (`content`) USING INVERTED
 PROPERTIES("parser" = "kuromoji", "parser_mode" = "search");

After indexing, MATCH, MATCH_PHRASE and TOKENIZE() run against the segmented Japanese terms.

How it works:

  • Native C++ under be/src/storage/index/inverted/analyzer/kuromoji/, so there's no JVM on the indexing path. KuromojiAnalyzer / KuromojiTokenizer mirror the IK analyzer/tokenizer, with a Viterbi cost-model segmenter over the IPADIC connection-cost matrix.
    • The dictionary is a process-wide singleton loaded once from ${inverted_index_dict_path}/kuromoji. An offline converter compiles raw IPADIC into a compact C++ runtime format (double-array trie + cost matrix + char/unknown tables) at build time, so no binary blob is committed.
    • search (default), normal and extended modes are supported. No thrift/proto changes — parser and mode ride as strings in the index properties.

Dictionary source is mecab-ipadic-2.7.0-20070801 (NAIST-2003 license, the same lexicon Lucene kuromoji uses).

Release note

Support Japanese text tokenization in the inverted index via a new kuromoji parser (PROPERTIES("parser"="kuromoji")), with search/normal/extended modes.

Check List (For Author)

  • Test
    • Regression test
    • Unit Test
    • Manual test (add detailed scripts or steps below)
  CREATE TABLE test_jp (
    id BIGINT,
    content TEXT,
    INDEX idx_content (content) USING INVERTED
      PROPERTIES("parser" = "kuromoji", "parser_mode" = "search")
  ) ENGINE=OLAP
  DUPLICATE KEY(id)
  DISTRIBUTED BY HASH(id) BUCKETS 1
  PROPERTIES("replication_num" = "1");

  INSERT INTO test_jp VALUES
    (1, '東京都に住んでいます'),
    (2, '日本語の形態素解析エンジン');

  -- search-mode decompounding: 東京都 also matches 東京
  SELECT id FROM test_jp WHERE content MATCH '東京';          -- expect: 1
  SELECT id FROM test_jp WHERE content MATCH_PHRASE '形態素解析'; -- expect: 2

  -- inspect segmentation directly
  SELECT TOKENIZE('東京都に住んでいます', '"parser"="kuromoji","parser_mode"="search"');
  • Behavior changed:
    • No.
    • Yes. It adds a new opt-in kuromoji parser. Existing parsers and their output are unchanged; the new behavior only applies to indexes that explicitly set parser="kuromoji".
  • Does this need documentation?
    • No.
    • Yes. PR Link to Doris-Website.

Check List (For Reviewer who merge this PR)

  • Confirm the release note
  • Confirm test cases
  • Confirm document
  • Add branch pick label

@hello-stephen

Copy link
Copy Markdown
Contributor

Thank you for your contribution to Apache Doris.
Don't know what should be done next? See How to process your PR.

Please clearly describe your PR:

  1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
  2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
  3. What features were added. Why was this function added?
  4. Which code was refactored and why was this part of the code refactored?
  5. Which functions were optimized and what is the difference before and after the optimization?

@nishant94

Copy link
Copy Markdown
Author

run buildall

@yiguolei

Copy link
Copy Markdown
Contributor

@nishant94 have you tried icu analyzer? because I think icu could handle many different languages.

@nishant94

nishant94 commented Jun 22, 2026

Copy link
Copy Markdown
Author

@nishant94 have you tried icu analyzer? because I think icu could handle many different languages.

@yiguolei The ICU Analyzer is not good as the Kuromoji. There is huge difference between icu and kuromoji when it comes to morphology of the Japanese words. So I think it worth it adding this new parser.

@BiteTheDDDDt

Copy link
Copy Markdown
Contributor

Is the code under be/src/storage/index/inverted/analyzer/kuromoji entirely original or derived from other projects? Perhaps we need to clarify the situation regarding this part.

@nishant94

Copy link
Copy Markdown
Author

Is the code under be/src/storage/index/inverted/analyzer/kuromoji entirely original or derived from other projects? Perhaps we need to clarify the situation regarding this part.

This is original code but it is modeled on Apache Lucene's kuromoji.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 44.44% (4/9) 🎉
Increment coverage report
Complete coverage report

@nishant94
nishant94 force-pushed the feat/kuromoji-japanese-analyzer branch from 389fcfb to b79db3c Compare June 22, 2026 09:57
@nishant94

Copy link
Copy Markdown
Author

run buildall

@hello-stephen

Copy link
Copy Markdown
Contributor

BE UT Coverage Report

Increment line coverage 82.40% (791/960) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 54.51% (21439/39327)
Line Coverage 38.17% (205347/537919)
Region Coverage 34.16% (161044/471416)
Branch Coverage 35.14% (70517/200651)

@hello-stephen

Copy link
Copy Markdown
Contributor

BE UT Coverage Report

Increment line coverage 84.10% (836/994) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 54.50% (21433/39329)
Line Coverage 38.13% (205092/537920)
Region Coverage 34.11% (160793/471446)
Branch Coverage 35.11% (70468/200678)

@hello-stephen

Copy link
Copy Markdown
Contributor

BE Regression && UT Coverage Report

Increment line coverage 83.85% (462/551) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 74.11% (28441/38375)
Line Coverage 58.02% (309954/534209)
Region Coverage 54.69% (258833/473301)
Branch Coverage 56.10% (112608/200725)

@hello-stephen

Copy link
Copy Markdown
Contributor

FE Regression Coverage Report

Increment line coverage 66.67% (6/9) 🎉
Increment coverage report
Complete coverage report

@nishant94

Copy link
Copy Markdown
Author

run buildall

@morningman morningman self-assigned this Jun 23, 2026
@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 44.44% (4/9) 🎉
Increment coverage report
Complete coverage report

@hello-stephen

Copy link
Copy Markdown
Contributor

FE Regression Coverage Report

Increment line coverage 35.29% (6/17) 🎉
Increment coverage report
Complete coverage report

@hello-stephen

Copy link
Copy Markdown
Contributor

BE UT Coverage Report

Increment line coverage 84.10% (836/994) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 54.72% (21523/39332)
Line Coverage 38.18% (205493/538169)
Region Coverage 34.17% (161179/471738)
Branch Coverage 35.13% (70561/200832)

@hello-stephen

Copy link
Copy Markdown
Contributor

BE Regression && UT Coverage Report

Increment line coverage 83.85% (462/551) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 74.19% (28466/38371)
Line Coverage 58.03% (310151/534436)
Region Coverage 54.77% (259367/473580)
Branch Coverage 56.13% (112755/200875)

Comment thread be/src/storage/index/inverted/analyzer/analyzer.cpp
@nishant94
nishant94 force-pushed the feat/kuromoji-japanese-analyzer branch from db0ee69 to 06b4ef6 Compare June 24, 2026 03:59
@nishant94
nishant94 requested a review from yiguolei June 24, 2026 05:18
@nishant94

Copy link
Copy Markdown
Author

run buildall

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 44.44% (4/9) 🎉
Increment coverage report
Complete coverage report

@hello-stephen

Copy link
Copy Markdown
Contributor

BE UT Coverage Report

Increment line coverage 84.20% (842/1000) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 54.58% (21476/39348)
Line Coverage 38.09% (205045/538313)
Region Coverage 34.07% (160754/471838)
Branch Coverage 35.04% (70387/200890)

@hello-stephen

Copy link
Copy Markdown
Contributor

BE Regression && UT Coverage Report

Increment line coverage 84.02% (468/557) 🎉

Increment coverage report
Complete coverage report

Category Coverage
Function Coverage 74.22% (28491/38387)
Line Coverage 58.10% (310621/534591)
Region Coverage 55.02% (260603/473686)
Branch Coverage 56.29% (113100/200937)

Comment thread be/dict/kuromoji/README.md
…wn words

- Implemented functionality in the Kuromoji Viterbi segmenter to decompose unknown (out-of-vocabulary) words into per-character unigrams when in extended mode, aligning with Lucene's JapaneseTokenizer behavior.
- Added unit tests to validate the correct segmentation of unknown words in both normal and extended modes, ensuring expected outputs for various input scenarios.
- Modified error messages to include 'kuromoji' parser in the parser mode validation.
- Enhanced tests for the Japanese analyzer to assert expected tokenization results.
- Introduced a new configuration option `enable_kuromoji_analyzer` to toggle the Kuromoji analyzer functionality.
- Updated unit tests to validate the behavior of the Kuromoji analyzer when enabled and disabled.
- Modified tests to enable the Kuromoji analyzer for specific test cases.
- Updated the namespace for Kuromoji components from `doris::segment_v2::kuromoji` to `doris::segment_v2::inverted_index::kuromoji` across multiple files for better organization and clarity.
- Updated the CMake configuration to ensure the required Kuromoji dictionary files are present at build time, failing the build if any are missing.
- Modified the KuromojiAnalyzer and KuromojiTokenizer to throw exceptions when the dictionary is not loaded, preventing silent fallbacks to per-codepoint tokenization.
- Improved error handling and validation in the dictionary loading process to ensure robust operation.
- Updated unit tests to validate the new behavior, ensuring that missing dictionaries trigger appropriate errors.
- Replaced the `ending_at` vector with `end_head` and `end_next` for better memory management and performance during node processing.
- Updated node addition and traversal logic to utilize the new data structures, enhancing the segmenter's efficiency in handling word segmentation.
- Changed the values in the `unk.per_category[CAT_DEFAULT]` entry from `{5, 5, 4769, "unk-default"}` to `{2, 2, 4769, "unk-default"}` to correct the test setup.
- Modified CMake configuration to conditionally include the Kuromoji dictionary files only for non-test builds (MAKE_TEST=ON).
- Adjusted the custom target for generating the Kuromoji dictionary to reflect the new conditional behavior, ensuring it remains a manual target during unit-test builds.
- Added checks for empty trie and out-of-range category mappings in the Kuromoji dictionary.
- Updated tests
- Added logic to return the Kuromoji search mode based on the analyzer property.
- Updated unit tests accordingly.
- This enhancement ensures that the necessary Kuromoji dictionary source is available for builds, improving the setup process for users.
- Updated test cases in `test_japanese_analyzer.groovy` to use query-time (qt_) assertions for better readability and maintainability.
- Introduced a penalty calculation mechanism for segmenting words based on the analyzer mode, improving the accuracy of word segmentation.
- Added caching for the current same-category run's byte end to optimize processing of grouped unknown words, reducing unnecessary rescans.
- Moved mecab-ipadic staging into a conditional block based on the BUILD_BE flag.
- Refactored the logic for setting the Kuromoji analyzer mode to ensure it defaults to the search mode when the parser mode is empty or set to coarse granularity.
- Introduced sorting of CSV file paths before processing to ensure consistent order.
- Enhanced error handling during lexicon parsing, including detailed error messages for failed parses.
- Added sorting of BuilderWord entries by cost and IDs.
- Implemented a new utility function to decode the first UTF-8 code point from a given string view, enhancing character processing capabilities.
- Updated the KuromojiTokenizer to skip unknown tokens based on their character category, improving tokenization accuracy.
- Introduced a new executable `kuromoji_build_dict` to compile the UTF-8 mecab-ipadic source into binary files.
- Added custom commands and targets to generate the Kuromoji dictionary, ensuring it is built as part of the overall project unless in test mode.
- Updated the CMake configuration to prepend the Kuromoji JVM library directory to the DYLD_LIBRARY_PATH and LD_LIBRARY_PATH environment variables during the dictionary generation process.
@nishant94
nishant94 force-pushed the feat/kuromoji-japanese-analyzer branch from de67da3 to 8de3899 Compare August 5, 2026 07:27
@nishant94

Copy link
Copy Markdown
Author

run buildall

@yiguolei

yiguolei commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

/review

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Codex automated review failed and did not complete.

Error: All Codex review accounts are usage-limited; earliest retry is 2026-08-08T03:32:00Z.
Workflow run: https://github.com/apache/doris/actions/runs/31204648726

Please trigger /review again after that time.

@yiguolei

yiguolei commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

/review

@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Codex automated review failed and did not complete.

Error: Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.
Workflow run: https://github.com/apache/doris/actions/runs/31283364478

Please inspect the workflow logs and rerun the review after the underlying issue is resolved.

@yiguolei

yiguolei commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated full-scope review of 8de3899cf47421e67ca2bfd2527c1bc9d94becdb. There was no additional user-provided focus, so I reviewed the entire supplied PR diff. I found five distinct new issues (three major, two minor) after duplicate-suppressing against all current review threads.

Critical checkpoint conclusions:

  • Goal/end-to-end behavior: the PR coherently adds IPADIC generation/loading and routes Kuromoji through index writes, indexed and slow MATCH-family analysis, SEARCH construction, and TOKENIZE; ordinary long-term correctness is blocked by the term-clipping finding.
  • Scope and API/storage/SQL compatibility: the broad build, runtime, FE, license, and test changes are feature-related. No new thrift or transaction schema is introduced; persisted analyzer strings and index segments remain subject to rolling-version issues already owned by live threads.
  • Concurrency, initialization, and lifecycle: successful dictionaries are mutex-published, immutable, process-lived, and safely back analyzer raw pointers; token streams are not shared across query calls. Failed-load lifetime is defective because a null cache entry can never recover at the same path. No separate lock-order, static-initialization, callback, or ownership issue was found.
  • Configuration semantics: the enable flag is mutable and checked on analyzer creation. Homogeneous current FE/BE defaults agree, but the regression destructively resets per-BE state. Readiness/config skew and analyzer-only validation gaps remain current but are already covered by live threads.
  • Runtime/version compatibility: current FE/BE parser and mode behavior agrees. Old-FE/old-BE rolling behavior and a legacy custom analyzer named kuromoji remain unsafe under existing owned discussions; the new distinct compatibility failure is use of a CMake 3.25-only command on the declared 3.19.2+ build path.
  • Parallel paths and control flow: scalar/array writers, indexed/slow MATCH, SEARCH, phrase-family construction, and TOKENIZE were traced to the same analyzer/mode. Loader errors fail visibly. Remaining position, punctuation, compound-emission, malformed-input, and corrupt-artifact cases are already owned by live threads.
  • Tests and expected results: synthetic BE/FE tests are discovered, while real-dictionary UTs can skip and the new P0 output/format/phrase coverage gaps remain current under existing threads. The distinct additional isolation issue is failure to restore the cluster configuration. No builds or tests were run, as required by the review prompt.
  • Observability: load failures log their directory and status and analyzer construction surfaces the error; no distinct missing metric/log issue was substantiated.
  • Transactions, persistence, and data writes: no transaction/EditLog protocol changes were introduced. Current-version write/query analysis agrees, aside from deterministic long-term aliasing; distributed rolling/config-write hazards are already covered live-thread issues.
  • FE/BE variables: parser, analyzer, and mode strings use the existing property/MatchPredicate paths with no missing send site found.
  • Performance: offline generation is one-time and successful mmap reuse is read-only. Long-OOV CPU/lattice amplification is already owned by an existing thread; no additional performance issue survived review.
  • Other correctness: packaging, thirdparty staging, deterministic generation, licenses, dictionary structure, UTF-8 stepping, Viterbi cost orientation, normalization, and all changed tests were rechecked. The five inline findings below are the complete non-duplicate set for this head.

Comment thread be/CMakeLists.txt
"${KUROMOJI_DICT_OUT}/chardef.bin" "${KUROMOJI_DICT_OUT}/unkdict.bin"
COMMAND ${CMAKE_COMMAND} -E make_directory "${KUROMOJI_DICT_OUT}"
COMMAND ${CMAKE_COMMAND} -E env
--modify "DYLD_LIBRARY_PATH=path_list_prepend:${KUROMOJI_LIBJVM_DIR}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Keep this command compatible with the declared CMake minimum. cmake -E env --modify was added in CMake 3.25, while this project still accepts 3.19.2 and docker/compilation/Dockerfile.gcc10 pins 3.22.1. On those supported toolchains configuration succeeds, but the ALL kuromoji_dict edge fails before producing the four binaries because CMake does not recognize --modify. Use a 3.19-compatible environment wrapper/syntax, or raise and enforce the minimum before configuring.

Status st = load(dir, &dict);
if (!st.ok()) {
LOG(WARNING) << "kuromoji: failed to load dictionary from " << dir << ": " << st;
cache.emplace(dir, nullptr);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Do not cache a failed dictionary load for the lifetime of the BE. If the first request observes a missing, corrupt, or temporarily unavailable file, this inserts nullptr for the directory; every later analyzer creation returns that cached failure even after all four valid artifacts are repaired or restored at the same path. The mutable feature gate makes first access after startup a supported lifecycle, but neither toggling it nor repairing the files can recover this BE. Cache successful immutable dictionaries only, or give negative entries a bounded retry/invalidation path, and cover fail-then-install-then-retry at one directory.

std::string& token_text = tokens_text_[buffer_index_++];
// reset() already segmented and normalized the terms; hand them out one at a
// time, capped at the CLucene maximum term length.
size_t size = std::min(token_text.size(), static_cast<size_t>(LUCENE_MAX_WORD_LEN));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Do not silently truncate a Kuromoji morpheme to 255 bytes. Grouped OOV tokens can be up to 1,024 code points, so two terms with the same first 255 bytes but different suffixes become identical in both the index and query analyzer, creating false MATCH-family hits; a Japanese/supplementary token can also be cut in the middle of a UTF-8 code point and leak malformed output through TOKENIZE. Reject/drop over-limit terms under one explicit index/query policy, or split them on validated UTF-8 boundaries, and test differing long suffixes plus a multibyte boundary.

assertTrue(tokenStr.contains('"token": "東京"'))
} finally {
sql "DROP TABLE IF EXISTS ${tableName}"
set_be_config("enable_kuromoji_analyzer", "false")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Minor] Restore each backend's original enable_kuromoji_analyzer value instead of forcing false here. The setting is mutable and true is a valid pre-suite state (with different BEs potentially configured differently), so a successful or failed run currently changes the shared cluster for later suites. Snapshot the value per BE before enabling it, check each update result, and restore those values in finally.

sh thirdparty/build-thirdparty.sh mecab_ipadic

# 2. the CMake target builds the offline compiler and produces the *.bin here
ninja -C be/ut_build_RELEASE kuromoji_dict

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Minor] Point this command at a build tree that actually defines kuromoji_dict. The named be/ut_build_RELEASE directory is configured by run-be-ut.sh with MAKE_TEST=ON, while be/CMakeLists.txt creates both Kuromoji generator targets only under if (NOT MAKE_TEST), so following these checked-in regeneration instructions fails with an unknown target. Document a normal MAKE_TEST=OFF build directory, or intentionally expose the target in the documented graph.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants