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
Get Updates on the Splunk Community!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...