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!

Accelerating Observability as Code with the Splunk AI Assistant

We’ve seen in previous posts what Observability as Code (OaC) is and how it’s now essential for managing ...

Integrating Splunk Search API and Quarto to Create Reproducible Investigation ...

 Splunk is More Than Just the Web Console For Digital Forensics and Incident Response (DFIR) practitioners, ...

Congratulations to the 2025-2026 SplunkTrust!

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