Comparison and Conditional functions - Splunk Documentation (2024)

The following list contains the functions that you can use to compare values or specify conditional statements.

For information about using string and numeric fields in functions, and nesting functions, see Overview of SPL2 evaluation functions.

case(<condition>, <value>, ...)

This function takes pairs of <condition> and <value> arguments and returns the first value for which the condition evaluates to TRUE.

Usage

The <condition> arguments are Boolean expressions that are evaluated from first to last. When the first <condition> expression is encountered that evaluates to TRUE, the corresponding <value> argument is returned. The function defaults to NULL if none of the <condition> arguments are true.

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Basic examples

Specifying conditions and values

The following example returns descriptions for the corresponding HTTP status code.

$search = from my_dataset where sourcetype="access_*" | eval description=case(status == 200, "OK", status == 404, "Not found", status == 500, "Internal Server Error") | fields status, description

The results look something like this:

statusdescription
200OK
200OK
408
200OK
404Not found
200OK
406
500Internal Server Error
200OK

Specifying a default value

In the above example, the description column is empty for status=406 and status=408.

To display a default value when the status does not match one of the values specified, use the literal true(). For example:

|from my_dataset where sourcetype="access_*" | eval description=case(status == 200, "OK", status ==404, "Not found", status == 500, "Internal Server Error", true(), "Other")| table status description

The word Other displays in the search results for status=406 and status=408.

Pipeline router example with a default value

The following pipeline example attempts to identify the type of router specified in the _raw field for each event. If the router can't be identified based on the conditions, "other" is returned.

$pipeline = from $source | eval router = case(match(_raw, /SSLVPN/i), "citrix", match(_raw, /ASA-6/i), "cisco", match(_raw, /OBSERVED/i), "bluecoat", match(_raw, /pa-vm/i), "palo", true(), "other")| into $destination

Extended example

This example shows you how to use the case function in two different ways, to create categories and to create a custom sort order.

This example uses earthquake data downloaded from the USGS Earthquakes website. The data is a comma separated ASCII text file that contains magnitude (mag), coordinates (latitude, longitude), region (place), and so forth, for each earthquake recorded.

You want classify earthquakes based on depth. Shallow-focus earthquakes occur at depths less than 70 km. Mid-focus earthquakes occur at depths between 70 and 300 km. Deep-focus earthquakes occur at depths greater than 300 km. We'll use Low, Mid, and Deep for the category names.

| from my_dataset where source="all_month.csv"| eval Description=case(depth<=70, "Low", depth>70 AND depth<=300, "Mid", depth>300, "Deep") | stats count min(mag) max(mag) by Description

The eval command is used to create a field called Description, which takes the value of "Low", "Mid", or "Deep" based on the Depth of the earthquake. The case() function is used to specify which ranges of the depth fits each description. For example, if the depth is less than 70 km, the earthquake is characterized as a shallow-focus quake; and the resulting Description is Low.

The search also pipes the results of the eval command into the stats command to count the number of earthquakes and display the minimum and maximum magnitudes for each Description.

The results look something like this:

Descriptioncountmin(Mag)max(Mag)
Deep354.16.7
Low6236-0.607.70
Mid6350.86.3

You can sort the results in the Description column by clicking the sort icon in Splunk Web. However in this example the order would be alphabetical returning results in Deep, Low, Mid or Mid, Low, Deep order.

You can also use the case function to sort the results in a custom order, such as Low, Mid, Deep. You create the custom sort order by giving the values a numerical ranking and then sorting based on that ranking.

from my_dataset where source="all_month.csv"| eval Description=case(depth<=70, "Low", depth>70 AND depth<=300, "Mid", depth>300, "Deep") | stats count min(mag) max(mag) by Description| eval sort_field=case(Description="Low", 1, Description="Mid", 2, Description="Deep",3) | sort sort_field

The results look something like this:

Descriptioncountmin(Mag)max(Mag)
Low6236-0.607.70
Mid6350.86.3
Deep354.16.7

cidrmatch(<cidr>, <ip>)

Returns TRUE or FALSE based on whether an IP address matches a CIDR notation.

This function returns TRUE when an IP address, <ip>, belongs to a particular CIDR subnet, <cidr>. This function is compatible with IPv6.

