Splunk Search

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

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

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

SplunkTrust
SplunkTrust

What results do you get?

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

New Member

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

0 Karma
State of Splunk Careers

Access the Splunk Careers Report to see real data that shows how Splunk mastery increases your value and job satisfaction.

Find out what your skills are worth!