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.

Merge origin/main into fix/qs-negation-1299

xerj-org7198b113c583
diff --cc engine/crates/xerj-query/src/parser.rs
index fc237139f,5cd95daee..9a920f46c
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@@ -1996,87 -2078,100 +2074,113 @@@ fn parse_qs_or
ctx: QsFields<'_>,
default_op: Option<BoolOperator>,
) -> Option<QueryNode> {
- let mut clauses: Vec<QueryNode> = Vec::new();
- let mut not_clauses: Vec<QueryNode> = Vec::new();
- let mut explicit_and = false;
- loop {
- // Optional + / - / NOT prefix for each clause.
- let mut force_not = false;
- while *pos < toks.len() {
- match &toks[*pos] {
- QsTok::Must => {
- *pos += 1;
- }
- QsTok::Not => {
- force_not = true;
- *pos += 1;
- }
+ let default_and = matches!(default_op, Some(BoolOperator::And));
+ let mut clauses: Vec<(QsOccur, QueryNode)> = Vec::new();
+ while *pos < toks.len() && !matches!(toks[*pos], QsTok::RParen) {
+ let mut conj = QsConj::None;
+ while let Some(t) = toks.get(*pos) {
+ match t {
+ QsTok::And => conj = QsConj::And,
+ QsTok::Or => conj = QsConj::Or,
_ => break,
}
+ *pos += 1;
}
- let node = parse_qs_unary(toks, pos, ctx, default_op)?;
- if force_not {
- not_clauses.push(node);
- } else {
- clauses.push(node);
- }
- if *pos >= toks.len() {
- break;
- }
- match &toks[*pos] {
- QsTok::And => {
- explicit_and = true;
- *pos += 1;
- continue;
+ let (mut req_mod, mut not_mod) = (false, false);
+ while let Some(t) = toks.get(*pos) {
+ match t {
+ QsTok::Must => req_mod = true,
+ QsTok::Not => not_mod = true,
+ _ => break,
}
- QsTok::Or | QsTok::RParen => break,
- _ => {
- // Juxtaposition — treat as OR unless default_op is AND.
- if matches!(default_op, Some(BoolOperator::And)) || explicit_and {
- continue;
+ *pos += 1;
+ }
+ // A dangling operator (`kiwi AND`, `kiwi -`) has no clause to apply
+ // to: decline, and the caller falls back to the opaque node.
- let node = parse_qs_unary(toks, pos, ctx)?;
++ // `default_op` is threaded so a `field:( … )` group inside a clause
++ // (#1298) keeps the operator in effect.
++ let node = parse_qs_unary(toks, pos, ctx, default_op)?;
+
+ if let Some(prev) = clauses.last_mut() {
+ if prev.0 != QsOccur::MustNot {
+ if conj == QsConj::And {
+ prev.0 = QsOccur::Must;
+ } else if conj == QsConj::Or && default_and {
+ prev.0 = QsOccur::Should;
}
- break;
}
}
+ let required = if default_and {
+ !not_mod && conj != QsConj::Or
+ } else {
+ req_mod || (conj == QsConj::And && !not_mod)
+ };
+ let occur = if not_mod {
+ QsOccur::MustNot
+ } else if required {
+ QsOccur::Must
+ } else {
+ QsOccur::Should
+ };
+ clauses.push((occur, node));
}
- if clauses.len() == 1 && not_clauses.is_empty() {
- return Some(clauses.pop().unwrap());
+
+ if clauses.len() == 1 && clauses[0].0 != QsOccur::MustNot {
+ return clauses.pop().map(|(_, n)| n);
}
- let should_mode =
- !explicit_and && !clauses.is_empty() && !matches!(default_op, Some(BoolOperator::And));
- let node = if should_mode {
- QueryNode::Bool {
- must: vec![],
- filter: vec![],
- must_not: not_clauses,
- should: clauses,
- minimum_should_match: Some(MinShouldMatch::Fixed(1)),
- }
- } else {
- QueryNode::Bool {
- must: clauses,
- filter: vec![],
- must_not: not_clauses,
- should: vec![],
- minimum_should_match: None,
+ if clauses.is_empty() {
+ return None;
+ }
+ let (mut must, mut should, mut must_not) = (Vec::new(), Vec::new(), Vec::new());
+ for (occur, node) in clauses {
+ match occur {
+ QsOccur::Must => must.push(node),
+ QsOccur::Should => should.push(node),
+ QsOccur::MustNot => must_not.push(node),
}
- };
- Some(node)
+ }
+ // With a required clause, the optional ones only add score (Lucene and
+ // ES `bool`); with none, at least one of them must match.
+ let minimum_should_match =
+ (must.is_empty() && !should.is_empty()).then_some(MinShouldMatch::Fixed(1));
+ Some(QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ filter: vec![],
+ minimum_should_match,
+ })
}
- fn parse_qs_unary(toks: &[QsTok], pos: &mut usize, ctx: QsFields<'_>) -> Option<QueryNode> {
+ fn parse_qs_unary(
+ toks: &[QsTok],
+ pos: &mut usize,
+ ctx: QsFields<'_>,
+ default_op: Option<BoolOperator>,
+ ) -> Option<QueryNode> {
if *pos >= toks.len() {
return None;
}
match toks[*pos].clone() {
+ QsTok::FieldGroup(field) => {
+ // `field:( … )` (#1298): parse the group as if `field` were the
+ // only default field, so every unqualified clause inside it
+ // (terms, phrases, wildcards, ranges, nested groups) targets
+ // `field`. A clause inside that names its own field keeps it,
+ // as in ES. The tokenizer always emits `LParen` next.
+ *pos += 1;
+ if !matches!(toks.get(*pos), Some(QsTok::LParen)) {
+ return None;
+ }
+ let scoped = QsFields {
+ default_field: Some(&field),
+ fields: &[],
++ // Leniency is decided once per `query_string` (#1284), so the
++ // scoped group inherits the parent clause's setting.
++ lenient: ctx.lenient,
+ };
+ parse_qs_unary(toks, pos, scoped, default_op)
+ }
QsTok::LParen => {
*pos += 1;
// Bound paren-nesting depth. The shared thread-local `QUERY_DEPTH`
@@@ -5478,116 -5589,104 +5598,214 @@@ mod tests
assert_eq!(lte, Some(json!(5)));
}
+ /// The `query` of each bare `Match` in `nodes`, in order.
+ fn match_terms(nodes: &[QueryNode]) -> Vec<&str> {
+ nodes
+ .iter()
+ .map(|n| match n {
+ QueryNode::Match { query, .. } => query.as_str(),
+ other => panic!("expected a bare match, got {other:?}"),
+ })
+ .collect()
+ }
+
+ /// One query-string boolean level as (must, should, must_not, msm).
+ fn occurs(
+ query: &str,
+ default_operator: Option<&str>,
+ ) -> (
+ Vec<String>,
+ Vec<String>,
+ Vec<String>,
+ Option<MinShouldMatch>,
+ ) {
+ let mut body = json!({"query": query, "default_field": "t"});
+ if let Some(op) = default_operator {
+ body["default_operator"] = json!(op);
+ }
+ match q(json!({ "query_string": body })) {
+ QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ minimum_should_match,
+ ..
+ } => {
+ let own = |v: &[QueryNode]| match_terms(v).into_iter().map(String::from).collect();
+ (
+ own(&must),
+ own(&should),
+ own(&must_not),
+ minimum_should_match,
+ )
+ }
+ other => panic!("{query}: expected a Bool, got {other:?}"),
+ }
+ }
+
+ fn strs(v: &[&str]) -> Vec<String> {
+ v.iter().map(|s| s.to_string()).collect()
+ }
+
+ /// #1299: a prohibited clause excludes from its whole level. `alpha
+ /// -beta` used to lower to `alpha OR (NOT beta)`, whose pure-negative
+ /// branch matched every document without `beta`.
+ #[test]
+ fn query_string_negation_excludes_from_the_whole_level() {
+ let one = Some(MinShouldMatch::Fixed(1));
+ for query in [
+ "alpha -beta",
+ "-beta alpha",
+ "alpha NOT beta",
+ "alpha OR -beta",
+ ] {
+ assert_eq!(
+ occurs(query, None),
+ (vec![], strs(&["alpha"]), strs(&["beta"]), one.clone()),
+ "{query}"
+ );
+ }
+ assert_eq!(
+ occurs("alpha beta -gamma", None),
+ (vec![], strs(&["alpha", "beta"]), strs(&["gamma"]), one)
+ );
+ // `+` makes a clause required and the rest only score.
+ assert_eq!(
+ occurs("+alpha beta -gamma", None),
+ (strs(&["alpha"]), strs(&["beta"]), strs(&["gamma"]), None)
+ );
+ }
+
+ /// Mixed `AND` / `OR` follow Lucene's classic parser, as ES 8.13.4 does:
+ /// `AND` makes the clause before it required too, and under
+ /// `default_operator: AND` an `OR` makes the clause before it optional.
+ #[test]
+ fn query_string_mixed_operators_follow_the_classic_parser() {
+ assert_eq!(
+ occurs("kiwi OR lime AND plum", None),
+ (strs(&["lime", "plum"]), strs(&["kiwi"]), vec![], None)
+ );
+ assert_eq!(
+ occurs("kiwi AND lime OR plum", None),
+ (strs(&["kiwi", "lime"]), strs(&["plum"]), vec![], None)
+ );
+ assert_eq!(
+ occurs("kiwi AND NOT lime OR plum", None),
+ (strs(&["kiwi"]), strs(&["plum"]), strs(&["lime"]), None)
+ );
+ assert_eq!(
+ occurs("kiwi OR lime plum", Some("AND")),
+ (strs(&["plum"]), strs(&["kiwi", "lime"]), vec![], None)
+ );
+ assert_eq!(
+ occurs("-kiwi lime OR plum", Some("AND")),
+ (
+ vec![],
+ strs(&["lime", "plum"]),
+ strs(&["kiwi"]),
+ Some(MinShouldMatch::Fixed(1))
+ )
+ );
+ }
+
+ /// Every (field, value) leaf of a lowered query_string, in tree order.
+ fn qs_leaves(node: &QueryNode) -> Vec<(String, String)> {
+ fn walk(n: &QueryNode, out: &mut Vec<(String, String)>) {
+ match n {
+ QueryNode::Match { field, query, .. }
+ | QueryNode::MatchPhrase { field, query, .. } => {
+ out.push((field.clone(), query.clone()))
+ }
+ QueryNode::Wildcard { field, value, .. } => {
+ out.push((field.clone(), value.clone()))
+ }
+ QueryNode::Range { field, .. } => out.push((field.clone(), "<range>".into())),
+ QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ filter,
+ ..
+ } => {
+ for c in must.iter().chain(should).chain(must_not).chain(filter) {
+ walk(c, out);
+ }
+ }
+ QueryNode::DisMax { queries, .. } => queries.iter().for_each(|c| walk(c, out)),
+ QueryNode::Boosted { query, .. } => walk(query, out),
+ other => panic!("unexpected leaf {other:?}"),
+ }
+ }
+ let mut out = Vec::new();
+ walk(node, &mut out);
+ out
+ }
+
+ fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
+ v.iter()
+ .map(|(f, q)| (f.to_string(), q.to_string()))
+ .collect()
+ }
+
+ /// #1298: `field:( … )` scopes the whole group to `field`. It used to
+ /// lower to an empty-valued `Match` on `field` plus the group's terms on
+ /// the `*` placeholder, so the group searched every field.
+ #[test]
+ fn query_string_field_group_is_scoped_to_the_field() {
+ assert_eq!(qs_leaves(&qs("title:(beta)")), pairs(&[("title", "beta")]));
+ assert_eq!(qs_leaves(&qs("title: (beta)")), pairs(&[("title", "beta")]));
+ assert_eq!(
+ qs_leaves(&qs("title:(alpha OR (beta AND gamma))")),
+ pairs(&[("title", "alpha"), ("title", "beta"), ("title", "gamma")])
+ );
+ // Phrases and wildcards inside the group land on the field too.
+ assert_eq!(
+ qs_leaves(&qs("title:(\"alpha beta\" alp*)")),
+ pairs(&[("title", "alpha beta"), ("title", "alp*")])
+ );
+ // A clause that names its own field keeps it, as in ES.
+ assert_eq!(
+ qs_leaves(&qs("title:(alpha OR body:gamma)")),
+ pairs(&[("title", "alpha"), ("body", "gamma")])
+ );
+ // The group's field beats `default_field` / `fields`.
+ let with_default =
+ q(json!({"query_string": {"query": "title:(beta)", "default_field": "body"}}));
+ assert_eq!(qs_leaves(&with_default), pairs(&[("title", "beta")]));
+ let with_fields =
+ q(json!({"query_string": {"query": "title:(beta)", "fields": ["body", "x"]}}));
+ assert_eq!(qs_leaves(&with_fields), pairs(&[("title", "beta")]));
+ }
+
+ /// #1298: an unqualified range inside `n:( … )` has a concrete field and
+ /// lowers to a `Range` on it. It used to be refused ("requires an
+ /// explicit field").
+ #[test]
+ fn query_string_range_inside_a_field_group_targets_the_field() {
+ assert_eq!(qs_leaves(&qs("n:(>4)")), pairs(&[("n", "<range>")]));
+ assert_eq!(qs_leaves(&qs("n:([2 TO 8])")), pairs(&[("n", "<range>")]));
+ // Outside any field group the old refusal still holds.
+ assert!(parse_query(&json!({"query_string": {"query": "(>4)"}})).is_err());
+ }
+
+ /// `default_operator` reaches inside a group: ES 8.13.4 requires both
+ /// terms for `(alpha beta)` with `AND`. Groups used to be implicitly OR.
+ #[test]
+ fn query_string_default_operator_applies_inside_a_group() {
+ for query in ["title:(alpha beta)", "(alpha beta)"] {
+ let node = q(json!({"query_string": {
+ "query": query, "default_field": "title", "default_operator": "AND"
+ }}));
+ match node {
+ QueryNode::Bool { must, should, .. } => {
+ assert_eq!(must.len(), 2, "{query}: {must:?}");
+ assert!(should.is_empty(), "{query}: {should:?}");
+ }
+ other => panic!("{query}: expected a Bool, got {other:?}"),
+ }
+ }
+ }
+
/// `query_string`'s `fields` was accepted and ignored — the key never
/// reached this parser, so the query ran over every field regardless. It
/// now selects the targets for an unqualified clause, the same way