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!

Introducing the Splunk Community Dashboard Challenge!

Welcome to Splunk Community Dashboard Challenge! This is your chance to showcase your skills in creating ...

Built-in Service Level Objectives Management to Bridge the Gap Between Service & ...

Wednesday, May 29, 2024  |  11AM PST / 2PM ESTRegister now and join us to learn more about how you can ...

Get Your Exclusive Splunk Certified Cybersecurity Defense Engineer Certification at ...

We’re excited to announce a new Splunk certification exam being released at .conf24! If you’re headed to Vegas ...