Iniciar sesión

Custom patterns and optional parts

15 min · 2 ejercicio(s)

When no built-in pattern fits, write your own with a named capture group from regular expressions:

(?<order_id>ORD-\d{4}-\d{6})

(?<name>regex) works everywhere Grok works and can be mixed with %{…} patterns:

FROM lab-raw
| WHERE event.dataset == "kestrel.shop"
| GROK message """order_id=(?<order_id>ORD-\d{4}-\d{6}) customer=(?<customer>cust-\d+)"""
| KEEP @timestamp, order_id, customer

Optional parts

The sshd log writes failed logons in two flavours:

Failed password for root from 185.220.101.47 port 41822 ssh2
Failed password for invalid user oracle from 61.22.174.96 port 52570 ssh2

A non-capturing group with ? makes the words optional:

Failed password for (?:invalid user )?%{USERNAME:user} from %{IP:source_ip}

(?:…) groups without creating a field, the ? after it means "zero or one time".

Alternatives

| inside a group means or: Accepted (?:password|publickey) for. To capture which one matched, give the group a name: Accepted (?<method>password|publickey) for.

Custom pattern definitions in pipelines

In an ingest pipeline you can define reusable names with pattern_definitions and use them like built-in ones:

{
  "grok": {
    "field": "message",
    "pattern_definitions": { "ORDERID": "ORD-\\d{4}-\\d{6}" },
    "patterns": ["order_id=%{ORDERID:shop.order_id}"]
  }
}

ES|QL has no pattern_definitions, there you write the named group inline.

🔎 Profundiza: funciones, errores habituales y práctica

Grok uses the Oniguruma regex engine

The flavour is close to Perl/PCRE: \d, \w, \s, character classes [a-f0-9], quantifiers {4}, {1,3}, +, *, ?, lazy quantifiers +?, anchors ^ $, groups and alternation. Look-ahead works too, but rarely pays off in log parsing.

Keep custom patterns tight

(?<order_id>ORD-\d{4}-\d{6}) is better than (?<order_id>ORD-\S+): it documents the format and fails loudly when the application changes it. A pattern that silently matches garbage is worse than one that doesn't match.

Several patterns for one source

Real sources mix line types. An ingest pipeline's grok processor accepts a list of patterns and uses the first one that matches, so put the most specific first. In ES|QL you either filter the line type first (WHERE message LIKE "*Accepted*") and use one pattern per query, or you build one pattern with optional groups as above.

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. A pattern of your own

    Order IDs have the format ORD-<year>-<six digits>, for example ORD-2026-004321. No built-in pattern describes that. Write a named capture group that extracts the ID into order_id, wherever it appears in the line.

  2. 2. Valid and invalid accounts

    Failed SSH logons come in two flavours:

    … sshd[2211]: Failed password for root from 185.220.101.47 port 51234 ssh2
    … sshd[27460]: Failed password for invalid user ubuntu from 112.22.254.249 port 58777 ssh2

    Write one pattern that extracts user.name and source.ip from both.