Usage

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Both <cidr> and <ip> are string arguments. If you specify a literal string value, instead of a field name, that value must be enclosed in double quotation marks.

Basic examples

The following example uses the cidrmatch and if functions to set a field, isLocal, to "local" if the field ipAddress matches the subnet. If the ipAddress field does not match the subnet, the isLocal field is set to "not local".

... | eval isLocal=if(cidrmatch("192.0.2.0/24",ipAddress), "local", "not local")


The following example uses the cidrmatch function as a filter to remove events where the values in the mycidr field do not match the IP address.

... | where NOT cidrmatch(mycidr, "203.0.113.255")

coalesce(<values>)

This function takes one or more values and returns the first value that is not NULL.

Usage

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Basic examples

You have a set of events where the IP address is extracted to either clientip or ipaddress. This example defines a new field called ip, that takes the value of either the clientip field or ipaddress field, depending on which field is not NULL (does not exist in that event). If both the clientip and ipaddress field exist in the event, this function returns the value in first argument, the clientip field.

... | eval ip=coalesce(clientip, ipaddress)

If neither field exists in the events, you can specify a default value:

... | eval ip=coalesce(clientip, ipaddress, "203.0.113.255")

if(<predicate>, <true_value>, <false_value>)

If the <predicate> expression evaluates to TRUE, returns the <true_value>, otherwise the function returns the <false_value>.

See Predicate expressions in the SPL2 Search Manual.

Usage

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

The if function is frequently used in combination with other functions.

Basic examples

The following example looks at the values of the error field. If error=200, the function returns err=OK. Otherwise the function returns err=Error.

... | eval err=if(error == 200, "OK", "Error")


The following example uses the cidrmatch and if functions to set a field, isLocal, to "local" if the field ip matches the subnet. If the ip field does not match the subnet, the isLocal field is set to "not local".

... | eval isLocal=if(cidrmatch("123.132.32.0/25",ip), "local", "not local")


You can use the if function to replace the values in a field, based on the predicate expression. The following example works on an existing field score. If the value in the test field is Passed, the value in the score field remains unchanged. Otherwise the value in the score field is changed to 0 in the search results.

... | eval score=if(test="Passed", score, 0)

You can also reverse this search to something like this:

... | eval score=if(test="Failed", 0, score)

If the value in the test field is Failed, the value in the score field is changed to 0 in the search results. Otherwise the value in the score field remains unchanged.

in(<value>, <list>)

The function returns TRUE if one of the values in the list matches a value that you specify.

This function takes a list of comma-separated values.

Usage

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

The following syntax is supported:

...WHERE in(<value>, [<list>]) or ...| where in(<value>, [<list>])
...WHERE <value> in([<list>]) or ...| where <value> in([<list>])
...| eval new_field=if(in(<value>, [<list>]), "true_value", "false_value")

The eval command cannot accept a Boolean value. You must specify the in() function inside a function that can accept a Boolean value as input. Those functions are: code, if, and validate.

The string values must be enclosed in quotation marks. You cannot specify wildcard characters in the list of values to specify a group of similar values, such as HTTP error codes or CIDR IP address ranges. Use the IN operator instead.

The IN predicate operator is similar to the in() function. You can use the IN operator with the search command, as well as the same commands and clauses where you can use the in() function. See Predicate expressions in the SPL2 Search Manual.

Basic examples

Specifying a list of values

The following example uses the where command to return in=TRUE if one of the values in the status field matches one of the values in the list.

... | where status in("400", "401", "403", "404")

Specifying a list of fields

The following example uses the where command to return in=TRUE if the value 203.0.113.255 appears in either the ipaddress or clientip fields.

... | where "203.0.113.255" in(ipaddress, clientip)

Using the in function inside another function

The following example uses the in() function as the first parameter for the if() function. The evaluation expression returns TRUE if the value in the status field matches one of the values in the list.

... | eval error=if(in(status, "error", "failure", "severe"),"true","false")

Extended example

The following example combines the in function with the if function to evaluate the status field. The value of true is placed in the new field error if the status field contains one of the values 404, 500, or 503. Then a count is performed of the values in the error field.

