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(search): AND omitted match on log indices, date-type xferlog stamps (#2278)

xerj-org801a50c80827
diff --git a/engine/crates/xerj-autoindex/src/infer/dates.rs b/engine/crates/xerj-autoindex/src/infer/dates.rs
index 5e4ec4168..65c29f01e 100644
--- a/engine/crates/xerj-autoindex/src/infer/dates.rs
+++ b/engine/crates/xerj-autoindex/src/infer/dates.rs
@@ -4,7 +4,7 @@
//! (The engine's dynamic mapping has NO date detection — verified — so
//! autoindex is the date layer.)
-use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, SecondsFormat, TimeZone, Utc};
+use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, SecondsFormat, TimeZone, Utc, Weekday};
/// Epoch windows: 1990-01-01 .. 2100-01-01
pub const EPOCH_MS_MIN: i64 = 631_152_000_000;
@@ -22,6 +22,11 @@ pub enum DateEnc {
Rfc2822, // Tue, 01 Jul 2025 10:00:00 +0000
EpochMillis, // numeric
EpochSeconds, // numeric
+ /// vsftpd/wu-ftpd `xferlog` current-time: `Fri Oct 16 09:06:58 2026`
+ /// (ctime: weekday, month, day, time, year). No zone, so UTC is assumed,
+ /// the same assumption as the other naive encodings. Declared ahead of
+ /// [`DateEnc::BsdSyslog`] because it carries a year.
+ Asctime,
/// RFC 3164 timestamp: `Oct 17 22:26:01` / `Oct 5 09:06:58`. No year and
/// no zone. Appended last so a tie still prefers every encoding above,
/// which all carry a year.
@@ -39,6 +44,7 @@ impl DateEnc {
DateEnc::Rfc2822 => "rfc2822",
DateEnc::EpochMillis => "epoch-millis",
DateEnc::EpochSeconds => "epoch-seconds",
+ DateEnc::Asctime => "asctime (Www Mmm dd hh:mm:ss yyyy, assumed UTC)",
// The year is not in the stamp. It is the year of `now` unless
// that reading is more than 24h in the future, in which case it
// is the previous year (a December line read in January).
@@ -105,6 +111,9 @@ pub fn parse_date_str_at(s: &str, now: DateTime<Utc>) -> Option<(DateTime<Utc>,
if let Ok(dt) = DateTime::parse_from_rfc2822(t) {
return Some((dt.with_timezone(&Utc), DateEnc::Rfc2822));
}
+ if let Some(dt) = parse_asctime(t) {
+ return Some((dt, DateEnc::Asctime));
+ }
if let Some(dt) = parse_bsd_syslog(t, now) {
return Some((dt, DateEnc::BsdSyslog));
}
@@ -132,26 +141,66 @@ fn english_month(name: &str) -> Option<u32> {
})
}
-/// `Mmm dd hh:mm:ss` (day space-padded), the whole string and nothing else.
-/// Year: `now`'s UTC year, unless that instant is more than 24 hours ahead
-/// of `now`, in which case the previous year. A Feb 29 that is not a real
-/// day in the chosen year does not parse — inventing a different day would
-/// put the line on the wrong date.
-fn parse_bsd_syslog(t: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {
+/// `Www Mmm dd hh:mm:ss yyyy`, the whole string and nothing else. The weekday
+/// has to be the weekday of that civil date: a mismatched name is not a
+/// transfer-log stamp. No zone is present, so the instant is UTC.
+fn parse_asctime(t: &str) -> Option<DateTime<Utc>> {
let mut parts = t.split_whitespace();
+ let weekday = english_weekday(parts.next()?)?;
let month = english_month(parts.next()?)?;
let day: u32 = parts.next()?.parse().ok()?;
let time = parts.next()?;
+ let year: i32 = parts.next()?.parse().ok()?;
if parts.next().is_some() || !(1..=31).contains(&day) || time.len() != 8 {
return None;
}
+ let (hour, minute, second) = hms(time)?;
+ let date = NaiveDate::from_ymd_opt(year, month, day)?;
+ if date.weekday() != weekday {
+ return None;
+ }
+ date.and_hms_opt(hour, minute, second)
+ .map(|ndt| Utc.from_utc_datetime(&ndt))
+}
+
+fn english_weekday(name: &str) -> Option<Weekday> {
+ Some(match name {
+ "Mon" => Weekday::Mon,
+ "Tue" => Weekday::Tue,
+ "Wed" => Weekday::Wed,
+ "Thu" => Weekday::Thu,
+ "Fri" => Weekday::Fri,
+ "Sat" => Weekday::Sat,
+ "Sun" => Weekday::Sun,
+ _ => return None,
+ })
+}
+
+fn hms(time: &str) -> Option<(u32, u32, u32)> {
let mut hm = time.split(':');
let hour: u32 = hm.next()?.parse().ok()?;
let minute: u32 = hm.next()?.parse().ok()?;
let second: u32 = hm.next()?.parse().ok()?;
- if hm.next().is_some() {
+ if hm.next().is_some() || hour > 23 || minute > 59 || second > 59 {
return None;
}
+ Some((hour, minute, second))
+}
+
+/// `Mmm dd hh:mm:ss` (day space-padded), the whole string and nothing else.
+/// Year: `now`'s UTC year, unless that instant is more than 24 hours ahead
+/// of `now`, in which case the previous year. A Feb 29 that is not a real
+/// day in the chosen year does not parse — inventing a different day would
+/// put the line on the wrong date.
+fn parse_bsd_syslog(t: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {
+ let mut parts = t.split_whitespace();
+ let month = english_month(parts.next()?)?;
+ let day: u32 = parts.next()?.parse().ok()?;
+ let time = parts.next()?;
+ if parts.next().is_some() || !(1..=31).contains(&day) || time.len() != 8 {
+ return None;
+ }
+ let (hour, minute, second) = hms(time)?;
let at = |year: i32| {
NaiveDate::from_ymd_opt(year, month, day)?
.and_hms_opt(hour, minute, second)
@@ -293,4 +342,27 @@ mod tests {
!= DateEnc::BsdSyslog
);
}
+
+ /// #1504: vsftpd `xferlog` stamps the transfer as ctime (`Www Mmm dd
+ /// hh:mm:ss yyyy`). That string missed every encoding, so the column
+ /// mapped `keyword` and a time-range filter matched nothing. The weekday
+ /// has to be the real weekday of the date; a year-less RFC 3164 stamp
+ /// stays on the BSD path.
+ #[test]
+ fn xferlog_asctime_stamps_are_dates_and_a_wrong_weekday_is_not() {
+ let (dt, enc) = parse_date_str("Fri Oct 16 09:06:58 2026").unwrap();
+ assert_eq!(enc, DateEnc::Asctime);
+ assert_eq!(to_rfc3339_millis(&dt), "2026-10-16T09:06:58.000Z");
+
+ let (padded, enc) = parse_date_str("Mon Oct 5 09:06:58 2026").unwrap();
+ assert_eq!(enc, DateEnc::Asctime);
+ assert_eq!(to_rfc3339_millis(&padded), "2026-10-05T09:06:58.000Z");
+
+ // Oct 16 2026 is a Friday. Saturday is a different day.
+ assert!(parse_date_str("Sat Oct 16 09:06:58 2026").is_none());
+ // RFC 3164 has no weekday and no year. It must not become asctime.
+ let now = at(2026, 10, 17, 23, 0, 0);
+ let (_, enc) = parse_date_str_at("Oct 16 09:06:58", now).unwrap();
+ assert_eq!(enc, DateEnc::BsdSyslog);
+ }
}
diff --git a/engine/crates/xerj-autoindex/src/infer/mod.rs b/engine/crates/xerj-autoindex/src/infer/mod.rs
index 50016b805..ae3268ec0 100644
--- a/engine/crates/xerj-autoindex/src/infer/mod.rs
+++ b/engine/crates/xerj-autoindex/src/infer/mod.rs
@@ -894,6 +894,10 @@ impl CodeAnalyzer {
/// of the query, and only for this family — the global default stays
/// `"stemmer"` / `"standard"` because dropping stop words changes every
/// document's BM25 length norm (#1059).
+///
+/// This does not change `match`'s operator. Content words are still OR
+/// unless the index also sets `index.query.default_match_operator` to
+/// `and`, which a logs dataset's create body does.
pub const LOG_TEXT_ANALYZER: &str = "english";
/// Dataset text analyzer. `log_dataset` elects [`LOG_TEXT_ANALYZER`];
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 1dd6443e7..b76eec0ae 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -544,6 +544,17 @@ fn dataset_mapping_body(dataset: &PlanDataset, extra: &[infer::FieldSpec]) -> Va
} else {
create_body["settings"] = json!({"index.query.strict_unknown_fields": true});
}
+ // #1504: log messages are searched as phrases. The english analyzer
+ // already drops `is`; an omitted `match` is still OR for the content
+ // words, so `SIP 403 Forbidden` hits every line that contains `SIP`.
+ // The engine reads this key in `Index::search` and fills an omitted
+ // operator with AND. An explicit `"operator": "or"` is left alone, and
+ // a non-log index never gets the key, so the ES default stays OR.
+ // The key lives here, beside `strict_unknown_fields`, and not in
+ // `build_mapping`: that value is hashed into the generation contract.
+ if dataset.family == "logs" {
+ create_body["settings"]["index.query.default_match_operator"] = json!("and");
+ }
create_body
}
@@ -3926,9 +3937,91 @@ mod phase_a_grouping_tests {
Some(infer::LOG_TEXT_ANALYZER)
);
let names: Vec<&str> = logs[0].specs.iter().map(|s| s.name.as_str()).collect();
- for field in ["ts", "host", "program", "message"] {
+ for field in ["ts", "host", "program", "message", "severity"] {
assert!(names.contains(&field), "missing {field} in {names:?}");
}
+ let spec = |name: &str| {
+ logs[0]
+ .specs
+ .iter()
+ .find(|s| s.name == name)
+ .unwrap_or_else(|| panic!("missing {name}"))
+ };
+ assert_eq!(spec("ts").es_type, "date", "a time window filters on ts");
+ assert_eq!(logs[0].time_field.as_deref(), Some("ts"));
+ assert_eq!(spec("host").es_type, "keyword", "a device filter is exact");
+ assert_eq!(spec("severity").es_type, "keyword");
+ let body = dataset_create_body(logs[0]);
+ assert_eq!(
+ body["settings"]["index.query.default_match_operator"],
+ json!("and"),
+ "an omitted match on a log index requires every token"
+ );
+ }
+
+ /// #1504: vsftpd `xferlog` was already one record per line, but its ctime
+ /// stamp (`Fri Oct 16 09:06:58 2026`) was not a date, so a time-range
+ /// filter on the transfer log matched nothing. A prose file does not
+ /// pick up the log match-operator default.
+ #[test]
+ fn xferlog_timestamp_maps_as_date_and_prose_does_not_default_match_to_and() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ std::fs::write(
+ root.join("xferlog"),
+ "Fri Oct 16 09:06:58 2026 1 10.0.0.7 4242 /uploads/fw.bin b _ o r admin ftp 0 * c\n\
+ Fri Oct 16 09:07:10 2026 2 10.0.0.8 10 /uploads/invalid.bin b _ o r admin ftp 0 * i\n\
+ Sat Oct 17 11:00:00 2026 0 10.0.0.9 0 /pub/README a C i a guest ftp 1 guest c\n\
+ Sun Oct 18 08:30:00 2026 4 10.0.0.7 100 /var/log/a.log b _ o r admin ftp 0 * c\n\
+ Mon Oct 19 09:06:58 2026 1 10.0.0.7 50 /uploads/cfg.xml b _ i r admin ftp 0 * c\n\
+ Tue Oct 20 09:06:58 2026 1 10.0.0.4 50 /uploads/cfg.xml b _ i r admin ftp 0 * c\n",
+ )
+ .unwrap();
+ let plan = plan_for(root);
+ let logs: Vec<_> = plan
+ .datasets
+ .iter()
+ .filter(|d| d.family == "logs")
+ .collect();
+ assert_eq!(
+ logs.len(),
+ 1,
+ "{:?}",
+ plan.datasets.iter().map(|d| &d.family).collect::<Vec<_>>()
+ );
+ let ts = logs[0]
+ .specs
+ .iter()
+ .find(|s| s.name == "ts")
+ .expect("xferlog ts");
+ assert_eq!(ts.es_type, "date", "{ts:?}");
+ assert!(
+ ts.date_enc
+ .as_deref()
+ .is_some_and(|e| e.contains("asctime")),
+ "{ts:?}"
+ );
+ assert_eq!(logs[0].time_field.as_deref(), Some("ts"));
+ let host = logs[0].specs.iter().find(|s| s.name == "host").unwrap();
+ assert_eq!(host.es_type, "keyword");
+ assert_eq!(
+ dataset_create_body(logs[0])["settings"]["index.query.default_match_operator"],
+ json!("and")
+ );
+
+ let prose = tempfile::tempdir().unwrap();
+ std::fs::write(prose.path().join("README.md"), PROSE).unwrap();
+ let prose_plan = plan_for(prose.path());
+ assert!(!prose_plan.datasets.is_empty());
+ assert!(prose_plan.datasets.iter().all(|d| d.family != "logs"));
+ for dataset in &prose_plan.datasets {
+ assert!(
+ dataset_create_body(dataset)["settings"]
+ .get("index.query.default_match_operator")
+ .is_none(),
+ "a non-log index keeps match's OR default"
+ );
+ }
}
const CODE: &str = "// The event loop dispatches every ready connection to a worker.\n\
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index ec03572ea..697e57f10 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -20391,6 +20391,29 @@ impl Index {
}
/// Execute a search request against this index.
+ /// #1504. Autoindex writes `index.query.default_match_operator: and` on a
+ /// logs dataset so an omitted `match` requires every token. The key is
+ /// stored the way the create body sent it (a flat dotted key, or nested
+ /// under `index.query`). Any other value, including absence, keeps ES's
+ /// OR default.
+ fn match_operator_defaults_to_and(settings: &Value) -> bool {
+ let is_and = |v: &Value| v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("and"));
+ if settings
+ .pointer("/index/query/default_match_operator")
+ .is_some_and(is_and)
+ {
+ return true;
+ }
+ [Some(settings), settings.get("index")]
+ .into_iter()
+ .flatten()
+ .any(|container| {
+ container
+ .get("index.query.default_match_operator")
+ .is_some_and(is_and)
+ })
+ }
+
pub async fn search(&self, request: &SearchRequest) -> Result<SearchResult> {
use crate::collection_publication::ReadAdmission;
@@ -20500,6 +20523,22 @@ impl Index {
savings: None,
}
};
+ // #1504: a logs index resolves an omitted match operator to AND
+ // before the cache key is hashed, so a cached page cannot be the OR
+ // hit list. Indices without the setting keep the request as parsed
+ // (Omitted executes as OR). Explicit `"operator": "or"` is untouched.
+ let default_match_and = {
+ let settings = self.settings.read().await;
+ Self::match_operator_defaults_to_and(&settings)
+ };
+ let rewritten = if default_match_and {
+ let mut owned = request.clone();
+ xerj_query::apply_default_match_operator(&mut owned, xerj_query::BoolOperator::And);
+ Some(owned)
+ } else {
+ None
+ };
+ let request = rewritten.as_ref().unwrap_or(request);
// M3 framework: response cache. Hash the request shape and the
// current dataset version; on a hit return the cloned `Arc<SearchResult>`
// immediately, skipping the semaphore, search_inner, locks, and
@@ -47884,15 +47923,18 @@ pub(crate) fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Sc
}
let need = match operator {
xerj_query::ast::BoolOperator::And => q_tokens.len(),
- xerj_query::ast::BoolOperator::Or => match minimum_should_match {
- None => 1,
- Some(MinShouldMatch::Fixed(n)) => *n as usize,
- Some(MinShouldMatch::Percentage(pct)) => {
- ((q_tokens.len() as f32 * (*pct as f32 / 100.0)).floor() as usize)
- .max(1)
+ // Omitted is OR until a log index rewrites it (#1504).
+ xerj_query::ast::BoolOperator::Or | xerj_query::ast::BoolOperator::Omitted => {
+ match minimum_should_match {
+ None => 1,
+ Some(MinShouldMatch::Fixed(n)) => *n as usize,
+ Some(MinShouldMatch::Percentage(pct)) => {
+ ((q_tokens.len() as f32 * (*pct as f32 / 100.0)).floor() as usize)
+ .max(1)
+ }
+ Some(other) => other.required(q_tokens.len()).unwrap_or(1),
}
- Some(other) => other.required(q_tokens.len()).unwrap_or(1),
- },
+ }
};
let raw_values: Vec<String> = match get_field_value(source, field) {
Some(Value::String(value)) => vec![value],
@@ -48006,17 +48048,21 @@ pub(crate) fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Sc
// so the threshold applies across the union.
let need: usize = match operator {
xerj_query::ast::BoolOperator::And => q_tokens.len(),
- xerj_query::ast::BoolOperator::Or => match minimum_should_match {
- None => 1,
- Some(MinShouldMatch::Fixed(n)) => *n as usize,
- Some(MinShouldMatch::Percentage(pct)) => {
- ((q_tokens.len() as f32 * (*pct as f32 / 100.0)).floor() as usize).max(1)
+ // Omitted is OR until a log index rewrites it (#1504).
+ xerj_query::ast::BoolOperator::Or | xerj_query::ast::BoolOperator::Omitted => {
+ match minimum_should_match {
+ None => 1,
+ Some(MinShouldMatch::Fixed(n)) => *n as usize,
+ Some(MinShouldMatch::Percentage(pct)) => {
+ ((q_tokens.len() as f32 * (*pct as f32 / 100.0)).floor() as usize)
+ .max(1)
+ }
+ // #846: negative / negative-% / combination resolve against
+ // the token count; terms_set field/script counts aren't
+ // valid on a plain match, so degrade those to OR (need 1).
+ Some(other) => other.required(q_tokens.len()).unwrap_or(1),
}
- // #846: negative / negative-% / combination resolve against
- // the token count; terms_set field/script counts aren't
- // valid on a plain match, so degrade those to OR (need 1).
- Some(other) => other.required(q_tokens.len()).unwrap_or(1),
- },
+ }
};
let count_matched = |field_tokens: &[String]| -> usize {
q_tokens
@@ -62283,3 +62329,134 @@ mod exact_scan_hydration_tests {
);
}
}
+
+/// #1504: a logs index's omitted `match` requires every token. The same
+/// query on an index without the setting stays ES's OR, and an explicit
+/// `"operator": "or"` on the logs index stays OR too.
+#[cfg(test)]
+mod log_match_operator_tests {
+ use super::*;
+ use serde_json::json;
+
+ fn message_schema() -> Schema {
+ let mut schema = Schema::empty();
+ schema
+ .add_field(FieldConfig::new("message", FieldType::Text))
+ .unwrap();
+ schema
+ }
+
+ fn english() -> Value {
+ json!({"analysis": {"analyzer": {"default": {"type": "english"}}}})
+ }
+
+ async fn index_lines(idx: &Index, lines: &[(&str, &str)]) {
+ idx.abort_background_tasks();
+ for (id, message) in lines {
+ idx.index_document(Some((*id).to_string()), json!({"message": message}))
+ .await
+ .unwrap();
+ }
+ }
+
+ fn hit_ids(result: &SearchResult) -> Vec<String> {
+ let mut ids: Vec<String> = result.hits.iter().map(|hit| hit.id.clone()).collect();
+ ids.sort();
+ ids
+ }
+
+ const LINES: &[(&str, &str)] = &[
+ ("sip-only", "SIP engine not registered"),
+ ("forbidden", "SIP/2.0 403 Forbidden"),
+ ("is-only", "device is online"),
+ ("both-words", "invalid configuration detected"),
+ ];
+
+ #[test]
+ fn the_setting_is_read_from_a_flat_key_or_a_nested_object() {
+ assert!(Index::match_operator_defaults_to_and(&json!({
+ "index.query.default_match_operator": "and"
+ })));
+ assert!(Index::match_operator_defaults_to_and(&json!({
+ "index": {"query": {"default_match_operator": "AND"}}
+ })));
+ assert!(!Index::match_operator_defaults_to_and(&json!({
+ "analysis": {"analyzer": {"default": {"type": "english"}}}
+ })));
+ assert!(!Index::match_operator_defaults_to_and(&json!({
+ "index.query.default_match_operator": "or"
+ })));
+ }
+
+ #[tokio::test]
+ async fn a_log_index_match_requires_every_token_and_a_plain_index_does_not() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config).unwrap();
+
+ let mut logs_settings = english();
+ logs_settings["index.query.default_match_operator"] = json!("and");
+ engine
+ .create_index_with_settings("logs", message_schema(), logs_settings)
+ .unwrap();
+ engine
+ .create_index_with_settings("plain", message_schema(), english())
+ .unwrap();
+ let logs = engine.get_index("logs").unwrap();
+ let plain = engine.get_index("plain").unwrap();
+ index_lines(&logs, LINES).await;
+ index_lines(&plain, LINES).await;
+
+ let sip = xerj_query::parse_request(&json!({
+ "query": {"match": {"message": "SIP 403 Forbidden"}},
+ "size": 10
+ }))
+ .unwrap();
+ let sip_or = xerj_query::parse_request(&json!({
+ "query": {"match": {"message": {"query": "SIP 403 Forbidden", "operator": "or"}}},
+ "size": 10
+ }))
+ .unwrap();
+
+ // Memtable path (operator AND is a stored scan) and the flushed FTS
+ // path must agree: a line that only says SIP is not the phrase.
+ for idx in [&logs, &plain] {
+ let before = hit_ids(&idx.search(&sip).await.unwrap());
+ idx.flush().await.unwrap();
+ let after = hit_ids(&idx.search(&sip).await.unwrap());
+ assert_eq!(before, after, "flush must not change the hit set");
+ }
+ assert_eq!(
+ hit_ids(&logs.search(&sip).await.unwrap()),
+ vec!["forbidden".to_string()],
+ "SIP 403 Forbidden must not hit a line that only contains SIP"
+ );
+ assert_eq!(
+ hit_ids(&logs.search(&sip_or).await.unwrap()),
+ vec!["forbidden".to_string(), "sip-only".to_string()],
+ "an explicit operator or still matches any token"
+ );
+ let plain_hits = hit_ids(&plain.search(&sip).await.unwrap());
+ assert!(
+ plain_hits.contains(&"sip-only".to_string())
+ && plain_hits.contains(&"forbidden".to_string()),
+ "without the setting, match stays OR: {plain_hits:?}"
+ );
+
+ let phrase = xerj_query::parse_request(&json!({
+ "query": {"match": {"message": "configuration is invalid"}},
+ "size": 10
+ }))
+ .unwrap();
+ assert_eq!(
+ hit_ids(&logs.search(&phrase).await.unwrap()),
+ vec!["both-words".to_string()],
+ "is is not a term, and the other two words must both be present"
+ );
+ assert!(
+ !hit_ids(&plain.search(&phrase).await.unwrap()).contains(&"is-only".to_string()),
+ "the english analyzer already drops is, on a non-log index too"
+ );
+ }
+}
diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rs
index a9b195623..9e9b70682 100644
--- a/engine/crates/xerj-query/src/ast.rs
+++ b/engine/crates/xerj-query/src/ast.rs
@@ -33,6 +33,16 @@ pub enum BoolOperator {
Or,
/// All tokens must match.
And,
+ /// The request did not name an operator. Execution treats this as [`Or`]
+ /// unless the index sets `index.query.default_match_operator` to `and`
+ /// (#1504, log datasets). Not a wire value: the parser produces it only
+ /// when the `operator` key is absent, and [`crate::apply_default_match_operator`]
+ /// resolves it before a log index runs the query. An explicit `"or"` stays
+ /// [`Or`], so a caller can still ask for the ES default on a log index.
+ ///
+ /// Serde's missing-field default stays [`Or`]. A deserialized AST that
+ /// never went through the parser must not grow this variant.
+ Omitted,
}
/// Determines how scores are combined for `MultiMatch` queries.
diff --git a/engine/crates/xerj-query/src/lib.rs b/engine/crates/xerj-query/src/lib.rs
index 4d5ad71d4..b42965c6d 100644
--- a/engine/crates/xerj-query/src/lib.rs
+++ b/engine/crates/xerj-query/src/lib.rs
@@ -74,7 +74,7 @@ pub use error::{ParseError, QueryError, Result};
pub use parser::{parse_query, parse_request};
// Rewriter
-pub use rewriter::rewrite;
+pub use rewriter::{apply_default_match_operator, rewrite};
// Planner
pub use planner::{plan_query, ExecutionPlan};
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index 4b29c39a6..393a12064 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -523,7 +523,9 @@ fn parse_match(params: &Value) -> Result<QueryNode> {
return Ok(QueryNode::Match {
field,
query,
- operator: BoolOperator::Or,
+ // No `operator` key exists in the shorthand. Log indices resolve
+ // this to AND (#1504); every other index treats it as OR.
+ operator: BoolOperator::Omitted,
analyzer: None,
boost: None,
minimum_should_match: None,
@@ -544,7 +546,12 @@ fn parse_match(params: &Value) -> Result<QueryNode> {
.get("query")
.and_then(scalar_to_string)
.ok_or_else(|| qerr("`match.query` must be a non-empty scalar"))?;
- let operator = parse_bool_operator(vobj.get("operator"))?;
+ // Absent key → Omitted, not OR. An explicit "or" stays OR, including on
+ // a log index whose default is AND (#1504).
+ let operator = match vobj.get("operator") {
+ None => BoolOperator::Omitted,
+ some => parse_bool_operator(some)?,
+ };
let analyzer = vobj
.get("analyzer")
.and_then(|v| v.as_str())
@@ -5239,7 +5246,7 @@ mod tests {
fn test_match_shorthand() {
let node = q(json!({"match": {"title": "hello world"}}));
assert!(
- matches!(node, QueryNode::Match { ref field, ref query, operator: BoolOperator::Or, .. }
+ matches!(node, QueryNode::Match { ref field, ref query, operator: BoolOperator::Omitted, .. }
if field == "title" && query == "hello world")
);
}
@@ -5272,6 +5279,25 @@ mod tests {
}
}
+ /// #1504: a long-form `match` that leaves `operator` out is not the same
+ /// node as one that says `"operator": "or"`. The log-index default can
+ /// fill the gap; it must not override an explicit OR.
+ #[test]
+ fn match_without_an_operator_is_omitted_and_explicit_or_is_or() {
+ let omitted = q(json!({"match": {"message": {"query": "SIP 403 Forbidden"}}}));
+ match omitted {
+ QueryNode::Match { operator, .. } => assert_eq!(operator, BoolOperator::Omitted),
+ other => panic!("expected match, got {other:?}"),
+ }
+ let explicit = q(json!({
+ "match": {"message": {"query": "SIP 403 Forbidden", "operator": "or"}}
+ }));
+ match explicit {
+ QueryNode::Match { operator, .. } => assert_eq!(operator, BoolOperator::Or),
+ other => panic!("expected match, got {other:?}"),
+ }
+ }
+
// ── track_total_hits ──────────────────────────────────────────────────────
#[test]
diff --git a/engine/crates/xerj-query/src/rewriter.rs b/engine/crates/xerj-query/src/rewriter.rs
index 2169b0561..924524dcc 100644
--- a/engine/crates/xerj-query/src/rewriter.rs
+++ b/engine/crates/xerj-query/src/rewriter.rs
@@ -22,7 +22,138 @@
use tracing::trace;
-use crate::ast::QueryNode;
+use crate::ast::{BoolOperator, MultiMatchType, QueryNode, SearchRequest};
+
+/// Fill in `match` / `multi_match` operators the request left out (#1504).
+///
+/// A log dataset's index sets `index.query.default_match_operator` to `and`.
+/// The engine calls this with [`BoolOperator::And`] before hashing the query
+/// cache key, so an omitted operator requires every token and an explicit
+/// `"operator": "or"` does not change. Indices without the setting never call
+/// this: [`BoolOperator::Omitted`] is executed as OR, which is the ES default.
+///
+/// `minimum_should_match` without an operator is the OR form of that count
+/// (ES), so those clauses are left omitted. Phrase `multi_match` ignores
+/// `operator`; leaving it absent keeps that arm on the positional path.
+/// `query_string` is lowered at parse time with its own `default_operator`
+/// already applied, so this does not reach it.
+pub fn apply_default_match_operator(request: &mut SearchRequest, operator: BoolOperator) {
+ walk_match_operator(&mut request.query, operator);
+ for window in &mut request.rescore {
+ if let Some(inner) = window.query.as_mut() {
+ walk_match_operator(&mut inner.rescore_query, operator);
+ }
+ }
+}
+
+fn walk_match_operator(q: &mut QueryNode, operator: BoolOperator) {
+ match q {
+ QueryNode::Match {
+ operator: op,
+ minimum_should_match,
+ ..
+ } => {
+ if *op == BoolOperator::Omitted && minimum_should_match.is_none() {
+ *op = operator;
+ }
+ }
+ QueryNode::MultiMatch {
+ operator: op,
+ match_type,
+ ..
+ } => {
+ if op.is_none()
+ && !matches!(
+ match_type,
+ MultiMatchType::Phrase | MultiMatchType::PhrasePrefix
+ )
+ {
+ *op = Some(operator);
+ }
+ }
+ QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ filter,
+ ..
+ } => {
+ for child in must
+ .iter_mut()
+ .chain(should.iter_mut())
+ .chain(must_not.iter_mut())
+ .chain(filter.iter_mut())
+ {
+ walk_match_operator(child, operator);
+ }
+ }
+ QueryNode::Constant { query, .. }
+ | QueryNode::Boosted { query, .. }
+ | QueryNode::Named { query, .. }
+ | QueryNode::FunctionScore { query, .. }
+ | QueryNode::Nested { query, .. } => walk_match_operator(query, operator),
+ QueryNode::Boosting {
+ positive, negative, ..
+ } => {
+ walk_match_operator(positive, operator);
+ walk_match_operator(negative, operator);
+ }
+ QueryNode::DisMax { queries, .. } => {
+ for child in queries {
+ walk_match_operator(child, operator);
+ }
+ }
+ QueryNode::Pinned { organic, .. } => walk_match_operator(organic, operator),
+ QueryNode::Knn { filter, .. } | QueryNode::SemanticSearch { filter, .. } => {
+ if let Some(filter) = filter {
+ walk_match_operator(filter, operator);
+ }
+ }
+ QueryNode::Hybrid { queries, .. } => {
+ for weighted in queries {
+ walk_match_operator(&mut weighted.query, operator);
+ }
+ }
+ QueryNode::SpanNear { clauses, .. } | QueryNode::SpanOr { clauses } => {
+ for child in clauses {
+ walk_match_operator(child, operator);
+ }
+ }
+ QueryNode::SpanNot { include, exclude } => {
+ walk_match_operator(include, operator);
+ walk_match_operator(exclude, operator);
+ }
+ QueryNode::SpanFirst { match_query, .. } => walk_match_operator(match_query, operator),
+ QueryNode::SpanContaining { little, big } | QueryNode::SpanWithin { little, big } => {
+ walk_match_operator(little, operator);
+ walk_match_operator(big, operator);
+ }
+ QueryNode::MatchAll
+ | QueryNode::MatchNone
+ | QueryNode::Term { .. }
+ | QueryNode::Terms { .. }
+ | QueryNode::Range { .. }
+ | QueryNode::Prefix { .. }
+ | QueryNode::Wildcard { .. }
+ | QueryNode::Exists { .. }
+ | QueryNode::Ids { .. }
+ | QueryNode::Script { .. }
+ | QueryNode::MatchPhrase { .. }
+ | QueryNode::QueryString { .. }
+ | QueryNode::Fuzzy { .. }
+ | QueryNode::Regexp { .. }
+ | QueryNode::Intervals { .. }
+ | QueryNode::MatchPhrasePrefix { .. }
+ | QueryNode::SimpleQueryString { .. }
+ | QueryNode::GeoDistance { .. }
+ | QueryNode::GeoBoundingBox { .. }
+ | QueryNode::GeoPolygon { .. }
+ | QueryNode::GeoShape { .. }
+ | QueryNode::SpanTerm { .. }
+ | QueryNode::MoreLikeThis { .. }
+ | QueryNode::Percolate { .. } => {}
+ }
+}
/// Maximum number of rewrite passes before we give up trying to converge.
const MAX_PASSES: usize = 16;
@@ -419,7 +550,7 @@ fn push_to_filter(
#[cfg(test)]
mod tests {
use super::*;
- use crate::ast::QueryNode;
+ use crate::ast::{MinShouldMatch, QueryNode, SearchRequest};
fn term(field: &str, value: &str) -> QueryNode {
QueryNode::Term {
@@ -602,4 +733,106 @@ mod tests {
let q = bool_must(vec![bool_must(vec![bool_must(vec![t.clone()])])]);
assert_eq!(rewrite(q), t);
}
+
+ fn match_op(operator: BoolOperator, msm: Option<MinShouldMatch>) -> QueryNode {
+ QueryNode::Match {
+ field: "message".into(),
+ query: "SIP 403 Forbidden".into(),
+ operator,
+ analyzer: None,
+ boost: None,
+ minimum_should_match: msm,
+ lenient: false,
+ }
+ }
+
+ /// #1504: a log index asks for AND. Omitted operators take it. An explicit
+ /// OR, a `minimum_should_match` clause, and a phrase `multi_match` do not.
+ #[test]
+ fn default_and_fills_only_omitted_match_operators() {
+ let mut req = SearchRequest {
+ query: QueryNode::Bool {
+ must: vec![match_op(BoolOperator::Omitted, None)],
+ should: vec![match_op(BoolOperator::Or, None)],
+ must_not: vec![],
+ filter: vec![match_op(
+ BoolOperator::Omitted,
+ Some(MinShouldMatch::Fixed(2)),
+ )],
+ minimum_should_match: None,
+ },
+ rescore: vec![crate::ast::RescoreQuery {
+ window_size: 10,
+ query: Some(crate::ast::RescoreQueryInner {
+ rescore_query: QueryNode::MultiMatch {
+ fields: vec!["message".into()],
+ query: "SIP 403".into(),
+ match_type: crate::ast::MultiMatchType::BestFields,
+ operator: None,
+ analyzer: None,
+ boost: None,
+ slop: 0,
+ max_expansions: 50,
+ lenient: false,
+ },
+ query_weight: 1.0,
+ rescore_query_weight: 1.0,
+ }),
+ script: None,
+ }],
+ ..SearchRequest::default()
+ };
+ apply_default_match_operator(&mut req, BoolOperator::And);
+
+ let QueryNode::Bool {
+ must,
+ should,
+ filter,
+ ..
+ } = req.query
+ else {
+ panic!("expected bool");
+ };
+ assert!(
+ matches!(
+ must[0],
+ QueryNode::Match {
+ operator: BoolOperator::And,
+ ..
+ }
+ ),
+ "omitted match becomes AND"
+ );
+ assert!(
+ matches!(
+ should[0],
+ QueryNode::Match {
+ operator: BoolOperator::Or,
+ ..
+ }
+ ),
+ "explicit OR stays OR"
+ );
+ assert!(
+ matches!(
+ filter[0],
+ QueryNode::Match {
+ operator: BoolOperator::Omitted,
+ ..
+ }
+ ),
+ "minimum_should_match keeps the omitted OR form"
+ );
+ let rescore = req.rescore[0].query.as_ref().unwrap();
+ assert!(
+ matches!(
+ rescore.rescore_query,
+ QueryNode::MultiMatch {
+ operator: Some(BoolOperator::And),
+ ..
+ }
+ ),
+ "an omitted multi_match operator, including inside rescore, becomes AND"
+ );
+ }
}