WHERE and SORT
12 min · 2 ejercicio(s)
Filtering with WHERE
WHERE keeps rows for which a boolean expression is true. ES|QL uses == for equality, !=, <, >, <=, >=, and the keywords AND, OR, NOT. Strings are in double quotes.
FROM lab-auth
| WHERE event.outcome == "failure" AND service.name == "ssh"Useful operators for security data:
| Operator / function | Example |
|---|---|
IN |
WHERE process.name IN ("whoami.exe", "net.exe") |
LIKE (wildcards * and ?) |
WHERE user_agent.original LIKE "sqlmap*" |
RLIKE (regular expression) |
`WHERE url.query RLIKE ".*(UNION |
IS NULL / IS NOT NULL |
WHERE url.query IS NOT NULL |
CIDR_MATCH |
WHERE NOT CIDR_MATCH(destination.ip, "10.0.0.0/8") |
TO_LOWER |
WHERE TO_LOWER(process.name) == "powershell.exe" |
Sorting
SORT orders rows, ascending by default. Add DESC for descending order. Several sort keys are separated by commas:
FROM lab-web
| WHERE http.response.status_code >= 500
| SORT @timestamp DESC
| LIMIT 5Order matters.
SORT … | LIMIT 1gives you the top row.LIMIT 1 | SORT …takes an arbitrary row and then sorts a table of one.
🔎 Profundiza: funciones, errores habituales y práctica
Operators and their null behaviour
| Expression | Note |
|---|---|
a == b, a != b |
case sensitive for strings; null == null is null, not true |
a IN (x, y) |
short form of several == |
a LIKE "x*" |
wildcards * and ?, case sensitive |
a RLIKE "regex" |
full regular expression (Lucene syntax, anchored to the whole value) |
a IS NULL |
the only correct way to test for missing values |
a : "text" |
full-text match function (MATCH), uses the field's analyzer |
Comparisons with null return null and the row is dropped by WHERE. WHERE NOT user.name == "x" therefore also removes rows without a user. Add OR user.name IS NULL if you want to keep them.
Case-insensitive comparisons
WHERE TO_LOWER(process.name) == "powershell.exe" works on any field. Newer versions also accept LIKE/RLIKE with case-insensitive variants. Check the docs of your version.
Sorting rules
SORT field DESC NULLS LASTcontrols wherenullends up.- Sorting needs memory. Combine
SORTwithLIMITso Elasticsearch only keeps the top N rows ("top-N" optimisation). - Put
WHEREas early as possible: filters directly afterFROMare pushed down to the search engine and use the index.