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!

Announcing Scheduled Export GA for Dashboard Studio

We're excited to announce the general availability of Scheduled Export for Dashboard Studio. Starting in ...

Extending Observability Content to Splunk Cloud

Watch Now!   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to leverage ...

More Control Over Your Monitoring Costs with Archived Metrics GA in US-AWS!

What if there was a way you could keep all the metrics data you need while saving on storage costs?This is now ...