Splunk Groupby: Examples with Stats

Last updated:
Table of Contents

Group-by in Splunk is done with the stats command.

General template: search criteria | extract fields if necessary | stats or timechart

Group by count

Example: count occurrences of each field my_field in the query output:

source=logs "xxx"
| rex "my\-field: (?<my_field>[a-z]) "
| stats count by my_field
| sort -count

Group by count, by time bucket

Use the timechart command instead of

source=logs "xxx"
| rex "my\-field: (?<my_field>[a-z]) "
| timechart span=30m count by my_field

Group by count distinct

How many unique values for my_field for each 1-minute bucket?

source=logs "xxx"
| rex "my\-field: (?<my_field>[a-z]) "
| timechart span=1m distinct_count(my_field)

Group by sum

Suppose we have logs like these:

... customer="john doe" order_value=20 ...
... customer="mary white" order_value=25 ...
... customer="john doe" order_value=100 ...

Sum the total order value for each different customer:

source=order_logs
| rex " customer=\"(?<customer>[^\"]+)\" " 
| rex " order_value=(?<order_value>[0-9]+) "
| stats sum(order_value) as sum_order_value by customer_id
| sort -sum_order_value

Result:

|---customer----|---sum_order_value--|
| john doe      | 120                |
| mary white    | 25                 |

Dialogue & Discussion