Iniciar sesión

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 5

Order matters. SORT … | LIMIT 1 gives 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 LAST controls where null ends up.
  • Sorting needs memory. Combine SORT with LIMIT so Elasticsearch only keeps the top N rows ("top-N" optimisation).
  • Put WHERE as early as possible: filters directly after FROM are pushed down to the search engine and use the index.

Ejercicios prácticos de esta lección

Resuelve estos ejercicios con una consulta en el laboratorio Elasticsearch real. Inicia sesión gratis para acceder al laboratorio, las pistas y la corrección automática.

  1. 1. The largest response

    Which url.path produced the single largest response (http.response.body.bytes) in lab-web?

  2. 2. First foothold

    Return all successful logons from outside 10.0.0.0/8 via ssh, newest first. Keep at least the columns @timestamp, user.name and source.ip. Graded by the source.ip values.