Elastic Workflows (Kibana 9.3.4): Extracting top_records / top_influencers from ML Anomaly Alert Payload to Query APM Data Streams & Send Teams Adaptive Card

Hi everyone,

I am building an Elastic Workflow in Kibana 9.3.4 triggered by an ML Anomaly Detection Alert (xpack.ml.anomaly_detection_alert) to enrich the alert with human-readable APM error context (error.grouping_name, message, transaction.name, etc.) and post an Adaptive Card to Microsoft Teams.

Context & Why We Are Doing This

  • I have multiple APM error data streams segregated by environment and custom namespaces (logs-apm.error-*).
  • Because APM agents post generic error.type: "Error" and include dynamic values in error.grouping_name (causing high cardinality), we configured our ML anomaly detection job on error.grouping_key partitioned by service.name and service.environment .
  • Since error.grouping_key is a hash, we want the workflow to take the triggered service.name and error.grouping_key from the alert payload, query logs-apm.error-* data-streams to fetch the latest matching error document, and include the actual error name and message in the Teams notification.

Current Issues I'm Hitting in the Workflow YAML

  1. Variable Extraction & Validation: Accessing nested array elements with dotted keys in event.alerts (specifically event.alerts[0]['kibana.alert.top_records'][0].partition_field_value and event.alerts[0]['kibana.alert.top_influencers'][0].influencer_field_value) either triggers variable-validation errors (when using Liquid assign or .first) or evaluates to empty strings ("") at runtime.
  2. Sorting in elasticsearch.search: Passing sort as a list or "@timestamp:desc" fails either the strict workflow schema validator or throws a query_shard_exception (No mapping found for [@timestamp:desc] in order to sort on) across backing indices.

Document of Anomaly Record type alert example:

