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(engine): dynamic string fields get the ES-default .keyword multi-field (#209)

xerj-orgdbac2548f5b1
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 36f2c6327..b488edcaa 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -14564,6 +14564,9 @@ pub fn schema_to_es_properties(schema: &Schema) -> serde_json::Map<String, Value
let es_type = native_type_to_es(&field.field_type);
let mut field_obj = serde_json::Map::new();
field_obj.insert("type".to_string(), Value::String(es_type.to_string()));
+ if let Some(n) = field.options.ignore_above {
+ field_obj.insert("ignore_above".to_string(), Value::Number(n.into()));
+ }
if !field.fields.is_empty() {
let sub_schema = Schema {
fields: field.fields.clone(),
@@ -14571,7 +14574,17 @@ pub fn schema_to_es_properties(schema: &Schema) -> serde_json::Map<String, Value
updated_at: Utc::now(),
};
let sub_props = schema_to_es_properties(&sub_schema);
- field_obj.insert("properties".to_string(), Value::Object(sub_props));
+ // Children of an object-like parent are real sub-properties;
+ // children of a LEAF parent are multi-fields (e.g. the
+ // auto-created `keyword` sub-field on a dynamically mapped
+ // string, #209) and ES renders those under `fields`, not
+ // `properties` — `_field_caps` also discovers `<f>.keyword`
+ // from exactly this `fields` shape (`collect_multi_fields`).
+ let key = match field.field_type {
+ FieldType::Object | FieldType::Nested => "properties",
+ _ => "fields",
+ };
+ field_obj.insert(key.to_string(), Value::Object(sub_props));
}
props.insert(field.name.clone(), Value::Object(field_obj));
}
@@ -18567,6 +18580,91 @@ mod flat_object_field_caps_tests {
);
}
+ /// #209: dynamic mapping inferred every string as bare `text` — no
+ /// `keyword` multi-field — so `GET _mapping` never advertised
+ /// `<field>.keyword` and `_field_caps` (what Kibana uses for field
+ /// discovery) never listed it, even though the query path resolves it.
+ /// ES default dynamic mapping emits
+ /// `{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}`;
+ /// mirror that shape for dynamically discovered strings.
+ #[tokio::test]
+ async fn dynamic_string_mapping_advertises_keyword_multi_field() {
+ let router = crate::router::build_es_compat_router(test_state());
+
+ // Auto-create the index by writing a doc — pure dynamic mapping.
+ let write = router
+ .clone()
+ .oneshot(
+ Request::put("/dyn-kw-e2e/_doc/1")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"category": "books", "city": "New York", "price": 9.99}).to_string(),
+ ))
+ .expect("request"),
+ )
+ .await
+ .expect("write response");
+ assert!(write.status().is_success());
+
+ // GET _mapping must render the ES default multi-field shape.
+ let mapping_resp = router
+ .clone()
+ .oneshot(
+ Request::get("/dyn-kw-e2e/_mapping")
+ .body(Body::empty())
+ .expect("request"),
+ )
+ .await
+ .expect("mapping response");
+ assert!(mapping_resp.status().is_success());
+ let bytes = to_bytes(mapping_resp.into_body(), usize::MAX)
+ .await
+ .expect("response bytes");
+ let mapping: Value = serde_json::from_slice(&bytes).expect("JSON response");
+ let props = &mapping["dyn-kw-e2e"]["mappings"]["properties"];
+ for f in ["category", "city"] {
+ assert_eq!(props[f]["type"], "text", "{f} type, got: {mapping}");
+ assert_eq!(
+ props[f]["fields"]["keyword"]["type"], "keyword",
+ "{f} must carry a keyword multi-field, got: {mapping}"
+ );
+ assert_eq!(
+ props[f]["fields"]["keyword"]["ignore_above"], 256,
+ "{f}.keyword must advertise ignore_above 256, got: {mapping}"
+ );
+ }
+ // Numbers stay plain — no multi-field.
+ assert_eq!(props["price"]["type"], "double", "got: {mapping}");
+ assert!(
+ props["price"].get("fields").is_none(),
+ "price must not grow a multi-field: {mapping}"
+ );
+
+ // _field_caps must list `<field>.keyword` as an aggregatable keyword
+ // (this is how Kibana/index-pattern discovery finds it).
+ let caps_resp = router
+ .oneshot(
+ Request::get("/dyn-kw-e2e/_field_caps?fields=*")
+ .body(Body::empty())
+ .expect("request"),
+ )
+ .await
+ .expect("field_caps response");
+ assert!(caps_resp.status().is_success());
+ let bytes = to_bytes(caps_resp.into_body(), usize::MAX)
+ .await
+ .expect("response bytes");
+ let caps: Value = serde_json::from_slice(&bytes).expect("JSON response");
+ assert_eq!(
+ caps["fields"]["category.keyword"]["keyword"]["aggregatable"], true,
+ "category.keyword must be an aggregatable keyword in _field_caps, got: {caps}"
+ );
+ assert_eq!(
+ caps["fields"]["city.keyword"]["keyword"]["type"], "keyword",
+ "city.keyword must appear in _field_caps, got: {caps}"
+ );
+ }
+
/// Regression test for a real bug found live: `GET _mapping` correctly
/// round-trips `float`/`integer` (it returns the stored mapping JSON
/// verbatim), but `_field_caps` derived its reported type from the
diff --git a/engine/crates/xerj-common/src/types.rs b/engine/crates/xerj-common/src/types.rs
index 5b1afc9f4..5c9b6ff1d 100644
--- a/engine/crates/xerj-common/src/types.rs
+++ b/engine/crates/xerj-common/src/types.rs
@@ -301,6 +301,12 @@ pub struct FieldOptions {
/// Null value to substitute when the field is missing from a document.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub null_value: Option<serde_json::Value>,
+ /// Maximum string length advertised for keyword indexing (ES
+ /// `ignore_above`). Recorded on the auto-created `keyword` sub-field of
+ /// dynamically mapped string fields so the ES-compat mapping renders the
+ /// exact default shape ES emits (`ignore_above: 256`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ignore_above: Option<u32>,
/// Allow the field to appear more than once in a document (always `true` for arrays).
#[serde(default = "bool_true")]
pub multi_value: bool,
@@ -329,6 +335,7 @@ impl Default for FieldOptions {
similarity: None,
quantization: None,
null_value: None,
+ ignore_above: None,
multi_value: true,
boost: 1.0,
}
@@ -370,7 +377,12 @@ pub struct FieldConfig {
/// Optional embedding pipeline configuration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub embedding: Option<EmbeddingConfig>,
- /// Sub-fields (for `Object` and `Nested` fields).
+ /// Sub-fields. Two distinct meanings, keyed off this field's own type:
+ /// on `Object`/`Nested` these are real child *properties*; on a leaf type
+ /// they are ES *multi-fields* — the same value indexed a second way, e.g.
+ /// the `keyword` sub-field auto-created on dynamically mapped strings
+ /// (#209). The ES-compat mapping renderer picks `properties` vs `fields`
+ /// on exactly that distinction.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<FieldConfig>,
}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c5c5b1a9f..5dc7c6e0e 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -17352,8 +17352,8 @@ impl Index {
continue;
}
if !schema.schema.has_field(key) && !out.iter().any(|(k, _)| k == key) {
- let ft = infer_field_type(val, date_detection);
- out.push((key.clone(), FieldConfig::new(key.clone(), ft)));
+ let fc = dynamic_field_config(key, val, date_detection);
+ out.push((key.clone(), fc));
}
}
}
@@ -17435,10 +17435,7 @@ impl Index {
.filter(|(key, _)| {
!key.starts_with(PASSAGE_METADATA_PREFIX) && !schema.schema.has_field(key)
})
- .map(|(key, val)| {
- let ft = infer_field_type(val, date_detection);
- (key.clone(), FieldConfig::new(key.clone(), ft))
- })
+ .map(|(key, val)| (key.clone(), dynamic_field_config(key, val, date_detection)))
.collect()
};
@@ -27207,6 +27204,35 @@ fn infer_field_type(val: &Value, date_detection: bool) -> FieldType {
}
}
+/// ES `ignore_above` default on the auto-created `keyword` sub-field of a
+/// dynamically mapped string (ES `DynamicFieldsBuilder`: `TextFieldMapper` +
+/// `KeywordFieldMapper("keyword").ignoreAbove(256)`).
+const DYNAMIC_KEYWORD_IGNORE_ABOVE: u32 = 256;
+
+/// Build the [`FieldConfig`] for a dynamically discovered field.
+///
+/// Wraps [`infer_field_type`] and mirrors the ES default dynamic mapping for
+/// strings: any field inferred as `Text` gets a `keyword` multi-field
+/// sub-field (`ignore_above: 256`), so the standard ES habit of exact-match
+/// filtering / aggregating on `<field>.keyword` is discoverable from the
+/// mapping (`GET _mapping`, `_field_caps`) exactly like on ES (#209).
+///
+/// The query path already resolves `<field>.keyword` to the parent's
+/// doc-values column (see `fast_aggs::dv_col`, `aggs::get_nested_field`);
+/// this records that contract in the schema rather than leaving it implicit.
+/// Sub-fields of a leaf parent are NOT top-level `schema.fields` entries, so
+/// the search path's text/keyword field sets are unaffected.
+fn dynamic_field_config(key: &str, val: &Value, date_detection: bool) -> FieldConfig {
+ let ft = infer_field_type(val, date_detection);
+ let mut fc = FieldConfig::new(key.to_string(), ft);
+ if matches!(fc.field_type, FieldType::Text) {
+ let mut kw = FieldConfig::new("keyword".to_string(), FieldType::Keyword);
+ kw.options.ignore_above = Some(DYNAMIC_KEYWORD_IGNORE_ABOVE);
+ fc.fields.push(kw);
+ }
+ fc
+}
+
// ── DocValues fast-path helpers ───────────────────────────────────────────────
/// Try to resolve a Term or Range query directly from the memtable's DocValues
@@ -34988,6 +35014,55 @@ mod date_detection_tests {
assert!(matches!(infer_field_type(&num, true), FieldType::Long));
}
+ /// #209: dynamically discovered string fields must carry the ES-default
+ /// `keyword` multi-field (`ignore_above: 256`) so `<field>.keyword` is
+ /// discoverable from the mapping, exactly like ES default dynamic
+ /// mapping (`DynamicFieldsBuilder`: text + keyword(ignore_above=256)).
+ #[test]
+ fn dynamic_string_gets_keyword_multi_field() {
+ let fc = dynamic_field_config("category", &serde_json::json!("books"), true);
+ assert!(matches!(fc.field_type, FieldType::Text));
+ assert_eq!(fc.fields.len(), 1, "expected exactly one sub-field");
+ let kw = &fc.fields[0];
+ assert_eq!(kw.name, "keyword");
+ assert!(matches!(kw.field_type, FieldType::Keyword));
+ assert_eq!(kw.options.ignore_above, Some(256));
+
+ // Whitespace strings are still Text (+ keyword sub-field): the
+ // multi-field replaces the never-wired short-string→Keyword split.
+ let fc = dynamic_field_config("city", &serde_json::json!("New York"), true);
+ assert!(matches!(fc.field_type, FieldType::Text));
+ assert_eq!(fc.fields.len(), 1);
+
+ // Arrays of strings behave like strings (ES maps them identically).
+ let fc = dynamic_field_config("tags", &serde_json::json!(["a", "b"]), true);
+ assert!(matches!(fc.field_type, FieldType::Text));
+ assert_eq!(fc.fields.len(), 1);
+
+ // Null pins Text in xerj (pre-existing behavior) — keep the
+ // invariant "every dynamic Text field has a .keyword sub-field".
+ let fc = dynamic_field_config("maybe", &Value::Null, true);
+ assert!(matches!(fc.field_type, FieldType::Text));
+ assert_eq!(fc.fields.len(), 1);
+
+ // Non-string inferences carry NO multi-field.
+ for (val, want_sub) in [
+ (serde_json::json!(42), 0usize),
+ (serde_json::json!(2.5), 0),
+ (serde_json::json!(true), 0),
+ (serde_json::json!("2026-07-25T10:30:00Z"), 0), // date-detected
+ (serde_json::json!({"a": 1}), 0),
+ ] {
+ let fc = dynamic_field_config("f", &val, true);
+ assert_eq!(fc.fields.len(), want_sub, "value {val} sub-field count");
+ }
+
+ // date_detection=false: the ISO string is Text again → gets keyword.
+ let fc = dynamic_field_config("ts", &serde_json::json!("2026-07-25T10:30:00Z"), false);
+ assert!(matches!(fc.field_type, FieldType::Text));
+ assert_eq!(fc.fields.len(), 1);
+ }
+
/// Ingest-time acceptance for default-format date fields: lenient on
/// everything ES could parse, rejecting only impossible shapes.
#[test]