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!

Modernize your Splunk Apps – Introducing Python 3.13 in Splunk

We are excited to announce that the upcoming releases of Splunk Enterprise 10.2.x and Splunk Cloud Platform ...

New Release | Splunk Cloud Platform 10.1.2507

Hello Splunk Community!We are thrilled to announce the General Availability of Splunk Cloud Platform 10.1.2507 ...

🌟 From Audit Chaos to Clarity: Welcoming Audit Trail v2

🗣 You Spoke, We Listened  Audit Trail v2 wasn’t written in isolation—it was shaped by your voices.  In ...