Enrich
Synopsis
Enriches documents by performing SQL queries against lookup tables loaded from CSV files. It can then join the data with externally referenced information to add context and semantic depth.
Schema
- enrich:
lookup_table: <string[]>
dataset_name: <string[]>
query: <string>
type: <string>
database_file: <string>
description: <text>
if: <script>
tag: <string>
on_success: <processor[]>
on_failure: <processor[]>
override: <boolean>
ignore_missing: <boolean>
ignore_failure: <boolean>
Configuration
The following fields are used to define the processor:
| Field | Required | Default | Description |
|---|---|---|---|
lookup_table | N | - | Array of paths to CSV files containing lookup data |
dataset_name | N | - | Has no effect. The names are accepted, but the step doesn't read them: no dataset is loaded and no error is raised. Use lookup_table instead |
query | Y | - | SQL or KQL query to execute for enrichment |
type | N | - | Query language: kusto for KQL, sql for SQL. Left empty, the language is told from the query. See Choosing the Language |
database_file | N | - | MaxMind GeoIP2 or GeoLite2 City database that KQL's geo_info_from_ip_address() reads. See IP Address Locations |
description | N | - | Explanatory note |
if | N | - | Condition to run |
ignore_failure | N | false | Continue processing if enrichment fails |
ignore_missing | N | false | Skip if fields don't exist |
on_failure | N | - | Processors to run on failure |
on_success | N | - | Processors to run on success |
override | N | false | If true, replaces existing document with query results |
tag | N | - | Identifier for logging |
disabled | N | false | When true, the processor is skipped and the event continues to the next one. Lets you take a processor out of the path without removing its configuration |
Details
Information gathering from external sources involves
- loading lookup data from CSV files, which may involve using SQL or Kusto Query Language (KQL) queries,
- extracting and manipulating JSON data, overriding fields, and
- resolving conflicts.
Queries run on Search, the same engine as OmniSearch, on Directors and on Agents. SQL runs in the engine's PostgreSQL-flavoured dialect. KQL runs on OmniSearch's own KQL, which reads column types as Azure Data Explorer (ADX) does.
The processor provides the following special tables and fields for queries:
_ingest | Contains the current document's data |
_message | JSON string of the entire document |
lookup_table | Contains data loaded from CSV files |
CSV files must have headers in the first row as the column names become field names in queries. Fields are separated by commas. A record with fewer fields than the header has empty (NULL) values in the rest, and the fields of a record past the header's are left out. When lookup_table names several files, their rows form one table: the first file's header names its columns, and every later file's header must name some of those columns. A column a file doesn't have is NULL in that file's rows.
As large CSV files are loaded directly into memory, the impact of using very large lookup tables must be carefully considered.
Choosing the Language
type: kustoruns the query as KQL.type: sqlruns it as SQL.- With no
type, the engine tells KQL from SQL by reading the query.
SQL Follows PostgreSQL's Rules
SQL runs in the engine's PostgreSQL-flavoured dialect, not SQLite's. A query written for SQLite may need changes:
- A double-quoted string is a column name. A text value needs single quotes:
'Yusuf Ozturk', not"Yusuf Ozturk". typeof()names types as the engine does, such asBOOLEAN,VARCHAR,BIGINTandTIMESTAMP_NS.json_extract(_message, '$.a')gives a JSON value. To compare it with text, as in a join key, usejson_extract_string(_message, '$.a').LIKEis case-sensitive. UseILIKEfor a match in any case.
Times Are Timestamps
A time field is a timestamp, not text. SQLite's text functions on a time give way to the engine's:
| Before | Now |
|---|---|
substr(ts, 1, 4) | extract(year from ts) |
strftime('%H', ts) | extract(hour from ts), or strftime(ts, '%H'), with the arguments in that order |
datetime(ts, '+1 hour') | ts + INTERVAL '1 hour' |
The enrich step has no to_char().
A time outside UTC keeps its instant: a time of 10:20+03:00 comes back as 07:20Z. In earlier releases, it came back as 10:20Z.
KQL Checks Types as ADX Does
A comparison of a string field with a number fails for that record, as it would in ADX, unless the query converts one side with tolong() or tostring(). See When a Record's Values Make the Query Fail.
The functions that read a datetime take a datetime, not a string or a dynamic value, as in ADX. They are dayofweek(), dayofmonth(), dayofyear(), weekofyear(), week_of_year(), getyear(), getmonth(), monthofyear(), hourofday(), the startof...() and endof...() functions, datetime_part(), datetime_add(), datetime_diff(), format_datetime(), datetime_utc_to_local() and datetime_local_to_utc().
| The argument | Result |
|---|---|
| a datetime | The function's answer |
| a string field, a string literal or a dynamic value | Refused: dayofweek() takes a datetime, not a string: convert it with todatetime() |
A record's time field that arrives as text is a string, so a query that reads it with one of these functions converts it first: dayofweek(todatetime(event_time)). The refusal comes when the query runs on a record, so the record goes on without the enrichment, as in When a Record's Values Make the Query Fail.
KQL Gives ADX's Answers
A KQL query gives the answer ADX gives. In earlier releases, the step translated KQL into SQLite's SQL, and some answers differed. A query that meets one of the cases below can write other values after the upgrade.
Missing values. ADX's strings are never null: a missing string is "". For a number x that is null:
| KQL | Answer |
|---|---|
where x != 5, where not(x == 5), where x !in (1, 2) | Keeps the row |
countif(x != 5) | Counts the row |
x == 5, x != 5, as values | false and true, not null |
iff(x != 5, a, b) | a |
max_of(x, 3), min_of(x, 3) | 3: the null is left out |
isempty(d.a), isnotempty(d.a), where d.a is a JSON null | true and false |
tostring(d.missing) | "", so == "" and contains "" are true |
Text.
| KQL | Answer |
|---|---|
"a_log" has "log" | true. A term is a run of letters and digits of any script. Every other character separates terms, an underscore among them |
"blog" has "log" | false: has matches whole terms |
"a_log" hasprefix "lo" | true: hasprefix reads the start of any term |
"ÖZTÜRK" contains "öz" | true: case is ignored as ADX ignores it, in every script |
"IŞIK" =~ "ışık", "İSTANBUL" =~ "istanbul" | false, as in ADX |
tolower("IŞIK"), toupper("ışık") | "işik", "IŞIK" |
s contains "%" | true only when s holds a % |
contains_cs, startswith_cs, endswith_cs | Match case |
\w, \d and \s in matches regex and extract() | Match letters, digits and spaces of any script |
has_any (L), has_all (L), in (L), where L is a dynamic array or a let bound to one | Read the array's items, nested arrays included |
Tables, summarize and joins.
| KQL | Answer |
|---|---|
union of tables whose columns differ | Columns are paired by name. A name with two types gets a column for each type, such as a_long and a_string, with a number added where that name is taken (a_string1). A missing string column is "", any other null. kind=inner keeps the columns that every table has |
summarize arg_max(T, c) by k | T's greatest value and the c of its row. arg_min() likewise |
summarize arg_max(T, *) by k | The whole row of the greatest T in each group. Ties take the first row, and a group whose T is always null gives its first row |
summarize Latest = arg_max(T, *) by k | The same row, with T's column named Latest |
summarize arg_max(T, *), c = count() by k | The row, with the other aggregate beside it |
tostring(arg_max(T, c)) | ADX's array of the row's values, such as ["2024-01-02T00:00:00.0000000Z","2.2.2.2"] |
join kind=rightsemi | Each right-side row that has a match, once, with the right side's columns |
join kind=rightanti | Each right-side row that has no match |
project-away, project-rename | Work over every column |
datatable() [] | A table with no columns and no rows |
A name may begin with digits, as in ADX: a column such as 5Minutebin, or a table bound with let 5Events = .... mvexpand and mvapply are read as mv-expand and mv-apply.
Summarize keys. A key with no name of its own gets the name ADX gives it:
| Key | Column name |
|---|---|
tostring(s), (s), bin(t, 1h), tostring(column_ifexists("s", "")) | The column's own name: s, t |
strlen(s) | strlen_s |
tostring(d.a) | d_a |
toupper(s), n % 2, n > 2, 5 | Column1, then Column2 and so on |
parity = k % 2, bin(T = t, 1h) | The name the query gives: parity, T |
- A name that an earlier column already has gets a number added:
summarize count(), count() by kgivescount_andcount_1. - A numbered name skips a name that a column of the rows already has. After
extend Column1 = 5, the first unnamed key isColumn2. - In earlier releases, some keys had other names. A later step that reads such an enriched field must read it under the name above.
Numbers, lists and times.
| KQL | Answer |
|---|---|
9223372036854775807 + 1 | -9223372036854775808: long arithmetic wraps around |
toint("abc"), tolong("12.7") | null |
toint(" 12 "), toint("0x10") | 12, 16 |
toint(2147483648) | -2147483648: toint() keeps 32 bits |
split("ali@x.com", "@")[1] | "x.com". A part past the end is null |
d[1], d[-1], d.a[0], d["user name"] | The element. d[-1] is the last one |
parse_json(s).a | The value at the path. Null for text that isn't JSON |
extract("id=(\\d+)", 1, s) | The group's text. "" when nothing matches, or null with typeof(int) |
floor(t, 1h) of a datetime | t rounded down, as bin() rounds it |
bin(-7, 2) | -8 |
hourofday(t) > 18 | Compares numbers |
dayofweek(d) == 1d | true on a Monday |
bin(T, 1min), bin(T, 1hour) | The timespans 1m and 1h. ADX's long unit names are read, in lower case |
Lookup Table Columns Have Types
The engine infers each lookup column's type from all of its rows, as ADX tables have types. A KQL query can join or compare a long field with a lookup column of numbers without tostring(). When the files of one lookup table disagree on a column's type, that column is text, and the other columns keep their types.
Values Written Back
Each value a query returns is written to the document as what it is:
| Value | Written as |
|---|---|
| bool | true or false. In earlier releases, SQL wrote 1 or 0. |
| bag or array | A real object or list. A list field the query returns unchanged comes back as the list, not as text such as [a b]. |
| datetime | A time, with its fraction of a second. |
| timespan | Its seconds: 1h is 3600, 1.5s is 1.5. |
| dynamic string or number | That string or number. |
| decimal | A whole decimal exactly, as a whole number. Any other decimal as a floating-point number. |
| null | No field. |
Reloading Lookup Tables
The processor loads the files lookup_table names when the first record reaches it. An edited file is picked up without restarting the pipeline:
- As records arrive, and at most once every 5 seconds, the processor checks each file's modification time and size. When either has changed, it loads the files again. A processor that receives no records checks nothing.
- When a reload fails, for example because a file is briefly missing or cannot be read as CSV, the table loaded last keeps answering queries, and the next check loads the files again.
- A file read while it is being rewritten can also load only in part. Its modification time or size changes again when the write ends, so the next check loads it whole. To avoid that window, write the new file under another name and rename it over the old one.
- When the first load fails, there is no table to fall back on. Each record fails as on any other processor error:
ignore_failureandon_failureapply. The first record that arrives 5 seconds or more after the failure tries the load again. - Enrich processors that name the same files in the same order share one loaded copy, across every pipeline the same Director or Agent runs. The memory warning above therefore applies once per distinct list of files, not once per processor.
- Each enrich processor queries the files its own
lookup_tablenames, also when one pipeline contains several. In earlier releases, every enrich processor in a pipeline queried the table the first one had loaded.
When the Query Can't Run
Some queries can't run whatever the record. That is the case when Search, the engine that runs enrich queries, can't prepare the query, KQL or SQL, for example because of a syntax error. The step then does not fail the records:
| What | What happens |
|---|---|
| Records | Unless the step has an on_failure of its own (see the last row), each record goes on without the enrichment, through the rest of the pipeline. The pipeline's on_failure doesn't run for it, so the default error handler doesn't drop it. |
| Log | One Error each time the configuration loads, naming the pipeline, the step (its tag, its description or the start of its query) and the reason. Not one per record. |
| Pipeline metrics | With stats_pipeline_metrics on, enrich_query_unusable counts each record that the step couldn't enrich this way. Its value shows how much data went on without the enrichment. |
| Debugger | A test run shows a step without an on_failure of its own as skipped, with the reason as its error. |
ignore_failure: true | The record goes on, as before. |
The step's own on_failure | Its processors run for each record, as before, with the _ingest.on_failure_* fields set. After them, the failure goes on to the pipeline's on_failure, as for any processor, unless the chain ends with recover. |
A step's own on_failure that doesn't end with recover doesn't save the record. After the step's on_failure processors run, the record still goes on to the pipeline's on_failure, and the pipeline's default on_failure drops it. This is the rule for every processor, not only enrich. To keep the records, end the step's on_failure with recover, or leave out the step's on_failure: a step without one lets the records go on by itself.
In earlier releases, a step whose query couldn't run failed every record that reached it, and a pipeline with no on_failure of its own dropped those records, with an Error logged for each one. After the upgrade, those records reach their targets without the enrichment.
When a Record's Values Make the Query Fail
A query can also fail on one record's values, such as a string field compared with a number in KQL. Unless the step has an on_failure of its own, such a record goes on without the enrichment, and the pipeline doesn't drop it:
| What | What happens |
|---|---|
| Records | Unless the step has an on_failure of its own, the record goes on without the enrichment, through the rest of the pipeline. The pipeline's on_failure doesn't run for it. |
| Log | One Warning each time the configuration loads, naming the pipeline, the step and why the first such record failed. Not one per record. |
| Pipeline metrics | With stats_pipeline_metrics on, enrich_record_failed counts each such record. |
The step's own on_failure | Its processors still run for such a record, as in When the Query Can't Run. After them, the failure goes on to the pipeline's on_failure, which drops the record by default, unless the chain ends with recover. |
A lookup table that can't be loaded, such as a file that isn't there, is no fault of the record's values. It still fails the record as before: the step's on_failure runs, or the pipeline's, which drops the record by default. See Reloading Lookup Tables.
Running on Agents
The processor runs on Agents as well as on the Director, in every pipeline an Agent runs, preprocessing pipelines included.
- Lookup tables.
lookup_tablepaths are read on the host that runs the pipeline: on an Agent, the Agent's own host. The Director does not send these files. A table kept in the Library reaches an Agent through the Lookup processor instead. - SQL queries run on an Agent as they do on the Director.
- KQL queries run on the Agent itself, on OmniSearch's KQL, as they do on the Director. The Agent needs version 2.8.0 or later for that.
- An Agent older than 2.8.0 can't run a KQL enrich step behind a 2.8.0 Director. Such an Agent ran KQL as SQL that its Director translated for it, and a 2.8.0 Director no longer translates it. Each record then fails the step with the error the director sent no SQL for this KQL enrich query. The step's
ignore_failureandon_failureapply, and a pipeline without anon_failureof its own drops the record. The Director logs a Warning that names the Agent and its pipelines with a KQL enrich step. Upgrade such an Agent together with its Director.
Spatial Functions
A KQL query can call two spatial functions:
geo_distance_2points(lon1, lat1, lon2, lat2)gives the distance in meters on KQL's sphere of 6,371,010 meters.geo_point_in_polygon(lon, lat, polygon)takes a GeoJSONPolygonorMultiPolygonwritten in the query. Its edges are straight lines in longitude and latitude, while KQL defines them as the shortest paths on the earth, so near a long edge the answer can differ.
Both give NULL for a longitude outside -180 to 180 or a latitude outside -90 to 90.
Spatial functions run on the Director, not on Agents. See Geometry and Geography for the SQL types and functions behind them.
IP Address Locations
A KQL query can call geo_info_from_ip_address(ip) when its step names a GeoIP database in database_file. It gives a dynamic value, as ADX's function does:
| The address | Result |
|---|---|
| An address the database places | A property bag of country, state, city, latitude and longitude, in that order. A name the database doesn't give is left out. Names are in English. |
An address the database places nowhere, such as a private address (10.1.2.3) | An empty bag, {} |
Text that isn't an IP address: empty, with a space, a port or a prefix (8.8.8.8:53, 8.8.8.0/24), or with a leading zero | null |
An IPv4 address written as IPv6 (::ffff:8.8.8.8) | The IPv4 address's place |
The function takes a string. A number or a dynamic value is refused, as ADX refuses it.
The places come from the configured database, not from ADX's. The same address can give another city, or other coordinates, than ADX gives. A newer database file can also change an address's answer.
database_file names the database as the Geo IP processor's database_file does:
| Value | Result |
|---|---|
A file name, such as GeoLite2-City.mmdb | The file in the package's database directory |
| A path | That file |
| A path, in a debug or test run (the pipeline debugger) | Refused: database_file "..." must be a file name, not a path, in a debug or test run |
| Not set | No database. A KQL query that calls geo_info_from_ip_address() is refused: geo_info_from_ip_address() needs a GeoIP database: set the enrich processor's database_file to a MaxMind GeoIP2 or GeoLite2 City database |
There is no default. Unlike the Geo IP processor, enrich does not fall back to GeoLite2-City.mmdb.
- The database must be a MaxMind GeoIP2 or GeoLite2 City database. A Country or ASN database is refused: the enrich step's database_file "..." is a GeoLite2-ASN database, and geo_info_from_ip_address() reads a City database.
- A file that can't be opened is refused: the enrich step's database_file "..." can't be opened: ....
- Both refusals make the step's query one that can't run: see When the Query Can't Run. A query that calls the function with no
database_fileis refused as it runs on each record instead: see When a Record's Values Make the Query Fail. Either way, the records go on without the enrichment. - The database is opened once and shared with every
geoipandenrichstep that names the same file. - SQL enrich queries don't read the database. The option matters only to a KQL query (
type: kusto) that callsgeo_info_from_ip_address(). - The function runs on Agents as well as on the Director. The database file must be on the host that runs the pipeline, as for the Geo IP processor.
- enrich:
type: kusto
database_file: GeoLite2-City.mmdb
query: _ingest | project geo = geo_info_from_ip_address(src_ip)
Examples
CSV Lookup
Enriching logs with data from a CSV table... | |
adds description: | |
KQL Queries
Processing logs using Kusto Query Language... | |
adds computed fields: | |
Multiple CSV Files
Joining user and department rows from two CSV files. Both files have | |
combines the matching user and department rows: | |
Override Mode
Replacing the document with query results... | |
keeps only the selected fields: | |