Splunk Search

How to extract three latest values of a field by field?

pomazanelvira
New Member

Hi! I have different events and for every event i have a list of reasons. I want to display only three of the reasons for each event, which are latest by time. I use this code:
| stats values(Reason) as Reason, values(_time) AS Time by event
| sort Reason by Time
| eval Reason=mvindex(Reason,0,2)
| table event, Time, Reason
This doesn't work. What should I do to make it work?

0 Karma

wmyersas
Builder

What I've done when I want the Xth-many/most recent items is the following:

<search>
| eval field_time=_time+"|"+field
| stats values(field_time) as field_time <rest of stats here>
| eval recent_1st=mvindex(field_time,-1), recent_2nd=mvindex(field_time,-2) [, etc etc]
| rex field=recent_1st "(?<when_1st>\d+)\|(?<field_1st>.+)"
| rex field=recent_2nd "(?<when_2nd>\d+)\|(?<field_2nd>.+)"
| ...more rex lines as needed
| table field_1st when_1st field_2nd when_2nd <other fields as desired>
| eval when_1st=strftime(when_1st,"%c"), when_2nd=strftime(when_2nd,"%c) [,etc etc]

Feel free to use different strftime formatting as desired

You have to combine the time into the field so that it sorts the way you want with values()

0 Karma

richgalloway
SplunkTrust
SplunkTrust

What results do you get?

---
If this reply helps you, Karma would be appreciated.
0 Karma

pomazanelvira
New Member

I get a table, but Reasons are not sorted by time. So, i don't get the latest reasons

0 Karma
Get Updates on the Splunk Community!

Modern way of developing distributed application using OTel

Recently, I had the opportunity to work on a complex microservice using Spring boot and Quarkus to develop a ...

Enterprise Security Content Update (ESCU) | New Releases

Last month, the Splunk Threat Research Team had 3 releases of new security content via the Enterprise Security ...

Archived Metrics Now Available for APAC and EMEA realms

We’re excited to announce the launch of Archived Metrics in Splunk Infrastructure Monitoring for our customers ...