Skip to content

Commit 4d3de2e

Browse files
Handle nested flattened fields
1 parent 39116a1 commit 4d3de2e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

detection_rules/index_mappings.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,14 @@ def prepare_integration_mappings( # noqa: PLR0913
147147
f"Removing parent field from schema for ES|QL validation."
148148
)
149149
utils.delete_nested_key_from_dict(stream_mappings, field_name)
150+
nested_flattened_fields = find_flattened_fields_with_subfields(stream_mappings)
151+
for field in nested_flattened_fields:
152+
field_name = str(field).split(".fields.")[0].replace(".", ".properties.") + ".fields"
153+
log(
154+
f"Warning: flattened field `{field}` found in `{integration}-{stream}` with sub fields. "
155+
f"Removing parent field from schema for ES|QL validation."
156+
)
157+
utils.delete_nested_key_from_dict(stream_mappings, field_name)
150158
utils.combine_dicts(integration_mappings, stream_mappings)
151159
index_lookup[f"{integration}-{stream}"] = stream_mappings
152160

@@ -229,6 +237,27 @@ def find_nested_multifields(mapping: dict[str, Any], path: str = "") -> list[Any
229237
return nested_multifields # type: ignore[reportUnknownVariableType]
230238

231239

240+
def find_flattened_fields_with_subfields(mapping: dict[str, Any], path: str = "") -> list[str]:
241+
"""Recursively search for fields of type 'flattened' that have a 'fields' key in Elasticsearch mappings."""
242+
flattened_fields_with_subfields = []
243+
244+
for field, properties in mapping.items():
245+
current_path = f"{path}.{field}" if path else field
246+
247+
if isinstance(properties, dict):
248+
# Check if the field is of type 'flattened' and has a 'fields' key
249+
if properties.get("type") == "flattened" and "fields" in properties: # type: ignore[reportUnknownVariableType]
250+
flattened_fields_with_subfields.append(current_path) # type: ignore[reportUnknownVariableType]
251+
252+
# Recurse into subfields
253+
if "properties" in properties:
254+
flattened_fields_with_subfields.extend( # type: ignore[reportUnknownVariableType]
255+
find_flattened_fields_with_subfields(properties["properties"], current_path) # type: ignore[reportUnknownVariableType]
256+
)
257+
258+
return flattened_fields_with_subfields # type: ignore[reportUnknownVariableType]
259+
260+
232261
def get_ecs_schema_mappings(current_version: Version) -> dict[str, Any]:
233262
"""Get the ECS schema in an index mapping format (nested schema) handling scaled floats."""
234263
ecs_version = get_stack_schemas()[str(current_version)]["ecs"]

0 commit comments

Comments
 (0)