1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! Field mapping system for OpenSearch.
//!
//! This module handles field type detection and intelligent query building
//! based on OpenSearch mappings.
use super::error::Result;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
/// Field types in OpenSearch
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldType {
/// Keyword field (exact match)
Keyword,
/// Text field (full-text search)
Text,
/// Long integer
Long,
/// Double precision floating point
Double,
/// Boolean
Boolean,
/// Date/datetime
Date,
/// IP address
Ip,
/// Object (nested JSON)
Object,
/// Nested (array of objects)
Nested,
}
/// Field mapping information
#[derive(Debug, Clone)]
pub struct FieldMapping {
/// The field type
pub field_type: FieldType,
/// Subfields (e.g., .keyword for text fields)
pub subfields: HashMap<String, FieldType>,
}
/// Collection of field mappings for an index
#[derive(Debug, Clone)]
pub struct FieldMappings {
mappings: HashMap<String, FieldMapping>,
}
impl FieldMappings {
/// Create an empty field mappings collection
pub fn new() -> Self {
Self {
mappings: HashMap::new(),
}
}
/// Create from OpenSearch index mappings response
///
/// # Arguments
///
/// * `response` - The JSON response from OpenSearch mappings API
///
/// # Example
///
/// ```ignore
/// let response = client.indices().get_mapping().send().await?;
/// let mappings = FieldMappings::from_opensearch_response(response)?;
/// ```
pub fn from_opensearch_response(response: JsonValue) -> Result<Self> {
let mut mappings = HashMap::new();
// Parse OpenSearch mappings response
// Expected format:
// {
// "index_name": {
// "mappings": {
// "properties": {
// "field_name": {
// "type": "text",
// "fields": {
// "keyword": { "type": "keyword" }
// }
// }
// }
// }
// }
// }
// Handle different response formats
let properties = if let Some(index_obj) = response.as_object() {
// Get the first index (usually there's only one)
if let Some((_index_name, index_data)) = index_obj.iter().next() {
if let Some(mappings_obj) = index_data.get("mappings") {
mappings_obj.get("properties")
} else {
None
}
} else {
None
}
} else {
None
};
if let Some(properties) = properties {
if let Some(props_obj) = properties.as_object() {
for (field_name, field_def) in props_obj {
if let Some(mapping) = Self::parse_field_definition(field_def) {
mappings.insert(field_name.clone(), mapping);
}
}
}
}
Ok(Self { mappings })
}
/// Create from pre-extracted properties (e.g., from index template's mappings.properties)
///
/// This is useful when field mappings have already been extracted from an index template
/// and don't need the full OpenSearch response wrapper.
///
/// # Arguments
///
/// * `properties` - A HashMap of field names to their type definitions
///
/// # Example
///
/// ```ignore
/// let properties = template.get_tql_field_mappings(Some(&["event.code", "message"]));
/// let mappings = FieldMappings::from_properties(properties);
/// ```
pub fn from_properties(properties: HashMap<String, JsonValue>) -> Self {
let mut mappings = HashMap::new();
for (field_name, field_def) in properties {
if let Some(mapping) = Self::parse_field_definition(&field_def) {
mappings.insert(field_name, mapping);
}
}
Self { mappings }
}
fn parse_field_definition(field_def: &JsonValue) -> Option<FieldMapping> {
let field_type_str = field_def.get("type")?.as_str()?;
let field_type = Self::parse_field_type(field_type_str)?;
let mut subfields = HashMap::new();
// Parse subfields if they exist
if let Some(fields) = field_def.get("fields") {
if let Some(fields_obj) = fields.as_object() {
for (subfield_name, subfield_def) in fields_obj {
if let Some(subfield_type_str) =
subfield_def.get("type").and_then(|v| v.as_str())
{
if let Some(subfield_type) = Self::parse_field_type(subfield_type_str) {
subfields.insert(subfield_name.clone(), subfield_type);
}
}
}
}
}
Some(FieldMapping {
field_type,
subfields,
})
}
fn parse_field_type(type_str: &str) -> Option<FieldType> {
match type_str {
"keyword" => Some(FieldType::Keyword),
"text" => Some(FieldType::Text),
"long" | "integer" | "short" | "byte" => Some(FieldType::Long),
"double" | "float" | "half_float" | "scaled_float" => Some(FieldType::Double),
"boolean" => Some(FieldType::Boolean),
"date" => Some(FieldType::Date),
"ip" => Some(FieldType::Ip),
"object" => Some(FieldType::Object),
"nested" => Some(FieldType::Nested),
_ => None, // Unknown type
}
}
/// Get the appropriate field name for a query operation
///
/// For example, for "message contains", this might return "message.keyword"
/// or just "message" depending on the field mapping and operator.
///
/// # Arguments
///
/// * `field` - The field name
/// * `operator` - The TQL operator being used
pub fn get_query_field(&self, field: &str, operator: &str) -> String {
// If we have a mapping for this field
if let Some(mapping) = self.mappings.get(field) {
// For exact-match operators on text fields, use .keyword subfield if available.
// Operators like contains, startswith, endswith, and matches use wildcard/regexp
// queries that work on the base text field — they should NOT redirect to .keyword.
if matches!(operator, "eq" | "ne" | "in")
&& mapping.field_type == FieldType::Text
&& mapping.subfields.contains_key("keyword")
{
return format!("{}.keyword", field);
}
}
// Default: use the field as-is
field.to_string()
}
/// Determine if a field should use term query vs match query
///
/// # Arguments
///
/// * `field` - The field name
///
/// # Returns
///
/// `true` if term query should be used (exact match), `false` for match query
pub fn should_use_term_query(&self, field: &str) -> bool {
if let Some(mapping) = self.mappings.get(field) {
matches!(
mapping.field_type,
FieldType::Keyword
| FieldType::Long
| FieldType::Double
| FieldType::Boolean
| FieldType::Date
| FieldType::Ip
)
} else {
// Default to term query if we don't know the type
true
}
}
/// Get the field type for a given field
pub fn get_field_type(&self, field: &str) -> Option<&FieldType> {
self.mappings.get(field).map(|m| &m.field_type)
}
/// Add a field mapping
pub fn add_mapping(&mut self, field: String, mapping: FieldMapping) {
self.mappings.insert(field, mapping);
}
/// Get the number of field mappings
pub fn len(&self) -> usize {
self.mappings.len()
}
/// Check if there are no field mappings
pub fn is_empty(&self) -> bool {
self.mappings.is_empty()
}
}
impl Default for FieldMappings {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_mappings() {
let mappings = FieldMappings::new();
assert_eq!(mappings.get_query_field("test", "eq"), "test");
assert!(mappings.should_use_term_query("test"));
}
#[test]
fn test_text_field_with_keyword() {
let mut mappings = FieldMappings::new();
let mut subfields = HashMap::new();
subfields.insert("keyword".to_string(), FieldType::Keyword);
mappings.add_mapping(
"message".to_string(),
FieldMapping {
field_type: FieldType::Text,
subfields,
},
);
// For eq operator, should use .keyword subfield
assert_eq!(mappings.get_query_field("message", "eq"), "message.keyword");
// For contains operator, should use base field
assert_eq!(mappings.get_query_field("message", "contains"), "message");
}
#[test]
fn test_keyword_field() {
let mut mappings = FieldMappings::new();
mappings.add_mapping(
"status".to_string(),
FieldMapping {
field_type: FieldType::Keyword,
subfields: HashMap::new(),
},
);
assert_eq!(mappings.get_query_field("status", "eq"), "status");
assert!(mappings.should_use_term_query("status"));
}
}