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

Explanation: The comparison operators in Splunk are: =?= , ==, <=, and != .

What is the use of eval in Splunk? ›

With eval, any Splunker can create a field containing custom text. This field can then be tailored using the content of other fields. Handling multivalue data: Some eval functions are specifically designed to read, create, or modify fields that contain multiple values per event.

What is 1:1 in Splunk? ›

My understanding the 1=1 is checking all the scenarios to make sure they are true, but after the comma is the filed name its attached to or representing as a default.

What is the most efficient way to limit search results returned in Splunk? ›

You can specify a limit to the number of events retrieved in a couple of ways: Use the head command. The head command retrieves only the most recent N events for a historical search, or the first N captured events for a realtime search.

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 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 coalesce in Splunk? ›

Coalesce takes the first non-null value to combine. In these use cases you can imagine how difficult it would be to try and build a schema around this in a traditional relational database, but with Splunk we make it easy.

What are functions in eval? ›

The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function. For example, Eval("Chr$(65)") returns "A".

How to fill null values in Splunk? ›

Solution. You can use fillnull and filldown to replace null values in your results. The fillnull command replaces null values in all fields with a zero by default.

How to pull data from Splunk? ›

There are three common ways to extract data from Splunk Infrastructure Monitoring: by using SignalFlow, Splunk's streaming analytics API; by using the /timeserieswindow endpoint in the Splunk API; or from the Splunk UI.

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.

How do I make Splunk search faster? ›

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 is the 50000 limit in Splunk stats? ›

This means that you hit the number of the row with the limit, 50,000, in "chart" command. There were more than 50,000 different source IPs for the day in the search result. The chart command's limit can be changed by [stats] stanza. So, you can increase the number by [stats] stanza in limits.

What is the maximum number of rows in Splunk? ›

You hit 10000 rows limit that @gcusello mentioned if you are using lookups as a subsearch with inputlookup command. This is subsearch results limit. Please use lookup command for searching inside lookup, lookup command has no limit.

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

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.

Top Articles
Hurricane Beryl Cat. 4 Landfall In Windward Islands | Weather.com
Remnant 2 Review - IGN
122242843 Routing Number BANK OF THE WEST CA - Wise
Pnct Terminal Camera
Cash4Life Maryland Winning Numbers
Dr Doe's Chemistry Quiz Answer Key
Ou Class Nav
Pollen Count Los Altos
Luciipurrrr_
DIN 41612 - FCI - PDF Catalogs | Technical Documentation
Dusk
Sport Clip Hours
8 Ways to Make a Friend Feel Special on Valentine's Day
Images of CGC-graded Comic Books Now Available Using the CGC Certification Verification Tool
Obsidian Guard's Cutlass
Unterwegs im autonomen Freightliner Cascadia: Finger weg, jetzt fahre ich!
Robert Deshawn Swonger Net Worth
Tips on How to Make Dutch Friends & Cultural Norms
Yonkers Results For Tonight
The Many Faces of the Craigslist Killer
Weldmotor Vehicle.com
D2L Brightspace Clc
Cognitive Science Cornell
Robotization Deviantart
Tracking every 2024 Trade Deadline deal
Yu-Gi-Oh Card Database
In hunt for cartel hitmen, Texas Ranger's biggest obstacle may be the border itself (2024)
Emuaid Max First Aid Ointment 2 Ounce Fake Review Analysis
Restaurants Near Calvary Cemetery
R3Vlimited Forum
Egg Crutch Glove Envelope
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
Ippa 番号
Ljw Obits
Go Smiles Herndon Reviews
Husker Football
Lamont Mortuary Globe Az
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Winta Zesu Net Worth
Penny Paws San Antonio Photos
Cch Staffnet
R/Gnv
Tropical Smoothie Address
Conan Exiles Colored Crystal
Ajpw Sugar Glider Worth
Anonib New
Here’s What Goes on at a Gentlemen’s Club – Crafternoon Cabaret Club
Dolce Luna Italian Restaurant & Pizzeria
Nkey rollover - Hitta bästa priset på Prisjakt
Tenichtop
Land of Samurai: One Piece’s Wano Kuni Arc Explained
Guidance | GreenStar™ 3 2630 Display
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5768

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.