{
  "alerts": [
    {
      "_index": ".internal.alerts-ml.anomaly-detection.alerts-default-000005",
      "kibana.alert.status": "active",
      "kibana.alert.job_id": "logs-apm-grouping_key-errors",
      "kibana.alert.url": "/app/ml/explorer/?_g=(ml%3A(jobIds%3A!(logs-apm-grouping_key-errors))%2Ctime%3A(from%3A'2026-11-25T10%3A30%3A00.000Z'%2Cmode%3Aabsolute%2Cto%3A'2026-11-25T12%3A10%3A00.000Z'))&_a=(explorer%3A(mlExplorerFilter%3A()%2CmlExplorerSwimlane%3A()))",
      "kibana.alert.anomaly_score": [
        83.22616296216471,
        83.22616296216471
      ],
      "kibana.alert.rule.tags": [
        "anomaly",
        "ml"
      ],
      "kibana.alert.rule.producer": "ml",
      "kibana.alert.rule.rule_type_id": "xpack.ml.anomaly_detection_alert",
      "kibana.alert.top_records": [
        {
          "actual": [
            0
          ],
          "partition_field_name": "service.name",
          "partition_field_value": "mobily",
          "initial_record_score": 83.22616296216471,
          "job_id": "logs-apm-grouping_key-errors",
          "function": "high_count",
          "typical": [
            0.23359694021425237
          ],
          "record_score": 83.22616296216471,
          "is_interim": true,
          "detector_index": 0,
          "timestamp": 1795605600000
        },
        {
          "actual": [
            0
          ],
          "partition_field_name": "service.name",
          "partition_field_value": "mobily",
          "initial_record_score": 80.88416477376916,
          "job_id": "logs-apm-grouping_key-errors",
          "function": "high_count",
          "typical": [
            0.2805849055056184
          ],
          "record_score": 80.88416477376916,
          "is_interim": true,
          "detector_index": 0,
          "timestamp": 1795605600000
        },
        {
          "actual": [
            0
          ],
          "partition_field_name": "service.name",
          "partition_field_value": "mobily",
          "initial_record_score": 30.68797146720346,
          "job_id": "logs-apm-grouping_key-errors",
          "function": "high_count",
          "typical": [
            0.38743922790463015
          ],
          "record_score": 30.68797146720346,
          "is_interim": true,
          "detector_index": 0,
          "timestamp": 1795605600000
        }
      ],
      "kibana.alert.instance.id": "logs-apm-grouping_key-errors",
      "kibana.alert.muted": false,
      "kibana.alert.rule.name": "Anomaly detection rule - APM Error - Grouping Key - Record - 25",
      "kibana.alert.flapping": true,
      "event.kind": "signal",
      "kibana.alert.maintenance_window_names": [],
      "kibana.alert.top_influencers": [
        {
          "initial_influencer_score": 83.22616296216474,
          "job_id": "logs-apm-grouping_key-errors",
          "influencer_field_name": "error.grouping_key",
          "influencer_field_value": "08ef50b5",
          "is_interim": true,
          "influencer_score": 83.22616296216474,
          "timestamp": 1795605600000
        },
        {
          "initial_influencer_score": 80.88416477376916,
          "job_id": "logs-apm-grouping_key-errors",
          "influencer_field_name": "error.grouping_key",
          "influencer_field_value": "bb10",
          "is_interim": true,
          "influencer_score": 80.88416477376916,
          "timestamp": 1795605600000
        },
        {
          "initial_influencer_score": 27.972741366035926,
          "job_id": "logs-apm-grouping_key-errors",
          "influencer_field_name": "error.grouping_key",
          "influencer_field_value": "363797",
          "is_interim": true,
          "influencer_score": 27.972741366035926,
          "timestamp": 1795605600000
        }
      ],
      "kibana.alert.workflow_status": "open",
      "kibana.alert.rule.uuid": "d361caf4-924d-4ef",
      "kibana.alert.previous_action_group": "anomaly_score_match",
      "kibana.alert.time_range": {
        "gte": "2026-11-25T10:54:28.885Z"
      },
      "kibana.alert.consecutive_matches": 30,
      "kibana.alert.pending_recovered_count": 0,
      "kibana.alert.reason": "Anomaly in high_count by \"error.grouping_key\" partition_field_name=\"service.name\" found for error.grouping_key- 08ef50b5 detected in service.name- mobily. Unexpected zero value.",
      "kibana.alert.flapping_history": [
        false,
        true,
        true,
        false,
        false,
        false,
        true,
        true,
        false,
        false,
        false,
        true,
        true,
        false,
        false,
        false,
        true,
        true,
        false,
        false
      ],
      "kibana.alert.rule.consumer": "stackAlerts",
      "kibana.alert.anomaly_timestamp": 1795605600000,
      "kibana.alert.action_group": "anomaly_score_match",
      "tags": [
        "anomaly",
        "ml"
      ],
      "kibana.alert.rule.category": "Anomaly detection",
      "kibana.alert.start": "2026-11-25T10:54:28.885Z",
      "event.action": "active",
      "@timestamp": "2026-11-25T11:23:31.151Z",
      "kibana.alert.duration.us": 1742266000,
      "kibana.alert.maintenance_window_ids": [],
      "kibana.alert.rule.execution.timestamp": "2026-11-25T11:23:31.151Z",
      "kibana.alert.rule.execution.uuid": "8bcfdf31-7c21-4164-821a-b44d98bd0384",
      "kibana.space_ids": [
        "default"
      ],
      "kibana.alert.uuid": "c1a90fdd-16c1-4035-be64-2587a09c5b04",
      "_id": "c1a90fdd-16c1-4035-be64-2587a09c5b04",
      "kibana.alert.is_interim": true,
      "kibana.version": "9.3.4",
      "kibana.alert.rule.parameters": {
        "severity": 25,
        "jobSelection": {
          "jobIds": [
            "logs-apm-grouping_key-errors"
          ],
          "groupIds": []
        },
        "lookbackInterval": "5m",
        "kqlQueryString": null,
        "includeInterim": true,
        "topNBuckets": null,
        "resultType": "record"
      },
      "kibana.alert.rule.revision": 5
    }
  ],
  "rule": {
    "id": "d361caf4-924d-4ef",
    "name": "Anomaly detection rule - APM Error - Grouping Key - Record - 25",
    "tags": [
      "anomaly",
      "ml"
    ],
    "consumer": "stackAlerts",
    "producer": "ml",
    "ruleTypeId": "xpack.ml.anomaly_detection_alert"
  },
  "spaceId": "default"
}

Here is the complete workflow that i have so far.

name: apm-error-anomaly-teams-alert
triggers:
  - type: alert

consts:
  indexName: "logs-apm.error-*"
  endpoints:
    api: "https://{RADACTED}"

