Casting
DSP is strongly and implicitly typed. This means that in order to satisfy the type checker, sometimes data needs to be converted and/or casted to different types. The following scalar functions can be used for type conversions. See Data Stream Processor data types for information on casting between data types.
cast
Converts a field from one data type to another data type based on the conversion rules. For common conversions (especially from a string to another primitive type) there often exists a conversion function, and those should be preferred when available. However, conversion functions between types don't always exist (eg. from int to long), and the cast
function can always be used as a fall back. If the requested conversion is not supported, null
is returned.
The cast
function deals with conversion between primitive types. To change the types of more complex types such as maps and collections, use ucast
.
- Function Input
- input: InT
- target_type: string
- Function Output
- type:OutT
1. SPL2 example
Casts the body
field to type string.
... | eval body=cast(body, "string") | ...;
2. SPL2 example
Cast the body
field to type string. Filters records based on whether ASA-x-xxxxxx matches any value in the body field.
... | where match_regex(cast(body, "string"), /%ASA-\d-\d{6}/) | ...;
ucast
Casts data to a new type. Unsafe cast, known as ucast, simply assigns the specified type to the data, and correctness is not checked until run time. If a cast failure occurs at run time, then the value specified in default-value
will be returned.
The ucast
function provides a way to cast maps and collections, regardless of the data type that the map or collection may contain.
- Function Input
- input: InT
- target-type: string
- default-value: any
- Function Output
- type:OutT
1. SPL2 example
The following example performs an unsafe cast on the nested_map
field in attributes
to have type map<string, any>
.
...| eval n=ucast( map_get(attributes, "nested_map"), "map<string, any>", null) | ...;
2. SPL2 example
Suppose the body
field contained a JSON array: {"name":"demo","unit":"percent","type":"GAUGE","value":37,"dimensions":{"region":"us-east-1","sf_hires":"1"}}
and you wanted to convert it to JSON. This following example casts body
to type collection<any>
to return [{"name":"demo","unit":"percent","type":"GAUGE","value":37,"dimensions":{"region":"us-east-1","sf_hires":"1"}}]
in field n
.
...| eval n=ucast(body, "collection<any>", null) | ...;
Overview of evaluation scalar functions | Conditional |
This documentation applies to the following versions of Splunk® Data Stream Processor: 1.1.0
Feedback submitted, thanks!