Skip to Content
KubeSense

Search Processing Language (SPL)

The Search Processing Language (SPL) is KubeSense's pipeline-style query language for searching, filtering, transforming and aggregating log data. It follows Splunk's SPL: you write a query as commands separated by the pipe character |, and each command works on the output of the one before it. If you know Splunk, most of your searches work as they are.

SPL is available in the Log Explorer search bar. Switch to advanced query mode and start typing.

This page covers how SPL works, searching, field names and the core commands. The rest of the reference:


How SPL Works

Every SPL query is a pipeline:

<search> | <command> | <command> | ...

Each command receives the rows the previous command produced. sort a | sort b sorts by b, head 5 | stats count counts five rows, and eval x = … | where x > 1 filters on the new x.

Queries read your logs and are always limited to the time range and cluster(s) selected in the Log Explorer.

A Simple Example

level=error namespace=checkout
| sort -_time
| head 50

This finds the error logs in the checkout namespace and returns the 50 newest.

A Complex Example

fields timestamp, workload as application_name, level as severity, body as text
| filter application_name != "" and severity in ["ERROR", "WARN", "INFO"]
| stats count as total, sum(severity = "ERROR") as errors, sum(severity = "WARN") as warns by application_name
| eval error_rate = errors / total
| sort -error_rate

This computes the error rate of every application: total logs, error count, warning count and the error rate per workload.

Comments

Everything from # to the end of the line is a comment, outside quoted text:

# Non-200 responses from API logs
"APICallLogs:"
| parse 'Path:* Method:* StatusCode:*' as path, method, code
| where code != "200"   # successful requests excluded
| stats count as errors by path, code

Built-in Field Names

SPL provides built-in names for your log columns. Use them in any command:

NameDescription
_time / @timestamp / timestampLog event time (UTC)
_raw / @message / bodyThe log message text
levelLog severity (ERROR, WARN, INFO, etc.)
clusterKubernetes cluster name
namespaceKubernetes namespace
workloadWorkload name (Deployment, StatefulSet, etc.)
pod_namePod name
container_nameContainer name
hostNode hostname
serviceService name
sourceLog source identifier
node_nameKubernetes node name
env_typeEnvironment type
_indextimeWhen the log was received

The table also accepts a few aliases: type (= level), domain (= cluster), container (= container_name), node (= node_name), @loggroup (= workload) and @logstream (= pod_name), plus the format and raw columns.

Accessing Parsed Log Fields and Attributes

Fields parsed from structured logs (JSON, logfmt, etc.) and log attributes are used by name, just like the built-in fields:

status=500
| stats count by url
fields @timestamp, url, status, duration
| where duration > 1000
stats avg(duration) as avg_duration by http.method

Results use the name you typed: fields status returns a status column, and stats count by url returns a url column. A name with a dot, such as http.method, comes back with an underscore: http_method.

A field is looked up in string attributes first, then float attributes, then the JSON-parsed log body.

Attributes are stored as text, but they behave as numbers where it matters, as in Splunk. duration > 1000 compares numerically, sort -duration puts 900 before 80, and if(cond, 0, duration) gives a number.

How a name is resolved:

  1. Built-in fields win. A name from the table above always refers to that column.
  2. Names your query creates win next. An eval target, a fields … as or stats … as alias, a default aggregate name such as count or avg_duration, a parse or rex capture, or a rename target refers to that value.
  3. Anything else is an attribute. region=us-east reads the region attribute.

When an Attribute Has the Same Name as a Column

The built-in column always wins. If your logs have an attribute called level or service, then level and service still read the built-in columns.

To read the attribute instead, put lp_ or log_processed. in front of its name:

where lp_level = "debug"
| stats count by level