steps:
  # Step 1: Extract & log alert variables
  - name: extract_alert_vars
    type: console
    with:
      message: |
        {
          "service_name": "{{event.alerts[0].kibana.alert.top_records[0].partition_field_value}}",
          "grouping_key": "{{ event.alerts[0].kibana.alert.top_influencers[0].influencer_field_value }}",
          "actual_count": "{{ event.alerts[0]['kibana.alert.top_records'][0].actual[0] }}",
          "typical_count": "{{ event.alerts[0]['kibana.alert.top_records'][0].typical[0] | round: 2 }}",
          "record_score": "{{ event.alerts[0]['kibana.alert.top_records'][0].record_score | round: 1 }}"
        }


  # Step 2: Query APM error indices
  - name: fetch_apm_error_details
    type: elasticsearch.search
    with:
      index: "{{ consts.indexName }}"
      ignore_unavailable: true
      size: 1
      _source: "service.name,service.environment,error.grouping_key,error.grouping_name,error.exception.type,error.exception.message,error.culprit,transaction.name,url.path,message,@timestamp"
      query:
        bool:
          filter:
            - term:
                error.grouping_key: "{{ event.alerts[0]['kibana.alert.top_influencers'][0].influencer_field_value }}"
            - term:
                service.name: "{{ event.alerts[0]['kibana.alert.top_records'][0].partition_field_value }}"
            - range:
                "@timestamp":
                  gte: "now-7d"
                  lte: "now"

  # Step 3: Send formatted Teams Adaptive Card
  - name: send_teams_adaptive_card
    type: http
    with:
      url: "{{ consts.endpoints.api }}"
      method: POST
      headers:
        Content-Type: "application/json"
      body: |
        {% assign alert = event.alerts[0] %}
        {% assign top_record = alert['kibana.alert.top_records'][0] %}
        {% assign top_influencer = alert['kibana.alert.top_influencers'][0] %}
        {% assign doc = steps.fetch_apm_error_details.output.hits.hits[0]._source %}
        {
          "type": "message",
          "attachments": [
            {
              "contentType": "application/vnd.microsoft.card.adaptive",
              "content": {
                "$schema": "http://adaptivecards.io",
                "type": "AdaptiveCard",
                "version": "1.4",
                "body": [
                  {
                    "type": "TextBlock",
                    "text": "🚨 APM Error Spike Detected — {{ top_record.partition_field_value | default: 'Unknown Service' }}",
                    "weight": "Bolder",
                    "size": "Medium",
                    "color": "Attention",
                    "wrap": true
                  },
                  {
                    "type": "FactSet",
                    "facts": [
                      {
                        "title": "Service",
                        "value": "{{ top_record.partition_field_value | default: 'N/A' }}"
                      },
                      {
                        "title": "Environment",
                        "value": "{{ doc['service.environment'] | default: consts.environment }}"
                      },
                      {
                        "title": "Error Name",
                        "value": "{{ doc['error.grouping_name'] | default: doc['error.exception.type'] | default: doc['error.culprit'] | default: 'Unknown Error' }}"
                      },
                      {
                        "title": "Endpoint / Tx",
                        "value": "{{ doc['transaction.name'] | default: doc['url.path'] | default: 'N/A' }}"
                      },
                      {
                        "title": "Grouping Key",
                        "value": "{{ top_influencer.influencer_field_value | default: 'N/A' }}"
                      },
                      {
                        "title": "Error Count",
                        "value": "{{ top_record.actual[0] | default: 'N/A' }} (Typical: {{ top_record.typical[0] | round: 2 | default: 'N/A' }})"
                      },
                      {
                        "title": "Severity Score",
                        "value": "{{ top_record.record_score | round: 1 | default: 'N/A' }}"
                      },
                      {
                        "title": "Occurrence Time",
                        "value": "{{ doc['@timestamp'] | default: 'N/A' }}"
                      }
                    ]
                  },
                  {
                    "type": "TextBlock",
                    "text": "**Error Message:**\n{{ doc['error.exception.message'] | default: doc['message'] | default: 'No error message captured' | escape }}",
                    "wrap": true
                  }
                ]
              }
            }
          ]
        }

Alert i am receiving:

🚨 APM Error Spike Detected — Unknown Service
Service
N/A
Environment
oci
Error Name
Unknown Error
Endpoint / Tx
N/A
Grouping Key
N/A
Error Count
N/A (Typical: 0)
Severity Score
0
Occurrence Time
N/A
Error Message:
No error message captured

it fails at the step 1 if i directly use the references then it also empty query being forward to fetch:

"{\n  \"service_name\": \"\",\n  \"grouping_key\": \"\",\n  \"actual_count\": \"\",\n  \"typical_count\": \"0\",\n  \"record_score\": \"0\"\n}\n"

Hey @kkumar123 :waving_hand:

Tal from the Workflows team here. In 9.3.x, workflows was "pre tech-preview" and many of the features and capabilities were still under building. Have you considered upgrading Kibana to newer versions? I haven't validated that 1-1 with the code but as far as I can remember, all of the issues you have are things that were solved/evolved on later versions.

Would be more then happy to help further if possible, but I strongly encourage you to upgrade as workflows has a lot of new exciting stuff on later versions.

If still needed - I can try to provide some workaround on the YAML you have now, do you mind sharing it with us?

which is stable version of elk for observability use cases ?

Then i will try to upgrade the elastic to latest version try that after that.,

thanks

9.5.7 at the moment, and 9.6 is releasing somewhere in the beginning of December.