Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(es-compat): honor fuzzy/match prefix_length (#848) (#859)

xerj-org4250e0655987
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 74d8293dd..c0d2e89a9 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -23425,18 +23425,22 @@ impl Index {
value,
max_edits,
case_insensitive,
+ prefix_length,
..
} => {
// #423/#406: case-sensitive keyword fuzzy (the ES default)
// compares the RAW term; case_insensitive folds both sides.
let ci = *case_insensitive;
+ let pl = *prefix_length;
let q_ref = if ci {
value.to_lowercase()
} else {
value.clone()
};
let term_matches = |cmp: &str| -> bool {
- if levenshtein_distance(cmp, &q_ref) <= *max_edits {
+ if fuzzy_prefix_ok(cmp, &q_ref, pl)
+ && levenshtein_distance(cmp, &q_ref) <= *max_edits
+ {
return true;
}
// #423/#406: the sub-token fallback is a FOLD-path leniency
@@ -23454,7 +23458,10 @@ impl Index {
}
cmp.split(|c: char| !c.is_alphanumeric())
.filter(|t| !t.is_empty())
- .any(|tok| levenshtein_distance(tok, &q_ref) <= *max_edits)
+ .any(|tok| {
+ fuzzy_prefix_ok(tok, &q_ref, pl)
+ && levenshtein_distance(tok, &q_ref) <= *max_edits
+ })
};
let mut map: HashMap<String, (usize, u64)> = HashMap::new();
for (meta, cols) in segments.iter().zip(seg_cols.iter()) {
@@ -35518,11 +35525,13 @@ fn strip_nested_path_in_query(q: &QueryNode, path: &str) -> QueryNode {
value,
fuzziness,
case_insensitive,
+ prefix_length,
} => QueryNode::Fuzzy {
field: strip(field),
value: value.clone(),
fuzziness: *fuzziness,
case_insensitive: *case_insensitive,
+ prefix_length: *prefix_length,
},
QueryNode::Regexp { field, pattern } => QueryNode::Regexp {
field: strip(field),
@@ -38207,11 +38216,13 @@ fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Schema) -> bo
value: query_value,
fuzziness,
case_insensitive,
+ prefix_length,
} => {
let max_edits = match fuzziness {
Fuzziness::Auto => auto_fuzziness(query_value),
Fuzziness::Fixed(n) => *n as usize,
};
+ let prefix_length = *prefix_length;
// ES's Fuzzy query matches at the TERM level with an UNANALYZED
// query term. For keyword fields the indexed term is the whole
// field value, so first compare the full string against the query —
@@ -38232,16 +38243,22 @@ fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Schema) -> bo
let q_lower = query_value.to_lowercase();
let token_match = |s: &str| -> bool {
if keyword_case_sensitive {
- return levenshtein_distance(s, query_value.as_str()) <= max_edits;
+ return fuzzy_prefix_ok(s, query_value.as_str(), prefix_length)
+ && levenshtein_distance(s, query_value.as_str()) <= max_edits;
}
let s_lower = s.to_lowercase();
- if levenshtein_distance(&s_lower, &q_lower) <= max_edits {
+ if fuzzy_prefix_ok(&s_lower, &q_lower, prefix_length)
+ && levenshtein_distance(&s_lower, &q_lower) <= max_edits
+ {
return true;
}
s_lower
.split(|c: char| !c.is_alphanumeric())
.filter(|t| !t.is_empty())
- .any(|tok| levenshtein_distance(tok, &q_lower) <= max_edits)
+ .any(|tok| {
+ fuzzy_prefix_ok(tok, &q_lower, prefix_length)
+ && levenshtein_distance(tok, &q_lower) <= max_edits
+ })
};
get_field_value(source, field)
.and_then(|v| match v {
@@ -41702,6 +41719,21 @@ fn wildcard_match_inner(text: &[char], pattern: &[char]) -> bool {
}
}
+/// #848: ES `prefix_length` guard — the first `prefix_length` characters of the
+/// query and a candidate term must be IDENTICAL (not subject to edits) before
+/// Levenshtein distance is consulted. `prefix_length == 0` (ES default) imposes
+/// no constraint. Compare the SAME (already case-folded, where applicable)
+/// strings that the distance call uses. Kept in lock-step with the copy in
+/// `xerj-fts/src/search.rs`.
+#[inline]
+fn fuzzy_prefix_ok(candidate: &str, query: &str, prefix_length: usize) -> bool {
+ prefix_length == 0
+ || candidate
+ .chars()
+ .take(prefix_length)
+ .eq(query.chars().take(prefix_length))
+}
+
/// Compute Levenshtein edit distance between two strings.
fn levenshtein_distance(a: &str, b: &str) -> usize {
// Damerau-Levenshtein (with transposition) — ES `fuzzy` queries default
@@ -43047,6 +43079,7 @@ fn query_node_to_fts_with_keyword_fields(
value,
fuzziness,
case_insensitive,
+ prefix_length,
} => {
// `fuzzy` on a KEYWORD field: expand the keyword FST term dictionary
// to every term within `max_edits` Damerau-Levenshtein distance and
@@ -43071,6 +43104,7 @@ fn query_node_to_fts_with_keyword_fields(
// keyword FST route is case-SENSITIVE (ES default); a
// query_string/term-ci fuzzy sets it true and keeps folding.
case_insensitive: *case_insensitive,
+ prefix_length: *prefix_length,
}));
}
// TEXT field: expand the term dictionary within `max_edits`
@@ -43090,6 +43124,7 @@ fn query_node_to_fts_with_keyword_fields(
max_edits,
boost: 1.0,
case_insensitive: false,
+ prefix_length: *prefix_length,
}));
}
None
@@ -43784,6 +43819,8 @@ enum ScoredPlan {
/// #423/#406: fold both sides when true; case-sensitive raw-term match
/// when false (standalone keyword fuzzy, ES default).
case_insensitive: bool,
+ /// #848: leading characters that must match exactly (ES default 0).
+ prefix_length: usize,
},
}
@@ -44393,6 +44430,7 @@ fn scored_fast_plan(
value,
fuzziness,
case_insensitive,
+ prefix_length,
} if fs.kw.contains(field) => {
let max_edits = match fuzziness {
Fuzziness::Auto => auto_fuzziness(value),
@@ -44404,6 +44442,7 @@ fn scored_fast_plan(
max_edits,
boost: 1.0,
case_insensitive: *case_insensitive,
+ prefix_length: *prefix_length,
})
}
// Filter-only bool: ES scores filter context 0.0 (the brute path's
@@ -46321,6 +46360,7 @@ mod fts_projection_tests {
value: "runbok".into(),
fuzziness: Fuzziness::Fixed(1),
case_insensitive: false,
+ prefix_length: 0,
};
match query_node_to_fts(&q, &tf, &kw(&[])).expect("text fuzzy projects") {
FtsQuery::Fuzzy(f) => {
diff --git a/engine/crates/xerj-engine/tests/fuzzy_prefix_length.rs b/engine/crates/xerj-engine/tests/fuzzy_prefix_length.rs
new file mode 100644
index 000000000..9c9288da4
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/fuzzy_prefix_length.rs
@@ -0,0 +1,90 @@
+//! Issue #848: ES `prefix_length` on a fuzzy/match query — the first N
+//! characters of the query and each candidate term must match EXACTLY (not
+//! subject to edits) before Levenshtein applies. XERJ ignored `prefix_length`
+//! entirely (grep = 0 hits across query/engine/fts), so a `prefix_length: N`
+//! (N>0) was silently dropped and terms differing in their first N chars were
+//! wrongly fuzzy-matched — MORE hits than ES.
+//!
+//! Covered here for BOTH a keyword field (memtable doc-scan + segment
+//! `KeywordFuzzy`) and a text field (memtable doc-scan + segment FST
+//! `expand_fuzzy`), each asserted flush-invariant: every query is answered
+//! buffered AND flushed, and the two must agree.
+
+use serde_json::json;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+
+async fn hits(engine: &Engine, q: &serde_json::Value) -> u64 {
+ let idx = engine.get_index("docs").expect("get index");
+ let req = parse_request(&json!({ "query": q, "size": 0 })).expect("parse_request");
+ idx.search(&req).await.expect("search").total.value
+}
+
+#[tokio::test]
+async fn fuzzy_prefix_length_requires_exact_leading_chars() {
+ let dir = TempDir::new().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(config).expect("engine");
+
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("name", FieldType::Keyword));
+ schema
+ .fields
+ .push(FieldConfig::new("body", FieldType::Text));
+ engine.create_index("docs", schema).expect("create");
+ let idx = engine.get_index("docs").expect("get");
+ idx.index_document(
+ Some("d0".to_string()),
+ json!({ "name": "axble", "body": "axble" }),
+ )
+ .await
+ .expect("index");
+
+ // fuzziness 1: "exble" is 1 edit from "axble" (leading char differs);
+ // "axcle" is 1 edit (a middle char differs, prefix "ax" intact).
+ let kw = |v: &str, pl: u64| json!({ "fuzzy": { "name": { "value": v, "fuzziness": 1, "prefix_length": pl } } });
+ let tx = |v: &str, pl: u64| json!({ "fuzzy": { "body": { "value": v, "fuzziness": 1, "prefix_length": pl } } });
+
+ // (query, expected_hits, label). Keyword field exercises the memtable
+ // doc-scan (buffered) and the columnar `KeywordFuzzy` (flushed); text field
+ // exercises the doc-scan (buffered) and the FST `expand_fuzzy` (flushed).
+ let cases = [
+ (
+ kw("exble", 0),
+ 1,
+ "kw prefix_length 0 imposes no constraint",
+ ),
+ (kw("exble", 1), 0, "kw leading char must match exactly"),
+ (kw("axcle", 2), 1, "kw in-prefix edit still matches"),
+ (
+ tx("exble", 0),
+ 1,
+ "tx prefix_length 0 imposes no constraint",
+ ),
+ (tx("exble", 1), 0, "tx leading char must match exactly"),
+ (tx("axcle", 2), 1, "tx in-prefix edit still matches"),
+ ];
+
+ // Answer every case BUFFERED first (memtable path), then flush ONCE and
+ // answer every case again (segment path) — so both paths are exercised for
+ // every query, not just the first.
+ let mut pre = Vec::new();
+ for (q, _, _) in &cases {
+ pre.push(hits(&engine, q).await);
+ }
+ idx.refresh().await.expect("refresh");
+ for (i, (q, expected, label)) in cases.iter().enumerate() {
+ let post = hits(&engine, q).await;
+ assert_eq!(
+ pre[i], post,
+ "#848: fuzzy prefix_length must be flush-invariant — {label}"
+ );
+ assert_eq!(post, *expected, "#848: {label}");
+ }
+}
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index c1177b4f1..8012efcdd 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -294,6 +294,11 @@ pub struct FuzzyQuery {
/// lowercased term dictionary without lowercasing the query term.
#[serde(default = "default_case_insensitive")]
pub case_insensitive: bool,
+ /// #848: ES `prefix_length` — the leading characters that must match
+ /// exactly (not subject to edits) before Levenshtein applies. Default `0`
+ /// (no constraint).
+ #[serde(default)]
+ pub prefix_length: usize,
}
impl FuzzyQuery {
@@ -304,6 +309,7 @@ impl FuzzyQuery {
max_edits,
boost: 1.0,
case_insensitive: true,
+ prefix_length: 0,
}
}
}
@@ -953,7 +959,13 @@ impl FtsSearcher {
// ── Fuzzy query ─────────────────────────────────────────────────────────────
fn execute_fuzzy(&self, fq: &FuzzyQuery, explain: bool) -> Result<Vec<ScoredHit>> {
- let terms = self.expand_fuzzy(&fq.field, &fq.value, fq.max_edits, fq.case_insensitive);
+ let terms = self.expand_fuzzy(
+ &fq.field,
+ &fq.value,
+ fq.max_edits,
+ fq.case_insensitive,
+ fq.prefix_length,
+ );
// Fuzzy keeps per-term scoring (ES rewrites fuzzy to a blended-frequency
// scoring query, NOT constant_score).
self.score_expanded_terms(&fq.field, &terms, fq.boost, explain, false)
@@ -973,6 +985,7 @@ impl FtsSearcher {
value: &str,
max_edits: usize,
case_insensitive: bool,
+ prefix_length: usize,
) -> Vec<String> {
// Streaming FST scan + deadline poll every 1 024 terms (RC4
// blocker 12): per-term edit distance is the most expensive
@@ -986,7 +999,7 @@ impl FtsSearcher {
if seen & 1023 == 0 && self.deadline_hit() {
return false;
}
- if term_matches_fuzzy(t, &q_lower, max_edits) {
+ if term_matches_fuzzy(t, &q_lower, max_edits, prefix_length) {
out.push(t.to_owned());
}
true
@@ -997,7 +1010,9 @@ impl FtsSearcher {
if seen & 1023 == 0 && self.deadline_hit() {
return false;
}
- if levenshtein_distance(t, value) <= max_edits {
+ if fuzzy_prefix_ok(t, value, prefix_length)
+ && levenshtein_distance(t, value) <= max_edits
+ {
out.push(t.to_owned());
}
true
@@ -1339,15 +1354,33 @@ fn term_matches_wildcard(term: &str, pat_lc: &str) -> bool {
/// `true` if `term` (case-folded) is within `max_edits` Damerau-Levenshtein
/// distance of the already-lowercased `q_lower`, as the whole value or any
/// sub-token.
-fn term_matches_fuzzy(term: &str, q_lower: &str, max_edits: usize) -> bool {
+fn term_matches_fuzzy(term: &str, q_lower: &str, max_edits: usize, prefix_length: usize) -> bool {
let s_lower = term.to_lowercase();
- if levenshtein_distance(&s_lower, q_lower) <= max_edits {
+ if fuzzy_prefix_ok(&s_lower, q_lower, prefix_length)
+ && levenshtein_distance(&s_lower, q_lower) <= max_edits
+ {
return true;
}
s_lower
.split(|c: char| !c.is_alphanumeric())
.filter(|t| !t.is_empty())
- .any(|tok| levenshtein_distance(tok, q_lower) <= max_edits)
+ .any(|tok| {
+ fuzzy_prefix_ok(tok, q_lower, prefix_length)
+ && levenshtein_distance(tok, q_lower) <= max_edits
+ })
+}
+
+/// #848: ES `prefix_length` guard — the first `prefix_length` characters of the
+/// query and a candidate term must be identical before Levenshtein applies.
+/// `0` (ES default) imposes no constraint. Lock-step with the engine's copy in
+/// `xerj-engine/src/index.rs`.
+#[inline]
+fn fuzzy_prefix_ok(candidate: &str, query: &str, prefix_length: usize) -> bool {
+ prefix_length == 0
+ || candidate
+ .chars()
+ .take(prefix_length)
+ .eq(query.chars().take(prefix_length))
}
/// Glob match: `*` = zero-or-more chars, `?` = exactly one. No case folding —
diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rs
index e2ccc111f..ec89d0b7b 100644
--- a/engine/crates/xerj-query/src/ast.rs
+++ b/engine/crates/xerj-query/src/ast.rs
@@ -274,6 +274,13 @@ fn is_false(b: &bool) -> bool {
!*b
}
+/// serde `skip_serializing_if` helper: omit a `usize` field when it is `0`
+/// (the ES default for `prefix_length`) so query round-trips stay byte-identical.
+#[inline]
+fn is_zero(n: &usize) -> bool {
+ *n == 0
+}
+
/// A single node in the query tree.
///
/// All query types — leaf and compound — are variants of this one enum.
@@ -554,6 +561,13 @@ pub enum QueryNode {
/// against the term dictionary). Ignored for `text` fields.
#[serde(default, skip_serializing_if = "is_false")]
case_insensitive: bool,
+ /// #848: the number of leading characters that must match EXACTLY
+ /// (not subject to edits) before Levenshtein applies. ES default `0`
+ /// (no constraint). `N > 0` requires the query and each candidate term
+ /// to share their first `N` characters — pruning fuzzy expansions that
+ /// differ in the prefix.
+ #[serde(default, skip_serializing_if = "is_zero")]
+ prefix_length: usize,
},
/// Regular expression match against a field value.
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index ff6ce98e8..43817ac40 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -859,6 +859,8 @@ fn parse_multi_match(params: &Value) -> Result<QueryNode> {
Value::Number(n) => crate::ast::Fuzziness::Fixed(n.as_u64().unwrap_or(0) as u32),
_ => crate::ast::Fuzziness::Auto,
});
+ // #848: `match` accepts `prefix_length` alongside `fuzziness`.
+ let prefix_length = parse_prefix_length(obj);
let raw_tokens: Vec<String> = if analyzer_opt.as_deref() == Some("keyword") {
vec![query.to_string()]
} else {
@@ -903,6 +905,7 @@ fn parse_multi_match(params: &Value) -> Result<QueryNode> {
value: tok.to_string(),
fuzziness: fz,
case_insensitive: false,
+ prefix_length,
}
} else {
QueryNode::Match {
@@ -2217,6 +2220,7 @@ fn parse_fuzzy(params: &Value) -> Result<QueryNode> {
value: value.to_string(),
fuzziness: Fuzziness::Auto,
case_insensitive: false,
+ prefix_length: 0,
});
}
@@ -2250,14 +2254,26 @@ fn parse_fuzzy(params: &Value) -> Result<QueryNode> {
.get("case_insensitive")
.and_then(|v| v.as_bool())
.unwrap_or(false);
+ let prefix_length = parse_prefix_length(inner);
Ok(QueryNode::Fuzzy {
field,
value,
fuzziness,
case_insensitive,
+ prefix_length,
})
}
+/// #848: read ES `prefix_length` off a fuzzy/match parameter object. Accepts a
+/// non-negative number or its string spelling; defaults to `0` (no constraint).
+fn parse_prefix_length(obj: &serde_json::Map<String, Value>) -> usize {
+ match obj.get("prefix_length") {
+ Some(Value::Number(n)) => n.as_u64().unwrap_or(0) as usize,
+ Some(Value::String(s)) => s.parse::<usize>().unwrap_or(0),
+ _ => 0,
+ }
+}
+
fn parse_regexp(params: &Value) -> Result<QueryNode> {
let obj = params
.as_object()
@@ -4208,48 +4224,50 @@ fn parse_match_bool_prefix(params: &Value) -> Result<QueryNode> {
let field = field.clone();
// Long-form accepts the same options as `match` + `operator` + mm.
- let (query_str, mm, operator_and, analyzer, fuzziness) = if let Some(s) = raw.as_str() {
- (s.to_string(), None, false, None, None)
- } else {
- let inner = raw
- .as_object()
- .ok_or_else(|| qerr("`match_bool_prefix` field value must be a string or object"))?;
- let q = string_field(inner, "query")?;
- let mm_val = inner.get("minimum_should_match").and_then(|v| match v {
- Value::Number(n) => n.as_u64().map(|i| MinShouldMatch::Fixed(i as u32)),
- Value::String(s) => {
- if let Some(p) = s.strip_suffix('%') {
- p.parse::<u32>().ok().map(MinShouldMatch::Percentage)
- } else {
- s.parse::<u32>().ok().map(MinShouldMatch::Fixed)
+ let (query_str, mm, operator_and, analyzer, fuzziness, prefix_length) =
+ if let Some(s) = raw.as_str() {
+ (s.to_string(), None, false, None, None, 0usize)
+ } else {
+ let inner = raw.as_object().ok_or_else(|| {
+ qerr("`match_bool_prefix` field value must be a string or object")
+ })?;
+ let q = string_field(inner, "query")?;
+ let mm_val = inner.get("minimum_should_match").and_then(|v| match v {
+ Value::Number(n) => n.as_u64().map(|i| MinShouldMatch::Fixed(i as u32)),
+ Value::String(s) => {
+ if let Some(p) = s.strip_suffix('%') {
+ p.parse::<u32>().ok().map(MinShouldMatch::Percentage)
+ } else {
+ s.parse::<u32>().ok().map(MinShouldMatch::Fixed)
+ }
}
- }
- _ => None,
- });
- let op_and = matches!(
- inner
- .get("operator")
+ _ => None,
+ });
+ let op_and = matches!(
+ inner
+ .get("operator")
+ .and_then(Value::as_str)
+ .map(|s| s.to_ascii_lowercase())
+ .as_deref(),
+ Some("and")
+ );
+ let analyzer = inner
+ .get("analyzer")
.and_then(Value::as_str)
- .map(|s| s.to_ascii_lowercase())
- .as_deref(),
- Some("and")
- );
- let analyzer = inner
- .get("analyzer")
- .and_then(Value::as_str)
- .map(str::to_string);
- let fuzziness = inner.get("fuzziness").map(|v| match v {
- Value::String(s) if s.eq_ignore_ascii_case("auto") => crate::ast::Fuzziness::Auto,
- Value::String(s) => s
- .parse::<u32>()
- .ok()
- .map(crate::ast::Fuzziness::Fixed)
- .unwrap_or(crate::ast::Fuzziness::Auto),
- Value::Number(n) => crate::ast::Fuzziness::Fixed(n.as_u64().unwrap_or(0) as u32),
- _ => crate::ast::Fuzziness::Auto,
- });
- (q, mm_val, op_and, analyzer, fuzziness)
- };
+ .map(str::to_string);
+ let fuzziness = inner.get("fuzziness").map(|v| match v {
+ Value::String(s) if s.eq_ignore_ascii_case("auto") => crate::ast::Fuzziness::Auto,
+ Value::String(s) => s
+ .parse::<u32>()
+ .ok()
+ .map(crate::ast::Fuzziness::Fixed)
+ .unwrap_or(crate::ast::Fuzziness::Auto),
+ Value::Number(n) => crate::ast::Fuzziness::Fixed(n.as_u64().unwrap_or(0) as u32),
+ _ => crate::ast::Fuzziness::Auto,
+ });
+ let prefix_length = parse_prefix_length(inner);
+ (q, mm_val, op_and, analyzer, fuzziness, prefix_length)
+ };
// Analyzer semantics: "whitespace" preserves case, "keyword" treats
// input as single token, default/standard lowercases. We approximate
@@ -4297,6 +4315,7 @@ fn parse_match_bool_prefix(params: &Value) -> Result<QueryNode> {
value: folded,
fuzziness: fz,
case_insensitive: true,
+ prefix_length,
}
} else {
QueryNode::Match {