#splunk #stats #spl #splunk_stats ## What is SPL stats ? The `stats` command in *Splunk Search Processing Language* (SPL) is a powerful tool for performing **statistical calculations** and **aggregations** on the queried data. ## Basic Syntax ``` jsx stats <function> by <field> ``` ### Common Functions - `count()`: **Counts** the number of events. - `sum(<field>)`: Calculates the **total** of values for the specified field. - `avg(<field>)`: Calculates the **average** of values for the specified field. - `min(<field>)`: Finds the **minimum** value for the specified field. - `max(<field>)`: Finds the **maximum** value for the specified field. - `list(<field>)`: Returns a **list of all values** for the specified field. ### Field We can also store the values in a different field with the command `as` : ``` jsx stats <function> as <field_name> by <field> ``` ### Search The search command can also be used to filter the results : ``` jsx stats <function> as <field_name> by <field> | search <your_search> ``` ## Examples ### Example 1 - count Here is a simple example using [BOTS V1]([GitHub - splunk/botsv1](https://github.com/splunk/botsv1)) and the Sysmon sourcetype: ``` jsx index=botsv1 sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" | stats count as CountEventCode by EventCode ``` **Result :** ![[Pasted image 20240516103147.png]] > As a result, we have the **EventCode** of events generated by Sysmon and the **number of events**. As we can see, the most generated events are the EventCode 3 (659.112 times). ### Example 2 - max We'll take an other example, we want to know which IP address sent the largest packet (max value) per source IP address on the http stream : ``` jsx index=botsv1 sourcetype="stream:http" | stats max(bytes_out) by c_ip ``` **Result :** ![[Pasted image 20240516094936.png]] > As we can see, this is the Source IP Address 192.168.250.100 that sent a packet of 5314799 bytes (5.314799 Megabytes). ### Example 3 - search We'll now combine various functions (count, max, avg) and the search command, to find all recevied packets (bytes_in) whose average packet size exceeds 500 bytes (0.5 Kylobyte). ``` jsx index=botsv1 sourcetype="stream:http" | stats count(bytes_in) as CountBytesIn, avg(bytes_in) as AvgBytesIn, max(bytes_in) as MaxBytesIn by c_ip | search AvgBytesIn > 500 ``` **Result :** ![[Pasted image 20240516105402.png]]