... | eval error=if(in(status, "404","500","503"),"true","false") | stats count() by error

For additional in function examples, see the blog Smooth operator | Searching for multiple field values.

like(<str>, <pattern>)

This function returns TRUE only if str matches pattern. The match can be an exact match or a match using a wildcard:

  • Use the percent (% ) symbol as a wildcard for matching multiple characters
  • Use the underscore ( _ ) character as a wildcard to match a single character

Usage

The <str> can be a field name or a string value. The <pattern> must be a string expression enclosed in double quotation marks.

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

The following syntax is supported:

commandsyntax
WHERE clause...WHERE like(<str>, <pattern>)

...WHERE <str> LIKE <pattern>

eval command...|eval new_field=if(like(<str>, <pattern>)
where command ...| where like(<str>, <pattern>)

...| where <str> LIKE <pattern>

The eval command cannot accept a Boolean value. You must specify the like() function inside the if() function, which can accept a Boolean value as input.

The LIKE predicate operator is similar to the like() function. You can use the LIKE operator with the same commands and clauses where you can use the like() function. See Predicate expressions in the SPL2 Search Manual.

Basic examples

The following example returns like=TRUE if the field value starts with foo:

... | eval is_a_foo=if(like(field, "foo%"), "yes a foo", "not a foo")


The following example uses the where command to return like=TRUE if the ipaddress field starts with the value 198.. The percent (% ) symbol is a wildcard with the like function:

... | where like(ipaddress, "198.%")

match(<str>, <regex>)

This function returns TRUE if the regular expression <regex> finds a match against any substring of the string value <str>. Otherwise returns FALSE.

Usage

The match function is regular expression, using the perl-compatible regular expressions (PCRE) syntax. For example use the backslash ( \ ) character to escape a special character, such as a quotation mark. Use the pipe ( | ) character to specify an OR condition.

The Edge Processor solution supports Regular Expression 2 (RE2) syntax instead of PCRE syntax. In particular RE2 and PCRE accept different syntax for named capture groups. See Regular expression syntax for Edge Processor pipelines in Use Edge Processors.

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Basic examples

The following example returns TRUE if, and only if, field matches the basic pattern of an IP address. This examples uses the caret ( ^ ) character and the dollar ( $ ) symbol to perform a full match.

... | eval n=if(match(field, "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"), 1, 0)


The following example uses the match function in an <eval-expression>. The <str> is a calculated field called test. The <regex> is the string yes.

... | eval matches = if(match(test,"yes"), 1, 0)

If the value is stored with quotation marks, you must use the backslash ( \ ) character to escape the embedded quotation marks. For example:

| from [{ }] | eval test="\"yes\"" | eval matches = if(match(test, "\"yes\""), 1, 0)

This example creates a single event using the from command and an empty dataset literal string value [{ }], which returns the _time field.

nullif(<field1>, <field2>)

This function compares the values in two fields and returns NULL if the value in <field1> is equal to the value in <field2>. Otherwise the function returns the value in <field1>.

Usage

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Basic examples

Using the repeat dataset function, the following search creates a field called names. Another field called ponies is created based on the names field. The if function is used to change the name buttercup to mistmane in the ponies field.

from repeat({},1)| eval _time=now()| eval names="buttercup rarity tenderhoof dash"| eval names=split(names," ")| mvexpand names| eval ponies = if(test="buttercup", "mistmane", names)

The results look like this:

_timenamesponies
14:57:12 PM 17 Oct 2022buttercupmistmane
14:57:12 PM 17 Oct 2022rarityrarity
14:57:12 PM 17 Oct 2022tenderhooftenderhoof
14:57:12 PM 17 Oct 2022dashdash

Using the nullif function, you can compare the values in the names and ponies fields. If the values are different, the value from the first field specified are displayed in the compare field. If the values are the same, no value is returned.

... eval compare = nullif(names, ponies)

The results look like this:

_timecomparenamesponies
14:57:12 PM 17 Oct 2022buttercupbuttercupmistmane
14:57:12 PM 17 Oct 2022rarityrarity
14:57:12 PM 17 Oct 2022tenderhooftenderhoof
14:57:12 PM 17 Oct 2022dashdash

searchmatch(<search_str>)

This function returns TRUE if the event matches the search string.

Usage

To use the searchmatch function with the eval command, you must use the searchmatch function inside the if function.

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Example

The following example creates an event the contains a timestamp and two fields x and y.

| from [{ }] | eval x="hi" | eval y="goodbye"

The results look like this:

_timexy
9/2/2020 1:29:58.000 PMhigoodbye

Add the searchmatch function to determine if the <search_str> matches the event:

| from [{ }] | eval x="hi" | eval y="goodbye" | eval test=if(searchmatch("x=hi y=*"), "yes", "no") | fields test x y


The results look like this:

testxy
yeshigoodbye

validate(<condition>, <value>, ...)

This function takes a list of conditions and values and returns the value that corresponds to the condition that evaluates to FALSE. This function defaults to NULL if all conditions evaluate to TRUE.

This function is the opposite of the case function.

Usage

The <condition> arguments must be expressions.

The <value> arguments must be strings.

You can use this function with the eval and where commands, in the WHERE clause of the from command, and as part of evaluation expressions with other commands.

Example

The following example runs a simple check for valid ports.

... | eval n=validate(isint(port), "ERROR: Port is not an integer", port >= 1 AND port <= 65535, "ERROR: Port is out of range")

See also

Function information
Quick Reference for SPL2 eval functions
Overview of SPL2 eval functions
Naming function arguments in the SPL2 Search Manual
Comparison and Conditional functions - Splunk Documentation (2024)

FAQs

What are the comparison operators in Splunk? ›

Examples of relational operators are equal to ( = ) and is greater than ( > ). An operator that performs a comparison between two expression.

What is the eval command used for in Splunk? ›

The eval command evaluates mathematical, string, and boolean expressions.

Which command enables you to write an expression to create a calculated field in Splunk? ›

Create a calculated field with Splunk Web. Use calculated fields as a shortcut for performing repetitive, long, or complex transformations using the eval command.

What is the coalesce function in Splunk? ›

The coalesce function allows users to view data from different, but similar, fields in a common field along with options to notate if data is available or unknown.

What are the 6 types of comparison operators? ›

The six comparison operators are 1) == or equal to, 2) != or not equal to, 3) > or greater than, 4) >= or greater than or equal to, 5) < or less than, and 6) <= or less than or equal to.

