Iniciar sesión

EVAL and CASE

12 min · 1 ejercicio(s)

EVAL adds calculated columns. You can use them in later commands like any other column:

FROM lab-endpoint
| WHERE event.category == "network"
| EVAL mb = ROUND(source.bytes / 1048576.0, 1)
| KEEP @timestamp, host.name, destination.ip, mb

CASE takes condition/value pairs and an optional default. It is great for labelling:

FROM lab-endpoint
| WHERE event.category == "network"
| EVAL zone = CASE(
    CIDR_MATCH(destination.ip, "10.0.0.0/8"), "internal",
    destination.port == 443, "web",
    "other")
| STATS connections = COUNT(*) BY zone

Watch the integer division: source.bytes / 1048576 divides two integers and drops the decimals. Use 1048576.0 or TO_DOUBLE() to get decimals.

Aggregate first, then calculate

EVAL also works after STATS. Sum the raw bytes per group and convert only the result:

… | STATS bytes = SUM(source.bytes) BY destination.ip
  | EVAL mb = bytes / 1048576

🔎 Profundiza: funciones, errores habituales y práctica

EVAL in practice

  • Several expressions in one command: EVAL mb = bytes / 1048576, gb = mb / 1024.
  • Overwrite a column by reusing its name: EVAL user.name = TO_LOWER(user.name).
  • Without a name the expression itself becomes the column name, which is hard to use later. Always name your columns.

Conditional functions

Function Example
CASE(cond1, v1, cond2, v2, default) classify ports, zones, risk scores
COALESCE(a, b, c) first non-null value: COALESCE(user.name, "unknown")
GREATEST(a, b), LEAST(a, b) larger/smaller of several values

Type conversion

TO_STRING, TO_INTEGER, TO_LONG, TO_DOUBLE, TO_IP, TO_DATETIME, TO_BOOLEAN. Shorthand: field::long. Integer division drops decimals (5 / 2 = 2), so convert one side to double when you need precision.

Scoring example

FROM lab-endpoint
| WHERE event.category == "process"
| EVAL score = CASE(process.name IN ("rundll32.exe", "regsvr32.exe"), 30, 0)
             + CASE(process.command_line LIKE "*-enc*", 40, 0)
             + CASE(process.parent.name IN ("WINWORD.EXE", "EXCEL.EXE"), 30, 0)
| WHERE score >= 40
| SORT score DESC

Simple additive scores like this are a common way to prioritise hunting leads.

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

    Calculate the total transferred megabytes (source.bytes / 1048576) per destination.ip in lab-endpoint and return only destinations with more than 1,000 MB. Graded by the destination.ip values.