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!

Cultivate Your Career Growth with Fresh Splunk Training

Growth doesn’t just happen—it’s nurtured. Like tending a garden, developing your Splunk skills takes the right ...

Introducing a Smarter Way to Discover Apps on Splunkbase

We’re excited to announce the launch of a foundational enhancement to Splunkbase: App Tiering.  Because we’ve ...

How to Send Splunk Observability Alerts to Webex teams in Minutes

As a Developer Evangelist at Splunk, my team and I are constantly tinkering with technology to explore its ...