lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
  • Coverage
  • 100%
    32 out of 32 items documented0 out of 6 items with examples
  • Size
  • Source code size: 1.0 MB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.1 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 2s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • Repository
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • i18nsite

license

English 简体中文 Français Deutsch Español 日本語 العربية Português Русский Italiano Nederlands 한국어 Türkçe Indonesia 正體中文 हिन्दी Polski தமிழ் Gaeilge Svenska বাংলা עברית ไทย Norsk Tiếng Việt मराठी Bahasa Melayu Dansk Română اردو Čeština فارسی తెలుగు ਪੰਜਾਬੀ ಕನ್ನಡ ગુજરાતી Ελληνικά Suomi Català Gàidhlig Қазақша Filipino Kiswahili ئۇيغۇرچە Magyar Українська Oʻzbekcha മലയാളം Slovenčina Afrikaans Hrvatski Српски Български አማርኛ Cymraeg ଓଡ଼ିଆ සිංහල Euskara Lietuvių Беларуская Galego မြန်မာ Slovenščina Azərbaycanca অসমীয়া ខ្មែរ नेपाली Kurdî Latviešu Eesti Татарча Íslenska ქართული Shqip Հայերեն Монгол Кыргызча Македонски ລາວ Тоҷикӣ Esperanto Nynorsk سۆرانی

lexf

In full-text search, a user searching for cut expects to hit cutting, searching for 数据库 expects to hit 數據庫, and searching for 1000.5 expects to hit 1,000.50.

lexf expands each token after segmentation into several search forms: first the normalized base form, then the stem and variants.

Indexing and querying use the same set of expansion rules, so both ends align naturally and recall works across inflections, traditional/simplified variants, and written formats.

All rules are based on algorithms and built-in tables; no dictionaries or models are loaded, there are no external dependencies, and no unsafe is used.

It is designed to work with segmentation results from mcut's CutMode::Search, and the output can be written directly into a PostgreSQL-compatible full-text index.

Usage

//! Expand search terms into normalized forms and stems

use lexf::{LangHint, LexConfig, Mode, Scratch, detect_lang, expand, expand_each};
use mcut::{Cut, CutMode, MCUT};

fn main() {
  // Index side: for each token, output the base form as well as the stem and variants
  let cfg = LexConfig::default();
  assert_eq!(expand("Cuting", cfg), ["cuting", "cut", "cute"]);
  assert_eq!(expand("database", cfg), ["database", "database"]);
  assert_eq!(expand("1,000.50", cfg), ["1,000.50", "1000.50", "1000.5"]);

  // Query side: prefix queries and exact phrases do not extract stems
  let norm = LexConfig {
    mode: Mode::Norm,
    ..cfg
  };
  assert_eq!(expand("Cuting", norm), ["cuting"]);

  // With mcut: detect the language once for the whole text and reuse the same set of buffers for all tokens
  let doc = "Die Häuser und der Wald";
  let cfg = LexConfig {
    lang: detect_lang(doc),
    ..cfg
  };
  assert_eq!(cfg.lang, LangHint::De);
  let mut scratch = Scratch::new();
  for tok in MCUT.cut(doc, CutMode::Search) {
    let mut form_li = Vec::new();
    expand_each(tok.text, cfg, &mut scratch, |form| form_li.push(form.to_owned()));
    println!("{} -> {form_li:?}", tok.text);
  }
}
cargo run -p lexf --example basic

Output:

Die -> ["die"]
Häuser -> ["häuser", "hauser", "haeuser", "haus"]
und -> ["und"]
der -> ["der"]
Wald -> ["wald"]

Expansion rules

All tokens first undergo general normalization: lowercase, full-width characters converted to half-width, decimal digits in each script converted to ASCII digits, curly quotes, various hyphens and spaces unified, and combining diacritics removed.

They are then processed according to the scripts that appear in the token:

Script Normalization Stemming
Latin Remove diacritics (café → cafe); German digraphs (häuser → haeuser); merge two-part hyphenated words (e-mail → email) English uses Snowball Porter2 plus lemmatization (studies → study); German, French, Spanish, Portuguese, Italian, Dutch, Swedish, and Turkish use simplified Snowball rules
Han Traditional to simplified (OpenCC table) None
Japanese kana Half-width katakana to full-width, katakana to hiragana Remove polite and inflectional endings (ます, ました, etc.)
Korean None Remove particles and endings (를, 에서, etc.)
Cyrillic ё → е Snowball Russian
Arabic Remove vowel marks, unify variants such as alef and taa marbuta Light10 prefix/suffix stripping
Greek Remove accents, ς → σ Common inflectional suffixes

Numbers and alphanumeric mixed tokens are handled separately:

  • Pure numbers: remove thousands separators (only when every group after a comma has three digits; 3,14 is unaffected), and remove trailing zeros in decimals.
  • Alphanumeric mixed tokens (gpt-4o, v1.2.0): normalization only, no stemming.

Hyphenated Latin words are not stemmed.

Interface

expand_each

pub fn expand_each(token: &str, cfg: LexConfig, scratch: &mut Scratch, emit: impl FnMut(&str))

Expand one token, calling emit once for each form produced.

The output order is fixed: normalized base form first, then normalized variants, and finally the stem.

Output is deduplicated, empty forms are not emitted, and at most cfg.max_form forms are output.

Leading and trailing whitespace is ignored, and whitespace-only tokens emit no forms.

expand

pub fn expand(token: &str, cfg: LexConfig) -> Vec<String>

Convenience version of expand_each that collects the results into a Vec<String>.

Each call allocates new buffers; use expand_each for batch processing.

LexConfig

pub struct LexConfig {
  pub lang: LangHint,
  pub max_form: usize,
  pub mode: Mode,
}
  • lang: language hint, default LangHint::Auto. For Han, kana, Korean, etc., the script itself determines how they are processed; this field mainly affects which language's stemming rules are chosen for Latin words.
  • max_form: maximum number of forms output per token, default DEFAULT_MAX_FORM (6). When 0, nothing is output.
  • mode: expansion depth, default Mode::NormAndStem.

When lang is Auto, Latin words are judged per token based on their own diacritics; if there are no diacritics, they are treated as English.

When lang is set to a non-Latin language such as Chinese or Japanese, Latin words within it are treated as English.

Mode

pub enum Mode {
  Norm,
  NormAndStem,
}
  • Norm: normalization only. Used for prefix queries (such as 'cutin':*) and exact phrases, to avoid stemming changing the prefix.
  • NormAndStem: normalization plus stemming, used for indexing and ordinary queries.

Scratch

pub struct Scratch

Reusable working buffers.

Pass the same Scratch repeatedly in a loop so that no heap memory is allocated while processing each token.

LangHint

pub enum LangHint {
  Auto, En, De, Fr, Es, Pt, It, Nl, Sv, Tr, Zh, Ja, Ko, Ru, Ar, El, Other,
}

Language hint.

LangHint::from_code accepts ISO codes or PostgreSQL full-text search configuration names, case-insensitively, such as "de" and "German"; returns None when unrecognized.

detect_lang

pub fn detect_lang(text: &str) -> LangHint

Detect the primary language of a piece of text; suitable for detecting once per document and then filling the result into LexConfig::lang.

Non-Latin scripts are counted by the Unicode block each character belongs to, and the most frequent one is chosen. When the proportion of kana is high enough, Han characters in the same segment are counted as Japanese.

Latin script is scored using language-specific diacritics and the function words unique to each language in the Snowball stopword lists.

Returns LangHint::Other when the text contains no letters from supported scripts; returns LangHint::En when Latin script cannot be distinguished.