This keeps the logs whose level attribute is debug and counts them by the built-in level column. log_processed.level reads the same attribute as lp_level.

  • Write the attribute name exactly after the prefix, dots included: lp_http.method reads http.method, while lp_http_method reads an attribute called http_method.
  • The result column is named lp_level. Add as to give it your own name: fields level, lp_level as level_attr.
  • You only need the prefix when the name clashes with a built-in field. For any other attribute, status and lp_status read the same thing.

warn: A misspelled field name does not cause an error. namespce=prod looks for an attribute named namespce, finds none and returns no rows. If a query unexpectedly returns nothing, check the field names first.


Searching

A query usually starts by choosing logs. Write the search first, with or without the search keyword:

level=error host=web-* "connection refused"
search level=error timeout
You writeIt matches
timeoutLogs whose message contains the word timeout
"connection refused"Logs whose message contains the phrase
time*Logs whose message contains a word starting with time
*Every log
level=errorlevel equal to error, ERROR or Error (see below)
host=web-*host starting with web- (* is a wildcard)
status=*Logs that have a status
status!=200Logs that have a status other than 200
NOT status=200Logs whose status is not 200, including logs without one
duration>=500Numeric comparison when the value is a number
user IN (alice, "bob smith")Any of the values
10.0.0.1, ip=10.0.0.1IP addresses and other dotted values need no quotes
a b / a AND bBoth
a OR b, NOT a, ( … )Either, not, grouping. As in Splunk, OR binds tighter than AND: level=error OR level=warn host=web is (level=error OR level=warn) AND host=web
earliest=-1h@h latest=nowNarrows the time range (see below)
index=mainIgnored: all your logs are in one index
  • Values need no quotes up to the next space: url=/api/v1/orders, pod=api-7c9f-xk2p. Quote values with spaces. * is a wildcard in quoted values too: user="svc-*".
  • Values compare ignoring case in search. On the built-in log fields (level, namespace, workload, host, pod_name, service, …), a value matches as you typed it, in lower case, in upper case or capitalized, so level=error finds error, ERROR and Error; this keeps the search on the fields' indexes. A value written in mixed case elsewhere, such as eRRor, matches only exactly. Attribute values match in any case. where and filter compare exactly.
  • A query that starts with a search needs no search keyword when it starts with a comparison (level=error), a quoted phrase, NOT, ( or *, or is a single word. To search for several unquoted words, start with search: search error timeout. This keeps a mistyped command, such as stat count, an error rather than a text search.
  • search can also come later in a pipeline, to filter results: stats count by host | search host=web*.

Time modifiers take a relative time, now, epoch seconds, or %m/%d/%Y:%H:%M:%S. A relative time is an offset, then an optional snap with @:

TimeMeans
-24h24 hours ago
-7d@dMidnight 7 days ago
@dMidnight today
@w1Midnight on the most recent Monday (@w0 is Sunday … @w6 Saturday)
@h+30mHalf past the current hour

Units: s, m, h, d, w, mon, q, y (and longer spellings such as min, hours, days). earliest/latest only narrow the time range selected in the Log Explorer; they never widen it.

Searches can contain a subsearch in square brackets: level=error [search status=503 | dedup user | fields user].


Command Reference

Command Overview

CommandDescription
searchFind logs with Splunk search syntax (see Searching)
where / filterKeep rows where an expression is true
fieldsChoose the columns to return, compute or remove columns
tableReturn exactly the listed columns
evalCompute columns (functions)
rex / parseExtract fields with a regular expression or a glob pattern
renameRename columns
statsAggregate, optionally grouped by fields
timechartAggregate per time bucket
top / rareMost or least common values
dedupRemove repeated values
sortOrder the rows
head / limit / tailFirst or last N rows
bin, chart, eventstats, streamstats, fillnull, addtotals, addcoltotals, accum, delta, autoregress, trendline, reverse, uniq, regex, replace, convert, strcat, rangemap, xyseries, untable, transpose, makeresults, extract, spath, makemv, mvexpand, mvcombine, nomv, fieldformatSee More Commands
[subsearch], append, appendcols, appendpipe, union, multisearch, set, join, selfjoin, map, transaction, foreach, return, format, eventcount, gentimesSee Combining Searches
lookup, inputlookup, tstatsSee Lookups and tstats
outlier, anomalydetection, predict, cluster, timewrapSee Analysis Commands

A command name only counts as a command where a command starts, so a field may still be called bin, delta or regex.


fields

Chooses the columns to return and computes new ones.

Syntax:

fields [+] <field> [as <alias>], <expr> as <alias>, ...
fields - <field>, ...

Fields are separated by commas or spaces, and may use * wildcards (fields container*, pod*). A wildcard matches the result's columns, the fields your query created and the default log columns. Attributes are not listed anywhere, so a wildcard cannot match them; name those in full.

Examples:

fields @timestamp, body, level
fields @timestamp, url, status, duration as dur
fields (level = "ERROR") as is_error
stats count as n_all, dc(level) as n_levels by host | fields - n_*

A parenthesized condition becomes 0 or 1, which can be summed by a later stats.

Columns that fields leaves out can still be read by later commands, as in CloudWatch Logs Insights: fields @timestamp, body | where level = "ERROR" works.

Without fields or table, log results show timestamp, body, level, cluster, namespace, workload, pod_name, container_name, host, service and source, plus any field your query creates with eval, rex or parse. fields * returns every column.


where / filter

Keeps the rows where an expression is true. where and filter are the same command. They use expression syntax, the same as eval: quote string values, and values compare exactly.

Syntax:

where <expression>

Operators:

OperatorDescriptionExample
= / ==Equallevel = "ERROR"
!= / <>Not equallevel != "DEBUG"
<, >, <=, >=Comparisons; numeric when one side is a numberduration > 1000
and / or / not / !Logical connectiveslevel = "ERROR" and namespace = "prod"
in (v1, v2, ...) / in [v1, v2, ...]Membershiplevel in ("ERROR", "WARN")
like "pattern%"SQL LIKE patternbody like "%timeout%"

Examples:

where level in ("ERROR", "WARN") and namespace = "production"
where not (level = "INFO")
where ispresent(url)
where match(url, "^/api/v[12]/")
stats count as total by level | where total > 100

A string in quotes on its own searches the message text: where "timeout" and level = "ERROR".


parse

Extracts values from a field with a glob pattern; each * captures one value.

Syntax:

parse [<field>] '<pattern>' as <alias>[, <alias> ...]

The field defaults to the message body.

Examples:

parse body '"user":"*"' as username
parse '* /api/*/*' as method, version, rest

rex

Extracts named groups from a field with a regular expression. Each group becomes a field.

Syntax:

rex [field=<field>] [max_match=<N>] "<regex>"
rex mode=sed [field=<field>] "s/<regex>/<replacement>/[g]"
  • Named groups are written (?<name>…), as in Splunk, or (?P<name>…).
  • The field defaults to _raw, the message body.
  • max_match=N extracts up to N matches into a multivalue field; max_match=0 extracts every match.
  • mode=sed edits the field in place: s/regex/replacement/ replaces the first match (g replaces every match, and \1 puts back a group), and y/abc/xyz/ replaces characters.

Examples:

rex field=_raw "(?<method>[A-Z]+) (?<path>/[^ ]*) HTTP/[0-9.]+"
| stats count as hits by method, path
| sort -hits
rex max_match=0 "user=(?<user>\w+)" | eval users = mvcount(user)
rex mode=sed field=body "s/password=[^ ]+/password=***/g"

eval

Computes new columns. Each assignment sees the ones before it.

Syntax:

eval <name> = <expression>, <name> = <expression>, ...

Examples:

eval is_error = (level = "ERROR")
eval score = case(level = "ERROR", 10, level = "WARN", 5, true(), 1)
eval full_path = service . "/" . endpoint
eval duration_ms = duration * 1000, slow = if(duration_ms > 2000, "yes", "no")
eval level = lower(level)

. joins strings, as does + when one side is a quoted string. Arithmetic reads attributes as numbers and times as epoch seconds, so eval age = now() - _time is an age in seconds; dividing by zero gives an empty value. Assigning _time (eval _time = _time + 3600) changes the time that bin, timechart and earliest/latest use. See Functions for every function. fieldformat and setfields work like eval.


stats

Aggregates rows, one result row per combination of the by fields, ordered by those fields.

Syntax:

stats <aggregation> [as <alias>] ... [by <field> ...]

Aggregations and by fields are separated by commas or spaces: stats count dc(pod_name) by host level. An aggregation can be arithmetic over aggregations: stats sum(bytes) / count as avg_bytes. Without an alias, the column is named after the function and field, such as avg_duration or perc95_duration.

See Functions for every aggregation.

Counting Rows

count needs no parentheses. stats count by host is the same as stats count(*) by host:

stats count by host

This returns one row per host with a count column. Add as to name the column yourself:

stats count as total by level
You writeIt countsColumn name
count / cEvery rowcount
count(*)Every rowcount
count(x)Rows that have a value for xcount_x
count(eval(cond))Rows where cond is true(add as)

Bare count works anywhere an aggregation goes, in stats, timechart, chart, eventstats and streamstats, and next to other aggregations:

stats count, avg(duration) as avg_dur by workload
timechart span=5m count by level

info: In an aggregation list, count always means the row count, even if your logs have an attribute named count. To count the rows where that attribute is set, write count(lp_count). Outside aggregations, for example in where count > 10 after a stats, count refers to the count column.

Sparklines

sparkline adds a trend to each row of a stats result. Each row gets an array with one value per time bucket across your selected time range, next to the row's totals:

stats sparkline count by host

This returns one row per host, with a sparkline column (log volume over time) and a count column (total logs).

In the results table, the sparkline column appears as a small line chart in each row. Hover over the chart to see the value of each time bucket. The API and exports return the column as an array of numbers, oldest bucket first.

Trend a different aggregation, or set the bucket size yourself:

stats sparkline(avg(duration), 5m) as latency_trend, count by workload
  • sparkline on its own is the same as sparkline(count).
  • The aggregation inside can be count, count(x), dc(x), sum(x), avg(x), min(x) or max(x).
  • The span is a number followed by s, m, h, d or w, such as 30s, 5m or 1h. If you leave it out, a span is chosen that gives about 30 points over the time range.
  • Buckets cover the whole time range. A bucket with no logs is 0.
  • Without an alias, the column is named sparkline, or sparkline_avg_duration for sparkline(avg(duration)).

info: sparkline works in stats only. To chart values over time, use timechart, which already returns one row per time bucket. A span that would give more than 1000 points over the selected time range is rejected, so pick a larger span or a shorter time range.

Examples:

stats count as total by level
stats count as requests, avg(duration) as avg_dur, p95(duration) as p95_dur by url
stats dc(pod_name) as active_pods, latest(level) as last_level by workload
stats count(eval(level="ERROR")) as errors, count as total by service | eval error_rate = errors / total

timechart

Aggregates per time bucket: one row per bucket, and per value of the by field.

Syntax:

timechart [span=<N><unit>] [options] <aggregation> [as <alias>] ... [by <field>] [options]

Span units: us, ms, cs (hundredths), ds (tenths), s, m, h, d, w, mon, q, y. Without span=, the span is chosen so the time range has at most 100 buckets (bins= changes the number). The bucket column is named _time.

OptionDefaultDescription
span=automaticBucket size, such as 5m or 1h
bins=100Most buckets an automatic span gives
minspan=Shortest span an automatic span may pick, such as 5m
aligntime=Where buckets start: earliest, latest or a time such as @d+30m. Applies to spans shorter than a day
limit=10Keep the N series with the largest totals; limit=0 keeps every series
agg=sumHow a series' total is computed from its first aggregation's values: sum, max, min, avg or count
useother=trueWith limit=, combine the remaining series as one OTHER series
otherstr=OTHERName of that series
usenull=trueKeep rows whose by field is empty; false drops them
cont=trueAdd the buckets with no logs, with a count of 0
fixedrange=trueAdd those buckets across the whole time range; false only between the first and last bucket with logs
partial=truefalse drops the first and last buckets when the time range covers them only in part

As in Splunk, timechart … by keeps the 10 largest series and combines the rest as OTHER. For counts and sums, OTHER is the sum of the other series; for other aggregations, such as avg or dc, it is computed again from their logs. format=, sep= and where= are not supported.

Results come back as one row per bucket and series (_time, the aggregations, the by field), not one column per series as in Splunk. Use chart or xyseries for a column per value. A timechart returns at most 10,000 rows unless you add head. As in Splunk, a span that splits the time range into more than 50,000 buckets is refused when cont=true: use a longer span or a shorter time range.

Examples:

timechart span=5m count as req_count
timechart span=1h count by level
timechart span=15m limit=5 avg(duration) as avg_latency by service
timechart minspan=1m limit=0 count by namespace
timechart span=1h per_second(bytes) as bytes_per_sec

dedup

Keeps the first N rows, in the current order, of each combination of the fields. On logs the current order is newest first, so dedup pod_name keeps each pod's latest log.

Syntax:

dedup [<N>] <field> ... [keepempty=<bool>] [consecutive=<bool>] [sortby [+|-]<field> ...]
OptionDefaultDescription
N1Rows to keep per combination
keepempty=falseKeep rows missing one of the fields (dropped by default)
consecutive=falseRemove only repeats of the row just before
sortbyWhich rows are kept, and the order of the result: dedup host sortby -duration keeps each host's longest request

Examples:

dedup pod_name
dedup 3 cluster namespace
dedup host sortby -_time

head / limit / tail

Syntax:

head [<N>] | head limit=<N> | head (<condition>) [keeplast=<bool>] [null=<bool>]
limit <N>
tail [<N>]
  • head N (and limit N) keeps the first N rows in the current order. Without a sort, log rows are newest first, so head 50 returns the 50 newest logs. N defaults to 10.
  • head (<condition>) keeps rows until the first row where the condition is false, however many there are; add a count (head 50 (…)) to stop sooner. keeplast=true also keeps that row. A condition that cannot be evaluated (a field is missing) counts as false; null=true counts it as true.
  • tail N keeps the last N rows, returned last first. On log rows that is the N oldest, oldest first.

Without head, limit or tail, a query returns at most 1000 rows.


sort

Orders rows by one or more fields. A sort applies to the commands after it: sort -count | head 5 takes the top five.

Syntax:

sort [<N> | limit=<N>] [+|-]<field> [asc|desc], ...
  • -field or field desc sorts descending; +field, field asc or nothing sorts ascending.
  • Fields are separated by commas or spaces.
  • sort N keeps the first N rows after sorting.
  • num(field), str(field) and ip(field) sort as numbers, text or IP addresses. Attributes and fields made from them sort numbers numerically first, then text, as Splunk's default does.

Examples:

sort -_time
sort level, -_time
stats count by workload | sort 10 -count
sort ip(client_ip)

rename

Renames columns. The old name still works in later commands.

Syntax:

rename <field> as <new>[,] <field> as <new> ...

Wildcards rename every matching column: rename *_ms as *_millis, rename *_duration as *, or rename * as old_* for every column.

Example:

stats count as c by level
| rename c as event_count, level as severity

table

Returns exactly the listed columns, in order. Fields are separated by commas or spaces and may use * wildcards: table * keeps every column, table host, * puts host first, and table http.* keeps the columns whose names start with http.. A column is listed once. Wildcards match the result's columns: on log events, the built-in fields and the fields the query made, not every attribute.

Example:

level=error
| table _time pod_name namespace body

top / rare

Returns the most (top) or least (rare) common values of fields, with a count and a percent column. With by, the limit applies to each group.

Syntax:

top [<N>] <field> ... [by <field> ...] [options]
rare [<N>] <field> ... [by <field> ...] [options]
OptionDefaultDescription
limit=10Values to return (same as N)
countfield=countName of the count column
percentfield=percentName of the percent column
showcount=trueReturn the count column
showperc=trueReturn the percent column
useother=falseAdd one OTHER row for the remaining values
otherstr=OTHERName of that row's value

Examples:

top 5 namespace
top 3 url by cluster
top limit=10 user useother=t
rare 3 pod_name
top 10 workload | where percent > 5

Practical Examples

Find Recent ERROR Logs

level=error
| head 50

Error Count by Service Over Time

level=error
| timechart span=10m count as errors by service

Top Slow API Endpoints

duration=*
| stats count as requests, avg(duration) as avg_dur, p95(duration) as p95 by url
| where requests > 10
| sort -p95
| head 20

Extract Structured Data with parse

parse body '"requestId":"*"' as request_id
| parse body '"statusCode":*,' as status_code
| where status_code != "200"
| table _time, request_id, status_code, body

Extract HTTP Method and Path with rex

rex "(?<method>[A-Z]+) (?<path>/[^ ]*) HTTP/[0-9.]+"
| stats count as hits by method, path
| sort -hits
| head 25

Compute a Risk Score with eval

eval severity_score = case(level = "ERROR", 3, level = "WARN", 1, true(), 0)
| stats sum(severity_score) as risk, count as total by workload
| eval risk_per_event = risk / total
| sort 15 -risk_per_event

Latest Error per Pod

level=error
| dedup pod_name
| table _time, pod_name, namespace, body

Search Text and Extract Latency

"KYC" "request time:"
| parse @message 'request time: * ms;' as latency
| timechart span=1m avg(latency) as avg_latency

Full Pipeline — Server Error Analysis

status IN (500, 502, 503, 504)
| eval is_timeout = if(status = 504, 1, 0)
| stats count as errors, sum(is_timeout) as timeouts, avg(duration) as avg_dur by url
| where errors > 5
| eval timeout_rate = timeouts / errors
| sort 10 -timeout_rate

Count Failed Requests by Message

"Request failed"
| stats count as failures by @message

Error Rate with a Share of Total

stats count(eval(level="ERROR")) as errors, count as total by workload
| eventstats sum(errors) as all_errors
| eval error_rate = errors / total, share = round(100 * errors / all_errors, 1)
| sort -error_rate

Performance Tips

  • Narrow your time range. Select the smallest window you need in the Log Explorer.
  • Search first. Field comparisons and text searches at the start of a query, before any eval, stats or sort, are applied while ClickHouse reads the logs and can use its indexes. The same condition after other commands has to read every log first.
  • Use tstats for counts over long ranges. It reads the pre-aggregated log tables instead of every log line. See Lookups and tstats.
  • Aggregate rather than return raw rows. For large datasets, use stats or timechart, and add head to raw-row queries.
  • Query timeout. Queries have a 300-second timeout.

Error Reference

If your SPL query fails, the Log Explorer shows an error message. Common error conditions include:

ErrorDescription
Parse errorSyntax error in your query — check for missing quotes, unbalanced parentheses or brackets, or invalid operators. unknown pipeline command also appears when several unquoted words start a query: start it with search. Text left over after a command, such as a missing `
Translation errorThe query is valid but cannot run as written, for example predict without a timechart before it
Execution errorThe query ran but encountered a runtime error (e.g., type mismatch, division by zero)
Query timeoutThe query exceeded the 300-second timeout — narrow your time range or add aggregation

On this page