Splunk Search

Multiple operations from a single if condition

cjohnk
Explorer

Is it possible to action multiple operations in a single if condition, like what can be done in other languages?

For example, in other scripting languages this can be done:

 

if(field==1){
  group=group+1;
  groups=groups+","+group;
}
else
{
  //this is a comment, do nothing
}

 

How can this be done in splunk?

Labels (1)
Tags (3)
0 Karma

yuanliu
SplunkTrust
SplunkTrust

As @ITWhisperer and @bowesmana said, SPL is not a procedural language and does not provide code block.  I do understand the semantic clarity, and maintainability of a code block.  So, I am going to use the specifics in your sample to give a very silly "block".

Obviously I have no idea what values are in field, group and groups.  So I made something up, with the constraint that group be numeric.

fieldgroupgroups
01010
12030
23060

The following will read like a block:

 

| eval bingo = if(field == 1, mvrange(group, group+1), null())
| foreach bingo mode=multivalue
    [eval group = <<ITEM>> + 1, groups = groups . "," . <<ITEM>>]

 

and the output is equivalent to your block code

fieldgroupgroups
01010
12130,20
23060

Is that code block? Not really.  Does it achieve semantic clarity?  Questionable.  But you are not repeating condition evaluation.

Also, if maintainability is super important, you can also do something like

 

| tojson group groups
| eval _raw = if(field == 1, json_set(_raw, "group", group + 1, "groups", groups . "," . group), _raw)
| fields - group groups
| spath

 

In a roundabout way, this has the true spirit of a code block.

The above mock data is produced with the following:

 

| makeresults format=csv data="field, group
0, 10
1, 20
2, 30"
| streamstats sum(group) as groups
``` data emulation above ```

 

 

0 Karma

ITWhisperer
SplunkTrust
SplunkTrust

Short answer is no.

Splunk SPL is not a procedural language (like some other languages). Essentially, the if function can be used to modify what is assigned by an eval command to a new or existing field in the event, although you can have multiple assignments in the same eval command e.g. | eval a=value1, b=value2

0 Karma

bowesmana
SplunkTrust
SplunkTrust

You can't do block ifs in Splunk, so you have to do all conditionals inside the | eval x=if(...) construct

0 Karma
Get Updates on the Splunk Community!

Prove Your Splunk Prowess at .conf25—No Prereqs Required!

Your Next Big Security Credential: No Prerequisites Needed We know you’ve got the skills, and now, earning the ...

Splunk Observability Cloud's AI Assistant in Action Series: Observability as Code

This is the sixth post in the Splunk Observability Cloud’s AI Assistant in Action series that digs into how to ...

Splunk Answers Content Calendar, July Edition I

Hello Community! Welcome to another month of Community Content Calendar series! For the month of July, we will ...