Splunk Search

How to get distinct values and their counts from fields arrays

karol
Engager

I got a stream of events in a following format:

[
  {
    "name": "event 1"
    "attributes": ["a", "b"],
  },
  {
    "name": "event 2"
    "attributes": ["a", "c"],
  }
]

I am looking to aggregate them in a following way:

a | 2
b | 1
c | 1

 The list is sorted in a descending order with counts for each unique entry in the attributes array.

Labels (2)
0 Karma
1 Solution

ITWhisperer
SplunkTrust
SplunkTrust

Is this part of a json structure? Assuming it is, you could do something like this

| makeresults
| eval _raw="{
\"array\": [
  {
    \"name\": \"event 1\",
    \"attributes\": [\"a\", \"b\"]
  },
  {
    \"name\": \"event 2\",
    \"attributes\": [\"a\", \"c\"]
  }
]}"
``` The lines above simulate something like the data you shared ```
| spath array{} output=array
| mvexpand array
| spath input=array attributes{} output=attributes
| stats count by attributes
| sort 0 -count

View solution in original post

PrewinThomas
Motivator

@karol 

With JSON array, you can use below.

| makeresults
| eval raw="[{\"name\":\"event 1\", \"attributes\":[\"a\",\"b\"]}, {\"name\":\"event 2\", \"attributes\":[\"a\",\"c\"]}]"
| spath input=raw path={} output=events
| mvexpand events
| spath input=events path=attributes{} output=attribute
| stats count by attribute
| sort - count

demo3.JPG

Regards,
Prewin
If this answer helped you, please consider marking it as the solution or giving a Karma. Thanks!

ITWhisperer
SplunkTrust
SplunkTrust

Is this part of a json structure? Assuming it is, you could do something like this

| makeresults
| eval _raw="{
\"array\": [
  {
    \"name\": \"event 1\",
    \"attributes\": [\"a\", \"b\"]
  },
  {
    \"name\": \"event 2\",
    \"attributes\": [\"a\", \"c\"]
  }
]}"
``` The lines above simulate something like the data you shared ```
| spath array{} output=array
| mvexpand array
| spath input=array attributes{} output=attributes
| stats count by attributes
| sort 0 -count
Get Updates on the Splunk Community!

Accelerating Observability as Code with the Splunk AI Assistant

We’ve seen in previous posts what Observability as Code (OaC) is and how it’s now essential for managing ...

Integrating Splunk Search API and Quarto to Create Reproducible Investigation ...

 Splunk is More Than Just the Web Console For Digital Forensics and Incident Response (DFIR) practitioners, ...

Congratulations to the 2025-2026 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...