---
title: "Advanced Mapping Functions"
description: "Lytics supports numerous built-in functions for light data transformation and logic evaluation to allow users to map only data that is relevant to their…"
url: "https://www.contentstack.com/docs/lytics/advanced-mapping"
product: "Contentstack"
doc_type: "guide"
audience:
  - developers
  - admins
version: "current"
last_updated: "2026-11-05"
---

# Advanced Mapping Functions

Lytics supports numerous built-in functions for light data transformation and logic evaluation to allow users to map only data that is relevant to their customer profile and format it the way they need for activation of their use cases.

For more complex data transformation and aggregation we suggest utilizing Cloud Connect (with or without Lytics Warehouse) for bringing in calculated attributes.

* * *

### Expressions

**Mapping Keys vs. Literals**

To map the data value passed in an event you will want to use the associated key within the Expression. When creating mappings it is important to remember that keys need to be wrapped in single backticks (\`\`).

Literals (which can be a string, int, float, bool, or timestamp) are used to map a static value to the field. These are often used with conditionals.

* * *

### Conditions

Conditions allow you to perform logical evaluations to determine when to store a value on a field based on any of the data passed within the same incoming event.

[Merge Operators](/docs/lytics/fields-mappings#merge-operators) Merge operators allow you to determine how a value will be written to a field in relation to the currently stored value.

[Data Types](/docs/lytics/fields-mappings#data-types) Kind = "int" | "number" | "string" | "date" | "\[\]string" |  
"ts\[\]string" | "map\[string\]int" | "map\[string\]number" | "map\[string\]string"

* * *

#### Screenshot Example of supplying expression / condition to a mapping

![](https://images.contentstack.io/v3/assets/blt2d43f51baca745a8/am5d1e1aab5df909a0/5a4e93e14161d6b9c150c944/2962fb3490e66cf6ba70549a82870fe53acf09ef6a855ae690af5400f425216a-Screenshot_2024-11-18_at_3.46.31_PM.png)

This example showcases the default mapping for the mo\_email\_unsub field from the Marketo Activity import. Here we see we are writing count over time in which we see activityTypeId as a key in the incoming event data. However, we are only writing this expression's results when that incoming event data evaluates the condition eq(activityTypeId, "9") as true.

* * *

  

* * *

* * *

## Math Functions

These functions perform numeric calculations. Non-numeric input that cannot be coerced to a number results in no value being written.

* * *

### sqrt

Returns the square root of a numeric value.

#### sqrt Example

**Example Event Data (JSON)**

```
{
	"page_views": 9,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
sqrt(`page_views`)
```

**Resulting Value**

```
3
```

* * *

### pow

Raises a number to a power: pow(base, exponent).

#### pow Example

**Example Event Data (JSON)**

```
{
	"base_score": 5,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
pow(`base_score`, 2)
```

**Resulting Value**

```
25
```

* * *

  

* * *

* * *

## String Functions

These functions are used to manipulate string fields.

* * *

### join

Join together multiple values, coerce them into strings. Last argument is which string to use to join (may be empty string).

#### join Example

**Example Event Data (JSON)**

```
{
  "street":"698 Candlewood Lane",
  "city":"Cabot Cove",
  "state":"ME",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
join(`street`,`city`,`state`,", ")
```

**Resulting Value**

```
698 Candlewood Lane, Cabot Cove, ME
```

**Breaking down the Example**

The join() function takes at minimum 2 arguments (utilizing the LAST argument as the "joining" string), and concatenates each argument in order utilizing the "joining" string. In this example we produce a single string consisting of street, city, state values concatenated utilizing the "joining" string , (comma followed by a space).

* * *

### len

Length (of array, string) find the length of a string, return integer value of length.

#### len Example

**Example Event Data (JSON)**

```
{
  "_e":"item_added_to_cart",
  "items_in_cart": [
    "ISBN_9780553119978",
    "ISBN_9780345324481"
  ],
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
len(`items_in_cart`)
```

**Resulting Value**

```
2
```

**Breaking down the Example**

The len() function here is operating on a field whose value is an array, so the output is the number of items in the array. Applying len() to a string results in the character length of the string.

* * *

### oneof

Choose value from the first field that has a non nil (empty string "" inclusive) value.

#### oneof Example

**Example Event Data (JSON)**

```
{
  "account_id":"000-000-001",
  "account_name":"Planet Express",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
oneof(`account_no`,`account_id`)
```

**Resulting Value**

```
000-000-001
```

**Breaking down the Example**

This oneof() function first checks and sees that the account\_no field does not exist in the event data, so it then moves to the account\_id which is found to be a non nil value and is returned.

![](https://images.contentstack.io/v3/assets/blt2d43f51baca745a8/amd46bb3fb561b8c60/e11ac177be11554282b90a32/a6c8130-image.png)

* * *

### replace

Converts the value to a string and then replaces the matching part of a string with another string. If no replacement string is passed or an empty string is passed the matched string is simply removed.

#### replace Example

**Example Event Data (JSON)**

```
{
  "_e":"search",
  "url":"https://pawneeindiana.com/parks-and-recreation",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
replace( replace( path(`url`),"/"),"-", " ")
```

**Resulting Value**

```
parks and recreation
```

**Breaking down the Example**

Using path finds the path of the url which is "/parks-and-recreation".

The inner replace finds all parts of the string that match "/" and since there is no specified string replacement "/" is replaced with nothing. This results in a value of "parks-and-recreation"

The outer replace() takes the resulting "parks-and-recreation" and finds all of the parts of the string that match "-" and replaces them with a space (" "). Leading to the final value of "parks and recreation"

* * *

### split

Breaks a variable into smaller fragments given a specific delimiter

#### split Example

**Example Event Data (JSON)**

```
{
 "_e":"preferences-set",
  "favorite-genres":"mystery|science fiction|fantasy",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
set( split(`favorite-genres`, "|"))
```

**Resulting Value**

```
[
"fantasy",
"mystery",
"science fiction"
]
```

**Breaking down the Example**

The split() splits the incoming value associated with the favorite-genres key at each of the "|" characters the value contains.

Because split() will split the value into fragments that are stored as an array, you will need to map it to a field that is a set data type (\[\]string or \[\]time) and you will also want to wrap set() (for strings) or totimeset() (for datetimes) around the function.

The order of a set of strings resulting from the **split** function will be alphabetical. The order of a set of datetimes resulting from the **split** function will be oldest to latest. However, if you use an array.index function to pull out a value based on position, the originally passed order will be referenced.

* * *

### strip

Strip removes leading and trailing whitespace (spaces, tabs, newline, carriage-return) from strings, or arrays of strings.

#### strip Example

**Example Event Data (JSON)**

```
{
  "_e":"preferences-set",
  "favorite-sub-genres":"detective fiction | cozy mystery | space opera | steampunk",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
strip( split(`favorite-sub-genres`, "|"))
```

**Resulting Value**

```
[
"detective fiction",
"cozy mystery",
"space opera",
"steampunk"
]
```

**Breaking down the Example**

The split() function splits the incoming value associated with the favorite-sub-genres key at each of the "|" characters the value contains. In this example it will create 4 strings that are stored in an array, in the order they appear.

The strip() function then removes the leading and trailing spaces around each of the strings within the array.

* * *

### string.lowercase

Convert strings to lower case

#### string.lowercase Example

**Example Event Data (JSON)**

```
{
  "_e":"registration",
  "vehicle_make":"DMC",
  "vehicle_model":"DeLorean",
  "plate_number":"outatime",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
string.lowercase(`vehicle_make`)
```

**Resulting Value**

```
dmc
```

**Breaking down the Example**

The string.lowercase() function looks at each character in the string value and converts to the lowercase equivalent.

* * *

### string.uppercase

Convert strings to upper case

#### string.uppercase Example

**Example Event Data (JSON)**

```
{
  "_e":"registration",
  "vehicle_make":"DMC",
  "vehicle_model":"DeLorean",
  "plate_number":"outatime",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
string.uppercase(`plate_number`)
```

**Resulting Value**

```
OUTATIME
```

**Breaking down the Example**

The string.uppercase() function looks at each character in the string value and converts to the uppercase equivalent.

* * *

### string.titlecase

Convert strings to title case

#### string.titlecase Example

**Example Event Data (JSON)**

```
{
  "_e":"profile-completed",
  "full_name":"ARTHUR DENT",
  "_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
string.titlecase( string.lowercase(`full_name`))
```

**Resulting Value**

```
Arthur Dent
```

Using string.titlecase() only operates on the first character of each "word" in the string, and thus will always require that you first convert the string to lowercase using string.lowercase() for the full traditional titlecase conversion.

**Breaking down the Example**

Using the string.lowercase() will first normalize the incoming string by converting it to lowercase.

Wrapping the string.titlecase() will then convert the string into title case.

* * *

### string.index

Find position of substring within a string, return ordinal starting position.

#### string.index Example

**Example Event Data (JSON)**

```
{
	"numberString":"0123456789",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
string.index(`numberString`, "1")
```

**Resulting Value**

```
1
```

**Breaking down the Example**

string.index() utilizes a '0' based index, so the first character in the string is at index 0, and the "1" being the second character in the string is at index 1

* * *

### string.substr

Extract a string from a string using positional start/end.

#### string.substr Example

**Example Event Data (JSON)**

```
{
	"numberString":"0123456789",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
string.substr(`numberString`, 3, 7)
```

**Resulting Value**

```
3456
```

**Breaking down the Example**

string.substr() utilizes a '0' based index and returns the substring of the provided string, starting at the provided start index up to but not including the end index. The end index is optional here, and will return from the start index through the remainder of the string.

*   string.substr("android",0,3) => "and"
*   string.substr("android",2) => "droid"

* * *

### contains

Does this value contain this string? Is a sub-string match, not full match (eq)

#### contains Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
contains(`stringExample`, "string")
```

**Resulting Value**

```
true
```

**Breaking down the Example**

The contains() function takes 2 arguments, the field (or raw string) to be searched, and the substring to search for. In this example the value for the stringExample field is searched for the substring "string", and being found returns the boolean value true

* * *

### hasprefix

Does this value start with this string?

#### hasprefix Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hasprefix(`stringExample`, "This is a string")
```

**Resulting Value**

```
true
```

**Breaking down the Example**

The hasprefix() function takes 2 arguments, the field (or raw string) to be searched, and the substring to check for a match starting at index 0 of the 1st argument. In this example the value for the stringExample field is checked for the substring "This is a string", and being found to match as the prefix returns the boolean value true

* * *

### hassuffix

Does this value end with this string?

#### hassuffix Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hassuffix(`stringExample`, "as an example")
```

**Resulting Value**

```
true
```

**Breaking down the Example**

The hassuffix() function takes 2 arguments, the field (or raw string) to be searched, and the substring to check for a match to end the 1st argument. In this example the value for the stringExample field is checked for the substring "as an example", and being found to match as the suffix returns the boolean value true

* * *

### regex.match

Does this value match the supplied regular expression? Returns the boolean value true if the pattern is found anywhere in the string, otherwise false. Patterns use [RE2 syntax](https://github.com/google/re2/wiki/Syntax) (the same engine Go's regexp package uses).

#### regex.match Example

**Example Event Data (JSON)**

```
{
	"sku":"ABC-12345",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
regex.match(`sku`, "^[A-Z]{3}-[0-9]{5}$")
```

**Resulting Value**

```
true
```

**Breaking down the Example**

The regex.match() function takes 2 arguments: the field (or raw string) to test, and a regular expression pattern (a string). In this example the value for the sku field is tested against the pattern ^\[A-Z\]{3}-\[0-9\]{5}$, which requires three uppercase letters, a hyphen, then five digits. The value ABC-12345 satisfies the pattern, so the function returns the boolean value true.

The match is **not** anchored by default — regex.match() returns true if the pattern matches any part of the value. Use the ^ and $ anchors (as in the example above) when you need to match the entire value. The second argument must be a valid regular expression; an invalid pattern or a non-string first argument will cause the expression to error rather than return false.

  

* * *

* * *

## Hash & Encoding Functions

You can apply hash functions to encode incoming data.

* * *

### hash.sip

Hash the given value using sip hash to integer output.

#### hash.sip Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hash.sip(`stringExample`)
```

**Resulting Value**

```
-1913777820508603599
```

* * *

### hash.md5

Hash the given value using md5.

#### hash.md5 Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hash.md5(`stringExample`)
```

**Resulting Value**

```
b6c4db114d07e225a8d9d77e47779f5c
```

* * *

### hash.sha1

Hash the given value using sha1.

#### hash.sha1 Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hash.sha1(`stringExample`)
```

**Resulting Value**

```
1fe04eb0f9ffd1df677657c914f42b68fff9e0cb
```

* * *

### hash.sha256

Hash the given value using sha256.

#### hash.sha256 Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hash.sha256(`stringExample`)
```

**Resulting Value**

```
e2f7ae28b1c04104c11ee09ab4ab79ca20da6ac4e665c13f1b91be2f02b0f986
```

* * *

### hash.sha512

Hash the given value using sha512.

#### hash.sha512 Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hash.sha512(`stringExample`)
```

**Resulting Value**

```
e0771e85eeb0ed73b38df14f42e2c20c6755356c1f1222bcd8d661503645e3659460f3bf668af527b75c1373fc419dd4f8e8493692fb0ca17329f1232898b7ca
```

* * *

### encoding.b64encode

base64 encode.

#### encoding.b64encode Example

**Example Event Data (JSON)**

```
{
	"stringExample":"This is a string being used as an example",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
encoding.b64encode(`stringExample`)
```

**Resulting Value**

```
VGhpcyBpcyBhIHN0cmluZyBiZWluZyB1c2VkIGFzIGFuIGV4YW1wbGU=
```

* * *

### encoding.b64decode

base64 decode.

#### encoding.b64decode Example

**Example Event Data (JSON)**

```
{
	"stringExample":"VGhpcyBpcyBhIHN0cmluZyBiZWluZyB1c2VkIGFzIGFuIGV4YW1wbGU=",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
encoding.b64decode(`stringExample`)
```

**Resulting Value**

```
This is a string being used as an example
```

  

* * *

* * *

## Casting & Conversion

These functions allow you to cast and convert data into different types.  
note: for [**todate**](#todate) conversion, see the Date / Time section below.

* * *

### toint

Converts strings to integers. Useful for converting a string to a number before applying a number-based expression

#### toint Example

**Example Event Data (JSON)**

```
{
	"stringOne":"1.7",
	"stringTwo":"2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
sum(toint(`stringOne`), toint(`stringTwo`))
```

**Resulting Value**

```
3
```

**Breaking down the Example**

Here we have a summation function applying to the result of converting two different string fields to int(s) and wrapping them in the sum() function. We first convert the value for stringOne = "1.7" into its int equivalent 1, then convert the value for stringTwo = "2" into its int equivalent 2... then the summation result of the two int values is 3

* * *

### tonumber

Converts strings to numbers. Useful for converting a string to a number while needing to keep decimal precision

#### tonumber Example

**Example Event Data (JSON)**

```
{
	"stringOne":"1.7",
	"stringTwo":"2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
sum(tonumber(`stringOne`), tonumber(`stringTwo`))
```

**Resulting Value**

```
3.7
```

**Breaking down the Example**

Here we have a summation function applying to the result of converting two different string fields to number(s) and wrapping them in the sum() function. We first convert the value for stringOne = "1.7" into its number equivalent 1.7 (keeping decimal precision), then convert the value for stringTwo = "2" into its number equivalent 2... then the summation result of the two number values is 3.7

* * *

### tobool

Casts to boolean:  
Numeric Values of 0/1 convert to **false**/**true** respectively  
String Values will convert as:

*   "0", "f", "F", "false", "FALSE", "False" -> **false**
*   "1", "t", "T", "true", "TRUE", "True" -> **true**

#### tobool Example

**Example Event Data (JSON)**

```
{
	"boolField":"F",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
tobool(`boolField`)
```

**Resulting Value**

```
false
```

* * *

### tostring

Converts a value to its string representation. Useful for storing numeric or boolean event data in a string field.

#### tostring Example

**Example Event Data (JSON)**

```
{
	"order_id": 82727,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
tostring(`order_id`)
```

**Resulting Value**

```
82727
```

**Breaking down the Example**

The incoming order\_id is a number; tostring() converts it so the resulting value is the string "82727" rather than the integer 82727.

* * *

### cast

Casts a value to an explicitly named type. Takes the value and the target type as a string: one of "char", "string", "int", or "float".

#### cast Example

**Example Event Data (JSON)**

```
{
	"order_total": "22.5",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
cast(`order_total`, "float")
```

**Resulting Value**

```
22.5
```

In raw LQL the SQL-style form cast(order\_total AS float) is also accepted and is equivalent.

* * *

### unsign

Converts a signed integer to its unsigned 64-bit representation, returned as a string. Positive numbers pass through unchanged; negative numbers wrap around the maximum unsigned value (18446744073709551615). This is primarily useful for identifiers exported from systems that store IDs as signed integers.

#### unsign Example

**Example Event Data (JSON)**

```
{
	"device_id": "-70",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
unsign(`device_id`)
```

**Resulting Value**

```
18446744073709551546
```

  

* * *

* * *

## Map & Set/Array Functions

These functions manipulate map or set fields.  
note: for the [**len**](#len) function see the String function listed above

* * *

### filter

Filter out values that match the specified criteria

#### filter Example

**Example Event Data (JSON)**

```
{
	"sliceField":"red, orange, yellow, green, blue, indigo, violet",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
filter(strip(split(`sliceField`, ",")), "bl*")
```

**Resulting Value**

```
[
	"red",
	"orange",
	"yellow",
	"green",
	"indigo",
	"violet"
]
```

**Breaking Down the Example**

This filter() operates on top of the array built by split()'ing and strip()'ing the sliceField. Once we have our base array, we then apply the filter "bl\*" (in which \* is a wildcard) to match the "blue" value and filter it OUT of the array (returning an array including all the unmatched values)

* * *

### map

Create an object/map of key-value pairs. Often used to keep a map of key (event-name?) to value (last occurrence date?). Or other user level key-value pair data.

#### map Example

**Example Event Data (JSON)**

```
{
	"listName":"Pretend Campaign",
	"subscribeStatus":"subscribed",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
map(`listName`, `subscribeStatus`)
```

**Resulting Value**

```
{
	"Pretend Campaign": "subscribed"
}
```

* * *

### match

Match a key, and then keep a map of key/values with the match value removed.

#### match Example

**Example Event Data (JSON)**

```
{
	"example_a":1,
	"example_b":2,
	"example_c":3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
match("example_")
```

**Resulting Value**

```
{
	"a": "1",
	"b": "2",
	"c": "3"
}
```

**Breaking Down the Example**

The match() function here looks for all keys prefixed with "example\_", and finding 3 results, creates a map of key (key suffix) -> value pairs from those results utilizing the suffix of the original keys to write to the map.

* * *

### mapkeys

Given a map, return a list of strings consisting of the keys from the map

#### mapkeys Example

**Example Event Data (JSON)**

```
{
	"example_a":1,
	"example_b":2,
	"example_c":3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
mapkeys(match("example_"))
```

**Resulting Value**

```
[
	"b",
	"c",
	"a"
]
```

**Breaking Down the Example**

The mapkeys() function here utilizes the result of the match() statement as its input map, and returns a list consisting of the keys from that map.

* * *

### mapvalues

Given a map, return a list of the values (as strings)

#### mapvalues Example

**Example Event Data (JSON)**

```
{
	"example_a":1,
	"example_b":2,
	"example_c":3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
mapvalues(match("example_"))
```

**Resulting Value**

```
[
	"3",
	"1",
	"2"
]
```

**Breaking Down the Example**

The mapvalues() function here utilizes the result of the match() statement as its input map, and returns a string list consisting of the values from that map.

* * *

### mapinvert

Given a map, return a map of type map\[string\]string, inverting the keys/values from the initial map

**Example Event Data (JSON)**

```
{
	"example_a":1,
	"example_b":2,
	"example_c":3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
mapinvert(match("example_"))
```

**Resulting Value**

```
{
	"1": "a",
	"2": "b",
	"3": "c"
}
```

**Breaking Down the Example**

The mapinvert() function here utilizes the result of the match() statement as its input map, and returns a map (map\[string\]string) with each key-> value pair inverted (value->key).

* * *

### array.index

Cherry pick a single item out of an array

#### array.index Example

**Example Event Data (JSON)**

```
{
	"fruits": ["apples", "oranges", "peaches"],
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
array.index(`fruits`, 0)
```

**Resulting Value**

```
apples
```

**Breaking Down the Example**

The array.index() function utilizes a 0 indexed array to cherry pick the requested index's value, in this case 0 being the first indexed item returns "apples".

* * *

### array.slice

Slice an array of items selecting some subset of them

#### array.slice Example

**Example Event Data (JSON)**

```
{
	"fruits": ["tomato", "apple", "orange", "peach"],
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
array.slice(`fruits`, 1, 4)
```

**Resulting Value**

```
[
	"apple",
	"orange",
	"peach"
]
```

**Breaking Down the Example**

For this example the array.slice() function takes 3 parameters (the 3rd being optional), and returns an array consisting of the subset of the initial array (1st parameter) beginning at the start index (2nd parameter) up to, but not including, the end index (3rd parameter, if not provided then it defaults to the end of the input array). Reminder that these functions utilize 0 indexed arrays, so the index of 1 is actually the 2nd item in the array.

* * *

### maptime

Creates a map of the key's value to a timestamp (map\[string\]time). With one argument the event's timestamp is used; an optional second argument supplies the timestamp instead: maptime(key, date\_field). Often used to keep a map of, for example, each event name to the time it last occurred.

#### maptime Example

**Example Event Data (JSON)**

```
{
	"product_sku": "ABC-12345",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
maptime(`product_sku`)
```

**Resulting Value**

```
{
	"ABC-12345": "2024-11-18T17:51:21Z"
}
```

* * *

### latestmap

Identical to [maptime](#maptime), but the function name also selects the merge behavior for the field: when new events arrive, latestmap keeps the **most recent** timestamp seen for each key in the map.

* * *

### oldestmap

Identical to [maptime](#maptime), but the function name also selects the merge behavior for the field: when new events arrive, oldestmap keeps the **earliest** timestamp seen for each key in the map (for example, the first time each event name was observed).

* * *

### match.transform

Like [match](#match), builds a map from all incoming keys that start with the given prefix (with the prefix removed), but additionally transforms the remaining key names. Supported transforms are "title", "upper", and "lower"; any other value leaves the key names unchanged.

#### match.transform Example

**Example Event Data (JSON)**

```
{
	"label_orange": "orange",
	"label_lime": "lime",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
match.transform("label_", "upper")
```

**Resulting Value**

```
{
	"ORANGE": "orange",
	"LIME": "lime"
}
```

* * *

### filtermatch

The keep-only counterpart to [filter](#filter): returns only the values that match the specified criteria (in which \* is a wildcard), instead of removing them. Operates on arrays, maps (matching on keys), or single strings, and accepts one or more match patterns.

#### filtermatch Example

**Example Event Data (JSON)**

```
{
	"sliceField":"red, orange, yellow, green, blue, indigo, violet",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
filtermatch(strip(split(`sliceField`, ",")), "bl*")
```

**Resulting Value**

```
[
	"blue"
]
```

* * *

### cap

Caps the number of entries stored for a multi-value field (a set or map): cap(expression, count). The wrapped expression evaluates normally; the cap is enforced when the profile is saved, so the field never grows beyond the given number of entries.

#### cap Example

**Example Event Data (JSON)**

```
{
	"favorite-genres":"mystery|science fiction|fantasy",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
cap(set(split(`favorite-genres`, "|")), 50)
```

**Resulting Value**

```
[
"fantasy",
"mystery",
"science fiction"
]
```

**Breaking Down the Example**

The inner expression builds a set of genres exactly as [set](#set) and [split](#split) normally would. Wrapping it in cap(..., 50) guarantees the stored set is limited to at most 50 entries as further events add values over time.

* * *

### maxkey

Given the name of a map field on the profile, returns the key holding the **largest** numeric value. Optional additional arguments provide a list of keys to include (limiting the comparison to those keys) and a list of keys to exclude. Note this function evaluates against the profile's stored field (passed as a quoted field name), not against incoming event data.

#### maxkey Example

**Expression**

```
maxkey("visits_by_channel")
```

**Resulting Value**

```
email
```

**Breaking Down the Example**

If the profile's visits\_by\_channel field holds {"email": 12, "web": 7, "sms": 2}, the key with the largest value — email — is returned.

* * *

### minkey

The counterpart to [maxkey](#maxkey): given the name of a map field on the profile, returns the key holding the **smallest** numeric value.

* * *

  

* * *

* * *

## URL/HTTP & Email Functions

These functions manipulate strings which are URLs or email addresses.

* * *

### email

Extract email address from "Bob <emailaddress@lytics.io>" format, note that the extracted email addresses are converted to lowercase and checked to ensure the existence of an @ symbol as well.

#### email Example

**Example Event Data (JSON)**

```
{
	"email":"Test <TEST@test.com>",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
email(`email`)
```

**Resulting Value**

```
test@test.com
```

**Breaking Down the Example**

In this example the email() function first extracts the email address of "[TEST@test.com](mailto:TEST@test.com)" from the input (this input can be in the simplified input already, and will then just apply the second part of the function). Once we have the email address, the function then performs a lowercase operation and checks to ensure the presence of an @ symbol. This check is fairly rudimentary and may change to provide stricter validation in the future.

* * *

### emailname

Extract _Bob_ from Bob <test@test.com>

#### emailname Example

**Example Event Data (JSON)**

```
{
	"email":"Test <TEST@test.com>",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
emailname(`email`)
```

**Resulting Value**

```
Test
```

* * *

### emaildomain

Extract _gmail.com_ from "Bob <emailaddress@gmail.com>" or email@gmail.com

**Example Event Data (JSON)**

```
{
	"email":"Test <TEST@test.com>",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
emaildomain(`email`)
```

**Resulting Value**

```
test.com
```

* * *

### emailclean

Cleans an email value by truncating it at each of the given delimiters (keeping the portion before the delimiter), then validating what remains as an email address and lowercasing it. If the remaining value is not a valid email address, nothing is written. Takes the value followed by one or more delimiter strings.

#### emailclean Example

**Example Event Data (JSON)**

```
{
	"email":"TEST@test.com;source=import",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
emailclean(`email`, ";")
```

**Resulting Value**

```
test@test.com
```

**Breaking Down the Example**

The value is split at the ";" delimiter and only the portion before it is kept (TEST@test.com). That remainder parses as a valid email address, so it is lowercased and returned.

* * *

### url

Checks if URL string is valid and returns URL if true

#### url Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
url(`_url`)
```

**Resulting Value**

```
https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2
```

* * *

### urlmain

Removes the query string and scheme from the url

#### urlmain Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urlmain(`_url`)
```

**Resulting Value**

```
subdomain.domain.tld/path/extended_path
```

**Breaking Down the Example**

The urlmain() function here strips the leading scheme ("https://") and query string parameters ("?qsparam=p1&qsp2=param2") from the provided url.

* * *

### domain

Extract domain from URL

#### domain Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
domain(`_url`)
```

**Resulting Value**

```
domain.tld
```

* * *

### domains

The list counterpart to [domain](#domain): extracts the domain from one or more URLs (a single URL or an array of URLs) and returns the results as a list of strings.

#### domains Example

**Example Event Data (JSON)**

```
{
	"urls": ["https://www.lytics.io/index.html", "https://blog.example.com/post"],
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
domains(`urls`)
```

**Resulting Value**

```
[
	"lytics.io",
	"example.com"
]
```

* * *

### host

Extract host from URL

#### host Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
host(`_url`)
```

**Resulting Value**

```
subdomain.domain.tld
```

* * *

### hosts

The list counterpart to [host](#host): extracts the host from one or more URLs (a single URL or an array of URLs) and returns the results as a list of strings.

#### hosts Example

**Example Event Data (JSON)**

```
{
	"urls": ["https://www.lytics.io/index.html", "https://blog.example.com/post"],
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hosts(`urls`)
```

**Resulting Value**

```
[
	"www.lytics.io",
	"blog.example.com"
]
```

* * *

### path

Extract the URL path from the URL

#### path Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
path(`_url`)
```

**Resulting Value**

```
/path/extended_path
```

* * *

### urldecode

Perform URL decoding on a field. (my%20value -> my value)

#### urldecode Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?spaced=this%20is%20spaced",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urldecode(qs(`_url`, "spaced"))
```

**Resulting Value**

```
this is spaced
```

**Breaking Down the Example**

With this example of urldecode() we want to decode the "spaced" query parameter value. To do this we first extract the parameter's value utilizing the qs() function, returning "this%20is%20spaced". We then proceed to use the urldecode() function to convert the "%20" to " ", and have our decoded string of "this is spaced".

* * *

### urlminusqs

Removes a specific query parameter and its value from a URL

#### urlminusqs Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsparam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urlminusqs(`_url`, "qsp2")
```

**Resulting Value**

```
https://subdomain.domain.tld/path/extended_path?qsparam=p1
```

* * *

### urlwithqs

Strips the scheme from a URL and keeps **only** the query string parameters whose names match one of the supplied patterns (regular expressions). With no patterns, returns just the host and path. Any parameter that matches none of the patterns is dropped.

#### urlwithqs Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path?utm_source=google&pid=123",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urlwithqs(`_url`, "pid")
```

**Resulting Value**

```
subdomain.domain.tld/path?pid=123
```

* * *

### url.matchqs

An alias of [urlwithqs](#urlwithqs) — identical behavior: keeps only the query string parameters matching the supplied patterns and strips the scheme.

* * *

### urlfilteredqs

The inverse of [urlwithqs](#urlwithqs): strips the scheme from a URL and **removes** the query string parameters whose names match one of the supplied patterns (regular expressions), keeping the rest. Unlike [urlminusqs](#urlminusqs), it accepts multiple patterns and matches them as patterns rather than exact names.

#### urlfilteredqs Example

**Example Event Data (JSON)**

```
{
	"_url": "https://www.google.com/?utm_campaign=spring&utm_source=facebook&pid=123",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urlfilteredqs(`_url`, "utm_")
```

**Resulting Value**

```
www.google.com/?pid=123
```

* * *

### urlmainqs

Strips the scheme from a URL and keeps only the query string parameters whose names **exactly** match one of the listed names. Similar to [urlwithqs](#urlwithqs), but arguments are exact parameter names rather than patterns.

#### urlmainqs Example

**Example Event Data (JSON)**

```
{
	"_url": "https://www.google.com/?q=golang&v=1",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
urlmainqs(`_url`, "q")
```

**Resulting Value**

```
www.google.com/?q=golang
```

* * *

### qs

Extract the query string parameter from URL

**Deprecated**

qs (and its alias qsl) is deprecated in favor of [qs2](#qs2). qs lowercases the **entire** URL — including parameter names and values — before matching, which can silently alter the extracted value. Use qs2 for new mappings; qs remains available for existing mappings that depend on the lowercasing behavior.

#### qs Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsParam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
qs(`_url`, "qsp2")
```

**Resulting Value**

```
param2
```

**Breaking Down the Example**

Here the qs() function attempts to find the requested query string parameter in the URL and returns it if found. It's important to note here that this function inherently lowercases the URL provided BEFORE attempting to match the query string, where [qs2()](#qs2) will search the raw URL provided without lowercasing. Effectively qs(url, param) == qs2(tolower(url), param)

* * *

### qs2

Extract a querystring parameter without lowercasing the URL before checking for the parameter

#### qs2 Example

**Example Event Data (JSON)**

```
{
	"_url": "https://subdomain.domain.tld/path/extended_path?qsParam=p1&qsp2=param2",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
qs2(`_url`, "qsParam")
```

**Resulting Value**

```
p1
```

* * *

### useragent

Extract info from user-agent string.

Below examples based on Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11

*   useragent(\_ua, "bot") - Extracts True/False is this a bot?
*   useragent(\_ua, "mobile") - Extracts True/False is this mobile?
*   useragent(\_ua, "mozilla") - Extracts "5.0"
*   useragent(\_ua, "platform") - Extracts "X11"
*   useragent(\_ua, "os") - Extracts "Linux x86\_64"
*   useragent(\_ua, "engine") - Extracts "AppleWebKit"
*   useragent(\_ua, "engine\_version") - Extracts "537.11"
*   useragent(\_ua, "browser") - Extracts "Chrome"
*   useragent(\_ua, "browser\_version") - Extracts "23.0.1271.97"
*   useragent.map(\_ua) - Extract map of all of above, see [useragent.map](#useragentmap).

#### useragent Example

**Example Event Data (JSON)**

```
{
	"_ua": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
useragent(`_ua`, "browser")
```

**Resulting Value**

```
Chrome
```

* * *

### useragent.map

Extracts **all** of the [useragent](#useragent) properties at once as a map (map\[string\]string).

#### useragent.map Example

**Example Event Data (JSON)**

```
{
	"_ua": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
useragent.map(`_ua`)
```

**Resulting Value**

```
{
	"bot": "false",
	"browser": "Chrome",
	"browser_version": "23.0.1271.97",
	"engine": "AppleWebKit",
	"engine_version": "537.11",
	"mobile": "false",
	"mozilla": "5.0",
	"os": "Linux x86_64",
	"platform": "X11"
	}
```

* * *

### uuid

Generates a new random UUID (v4). Takes no arguments. Commonly used to assign a unique identifier when the incoming event does not carry one.

#### uuid Example

**Expression**

```
uuid()
```

**Resulting Value**

```
0dd7c134-4dcd-4806-b6ac-6e37d3ab24f5
```

* * *

  

* * *

* * *

## IP Functions

These functions evaluate strings which are IP addresses.

* * *

### ipfilter

Evaluate whether an IP address is contained in a given CIDR range. Compatible with both IPv4 and IPv6.

#### ipfilter Example

**Example Event Data (JSON)**

```
{
	"ip_address":"75.164.253.177",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
ipfilter(`ip_address`, "75.164.253.0/24")
```

**Resulting Value**

```
true
```

  

* * *

* * *

## Geolocation Functions

The geo\* functions derive a location from an IP address. Called with no arguments they use the \_ip field on the incoming event (populated automatically for events collected by the Lytics JavaScript tag); alternatively an IP address can be passed as the single argument, e.g. geocity(ip\_field). If the IP cannot be resolved to a location, no value is written.

The remaining functions in this section normalize country/language values and work with ZIP codes and geo points.

* * *

### geocity

The city name for the event's IP address.

#### geocity Example

**Example Event Data (JSON)**

```
{
	"_ip": "75.164.253.177",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
geocity()
```

**Resulting Value**

```
Portland
```

* * *

### georegion

The region (state/province) for the event's IP address, as an ISO subdivision code.

#### georegion Example

**Expression**

```
georegion()
```

**Resulting Value**

```
OR
```

* * *

### geocountry

The country for the event's IP address, as an ISO 3166-1 alpha-2 code.

#### geocountry Example

**Expression**

```
geocountry()
```

**Resulting Value**

```
US
```

* * *

### geolatitude

The latitude for the event's IP address, as a number.

* * *

### geolongitude

The longitude for the event's IP address, as a number.

* * *

### geolocation

The full geo point for the event's IP address, as a map holding the latitude, longitude, and the accuracy radius (in kilometers) of the lookup. Fields built with geolocation() can be evaluated with [geodistance](#geodistance).

#### geolocation Example

**Expression**

```
geolocation()
```

**Resulting Value**

```
{
	"lat": 45.5234,
	"lon": -122.6762,
	"accuracy": 5
}
```

* * *

### geopostalcode

The postal code for the event's IP address.

#### geopostalcode Example

**Expression**

```
geopostalcode()
```

**Resulting Value**

```
97205
```

* * *

### countrycode

Normalizes a country name or code to its ISO 3166-1 alpha-2 code. Accepts full names ("United States"), alpha codes, or native-language names.

#### countrycode Example

**Example Event Data (JSON)**

```
{
	"country": "United States",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
countrycode(`country`)
```

**Resulting Value**

```
US
```

* * *

### languagecode

Normalizes a language name or code to its ISO 639-1 two-letter code.

#### languagecode Example

**Example Event Data (JSON)**

```
{
	"language": "English",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
languagecode(`language`)
```

**Resulting Value**

```
en
```

* * *

### ziplatlong

Converts a postal code to a latitude/longitude map. Supports 5-digit US ZIP codes (a ZIP+4 value is truncated to its first 5 digits) and Canadian postal codes (matched on the first 3 characters).

#### ziplatlong Example

**Example Event Data (JSON)**

```
{
	"zip": "97205",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
ziplatlong(`zip`)
```

**Resulting Value**

```
{
	"lat": 45.52,
	"long": -122.69
}
```

* * *

### ziptogeolocation

An alias of [ziplatlong](#ziplatlong) — identical behavior.

* * *

### geodistance

Evaluates whether a geo point field is within a given distance (in kilometers) of a target point: geodistance(geo\_field, "latitude,longitude", distance\_km). The first argument must be a geo point field (for example one built with [geolocation](#geolocation)); the target is a string of comma-separated latitude and longitude. Returns a boolean, so it is used in conditions rather than mappings.

#### geodistance Example

**Expression**

```
geodistance(`location`, "45.5234,-122.6762", 25)
```

**Resulting Value**

```
true
```

* * *

## Date & Time Functions

These functions manipulate date fields. Our core [Date Parser](https://github.com/araddon/dateparse) recognizes about 50 date formats, so in general these will operate on _any_ format.  
If you are using EU dates, you will need to specify the parser format.

* * *

### now

The current message/event time.

#### now Example

**Example Event Data (JSON)**

```
{
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
now()
```

**Resulting Value**

```
2024-11-18T17:51:21.483775672Z
```

**Breaking Down the Example**

The event in question contains no attribute defining the date/time of the event, and therefore is processed utilizing the current time as the datetime for the event (The time of this example being "2024-11-18T17:51:21.483775672Z").

* * *

### epochms

Unix MS of the date stamp on the current message being processed

**Example Event Data (JSON)**

```
{
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
epochms()
```

**Resulting Value**

```
1731952777954
```

**Breaking Down the Example**

Similar to the now() function, the epochms() function uses the current event's timestamp to produce a result. This time however, we return its representation as integer Unix milliseconds (UTC).

* * *

### createdms

Like [epochms](#epochms), returns the timestamp of the current message in epoch milliseconds (an optional date argument is parsed instead if provided). It exists to capture profile-creation time: map it with the **oldest** merge operator so the field permanently keeps the timestamp of the first event seen for the profile.

#### createdms Example

**Expression**

```
createdms()
```

**Resulting Value**

```
1731952777954
```

* * *

### todate

*   **todate** Converts strings to dates.
    *   Datemath: todate("now-3m") Date math relative to message timestamp.
    *   Parser: todate("02/01/2006") See [Date Parser](https://github.com/araddon/dateparse) for supported formats.
    *   Examples with 2 arguments: todate("02/01/2006","07/04/2014") use [golang's time package](http://golang.org/pkg/time/) formatting
        *   todate("02/01/2006","07/04/2014") Reformats the date 07/04/2014 from US formatting to UK formatting, with the resulting output being 04/07/2014
        *   todate("02/01/2006",date\_field\_name) Outputs date\_field\_name as European format (where 01 is a placeholder for month, 02 is a placeholder for day, and 2006 is a placeholder for year)

#### todate Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
todate(`dateExample`)
```

**Resulting Value**

```
2024-11-15T00:00:00Z
```

* * *

### todatein

Converts strings to dates while specifying a location / timezone. _We still convert back to UTC for storage_

#### todatein Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
todatein(`dateExample`, "America/Los_Angeles")
```

**Resulting Value**

```
2024-11-15T08:00:00Z
```

* * *

### totimestamp

Convert date(time) to Integer Unix Seconds (UTC)

#### totimestamp Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
totimestamp(`dateExample`)
```

**Resulting Value**

```
1731628800
```

* * *

### extract

Used to extract parts of a date(time). Example usage on the [strftime](http://strftime.org/) site

#### extract Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
extract(`dateExample`, "%d")
```

**Resulting Value**

```
15
```

* * *

### yy

Date conversion to YY format, so May 1 2014 is expressed as 14. yy(dob), or yy() for record time stamp

#### yy Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
yy(`dateExample`)
```

**Resulting Value**

```
24
```

* * *

### yymm

The YYMM date format, so May 1 2014 is expressed as 1405.

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
yymm(`dateExample`)
```

**Resulting Value**

```
2411
```

* * *

### mm

Date conversion to Integer month value (alias for [monthofyear](#monthofyear) )

#### mm Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-05-18",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
mm(`dateExample`)
```

**Resulting Value**

```
5
```

* * *

### monthofyear

See [mm](#mm)

* * *

### dayofweek

Integer representation of the day of the week. (0-6, 0=Sunday, 1=Monday, etc.)

#### dayofweek Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-18",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
dayofweek(`dateExample`)
```

**Resulting Value**

```
1
```

* * *

### hourofweek

0-167 Integer representing the hour of the week (12:00-12:59am || 00:00:00-00:59:59 on Sunday is 0 hour)

#### hourofweek Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15T00:00:00Z",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hourofweek(`dateExample`)
```

**Resulting Value**

```
120
```

* * *

### hourofday

Hour of day (12:00-12:59am || 00:00:00-00:59:59 = 0)

#### hourofday Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15T00:00:00Z",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
hourofday(`dateExample`)
```

**Resulting Value**

```
0
```

* * *

### seconds

The Integer number of seconds in a given time (works with datetime as well as MM:SS)

*   things like seconds("00:30") => 30 and seconds("10:30") => 630

#### seconds Example

**Example Event Data (JSON)**

```
{
	"dateExample": "2024-11-15T00:00:00Z",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
seconds(`dateExample`)
```

**Resulting Value**

```
1731628800
```

* * *

### unixtrunc

Truncates an epoch-milliseconds timestamp to seconds, returned as a string. With the optional second argument "seconds" the milliseconds are kept after the decimal point ("1438445529.707"); with "secondsmicro" a microsecond-precision input is truncated the same way.

#### unixtrunc Example

**Example Event Data (JSON)**

```
{
	"ts": "1438445529707",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
unixtrunc(`ts`)
```

**Resulting Value**

```
1438445529
```

* * *

### timebucket

Builds a rolling tabulation of daily event counts (a time-bucket structure) from a timestamp, which can then be evaluated with [timewindow](#timewindow) conditions ("seen X times in the last Y days"). The first argument must be a datetime or an epoch-milliseconds integer — typically now() to count occurrences of the event — and must fall within one year of the event's timestamp. Optional additional integer arguments set the amount to add to the bucket (default 1).

#### timebucket Example

**Expression**

```
timebucket(now())
```

**Breaking Down the Example**

Each matching event increments the count in the bucket for the day it occurred, so the field accumulates a day-by-day activity history rather than a single value.

* * *

### totimeset

Converts a value, or an array of values, into a set of datetimes (\[\]time). Strings are parsed with the same [Date Parser](https://github.com/araddon/dateparse) used by [todate](#todate) (datemath such as "now-3m" is also accepted). This is the datetime counterpart to wrapping [split](#split) results in set().

#### totimeset Example

**Example Event Data (JSON)**

```
{
	"visit_dates": "2024-11-01|2024-11-15",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
totimeset(split(`visit_dates`, "|"))
```

**Resulting Value**

```
[
"2024-11-01T00:00:00Z",
"2024-11-15T00:00:00Z"
]
```

* * *

  

* * *

* * *

## Aggregate Functions

There are a variety of expressions for building document type structures (maps, lists, sets). These are functional expressions but can only be used in Columns.

* * *

### count

Count of # of occurrences of the specified key

#### count Example

**Example Event Data (JSON)**

```
{
	"key": "value",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": "value_too",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
count(`key`)
```

**Resulting Value**

```
2
```

* * *

### valuect

Count of # of occurrences of each value for a specific key (stored as a map\[value\]count)

#### valuect Example

**Example Event Data (JSON)**

```
{
	"key": "value",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": "value_too",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
valuect(`key`)
```

**Resulting Value**

```
{
	"value": 1,
  "value_too": 1
}
```

* * *

### mapct

An alias of [valuect](#valuect) — identical behavior.

* * *

### sum

Summation of values for a specified key over time

#### sum Example

**Example Event Data (JSON)**

```
{
	"key": 30,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": 3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
sum(`key`)
```

**Resulting Value**

```
33
```

* * *

### avg

Average of the numeric values passed to it **within a single event** — a single value, an array of values, or multiple arguments. Note that unlike [sum](#sum) or [count](#count), avg does not accumulate across events over time.

#### avg Example

**Example Event Data (JSON)**

```
{
	"scores": [1, 2, 3],
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
avg(`scores`)
```

**Resulting Value**

```
2
```

* * *

### min

Minimum numeric value seen for the specified key over time

#### min Example

**Example Event Data (JSON)**

```
{
	"key": 30,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": 3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
min(`key`)
```

**Resulting Value**

```
3
```

* * *

### max

Maximum numeric value seen for the specified key over time

#### max Example

**Example Event Data (JSON)**

```
{
	"key": 30,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": 3,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
max(`key`)
```

**Resulting Value**

```
30
```

* * *

### set

Create a unique list/array of each value seen for this key over time

#### set Example

**Example Event Data (JSON)**

```
{
	"key": "value",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 2 (JSON)**

```
{
	"key": "value_too",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Example Event Data 3 (JSON)**

```
{
	"key": "value",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
set(`key`)
```

**Resulting Value**

```
[
	"value",
  "value_too"
]
```

* * *

### mapmax

Given a map of numeric values, returns the **key** holding the largest value.

#### mapmax Example

**Example Event Data (JSON)**

```
{
	"score_email": 2,
	"score_web": 7,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
mapmax(match("score_"))
```

**Resulting Value**

```
web
```

**Breaking Down the Example**

The inner [match](#match) builds the map {"email": 2, "web": 7}; mapmax() then returns the key with the highest value, web.

* * *

### numevents

The total number of events recorded for the profile (excluding Lytics-internal streams), computed from the profile's stream activity history. Takes no arguments and does not read the incoming event's data.

#### numevents Example

**Expression**

```
numevents()
```

**Resulting Value**

```
42
```

* * *

### numstreams

The number of distinct data streams the profile has appeared in (excluding Lytics-internal streams). Takes no arguments.

#### numstreams Example

**Expression**

```
numstreams()
```

**Resulting Value**

```
3
```

* * *

### numdays

The number of distinct days on which the profile had at least one event (excluding Lytics-internal streams). Takes no arguments.

#### numdays Example

**Expression**

```
numdays()
```

**Resulting Value**

```
17
```

* * *

### numaliases

The number of identifier (alias) values present on the profile, counted across the given list of identifier field names. Fields holding a set of values contribute one count per value.

#### numaliases Example

**Expression**

```
numaliases(set("email", "user_id"))
```

**Resulting Value**

```
2
```

* * *

### streamnames

The list of data stream names the profile has appeared in (excluding Lytics-internal streams). Takes no arguments.

#### streamnames Example

**Expression**

```
streamnames()
```

**Resulting Value**

```
[
	"default",
	"segment_web"
]
```

* * *

### stream

The name of the data stream the current event arrived on. Takes no arguments.

#### stream Example

**Expression**

```
stream()
```

**Resulting Value**

```
default
```

* * *

  

* * *

* * *

## Logical Functions

These functions are used for local evaluation (often as conditional statements), and return boolean values (true/false).

* * *

### all

Checks a list of values (or keys' values), and returns **true** if ALL those values (or keys' values) are non zero-values (keys that are missing from incoming data will result in a false return here).

#### all Example

**Example Event Data (JSON)**

```
{
	"key": "",
	"key_too":"value_too",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
all(`key`, `key_too`)
```

**Resulting Value**

```
false
```

* * *

### any

Similar to [all()](#all) , except only requires one of the given parameters to evaluate to true'ish (not a zero-value) for the result to be **true**

#### any Example

**Example Event Data (JSON)**

```
{
	"key": "",
	"key_too":"value_too",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
any(`key`, `key_too`)
```

**Resulting Value**

```
true
```

* * *

### exists

Checks for the existence of a key (or a passed value), and confirms the value (if it exists) is not the empty string.

#### exists Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
exists(`key`)
```

**Resulting Value**

```
true
```

* * *

### defined

An alias of [exists](#exists) — identical behavior.

* * *

### eq

Checks for equality

#### eq Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
eq(`key`, 0)
```

**Resulting Value**

```
true
```

* * *

### ne

Inverse of [eq()](#eq)

#### ne Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
ne(`key`, 0)
```

**Resulting Value**

```
false
```

* * *

### lt

Checks if the first argument is **less than** the second

#### lt Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"key_too": 1,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
lt(`key`, `key_too`)
```

**Resulting Value**

```
true
```

* * *

### le

Checks if the first argument is **less than OR equal to** the second.

#### le Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"key_too": 1,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
le(`key`, `key_too`)
```

**Resulting Value**

```
true
```

* * *

### gt

Checks if the first argument is **greater than** the second.

#### gt Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"key_too": 1,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
gt(`key`, `key_too`)
```

**Resulting Value**

```
false
```

* * *

### ge

Checks if the first argument is **greater than OR equal to** the second.

#### ge Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"key_too": 1,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
ge(`key`, `key_too`)
```

**Resulting Value**

```
false
```

* * *

### not

Returns the inverse of a boolean valuation (not(false) == true)

#### not Example

**Example Event Data (JSON)**

```
{
	"key": 0,
  "key_too": 1,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
not(eq(`key`, `key_too`))
```

**Resulting Value**

```
true
```

* * *

### in

Checks if <value> is in the supplied value list

#### in Example

**Example Event Data (JSON)**

```
{
	"key": 0,
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
`key` in (0, 2, 4, 6, 8)
```

**Resulting Value**

```
true
```

* * *

### and

Returns **true** only if every one of the given conditions is true. Conditions can also be combined with the infix form: condition1 AND condition2.

#### and Example

**Example Event Data (JSON)**

```
{
	"email": "test@test.com",
	"status": "active",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
and(exists(`email`), eq(`status`, "active"))
```

**Resulting Value**

```
true
```

* * *

### or

Returns **true** if at least one of the given conditions is true. Conditions can also be combined with the infix form: condition1 OR condition2.

#### or Example

**Example Event Data (JSON)**

```
{
	"domain": "google.com",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
or(exists(`domain`), contains(`referrer`, "google"))
```

**Resulting Value**

```
true
```

* * *

### ifelse

Returns one of two values based on a condition: ifelse(condition, value\_if\_true, value\_if\_false). The condition must evaluate to a boolean.

#### ifelse Example

**Example Event Data (JSON)**

```
{
	"is_trial": "t",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
ifelse(tobool(`is_trial`), "trial", "paid")
```

**Resulting Value**

```
trial
```

**Legacy LQL forms**

Raw LQL columns also support an inline conditional, {VALUE\_IF\_TRUE} IF {CONDITION} ELSE {VALUE\_IF\_FALSE}, and a multi-branch form, ifcase({VALUE\_1} IF {CONDITION\_1}, {VALUE\_2} IF {CONDITION\_2}, {DEFAULT\_VALUE}), which checks each condition in order and falls back to the final default value. In the Schema mapping UI, use ifelse() (optionally nested) instead.

* * *

### filterin

Checks whether the value of a key matches **any** of the given values (arguments may be single values or lists), returning **true** on a match. Similar to [in](#in), in function form.

#### filterin Example

**Example Event Data (JSON)**

```
{
	"role": "student",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
filterin(`role`, "student", "teacher")
```

**Resulting Value**

```
true
```

* * *

### filterout

The inverse of [filterin](#filterin): returns **true** only if the value of the key matches **none** of the given values.

#### filterout Example

**Example Event Data (JSON)**

```
{
	"role": "student",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
filterout(`role`, "bot", "employee")
```

**Resulting Value**

```
true
```

* * *

### timewindow

Evaluates a rolling activity window over a field built with [timebucket](#timebucket): timewindow(timebucket\_field, threshold, window) returns **true** if the field's event count reached the threshold within the trailing window of days. The threshold must be one of 1, 2, 5, 10, 25, 50, 100 and the window one of 7 or 30 days. Returns a boolean, so it is used in conditions (such as audience rules) rather than mappings.

#### timewindow Example

**Expression**

```
timewindow(`visits`, 5, 30)
```

**Resulting Value**

```
true
```

**Breaking Down the Example**

With visits defined as timebucket(now()), this condition is **true** while the profile has recorded at least 5 visits within the last 30 days.

* * *

### recurring

Evaluates whether a date field's anniversary falls on today's date in UTC: recurring(date\_field, period, offset\_days). The period is "yearly" (same month and day), "monthly" (same day of the month), "weekly" (same day of the week), or a positive whole number of days for an every-N-days cycle. The optional offset\_days moves the match that many days later, for example 182 with "yearly" for a half-birthday, and can't be negative. A date that doesn't exist in a period doesn't match: a Feb 29 date matches only in leap years, and the 31st only in months that have one. Returns a boolean, so it is used in conditions (such as audience rules) rather than mappings. In the audience builder it is the **recurring anniversary** operator on date fields.

#### recurring Example

**Expression**

```
recurring(`birth_date`, "yearly")
```

**Resulting Value**

```
true
```

**Breaking Down the Example**

This condition is **true** on each profile's birthday, every year.

* * *

### content\_filter

A specialized condition for content enrichment queries. Takes no arguments and returns **true** if the event passes the account's configured content filters — the content domain allowlist (content\_whitelist\_domains) and the content date cutoffs (content\_since\_date / content\_created\_since\_date) account settings. Only relevant in the WHERE clause of content queries.

* * *

  

* * *

* * *

## JSON Functions

These functions extract data from fields containing raw JSON.

* * *

### json.jmespath

Extracts a value from a JSON string using a [JMESPath](https://jmespath.org/) expression: json.jmespath(field, "path").

#### json.jmespath Example

**Example Event Data (JSON)**

```
{
	"items": "[{\"name\":\"n1\",\"ct\":8},{\"name\":\"n2\",\"ct\":10}]",
	"_uid":"0123-4567-8901-2345-6789"
}
```

**Expression**

```
json.jmespath(`items`, "[?name == 'n1'].ct | [0]")
```

**Resulting Value**

```
8
```

**Breaking Down the Example**

The items field holds a JSON array as a string. The JMESPath expression filters the array to the object whose name is "n1", projects its ct value, and | \[0\] unwraps the single-element result, yielding 8.

* * *

  

* * *

* * *

## Phone Number

These functions are used for converting phone numbers to a specific format

* * *

### phone.e164

Converts a phone number to the international E.164 format for the specified country. If no country is provided, the system defaults to "US" formatting.

**Example Event Data (JSON)**

```
{
	"phone_number": "(800) 555-1212",
	"country_code":"US"
}
```

**Expression**

```
phone.e164(`phone_number`, `country_code`)
```

**Resulting Value**

```
+18005551212
```

* * *

  

* * *

* * *