Splunk Search

How to pass the value returned from a subsearch to "earliest" in the main search?

sanjeevdixit
Explorer

Hi,

I want to pass the return value of a subsearch to "earliest" in a search. What is the correct way to do it? What I am trying is throwing an error.

index=idx sourcetype=ST earliest=**[search index=idx sourcetype=ST | head 1 | eval nowstring=strftime(now(), "%m") | eval timetouse = if(nowstring==1, "-13m@", "@y0") | return timetouse]** latest=now | 

Here I want to set the earliest time to -13 month if month is 1 (Jan), else it should be starting this year.

Thanks.

1 Solution

Ayn
Legend

You can check exactly what the output of the subsearch will be by running it on its own and adding "| format" at the end:

index=idx sourcetype=ST | head 1 | eval nowstring=strftime(now(), "%m") | eval timetouse = if(nowstring==1, "-13m@", "@y0") | return timetouse | format

Instead of having earliest=[subsearch] you could do [subsearch | ... | fields earliest] which would then expand into whatever earliest filter you defined in your subsearch.

View solution in original post

Ayn
Legend

You can check exactly what the output of the subsearch will be by running it on its own and adding "| format" at the end:

index=idx sourcetype=ST | head 1 | eval nowstring=strftime(now(), "%m") | eval timetouse = if(nowstring==1, "-13m@", "@y0") | return timetouse | format

Instead of having earliest=[subsearch] you could do [subsearch | ... | fields earliest] which would then expand into whatever earliest filter you defined in your subsearch.

sanjeevdixit
Explorer

Thanks Ayn.

It worked. Using return instead of fields is also giving same result. Which one is better to use?

0 Karma

Ayn
Legend

From a performance perspective fields is better because return is an external script rather than being directly built into Splunk. So fields would be the better option.

sanjeevdixit
Explorer

Great. Thanks for your help.

0 Karma

sanjeevdixit
Explorer

Hi Ayn,

Can you please elaborate a bit on "[subsearch | ... | fields earliest]" part using some example.

0 Karma

Ayn
Legend

Well, something like this:

index=idx sourcetype=ST earliest=[search index=idx sourcetype=ST | head 1 | eval nowstring=strftime(now(), "%m") | eval earliest = if(nowstring==1, "-13m@", "@y0") | fields earliest] latest=now
Career Survey
First 500 qualified respondents will receive a $20 gift card! Tell us about your professional Splunk journey.
Get Updates on the Splunk Community!

Tech Talk Recap | Mastering Threat Hunting

Mastering Threat HuntingDive into the world of threat hunting, exploring the key differences between ...

Observability for AI Applications: Troubleshooting Latency

If you’re working with proprietary company data, you’re probably going to have a locally hosted LLM or many ...

Splunk AI Assistant for SPL vs. ChatGPT: Which One is Better?

In the age of AI, every tool promises to make our lives easier. From summarizing content to writing code, ...