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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(query): terms_set minimum_should_match_field / _script
xerj-org553e411af0c2
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 86dbdaf57..7e67d34c9 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11338,7 +11338,7 @@ fn rewrite_query_aliases(q: &QueryNode, schema: &Schema) -> QueryNode {boost: *boost,operator: *operator,analyzer: analyzer.clone(),- minimum_should_match: *minimum_should_match,+ minimum_should_match: minimum_should_match.clone(),}}QueryNode::Bool {@@ -11364,7 +11364,7 @@ fn rewrite_query_aliases(q: &QueryNode, schema: &Schema) -> QueryNode {.iter().map(|c| rewrite_query_aliases(c, schema)).collect(),- minimum_should_match: *minimum_should_match,+ minimum_should_match: minimum_should_match.clone(),},// For all other query types, return as-is.other => other.clone(),@@ -11451,7 +11451,7 @@ fn strip_nested_path_in_query(q: &QueryNode, path: &str) -> QueryNode {boost: *boost,operator: *operator,analyzer: analyzer.clone(),- minimum_should_match: *minimum_should_match,+ minimum_should_match: minimum_should_match.clone(),},QueryNode::MatchPhrase {field,@@ -11546,7 +11546,7 @@ fn strip_nested_path_in_query(q: &QueryNode, path: &str) -> QueryNode {.iter().map(|c| strip_nested_path_in_query(c, path)).collect(),- minimum_should_match: *minimum_should_match,+ minimum_should_match: minimum_should_match.clone(),},QueryNode::Boosting {positive,@@ -12510,12 +12510,44 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {}// Should clauses: if present, at least minimum_should_match must match.if !should.is_empty() {+ // `should.len() + 1` is the "unsatisfiable" sentinel: `matched`+ // can never reach it, so the doc is forced to not match.+ let unsatisfiable = should.len() + 1;let min = match minimum_should_match {Some(MinShouldMatch::Fixed(n)) => *n as usize,Some(MinShouldMatch::Percentage(pct)) => {// Round down, minimum 1.((should.len() as f32 * (*pct as f32 / 100.0)).floor() as usize).max(1)}+ // terms_set: per-doc required count read from a numeric+ // field. Missing / non-numeric => the doc cannot match+ // (ES semantics).+ Some(MinShouldMatch::Field(name)) => {+ match get_field_value(source, name).and_then(|v| v.as_f64()) {+ Some(n) if n >= 0.0 => n as usize,+ _ => unsatisfiable,+ }+ }+ // terms_set: per-doc required count computed by a Painless+ // script, with `params.num_terms` injected. A script error+ // makes the doc unsatisfiable (fail-closed).+ Some(MinShouldMatch::Script {+ source: script_src,+ params,+ }) => {+ let mut p = params.clone().unwrap_or_else(|| serde_json::json!({}));+ if let Value::Object(map) = &mut p {+ map.insert("num_terms".to_string(), Value::from(should.len() as u64));+ }+ let ctx = crate::painless::PainlessCtx::new(source, &p, 0.0);+ match crate::painless::eval_painless(script_src, &ctx)+ .ok()+ .and_then(|v| v.as_f64())+ {+ Some(n) if n >= 0.0 => n as usize,+ _ => unsatisfiable,+ }+ }None => {// Default: if must/filter are empty, at least 1 should must match.if must.is_empty() && filter.is_empty() {@@ -16885,3 +16917,73 @@ mod span_containment_tests {assert!(!doc_matches_query(&q2, &doc2));}}++#[cfg(test)]+mod terms_set_tests {+ use super::*;+ use serde_json::json;+ use xerj_query::ast::{MinShouldMatch, QueryNode};++ /// Build the Bool that `terms_set` lowers to: a `should` of Term clauses+ /// over `codes` with the given `minimum_should_match`.+ fn terms_set_bool(codes: &[&str], msm: MinShouldMatch) -> QueryNode {+ QueryNode::Bool {+ must: vec![],+ must_not: vec![],+ filter: vec![],+ should: codes+ .iter()+ .map(|c| QueryNode::Term {+ field: "codes".into(),+ value: json!(c),+ boost: None,+ })+ .collect(),+ minimum_should_match: Some(msm),+ }+ }++ #[test]+ fn terms_set_field_required_count() {+ let q = terms_set_bool(&["a", "b", "c"], MinShouldMatch::Field("required".into()));++ // 2 of the codes present, required 2 => match.+ assert!(doc_matches_query(+ &q,+ &json!({ "codes": ["a", "b"], "required": 2 })+ ));+ // Only 1 present, required 2 => no match.+ assert!(!doc_matches_query(+ &q,+ &json!({ "codes": ["a"], "required": 2 })+ ));+ // required exceeds the number of matching terms => no match.+ assert!(!doc_matches_query(+ &q,+ &json!({ "codes": ["a", "b", "c"], "required": 4 })+ ));+ // required field missing => unsatisfiable, no match.+ assert!(!doc_matches_query(&q, &json!({ "codes": ["a", "b", "c"] })));+ // required field non-numeric => unsatisfiable, no match.+ assert!(!doc_matches_query(+ &q,+ &json!({ "codes": ["a", "b"], "required": "two" })+ ));+ }++ #[test]+ fn terms_set_script_num_terms() {+ // source `params.num_terms` => require ALL terms to match.+ let q = terms_set_bool(+ &["a", "b", "c"],+ MinShouldMatch::Script {+ source: "params.num_terms".into(),+ params: None,+ },+ );+ // All three present => match.+ assert!(doc_matches_query(&q, &json!({ "codes": ["a", "b", "c"] })));+ // Only two present => no match.+ assert!(!doc_matches_query(&q, &json!({ "codes": ["a", "b"] })));+ }+}diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rsindex 5937b56d7..86824c088 100644--- a/engine/crates/xerj-query/src/ast.rs+++ b/engine/crates/xerj-query/src/ast.rs@@ -85,14 +85,28 @@ pub enum Fuzziness {Fixed(u32),}-/// `minimum_should_match` — either an absolute count or a percentage.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+/// `minimum_should_match` — an absolute count, a percentage, or (for+/// `terms_set`) a per-document count sourced from a field or a script.+///+/// Not `Copy`/`Eq` because the `Script` variant carries an owned source+/// string and a free-form params object (`serde_json::Value` is not `Eq`).+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(untagged)]pub enum MinShouldMatch {/// Exact number of `should` clauses that must match.Fixed(u32),/// Percentage of `should` clauses that must match (0–100).Percentage(u32),+ /// `terms_set.minimum_should_match_field`: the required count is read+ /// per-document from this numeric field.+ Field(String),+ /// `terms_set.minimum_should_match_script`: the required count is the+ /// result of a Painless script (with `params.num_terms` injected).+ Script {+ source: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ params: Option<serde_json::Value>,+ },}// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rsindex 90b0a51c8..d317a542f 100644--- a/engine/crates/xerj-query/src/parser.rs+++ b/engine/crates/xerj-query/src/parser.rs@@ -611,7 +611,7 @@ fn parse_multi_match(params: &Value) -> Result<QueryNode> {let (im, is, imm) = if operator_and {(inner_clauses, vec![], None)} else {- (vec![], inner_clauses, mm_ms)+ (vec![], inner_clauses, mm_ms.clone())};let inner_bool = QueryNode::Bool {must: im,@@ -3473,19 +3473,28 @@ fn parse_terms_set(params: &Value) -> Result<QueryNode> {.ok_or_else(|| qerr("`terms_set.terms` must be an array"))?.clone();- let minimum_should_match = inner+ // `minimum_should_match_field` reads the per-doc required count from a+ // numeric field; `minimum_should_match_script` computes it from a+ // Painless script. Fall back to a literal `minimum_should_match`.+ let minimum_should_match = if let Some(field_name) = inner.get("minimum_should_match_field")- .or_else(|| inner.get("minimum_should_match_script"))- .map(|_| {- // Script/field-based minimum — fall back to 1 (parse without error).- crate::ast::MinShouldMatch::Fixed(1)- })- .or_else(|| {- inner- .get("minimum_should_match")- .map(parse_min_should_match)- .and_then(|r| r.ok())- });+ .and_then(Value::as_str)+ {+ Some(crate::ast::MinShouldMatch::Field(field_name.to_string()))+ } else if let Some(script) = inner.get("minimum_should_match_script") {+ let source = script+ .get("source")+ .and_then(Value::as_str)+ .ok_or_else(|| qerr("`terms_set.minimum_should_match_script` requires a `source`"))?+ .to_string();+ let params = script.get("params").cloned();+ Some(crate::ast::MinShouldMatch::Script { source, params })+ } else {+ inner+ .get("minimum_should_match")+ .map(parse_min_should_match)+ .and_then(|r| r.ok())+ };let should: Vec<QueryNode> = terms.iter()@@ -4582,4 +4591,48 @@ mod tests {})).is_err());}++ // ── terms_set minimum_should_match_field / _script ──────────────────────++ #[test]+ fn test_terms_set_minimum_should_match_field() {+ let node = q(json!({+ "terms_set": {+ "codes": {+ "terms": ["a", "b", "c"],+ "minimum_should_match_field": "required"+ }+ }+ }));+ match node {+ QueryNode::Bool {+ minimum_should_match: Some(MinShouldMatch::Field(name)),+ should,+ ..+ } => {+ assert_eq!(name, "required");+ assert_eq!(should.len(), 3);+ }+ other => panic!("expected bool w/ field msm, got {:?}", other),+ }+ }++ #[test]+ fn test_terms_set_minimum_should_match_script() {+ let node = q(json!({+ "terms_set": {+ "codes": {+ "terms": ["a", "b"],+ "minimum_should_match_script": { "source": "params.num_terms" }+ }+ }+ }));+ match node {+ QueryNode::Bool {+ minimum_should_match: Some(MinShouldMatch::Script { source, .. }),+ ..+ } => assert_eq!(source, "params.num_terms"),+ other => panic!("expected bool w/ script msm, got {:?}", other),+ }+ }}diff --git a/engine/tests/es-compat-yaml/yaml/search/terms_set.yml b/engine/tests/es-compat-yaml/yaml/search/terms_set.ymlnew file mode 100644index 000000000..bde587e11--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/search/terms_set.yml@@ -0,0 +1,70 @@+setup:+ - do:+ indices.create:+ index: tset+ body:+ mappings:+ properties:+ codes:+ type: keyword+ required:+ type: integer++ - do:+ bulk:+ refresh: true+ body:+ # 2 of {a,b,c} present, requires 2 => matches.+ - '{ "index": { "_index": "tset", "_id": "1" } }'+ - '{ "codes": ["a", "b"], "required": 2 }'+ # only 1 present, requires 2 => no match.+ - '{ "index": { "_index": "tset", "_id": "2" } }'+ - '{ "codes": ["a"], "required": 2 }'+ # all 3 present, requires 1 => matches.+ - '{ "index": { "_index": "tset", "_id": "3" } }'+ - '{ "codes": ["a", "b", "c"], "required": 1 }'+ # 2 present but requires 3 => no match (required exceeds matches).+ - '{ "index": { "_index": "tset", "_id": "4" } }'+ - '{ "codes": ["b", "c"], "required": 3 }'++---+"terms_set with minimum_should_match_field":++ - do:+ search:+ rest_total_hits_as_int: true+ index: tset+ body:+ size: 10+ sort: [ { _id: asc } ]+ query:+ terms_set:+ codes:+ terms: ["a", "b", "c"]+ minimum_should_match_field: required++ # docs 1 and 3 satisfy their per-doc required count; 2 and 4 do not.+ - match: { hits.total: 2 }+ - match: { hits.hits.0._id: "1" }+ - match: { hits.hits.1._id: "3" }++---+"terms_set with minimum_should_match_script params.num_terms":++ # params.num_terms == 3 => a doc must contain ALL three codes.+ - do:+ search:+ rest_total_hits_as_int: true+ index: tset+ body:+ size: 10+ query:+ terms_set:+ codes:+ terms: ["a", "b", "c"]+ minimum_should_match_script:+ source: "params.num_terms"++ # Only doc 3 has all of a, b and c.+ - match: { hits.total: 1 }+ - match: { hits.hits.0._id: "3" }