Bloblang Methods
Methods provide most of the power in Bloblang as they allow you to augment values and can be added to any expression (including other methods):
Methods support both named and nameless style arguments:
General
apply
Apply a declared mapping to a target value.
Parameters
mapping
<string> The mapping to apply.
Examples
catch
If the result of a target query fails (due to incorrect types, failed parsing, etc) the argument is returned instead.
Parameters
fallback
<query expression> A value to yield, or query to execute, if the target query fails.
Examples
The fallback argument can be a mapping, allowing you to capture the error string and yield structured data back.
When the input document is not structured attempting to reference structured fields with this
will result in an error. Therefore, a convenient way to delete non-structured data is with a catch.
exists
Checks that a field, identified via a dot path, exists in an object.
Parameters
path
<string> A dot path to a field.
Examples
from
Modifies a target query such that certain functions are executed from the perspective of another message in the batch. This allows you to mutate events based on the contents of other messages. Functions that support this behavior are content
, json
and meta
.
Parameters
index
<integer> The message index to use as a perspective.
Examples
For example, the following map extracts the contents of the JSON field foo
specifically from message index 1
of a batch, effectively overriding the field foo
for all messages of a batch to that of message 1:
from_all
Modifies a target query such that certain functions are executed from the perspective of each message in the batch, and returns the set of results as an array. Functions that support this behavior are content
, json
and meta
.
Examples
or
If the result of the target query fails or resolves to null
, returns the argument instead. This is an explicit method alternative to the coalesce pipe operator |
.
Parameters
fallback
<query expression> A value to yield, or query to execute, if the target query fails or resolves to null
.
Examples
String Manipulation
capitalize
Takes a string value and returns a copy with all Unicode letters that begin words mapped to their Unicode title case.
Examples
compare_argon2
Checks whether a string matches a hashed secret using Argon2.
Parameters
hashed_secret
<string> The hashed secret to compare with the input. This must be a fully-qualified string which encodes the Argon2 options used to generate the hash.
Examples
compare_bcrypt
Checks whether a string matches a hashed secret using bcrypt.
Parameters
hashed_secret
<string> The hashed secret value to compare with the input.
Examples
contains
Checks whether a string contains a substring and returns a boolean result.
Parameters
value
<unknown> A value to test against elements of the target.
Examples
escape_html
Escapes a string so that special characters like <
to become <
. It escapes only five such characters: <
, >
, &
, '
and "
so that it can be safely placed within an HTML entity.
Examples
escape_url_query
Escapes a string so that it can be safely placed within a URL query.
Examples
filepath_join
Joins an array of path elements into a single file path. The separator depends on the operating system of the machine.
Examples
filepath_split
Splits a file path immediately following the final Separator, separating it into a directory and file name component returned as a two element array of strings. If there is no Separator in the path, the first element will be empty and the second will contain the path. The separator depends on the operating system of the machine.
Examples
format
Use a value string as a format specifier in order to produce a new string, using any number of provided arguments. Please refer to the Go https://pkg.go.dev/fmt[`fmt` package documentation^] for the list of valid format verbs.
Examples
has_prefix
Checks whether a string has a prefix argument and returns a bool.
Parameters
value
<string> The string to test.
Examples
has_suffix
Checks whether a string has a suffix argument and returns a bool.
Parameters
value
<string> The string to test.
Examples
index_of
Returns the starting index of the argument substring in a string target, or -1
if the target doesn’t contain the argument.
Parameters
value
<string> A string to search for.
Examples
length
Returns the length of a string.
Examples
lowercase
Convert a string value into lowercase.
Examples
quote
Quotes a target string using escape sequences (\t
, \n
, \xFF
, \u0100
) for control characters and non-printable characters.
Examples
replace_all
Replaces all occurrences of the first argument in a target string with the second argument.
Parameters
old
<string> A string to match against.
new
<string> A string to replace with.
Examples
replace_all_many
For each pair of strings in an argument array, replaces all occurrences of the first item of the pair with the second. This is a more compact way of chaining a series of replace_all
methods.
Parameters
values
<array> An array of values, each even value will be replaced with the following odd value.
Examples
reverse
Returns the target string in reverse order.
Examples
slice
Extract a slice from a string by specifying two indices, a low and high bound, which selects a half-open range that includes the first character, but excludes the last one. If the second index is omitted then it defaults to the length of the input sequence.
Parameters
low
<integer> The low bound, which is the first element of the selection, or if negative selects from the end.
high
<(optional) integer> An optional high bound.
Examples
A negative low index can be used, indicating an offset from the end of the sequence. If the low index is greater than the length of the sequence then an empty result is returned.
slug
Creates a “slug” from a given string. Wraps the github.com/gosimple/slug package. See its docs for more information.
Introduced in version 4.2.0.
Parameters
lang
<(optional) string, default "en"
>
Examples
Creates a slug from an English string
Creates a slug from a French string
split
Split a string value into an array of strings by splitting it on a string separator.
Parameters
delimiter
<string> The delimiter to split with.
Examples
strip_html
Attempts to remove all HTML tags from a target string.
Parameters
preserve
<(optional) unknown> An optional array of element types to preserve in the output.
Examples
It’s also possible to provide an explicit list of element types to preserve in the output.
trim
Remove all leading and trailing characters from a string that are contained within an argument cutset. If no arguments are provided then whitespace is removed.
Parameters
cutset
<(optional) string> An optional string of characters to trim from the target value.
Examples
trim_prefix
Remove the provided leading prefix substring from a string. If the string does not have the prefix substring, it is returned unchanged.
Introduced in version 4.12.0.
Parameters
prefix
<string> The leading prefix substring to trim from the string.
Examples
trim_suffix
Remove the provided trailing suffix substring from a string. If the string does not have the suffix substring, it is returned unchanged.
Introduced in version 4.12.0.
Parameters
suffix
<string> The trailing suffix substring to trim from the string.
Examples
unescape_html
Unescapes a string so that entities like <
become <
. It unescapes a larger range of entities than escape_html
escapes. For example, á
unescapes to á
, as does á
and &xE1;
.
Examples
unescape_url_query
Expands escape sequences from a URL query string.
Examples
unquote
Unquotes a target string, expanding any escape sequences (\t
, \n
, \xFF
, \u0100
) for control characters and non-printable characters.
Examples
uppercase
Convert a string value into uppercase.
Examples
Regular Expressions
re_find_all
Returns an array containing all successive matches of a regular expression in a string.
Parameters
pattern
<string> The pattern to match against.
Examples
re_find_all_object
Returns an array of objects containing all matches of the regular expression and the matches of its subexpressions. The key of each match value is the name of the group when specified, otherwise it is the index of the matching group, starting with the expression as a whole at 0.
Parameters
pattern
<string> The pattern to match against.
Examples
re_find_all_submatch
Returns an array of arrays containing all successive matches of the regular expression in a string and the matches, if any, of its subexpressions.
Parameters
pattern
<string> The pattern to match against.
Examples
re_find_object
Returns an object containing the first match of the regular expression and the matches of its subexpressions. The key of each match value is the name of the group when specified, otherwise it is the index of the matching group, starting with the expression as a whole at 0.
Parameters
pattern
<string> The pattern to match against.
Examples
re_match
Checks whether a regular expression matches against any part of a string and returns a boolean.
Parameters
pattern
<string> The pattern to match against.
Examples
re_replace_all
Replaces all occurrences of the argument regular expression in a string with a value. Inside the value $ signs are interpreted as submatch expansions, e.g. $1
represents the text of the first submatch.
Parameters
pattern
<string> The pattern to match against.
value
<string> The value to replace with.
Examples
Number Manipulation
abs
Returns the absolute value of an int64 or float64 number. As a special case, when an integer is provided that is the minimum value it is converted to the maximum value.
Examples
ceil
Returns the least integer value greater than or equal to a number. If the resulting value fits within a 64-bit integer then that is returned, otherwise a new floating point number is returned.
Examples
cos
Calculates the cosine of a given angle specified in radians.
Examples
float32
Converts a numerical type into a 32-bit floating point number, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 32-bit floating point number. Please refer to the strconv.ParseFloat
documentation for details regarding the supported formats.
Examples
float64
Converts a numerical type into a 64-bit floating point number, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 64-bit floating point number. Please refer to the strconv.ParseFloat
documentation for details regarding the supported formats.
Examples
floor
Returns the greatest integer value less than or equal to the target number. If the resulting value fits within a 64-bit integer then that is returned, otherwise a new floating point number is returned.
Examples
int16
Converts a numerical type into a 16-bit signed integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 16-bit signed integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
int32
Converts a numerical type into a 32-bit signed integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 32-bit signed integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
int64
Converts a numerical type into a 64-bit signed integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 64-bit signed integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
int8
Converts a numerical type into a 8-bit signed integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 8-bit signed integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
log
Returns the natural logarithm of a number.
Examples
log10
Returns the decimal logarithm of a number.
Examples
max
Returns the largest numerical value found within an array. All values must be numerical and the array must not be empty, otherwise an error is returned.
Examples
min
Returns the smallest numerical value found within an array. All values must be numerical and the array must not be empty, otherwise an error is returned.
Examples
pow
Returns the number raised to the specified exponent.
Parameters
exponent
<float> The exponent you want to raise to the power of.
Examples
round
Rounds numbers to the nearest integer, rounding half away from zero. If the resulting value fits within a 64-bit integer then that is returned, otherwise a new floating point number is returned.
Examples
sin
Calculates the sine of a given angle specified in radians.
Examples
tan
Calculates the tangent of a given angle specified in radians.
Examples
uint16
Converts a numerical type into a 16-bit unsigned integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 16-bit unsigned integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
uint32
Converts a numerical type into a 32-bit unsigned integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 32-bit unsigned integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
uint64
Converts a numerical type into a 64-bit unsigned integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 64-bit unsigned integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
uint8
Converts a numerical type into a 8-bit unsigned integer, this is for advanced use cases where a specific data type is needed for a given component (such as the ClickHouse SQL driver).
If the value is a string then an attempt will be made to parse it as a 8-bit unsigned integer. If the target value exceeds the capacity of an integer or contains decimal values then this method will throw an error. In order to convert a floating point number containing decimals first use .round()
on the value. Please refer to the strconv.ParseInt
documentation for details regarding the supported formats.
Examples
Timestamp Manipulation
parse_duration
Attempts to parse a string as a duration and returns an integer of nanoseconds. A duration string is a possibly signed sequence of decimal numbers, each with an optional fraction and a unit suffix, such as “300ms”, “-1.5h” or “2h45m”. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”.
Examples
parse_duration_iso8601
Attempts to parse a string using ISO-8601 rules as a duration and returns an integer of nanoseconds. A duration string is represented by the format “P[n]Y[n]M[n]DT[n]H[n]M[n]S” or “P[n]W”. In these representations, the “[n]” is replaced by the value for each of the date and time elements that follow the “[n]”. For example, “P3Y6M4DT12H30M5S” represents a duration of “three years, six months, four days, twelve hours, thirty minutes, and five seconds”. The last field of the format allows fractions with one decimal place, so “P3.5S” will return 3500000000ns. Any additional decimals will be truncated.
Examples
Arbitrary ISO-8601 duration string to nanoseconds:
Two hours ISO-8601 duration string to seconds:
Two and a half seconds ISO-8601 duration string to seconds:
ts_add_iso8601
Parse parameter string as ISO 8601 period and add it to value with high precision for units larger than an hour.
Parameters
duration
<string> Duration in ISO 8601 format
ts_format
Attempts to format a timestamp value as a string according to a specified format, or RFC 3339 by default. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format.
The output format is defined by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006, would be displayed if it were the value. For an alternative way to specify formats check out the ts_strftime
method.
Parameters
format
<string, default "2006-01-02T15:04:05.999999999Z07:00"
> The output format to use.
tz
<(optional) string> An optional timezone to use, otherwise the timezone of the input string is used, or in the case of unix timestamps the local timezone is used.
Examples
An optional string argument can be used in order to specify the output format of the timestamp. The format is defined by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006, would be displayed if it were the value.
A second optional string argument can also be used in order to specify a timezone, otherwise the timezone of the input string is used, or in the case of unix timestamps the local timezone is used.
And ts_format
supports up to nanosecond precision with floating point timestamp values.
ts_parse
Attempts to parse a string as a timestamp following a specified format and outputs a timestamp, which can then be fed into methods such as ts_format
.
The input format is defined by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006, would be displayed if it were the value. For an alternative way to specify formats check out the ts_strptime
method.
Parameters
format
<string> The format of the target string.
Examples
ts_round
Returns the result of rounding a timestamp to the nearest multiple of the argument duration (nanoseconds). The rounding behavior for halfway values is to round up. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Introduced in version 4.2.0.
Parameters
duration
<integer> A duration measured in nanoseconds to round by.
Examples
Use the method parse_duration
to convert a duration string into an integer argument.
ts_strftime
Attempts to format a timestamp value as a string according to a specified strftime-compatible format. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format.
Parameters
format
<string> The output format to use.
tz
<(optional) string> An optional timezone to use, otherwise the timezone of the input string is used.
Examples
The format consists of zero or more conversion specifiers and ordinary characters (except %
). All ordinary characters are copied to the output string without modification. Each conversion specification begins with %
character followed by the character that determines the behavior of the specifier. Please refer to https://linux.die.net/man/3/strftime[man 3 strftime] for the list of format specifiers.
A second optional string argument can also be used in order to specify a timezone, otherwise the timezone of the input string is used, or in the case of unix timestamps the local timezone is used.
As an extension provided by the underlying formatting library, https://github.com/itchyny/timefmt-go[itchyny/timefmt-go], the %f
directive is supported for zero-padded microseconds, which originates from Python. Note that E and O modifier characters are not supported.
ts_strptime
Attempts to parse a string as a timestamp following a specified strptime-compatible format and outputs a timestamp, which can then be fed into ts_format
.
Parameters
format
<string> The format of the target string.
Examples
The format consists of zero or more conversion specifiers and ordinary characters (except %
). All ordinary characters are copied to the output string without modification. Each conversion specification begins with a %
character followed by the character that determines the behavior of the specifier. Please refer to https://linux.die.net/man/3/strptime[man 3 strptime] for the list of format specifiers.
As an extension provided by the underlying formatting library, https://github.com/itchyny/timefmt-go[itchyny/timefmt-go], the %f
directive is supported for zero-padded microseconds, which originates from Python. Note that E and O modifier characters are not supported.
ts_sub
Returns the difference in nanoseconds between the target timestamp (t1) and the timestamp provided as a parameter (t2). The ts_parse
method can be used in order to parse different timestamp formats.
Introduced in version 4.23.0.
Parameters
t2
<timestamp> The second timestamp to be subtracted from the method target.
Examples
Use the .abs()
method in order to calculate an absolute duration between two timestamps.
ts_sub_iso8601
Parse parameter string as ISO 8601 period and subtract it from value with high precision for units larger than an hour.
Parameters
duration
<string> Duration in ISO 8601 format
ts_tz
Returns the result of converting a timestamp to a specified timezone. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Introduced in version 4.3.0.
Parameters
tz
<string> The timezone to change to. If set to “UTC” then the timezone will be UTC. If set to “Local” then the local timezone will be used. Otherwise, the argument is taken to be a location name corresponding to a file in the IANA Time Zone database, such as “America/New_York”.
Examples
ts_unix
Attempts to format a timestamp value as a unix timestamp. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Examples
ts_unix_micro
Attempts to format a timestamp value as a unix timestamp with microsecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Examples
ts_unix_milli
Attempts to format a timestamp value as a unix timestamp with millisecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Examples
ts_unix_nano
Attempts to format a timestamp value as a unix timestamp with nanosecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
Examples
Type Coercion
array
Return an array containing the target value. If the value is already an array it is unchanged.
Examples
bool
Attempt to parse a value into a boolean. An optional argument can be provided, in which case if the value cannot be parsed the argument will be returned instead. If the value is a number then any non-zero value will resolve to true
, if the value is a string then any of the following values are considered valid: 1, t, T, TRUE, true, True, 0, f, F, FALSE
.
Parameters
default
<(optional) bool> An optional value to yield if the target cannot be parsed as a boolean.
Examples
bytes
Marshal a value into a byte array. If the value is already a byte array it is unchanged.
Examples
not_empty
Ensures that the given string, array or object value is not empty, and if so returns it, otherwise an error is returned.
Examples
not_null
Ensures that the given value is not null
, and if so returns it, otherwise an error is returned.
Examples
number
Attempt to parse a value into a number. An optional argument can be provided, in which case if the value cannot be parsed into a number the argument will be returned instead.
Parameters
default
<(optional) float> An optional value to yield if the target cannot be parsed as a number.
Examples
string
Marshal a value into a string. If the value is already a string it is unchanged.
Examples
type
Returns the type of a value as a string, providing one of the following values: string
, bytes
, number
, bool
, timestamp
, array
, object
or null
.
Examples
Object & Array Manipulation
all
Checks each element of an array against a query and returns true if all elements passed. An error occurs if the target is not an array, or if any element results in the provided query returning a non-boolean result. Returns false if the target array is empty.
Parameters
test
<query expression> A test query to apply to each element.
Examples
any
Checks the elements of an array against a query and returns true if any element passes. An error occurs if the target is not an array, or if an element results in the provided query returning a non-boolean result. Returns false if the target array is empty.
Parameters
test
<query expression> A test query to apply to each element.
Examples
append
Returns an array with new elements appended to the end.
Examples
assign
Merge a source object into an existing destination object. When a collision is found within the merged structures (both a source and destination object contain the same non-object keys) the value in the destination object will be overwritten by that of source object. In order to preserve both values on collision use the merge
method.
Parameters
with
<unknown> A value to merge the target value with.
Examples
collapse
Collapse an array or object into an object of key/value pairs for each field, where the key is the full path of the structured field in dot path notation. Empty arrays an objects are ignored by default.
Parameters
include_empty
<bool, default false
> Whether to include empty objects and arrays in the resulting object.
Examples
An optional boolean parameter can be set to true in order to include empty objects and arrays.
concat
Concatenates an array value with one or more argument arrays.
Examples
contains
Checks whether an array contains an element matching the argument, or an object contains a value matching the argument, and returns a boolean result. Numerical comparisons are made irrespective of the representation type (float versus integer).
Parameters
value
<unknown> A value to test against elements of the target.
Examples
diff
Create a diff by comparing the current value with the given one. Wraps the github.com/r3labs/diff/v3 package. See its docs for more information.
Introduced in version 4.25.0.
Parameters
other
<unknown> The value to compare against.
enumerated
Converts an array into a new array of objects, where each object has a field index containing the index
of the element and a field value
containing the original value of the element.
Examples
explode
Explodes an array or object at a xref:configuration:field_paths.adoc[field path].
Parameters
path
<string> A dot path to a field to explode.
Examples
On arrays
Exploding arrays results in an array containing elements matching the original document, where the target field of each element is an element of the exploded array:
On objects
Exploding objects results in an object where the keys match the target object, and the values match the original document but with the target field replaced by the exploded value:
filter
Executes a mapping query argument for each element of an array or key/value pair of an object. If the query returns false
the item is removed from the resulting array or object. The item will also be removed if the query returns any non-boolean value.
Parameters
test
<query expression> A query to apply to each element, if this query resolves to any value other than a boolean true
the element will be removed from the result.
Examples
On objects
When filtering objects the mapping query argument is provided a context with a field key
containing the value key, and a field value
containing the value.
find
Returns the index of the first occurrence of a value in an array. -1
is returned if there are no matches. Numerical comparisons are made irrespective of the representation type (float versus integer).
Parameters
value
<unknown> A value to find.
Examples
find_all
Returns an array containing the indexes of all occurrences of a value in an array. An empty array is returned if there are no matches. Numerical comparisons are made irrespective of the representation type (float versus integer).
Parameters
value
<unknown> A value to find.
Examples
find_all_by
Returns an array containing the indexes of all occurrences of an array where the provided query resolves to a boolean true
. An empty array is returned if there are no matches. Numerical comparisons are made irrespective of the representation type (float versus integer).
Parameters
query
<query expression> A query to execute for each element.
Examples
find_by
Returns the index of the first occurrence of an array where the provided query resolves to a boolean true
. -1
is returned if there are no matches.
Parameters
query
<query expression> A query to execute for each element.
Examples
flatten
Iterates an array and any element that is itself an array is removed and has its elements inserted directly in the resulting array.
Examples
fold
Takes two arguments: an initial value, and a mapping query. For each element of an array the mapping context is an object with two fields tally
and value
, where tally
contains the current accumulated value and value
is the value of the current element. The mapping must return the result of adding the value to the tally.
The first argument is the value that tally
will have on the first call.
Parameters
initial
<unknown> The initial value to start the fold with. For example, an empty object {}
, a zero count 0
, or an empty string ""
.
query
<query expression> A query to apply for each element. The query is provided an object with two fields; tally
containing the current tally, and value
containing the value of the current element. The query should result in a new tally to be passed to the next element query.
Examples
You can use fold to merge an array of objects together:
get
Extract a field value, identified via a dot path, from an object.
Parameters
path
<string> A dot path identifying a field to obtain.
Examples
index
Extract an element from an array by an index. The index can be negative, and if so the element will be selected from the end counting backwards starting from -1. E.g. an index of -1 returns the last element, an index of -2 returns the element before the last, and so on.
Parameters
index
<integer> The index to obtain from an array.
Examples
It is also possible to use this method on byte arrays, in which case the selected element will be returned as an integer.
join
Join an array of strings with an optional delimiter into a single string.
Parameters
delimiter
<(optional) string> An optional delimiter to add between each string.
Examples
json_path
Executes the given JSONPath expression on an object or array and returns the result. The JSONPath expression syntax can be found at https://goessner.net/articles/JsonPath/. For more complex logic, you can use Gval expressions (https://github.com/PaesslerAG/gval).
Parameters
expression
<string> The JSONPath expression to execute.
Examples
json_schema
Checks a JSON schema against a value and returns the value if it matches or throws and error if it does not.
Parameters
schema
<string> The schema to check values against.
Examples
In order to load a schema from a file use the file
function.
key_values
Returns the key/value pairs of an object as an array, where each element is an object with a key
field and a value
field. The order of the resulting array will be random.
Examples
keys
Returns the keys of an object as an array.
Examples
length
Returns the length of an array or object (number of keys).
Examples
map_each
Parameters
query
<query expression> A query that will be used to map each element.
Examples
On arrays
Apply a mapping to each element of an array and replace the element with the result. Within the argument mapping the context is the value of the element being mapped.
On objects
Apply a mapping to each value of an object and replace the value with the result. Within the argument mapping the context is an object with a field key
containing the value key, and a field value
.
map_each_key
Apply a mapping to each key of an object, and replace the key with the result, which must be a string.
Parameters
query
<query expression> A query that will be used to map each key.
Examples
merge
Merge a source object into an existing destination object. When a collision is found within the merged structures (both a source and destination object contain the same non-object keys) the result will be an array containing both values, where values that are already arrays will be expanded into the resulting array. In order to simply override destination fields on collision use the assign
method.
Parameters
with
<unknown> A value to merge the target value with.
Examples
patch
Create a diff by comparing the current value with the given one. Wraps the github.com/r3labs/diff/v3 package. See its docs for more information.
Introduced in version 4.25.0.
Parameters
changelog
<unknown> The changelog to apply.
slice
Extract a slice from an array by specifying two indices, a low and high bound, which selects a half-open range that includes the first element, but excludes the last one. If the second index is omitted then it defaults to the length of the input sequence.
Parameters
low
<integer> The low bound, which is the first element of the selection, or if negative selects from the end.
high
<(optional) integer> An optional high bound.
Examples
A negative low index can be used, indicating an offset from the end of the sequence. If the low index is greater than the length of the sequence then an empty result is returned.
sort
Attempts to sort the values of an array in increasing order. The type of all values must match in order for the ordering to succeed. Supports string and number values.
Parameters
compare
<(optional) query expression> An optional query that should explicitly compare elements left
and right
and provide a boolean result.
Examples
It’s also possible to specify a mapping argument, which is provided an object context with fields left
and right
, the mapping must return a boolean indicating whether the left
value is less than right
. This allows you to sort arrays containing non-string or non-number values.
sort_by
Attempts to sort the elements of an array, in increasing order, by a value emitted by an argument query applied to each element. The type of all values must match in order for the ordering to succeed. Supports string and number values.
Parameters
query
<query expression> A query to apply to each element that yields a value used for sorting.
Examples
squash
Squashes an array of objects into a single object, where key collisions result in the values being merged (following similar rules as the .merge()
method)
Examples
sum
Sum the numerical values of an array.
Examples
unique
Attempts to remove duplicate values from an array. The array may contain a combination of different value types, but numbers and strings are checked separately ("5"
is a different element to 5
).
Parameters
emit
<(optional) query expression> An optional query that can be used in order to yield a value for each element to determine uniqueness.
Examples
values
Returns the values of an object as an array. The order of the resulting array will be random.
Examples
with
Returns an object where all but one or more field path arguments are removed. Each path specifies a specific field to be retained from the input object, allowing for nested fields.
If a key within a nested path does not exist then it is ignored.
Examples
without
Returns an object where one or more xref:configuration:field_paths.adoc[field path] arguments are removed. Each path specifies a specific field to be deleted from the input object, allowing for nested fields.
If a key within a nested path does not exist or is not an object then it is not removed.
Examples
zip
Zip an array value with one or more argument arrays. Each array must match in length.
Examples
Parsing
bloblang
Executes an argument Bloblang mapping on the target. This method can be used in order to execute dynamic mappings. Imports and functions that interact with the environment, such as file
and env
, or that access message information directly, such as content
or json
, are not enabled for dynamic Bloblang mappings.
Parameters
mapping
<string> The mapping to execute.
Examples
format_json
Serializes a target value into a pretty-printed JSON byte array (with 4 space indentation by default).
Parameters
indent
<string, default " "
> Indentation string. Each element in a JSON object or array will begin on a new, indented line followed by one or more copies of indent according to the indentation nesting.
no_indent
<bool, default false
> Disable indentation.
escape_html
<bool, default true
> Escape problematic HTML characters.
Examples
Pass a string to the indent
parameter in order to customise the indentation.
Use the .string()
method in order to coerce the result into a string.
Set the no_indent
parameter to true to disable indentation. The result is equivalent to calling bytes()
.
Escapes problematic HTML characters.
Set the escape_html
parameter to false to disable escaping of problematic HTML characters.
format_msgpack
Formats data as a MessagePack message in bytes format.
Examples
format_xml
Serializes a target value into an XML byte array.
Parameters
indent
<string, default " "
> Indentation string. Each element in an XML object or array will begin on a new, indented line followed by one or more copies of indent according to the indentation nesting.
no_indent
<bool, default false
> Disable indentation.
Examples
Serializes a target value into a pretty-printed XML byte array (with 4 space indentation by default).
Pass a string to the indent
parameter in order to customise the indentation.
Use the .string()
method in order to coerce the result into a string.
Set the no_indent
parameter to true to disable indentation.
format_yaml
Serializes a target value into a YAML byte array.
Examples
Use the .string()
method in order to coerce the result into a string.
parse_csv
Attempts to parse a string into an array of objects by following the CSV format described in RFC 4180.
Parameters
parse_header_row
<bool, default true
> Whether to reference the first row as a header row. If set to true the output structure for messages will be an object where field keys are determined by the header row. Otherwise, the output will be an array of row arrays.
delimiter
<string, default ","
> The delimiter to use for splitting values in each record. It must be a single character.
lazy_quotes
<bool, default false
> If set to true
, a quote may appear in an unquoted field and a non-doubled quote may appear in a quoted field.
Examples
Parses CSV data with a header row
Parses CSV data without a header row
Parses CSV data delimited by dots
Parses CSV data containing a quote in an unquoted field
parse_form_url_encoded
Attempts to parse a url-encoded query string (from an x-www-form-urlencoded request body) and returns a structured result.
Examples
parse_json
Attempts to parse a string as a JSON document and returns the result.
Parameters
use_number
<(optional) bool> An optional flag that when set makes parsing numbers as json.Number instead of the default float64.
Examples
parse_msgpack
Parses a MessagePack message into a structured document.
Examples
parse_parquet
Decodes a Parquet file into an array of objects, one for each row within the file.
Parameters
byte_array_as_string
<bool, default false
> Deprecated: This parameter is no longer used.
Examples
parse_url
Attempts to parse a URL from a string value, returning a structured result that describes the various facets of the URL. The fields returned within the structured result roughly follow https://pkg.go.dev/net/url#URL, and may be expanded in future in order to present more information.
Examples
parse_xml
Attempts to parse a string as an XML document and returns a structured result, where elements appear as keys of an object according to the following rules:
- If an element contains attributes they are parsed by prefixing a hyphen,
-
, to the attribute label. - If the element is a simple element and has attributes, the element value is given the key
#text
. - XML comments, directives, and process instructions are ignored.
- When elements are repeated the resulting JSON value is an array.
- If cast is true, try to cast values to numbers and booleans instead of returning strings.
Parameters
cast
<(optional) bool, default false
> whether to try to cast values that are numbers and booleans to the right type.
Examples
parse_yaml
Attempts to parse a string as a single YAML document and returns the result.
Examples
Encoding and Encryption
compress
Compresses a string or byte array value according to a specified algorithm.
Parameters
algorithm
<string> One of flate
, gzip
, pgzip
, lz4
, snappy
, zlib
, zstd
.
level
<integer, default -1
> The level of compression to use. May not be applicable to all algorithms.
Examples
decode
Decodes an encoded string target according to a chosen scheme and returns the result as a byte array. When mapping the result to a JSON field the value should be cast to a string using the method string
, or encoded using the method encode
, otherwise it will be base64 encoded by default.
Available schemes are: base64
, base64url
https://rfc-editor.org/rfc/rfc4648.html[(RFC 4648 with padding characters)], base64rawurl
https://rfc-editor.org/rfc/rfc4648.html[(RFC 4648 without padding characters)], hex
, ascii85
.
Parameters
scheme
<string> The decoding scheme to use.
Examples
decompress
Decompresses a string or byte array value according to a specified algorithm. The result of decompression
Parameters
algorithm
<string> One of gzip
, pgzip
, zlib
, bzip2
, flate
, snappy
, lz4
, zstd
.
Examples
Use the .string()
method in order to coerce the result into a string, this makes it possible to place the data within a JSON document without automatic base64 encoding.
decrypt_aes
Decrypts an encrypted string or byte array target according to a chosen AES encryption method and returns the result as a byte array. The algorithms require a key and an initialization vector / nonce. Available schemes are: ctr
, gcm
, ofb
, cbc
.
Parameters
scheme
<string> The scheme to use for decryption, one of ctr
, gcm
, ofb
, cbc
.
key
<string> A key to decrypt with.
iv
<string> An initialization vector / nonce.
Examples
encode
Encodes a string or byte array target according to a chosen scheme and returns a string result. Available schemes are: base64
, base64url
https://rfc-editor.org/rfc/rfc4648.html[(RFC 4648 with padding characters)], base64rawurl
https://rfc-editor.org/rfc/rfc4648.html[(RFC 4648 without padding characters)], hex
, ascii85
.
Parameters
scheme
<string> The encoding scheme to use.
Examples
encrypt_aes
Encrypts a string or byte array target according to a chosen AES encryption method and returns a string result. The algorithms require a key and an initialization vector / nonce. Available schemes are: ctr
, gcm
, ofb
, cbc
.
Parameters
scheme
<string> The scheme to use for encryption, one of ctr
, gcm
, ofb
, cbc
.
key
<string> A key to encrypt with.
iv
<string> An initialization vector / nonce.
Examples
hash
Hashes a string or byte array according to a chosen algorithm and returns the result as a byte array. When mapping the result to a JSON field the value should be cast to a string using the method xref:guides:bloblang/methods.adoc#string[string
], or encoded using the method xref:guides:bloblang/methods.adoc#encode[encode
], otherwise it will be base64 encoded by default.
Available algorithms are: hmac_sha1
, hmac_sha256
, hmac_sha512
, md5
, sha1
, sha256
, sha512
, xxhash64
, crc32
, fnv32
.
The following algorithms require a key, which is specified as a second argument: hmac_sha1
, hmac_sha256
, hmac_sha512
.
Parameters
algorithm
<string> The hasing algorithm to use.
key
<(optional) string> An optional key to use.
polynomial
<string, default "IEEE"
> An optional polynomial key to use when selecting the crc32
algorithm, otherwise ignored. Options are IEEE
(default), Castagnoli
and Koopman
Examples
The crc32
algorithm supports options for the polynomial.
SQL
vector
Creates a vector from a given array of floating point numbers.
This vector can be inserted into various SQL databases if they have support for embeddings vectors (for example pgvector
).
Introduced in version 4.33.0.
Examples
Create a vector from an array literal
Create a vector from an array
JSON Web Tokens
parse_jwt_es256
Parses a claims object from a JWT string encoded with ES256. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The ES256 secret that was used for signing the token.
Examples
parse_jwt_es384
Parses a claims object from a JWT string encoded with ES384. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The ES384 secret that was used for signing the token.
Examples
parse_jwt_es512
Parses a claims object from a JWT string encoded with ES512. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The ES512 secret that was used for signing the token.
Examples
parse_jwt_hs256
Parses a claims object from a JWT string encoded with HS256. This method does not validate JWT claims.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The HS256 secret that was used for signing the token.
Examples
parse_jwt_hs384
Parses a claims object from a JWT string encoded with HS384. This method does not validate JWT claims.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The HS384 secret that was used for signing the token.
Examples
parse_jwt_hs512
Parses a claims object from a JWT string encoded with HS512. This method does not validate JWT claims.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The HS512 secret that was used for signing the token.
Examples
parse_jwt_rs256
Parses a claims object from a JWT string encoded with RS256. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The RS256 secret that was used for signing the token.
Examples
parse_jwt_rs384
Parses a claims object from a JWT string encoded with RS384. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The RS384 secret that was used for signing the token.
Examples
parse_jwt_rs512
Parses a claims object from a JWT string encoded with RS512. This method does not validate JWT claims.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The RS512 secret that was used for signing the token.
Examples
sign_jwt_es256
Hash and sign an object representing JSON Web Token (JWT) claims using ES256.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_es384
Hash and sign an object representing JSON Web Token (JWT) claims using ES384.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_es512
Hash and sign an object representing JSON Web Token (JWT) claims using ES512.
Introduced in version v4.20.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_hs256
Hash and sign an object representing JSON Web Token (JWT) claims using HS256.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_hs384
Hash and sign an object representing JSON Web Token (JWT) claims using HS384.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_hs512
Hash and sign an object representing JSON Web Token (JWT) claims using HS512.
Introduced in version v4.12.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_rs256
Hash and sign an object representing JSON Web Token (JWT) claims using RS256.
Introduced in version v4.18.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_rs384
Hash and sign an object representing JSON Web Token (JWT) claims using RS384.
Introduced in version v4.18.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
sign_jwt_rs512
Hash and sign an object representing JSON Web Token (JWT) claims using RS512.
Introduced in version v4.18.0.
Parameters
signing_secret
<string> The secret to use for signing the token.
Examples
GeoIP
geoip_anonymous_ip
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the anonymous IP associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_asn
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the ASN associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_city
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the city associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_connection_type
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the connection type associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_country
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the country associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_domain
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the domain associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_enterprise
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the enterprise associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
geoip_isp
Looks up an IP address against a MaxMind database file and, if found, returns an object describing the ISP associated with it.
Parameters
path
<string> A path to an mmdb (maxmind) file.
Deprecated
format_timestamp
Attempts to format a timestamp value as a string according to a specified format, or RFC 3339 by default. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format.
The output format is defined by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006, would be displayed if it were the value. For an alternative way to specify formats check out the ts_strftime
method.
Parameters
format
<string, default "2006-01-02T15:04:05.999999999Z07:00"
> The output format to use.
tz
<(optional) string> An optional timezone to use, otherwise the timezone of the input string is used, or in the case of unix timestamps the local timezone is used.
format_timestamp_strftime
Attempts to format a timestamp value as a string according to a specified strftime-compatible format. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format.
Parameters
format
<string> The output format to use.
tz
<(optional) string> An optional timezone to use, otherwise the timezone of the input string is used.
format_timestamp_unix
Attempts to format a timestamp value as a unix timestamp. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
format_timestamp_unix_micro
Attempts to format a timestamp value as a unix timestamp with microsecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
format_timestamp_unix_milli
Attempts to format a timestamp value as a unix timestamp with millisecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
format_timestamp_unix_nano
Attempts to format a timestamp value as a unix timestamp with nanosecond precision. Timestamp values can either be a numerical unix time in seconds (with up to nanosecond precision via decimals), or a string in RFC 3339 format. The ts_parse
method can be used in order to parse different timestamp formats.
parse_timestamp
Attempts to parse a string as a timestamp following a specified format and outputs a timestamp, which can then be fed into methods such as ts_format
.
The input format is defined by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006, would be displayed if it were the value. For an alternative way to specify formats check out the ts_strptime
method.
Parameters
format
<string> The format of the target string.
parse_timestamp_strptime
Attempts to parse a string as a timestamp following a specified strptime-compatible format and outputs a timestamp, which can then be fed into ts_format
.
Parameters
format
<string> The format of the target string.