What are three way comparison operators? ›

The three-way comparison operator “<=>” is called a spaceship operator. The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us.

How to put or condition in Splunk? ›

in host = x OR host = y you will retrieve data from both y and x hosts. you can also use OR in eval statements, such as |eval newhost=if(host = x OR host = y,"xy",host) would create a field called newhost with values xy when the host is either x or y, otherwise the value would be any other host value.

What command is best used for performing mathematical calculations in Splunk? ›

abs(value)

Mathematical evaluation function that returns a number's absolute value. Use this scalar function with the eval or the filter streaming functions.

How to write a Regular Expression in Splunk? ›

Use Regular Expression with two commands in Splunk

Splunk offers two commands — rex and regex — in SPL. These commands allow Splunk analysts to utilize regular expressions in order to assign values to new fields or narrow results on the fly as part of their search.

What is spath in Splunk? ›

What is the Splunk spath Command? The spath command extracts fields and their values from either XML or JSON data. You can specify location paths or allow spath to run in its native form.

How to do a subsearch in Splunk? ›

Use square brackets around your subsearch, for example: [search sourcetype=my_sourcetype | top limit=1 host | fields host]. This subsearch will return to main search a single host value that represents the top host in that sourcetype.

When should I use coalesce? ›

Usually, the SQL COALESCE function is used for NULL handling in the database. Instead of replacing NULL values at the application level, it allows you to deal with them directly at the data retrieval time.

What is the comparison operator ===? ›

The strict equality ( === ) operator checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

Which operators are used to perform comparison? ›

The < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal) comparison, also known as relational, operators compare their operands.

What are the six Boolean comparison operators? ›

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== . Logical operators — operators that combine multiple boolean expressions or values and provide a single boolean output.

What are comparison vs assignment operators? ›

Assignment Operators are used to assign a value to a property or variable. Assignment Operators can be numeric, date, system, time, or text. Comparison Operators are used to perform comparisons.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6496

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.