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, customerOptional 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 ssh2A 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.