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:
- Functions: every
evalandstatsfunction. - More Commands:
bin,chart,eventstats,streamstats,fillnull, multivalue fields and more. - Combining Searches: subsearches,
append,join,transaction,foreach. - Lookups and tstats: reference tables and fast counts over long time ranges.
- Analysis Commands:
outlier,anomalydetection,predict,cluster,timewrap. - Differences from Splunk: what works differently, and what is not supported.
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 50This 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_rateThis 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, codeBuilt-in Field Names
SPL provides built-in names for your log columns. Use them in any command:
| Name | Description |
|---|---|
_time / @timestamp / timestamp | Log event time (UTC) |
_raw / @message / body | The log message text |
level | Log severity (ERROR, WARN, INFO, etc.) |
cluster | Kubernetes cluster name |
namespace | Kubernetes namespace |
workload | Workload name (Deployment, StatefulSet, etc.) |
pod_name | Pod name |
container_name | Container name |
host | Node hostname |
service | Service name |
source | Log source identifier |
node_name | Kubernetes node name |
env_type | Environment type |
_indextime | When 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 urlfields @timestamp, url, status, duration
| where duration > 1000stats avg(duration) as avg_duration by http.methodResults 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:
- Built-in fields win. A name from the table above always refers to that column.
- Names your query creates win next. An
evaltarget, afields … asorstats … asalias, a default aggregate name such ascountoravg_duration, aparseorrexcapture, or arenametarget refers to that value. - Anything else is an attribute.
region=us-eastreads theregionattribute.
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 levelThis 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.methodreadshttp.method, whilelp_http_methodreads an attribute calledhttp_method. - The result column is named
lp_level. Addasto 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,
statusandlp_statusread 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 write | It matches |
|---|---|
timeout | Logs 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=error | level equal to error, ERROR or Error (see below) |
host=web-* | host starting with web- (* is a wildcard) |
status=* | Logs that have a status |
status!=200 | Logs that have a status other than 200 |
NOT status=200 | Logs whose status is not 200, including logs without one |
duration>=500 | Numeric comparison when the value is a number |
user IN (alice, "bob smith") | Any of the values |
10.0.0.1, ip=10.0.0.1 | IP addresses and other dotted values need no quotes |
a b / a AND b | Both |
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=now | Narrows the time range (see below) |
index=main | Ignored: 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, solevel=errorfindserror,ERRORandError; this keeps the search on the fields' indexes. A value written in mixed case elsewhere, such aseRRor, matches only exactly. Attribute values match in any case.whereandfiltercompare exactly. - A query that starts with a search needs no
searchkeyword 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 withsearch:search error timeout. This keeps a mistyped command, such asstat count, an error rather than a text search. searchcan 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 @:
| Time | Means |
|---|---|
-24h | 24 hours ago |
-7d@d | Midnight 7 days ago |
@d | Midnight today |
@w1 | Midnight on the most recent Monday (@w0 is Sunday … @w6 Saturday) |
@h+30m | Half 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
| Command | Description |
|---|---|
search | Find logs with Splunk search syntax (see Searching) |
where / filter | Keep rows where an expression is true |
fields | Choose the columns to return, compute or remove columns |
table | Return exactly the listed columns |
eval | Compute columns (functions) |
rex / parse | Extract fields with a regular expression or a glob pattern |
rename | Rename columns |
stats | Aggregate, optionally grouped by fields |
timechart | Aggregate per time bucket |
top / rare | Most or least common values |
dedup | Remove repeated values |
sort | Order the rows |
head / limit / tail | First 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, fieldformat | See More Commands |
[subsearch], append, appendcols, appendpipe, union, multisearch, set, join, selfjoin, map, transaction, foreach, return, format, eventcount, gentimes | See Combining Searches |
lookup, inputlookup, tstats | See Lookups and tstats |
outlier, anomalydetection, predict, cluster, timewrap | See 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:
| Operator | Description | Example |
|---|---|---|
= / == | Equal | level = "ERROR" |
!= / <> | Not equal | level != "DEBUG" |
<, >, <=, >= | Comparisons; numeric when one side is a number | duration > 1000 |
and / or / not / ! | Logical connectives | level = "ERROR" and namespace = "prod" |
in (v1, v2, ...) / in [v1, v2, ...] | Membership | level in ("ERROR", "WARN") |
like "pattern%" | SQL LIKE pattern | body 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 > 100A 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, restrex
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=Nextracts up to N matches into a multivalue field;max_match=0extracts every match.mode=sededits the field in place:s/regex/replacement/replaces the first match (greplaces every match, and\1puts back a group), andy/abc/xyz/replaces characters.
Examples:
rex field=_raw "(?<method>[A-Z]+) (?<path>/[^ ]*) HTTP/[0-9.]+"
| stats count as hits by method, path
| sort -hitsrex 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 hostThis returns one row per host with a count column. Add as to name the column yourself:
stats count as total by level| You write | It counts | Column name |
|---|---|---|
count / c | Every row | count |
count(*) | Every row | count |
count(x) | Rows that have a value for x | count_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 levelinfo: 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 hostThis 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 workloadsparklineon its own is the same assparkline(count).- The aggregation inside can be
count,count(x),dc(x),sum(x),avg(x),min(x)ormax(x). - The span is a number followed by
s,m,h,dorw, such as30s,5mor1h. 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, orsparkline_avg_durationforsparkline(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 / totaltimechart
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.
| Option | Default | Description |
|---|---|---|
span= | automatic | Bucket size, such as 5m or 1h |
bins= | 100 | Most 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= | 10 | Keep the N series with the largest totals; limit=0 keeps every series |
agg= | sum | How a series' total is computed from its first aggregation's values: sum, max, min, avg or count |
useother= | true | With limit=, combine the remaining series as one OTHER series |
otherstr= | OTHER | Name of that series |
usenull= | true | Keep rows whose by field is empty; false drops them |
cont= | true | Add the buckets with no logs, with a count of 0 |
fixedrange= | true | Add those buckets across the whole time range; false only between the first and last bucket with logs |
partial= | true | false 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_secdedup
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> ...]| Option | Default | Description |
|---|---|---|
N | 1 | Rows to keep per combination |
keepempty= | false | Keep rows missing one of the fields (dropped by default) |
consecutive= | false | Remove only repeats of the row just before |
sortby | Which 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 -_timehead / limit / tail
Syntax:
head [<N>] | head limit=<N> | head (<condition>) [keeplast=<bool>] [null=<bool>]
limit <N>
tail [<N>]head N(andlimit N) keeps the first N rows in the current order. Without asort, log rows are newest first, sohead 50returns 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=truealso keeps that row. A condition that cannot be evaluated (a field is missing) counts as false;null=truecounts it as true.tail Nkeeps 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], ...-fieldorfield descsorts descending;+field,field ascor nothing sorts ascending.- Fields are separated by commas or spaces.
sort Nkeeps the first N rows after sorting.num(field),str(field)andip(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 severitytable
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 bodytop / 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]| Option | Default | Description |
|---|---|---|
limit= | 10 | Values to return (same as N) |
countfield= | count | Name of the count column |
percentfield= | percent | Name of the percent column |
showcount= | true | Return the count column |
showperc= | true | Return the percent column |
useother= | false | Add one OTHER row for the remaining values |
otherstr= | OTHER | Name 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 > 5Practical Examples
Find Recent ERROR Logs
level=error
| head 50Error Count by Service Over Time
level=error
| timechart span=10m count as errors by serviceTop 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 20Extract 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, bodyExtract HTTP Method and Path with rex
rex "(?<method>[A-Z]+) (?<path>/[^ ]*) HTTP/[0-9.]+"
| stats count as hits by method, path
| sort -hits
| head 25Compute 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_eventLatest Error per Pod
level=error
| dedup pod_name
| table _time, pod_name, namespace, bodySearch Text and Extract Latency
"KYC" "request time:"
| parse @message 'request time: * ms;' as latency
| timechart span=1m avg(latency) as avg_latencyFull 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_rateCount Failed Requests by Message
"Request failed"
| stats count as failures by @messageError 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_ratePerformance 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,statsorsort, 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
tstatsfor 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
statsortimechart, and addheadto 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:
| Error | Description |
|---|---|
| Parse error | Syntax 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 error | The query is valid but cannot run as written, for example predict without a timechart before it |
| Execution error | The query ran but encountered a runtime error (e.g., type mismatch, division by zero) |
| Query timeout | The query exceeded the 300-second timeout — narrow your time range or add aggregation |