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 example

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

|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.

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? ›

An operator that performs a comparison between two expression. The supported logical operators are: AND, OR, NOT, and XOR.

What are the 4 types of searches in Splunk by performance? ›

How search types affect Splunk Enterprise performance
Search typeRef. indexer throughputPerformance impact
DenseUp to 50,000 matching events per second.CPU-bound
SparseUp to 5,000 matching events per second.CPU-bound
Super-sparseUp to 2 seconds per index bucket.I/O bound
RareFrom 10 to 50 index buckets per second.I/O bound

How to use 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 is the use of eval in Splunk? ›

In summary, the eval command in Splunk SPL is a powerful tool for manipulating and deriving fields, enabling you to unlock deeper insights from your data. Remember, by mastering the eval command, you can create more context for producing insightful reports and visualizations.

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. They can be used to compare different values in Python, such as integers or strings.

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.

What is the most efficient order in filtering for searches in Splunk? ›

A few things to remember about filters: time is the most efficient filter (smaller windows = faster results) and inclusion is better than exclusion (field=foo is better than field!= bar or NOT field=bar). Filtering using default fields is very important. Adding index, source, sourcetype, etc.

How to make Splunk searches more efficient? ›

Improve your searches
  1. Select an index in the first line of your search. ...
  2. Use the TERM directive. ...
  3. Use the tstats command. ...
  4. Avoid using table commands in the middle of searches and instead, place them at the end. ...
  5. Test your search string performance.
Apr 16, 2024

What are the 3 types of searching? ›

It is generally accepted that there are three main search types: transactional searches, navigational searches and informational searches. Most modern search engines are able to determine the type of search based on the search query entered and the format of that query.

What is the coalesce function in Splunk? ›

The Splunk Search Processing Language (SPL) coalesce function takes one or more values and returns the first value that is not null.

What is the replace function in Splunk? ›

What is the replace Command? The replace command in Splunk enables users to modify or substitute specific values within fields or events. It allows for dynamic transformations of data, facilitating clearer analysis and more accurate reporting.

How to write Splunk rules? ›

To create an admission rule using Splunk Web:
  1. In Splunk Web, click Settings > Workload Management > Admission Rules.
  2. Click Add Admission Rule.
  3. Define the following fields to configure a new admission rule: Field. Action. Name. Specify the name of the admission rule. Predicate (Condition) ...
  4. Click Submit.
May 15, 2024

What is the difference between stats and eval in Splunk? ›

The stats count() function is used to count the results of the eval expression. The eval eexpression uses the match() function to compare the from_domain to a regular expression that looks for the different suffixes in the domain.

What is the Ceil function in Splunk? ›

ceil(value)

Mathematical evaluation function that rounds a number up to the next highest integer. Returns the result as a double. Use this scalar function with the eval or the filter streaming functions. Numbers can be type int, long, float, or double.

How to check if a field exists in Splunk? ›

there is a SPL function called isnull() and isnotnull() you can use these together with the if function to check if fields/fieldvalues exist or not. Hi @avtandil, there is a SPL function called isnull() and isnotnull() you can use these together with the if function to check if fields/fieldvalues exist or not.

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? ›

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.

Which operator can be used to compare two? ›

The equality operator (==) is used to compare two values or expressions. It is used to compare numbers, strings, Boolean values, variables, objects, arrays, or functions.

What are set comparison operators? ›

Comparison Operators, sometimes referred to as relational or boolean operators, compare values in a database and determine if they are equal (=), not equal (!= , <>), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).

References

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5501

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.