Splunk Search

How do you use IF / Else statement to pull different fields including JSON elements?

ShoeBuster
Observer

Hello Community,

2 part question: First, how to use an IF / ELSE statement, secondly, how to specify the JSON elements in the query. Any examples or helpful

How would I do a search query that depending on the log source, pulls different fields?

 

For example

index=myIndex

| IF (source=Source1 OR sourcetype=sourceTypeB) pull JSON element1, element2, etc

| ELSE IF logSource=logSource2 pull fieldsname1, fieldname2, etc

Labels (1)
0 Karma

ericjorgensenjr
Path Finder

Re: "how to specify the JSON elements in the query":

Example:

- if you have a field titled field1 that has JSON formatted data (e.g. {"att1":"val1","att2":"val2"}

You can do the following:

index=myIndex 
| spath input=field1 ouput=att1 path=att1
| spath input=field1 output=att1 path=att2
| eval test=case(source=Source1 OR sourcetype=sourceTypeB, att1,logSource=logSource2,fieldname1) 

 

You can also use 

| spath input=field1

without any output or path if you want to extract all JSON fields. For more details on the spath command go here: https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchReference/Spath

0 Karma

richgalloway
SplunkTrust
SplunkTrust

Splunk does not have an IF/ELSE statement.  It does, however, have if and case functions that can be used in the eval and where commands.

index=myIndex
| eval foo = if(source=Source1 OR sourcetype=sourceTypeB), JSON element1, 
if(logSource=logSource2), fieldsname1, NULL), NULL)
| eval bar = case(source=Source1 OR sourcetype=sourceTypeB), JSON element2, logSource=logSource2, fieldname2, 1==1, NULL)
| ...
---
If this reply helps you, Karma would be appreciated.
0 Karma
Get Updates on the Splunk Community!

Enterprise Security Content Update (ESCU) | New Releases

In December, the Splunk Threat Research Team had 1 release of new security content via the Enterprise Security ...

Why am I not seeing the finding in Splunk Enterprise Security Analyst Queue?

(This is the first of a series of 2 blogs). Splunk Enterprise Security is a fantastic tool that offers robust ...

Index This | What are the 12 Days of Splunk-mas?

December 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...