API version: 0.3.0

---

# Expr Lang

[Expr Lang](https://github.com/expr-lang/expr) is a Go expression language and evaluation engine. Ember Nexus embeds
it wherever a client needs to compute a value from data it doesn't control ahead of time, instead of writing a custom
mini-language for every feature that needs it.

Expressions are sandboxed: they can only read the data explicitly passed into them, cannot call arbitrary Go code, and
cannot perform I/O. Ember Nexus uses expressions for [schema rules](/reference/schemas/rules.md), which every write of an
element of a type has to satisfy, and for parameterizing search steps that have no native concept of parameters:

- The [Elasticsearch query](/reference/search/elasticsearch-query-dsl-mixin.md#parameterized-elasticsearch-queries) step
  evaluates any `{{expression}}` found inside its `query` object.
- The [Element hydration](/reference/search/element-hydration.md) step's `elementIds` input accepts an expression instead
  of a literal array.

This page is the shared reference for the language itself, independent of which feature embeds it.

## Trying it out

The [playground](/reference/formats-and-languages/expr-lang/playground.md) runs expressions in the browser, with the same
version of Expr Lang and the same functions as the API. Paste an element or any JSON object and iterate on the
expression until it produces the value you want, then copy it into your rule or query. Every example on these pages
has a link which opens it in the playground.

## Core features

- **Familiar operators**: arithmetic (`+ - * / % ^`), comparison (`== != < >`), logical (`and or not`), and membership
  (`in`).
- **Nil coalescing and ternaries**: `a ?? b` falls back to `b` if `a` is nil; `condition ? a : b` picks between two
  values.
- **Safe navigation**: `a?.b` returns nil instead of erroring if `a` is nil.
- **Slicing**: `array[1:4]` extracts a subarray; negative indices count from the end.
- **The pipe operator**: `user.Name | lower()` passes the left-hand value as the first argument to the function on the
  right, letting you chain several transformations left to right.
- **Predicates and closures**: functions like `filter` and `map` take a predicate expression where `#` refers to the
  current array element (or its fields directly, e.g. `.score`), so `filter(elements, {.score > 1.0})` keeps only
  elements scoring above `1.0`.

See the full [language definition](https://expr-lang.org/docs/language-definition) for exhaustive syntax and typing
rules.

## Builtin functions

Expr Lang ships a large standard library of builtin functions, grouped roughly as follows - see the
[builtin function reference](https://expr-lang.org/docs/language-definition#builtin-functions) for their
descriptions:

- **String**: `trim`, `split`, `replace`, `upper`, `lower`, `indexOf`, `hasPrefix`, ...
- **Array**: `filter`, `map`, `sort`, `sortBy`, `all`, `any`, `none`, `find`, `reduce`, `flatten`, `join`, ...
- **Map**: `keys`, `values`, `toPairs`, `fromPairs`, ...
- **Number**: `max`, `min`, `abs`, `ceil`, `floor`, `round`, ...
- **Date/time**: `now`, `duration`, `date`, `timezone`, ...
- **Type conversion**: `int`, `float`, `string`, `toJSON`, `fromJSON`, `toBase64`, `fromBase64`, ...
- **Bitwise**: `bitand`, `bitor`, `bitxor`, `bitnot`, `bitshl`, `bitshr`, ...
- **Utility**: `len`, `get`, `type`, `count`, `uniq`, `reverse`, ...

## Operators

The operators, from the lowest to the highest precedence, generated from the code:

| Kind   | Precedence | Operators                                                                     | Associativity |
| ------ | ---------- | ----------------------------------------------------------------------------- | ------------- |
| binary | 0          | `\|`                                                                          | left          |
| binary | 10         | `or` `\|\|`                                                                   | left          |
| binary | 15         | `&&` `and`                                                                    | left          |
| binary | 20         | `!=` `<` `<=` `==` `>` `>=` `contains` `endsWith` `in` `matches` `startsWith` | left          |
| binary | 25         | `..`                                                                          | left          |
| binary | 30         | `+` `-`                                                                       | left          |
| binary | 60         | `%` `*` `/`                                                                   | left          |
| binary | 100        | `**` `^`                                                                      | right         |
| binary | 500        | `??`                                                                          | left          |
| unary  | 50         | `!` `not`                                                                     | left          |
| unary  | 90         | `+` `-`                                                                       | left          |

## Functions of Ember Nexus

Ember Nexus adds functions of its own. Their names have a prefix, so that they do not clash with builtins, operators
and the functions of future versions of Expr Lang.

- [Geo functions](/reference/formats-and-languages/expr-lang/geo-functions.md): `geoPoint`, `geoDistance`,
  `geoContains` and more, to read, measure and compare [GeoJSON](/reference/formats-and-languages/geojson.md)
  geometries.

### sleep

`sleep(ms int) any` - Available in search expressions.

Waits for the given number of milliseconds and returns `nil`. It exists only in search expressions, to test the
timeout of expressions (`expression.timeoutInMilliseconds`, see [configuration](/reference/configuration.md)): search
expressions run in their own process, which is stopped when it takes too long. Schema rules and the playground do not
have it.

**Errors**: none.

**Expression:**

```text
sleep(1)
```

**Result:**

```json
null
```

## Examples

Keep only elements scoring above `1.0`, sort by score descending, and extract just their ids. See
[parameterized element ids](/reference/search/element-hydration/parameterized-element-ids.md) for this exact expression
used inside a real request:

**Expression:**

```text
map(sortBy(filter(elements, {.score > 1.0}), {.score}, "desc"), {.id})
```

**Variables:**

```json
{
  "elements": [
    {"id": "a", "score": 0.9},
    {"id": "b", "score": 1.4},
    {"id": "c", "score": 1.1},
    {"id": "d", "score": 2}
  ]
}
```

**Result:**

```json
["d", "b", "c"]
```

Fall back to a default page size, then clamp it to a maximum of 100:

**Expression:**

```text
min(pageSize ?? 25, 100)
```

**Variables:**

```json
{"pageSize": 250}
```

**Result:**

```json
100
```

Build a string by combining several parameters:

**Expression:**

```text
"user:" + userId + ":" + (tag ?? "untagged")
```

**Variables:**

```json
{"userId": "02IiNr0GOnGDqcho5adnseWkNNcoz7fA7tFnO", "tag": null}
```

**Result:**

```json
"user:02IiNr0GOnGDqcho5adnseWkNNcoz7fA7tFnO:untagged"
```

## See also

- [Parameters and expressions](/guide/search/parameters-and-expressions.md) - how Ember Nexus resolves a step's
  `parameters` object before any expression sees it.
- [Understanding search errors](/guide/search/understanding-search-errors.md#errors-of-expressions) - how broken
  expressions are reported.
- [Playground](/reference/formats-and-languages/expr-lang/playground.md) - try expressions in the browser.
- [Expr Lang GitHub repository](https://github.com/expr-lang/expr) - source code, issue tracker and releases.
- [Expr Lang documentation](https://expr-lang.org/docs/language-definition) - the full language reference.

---

Home: [Ember Nexus API docs](/index.md)

Full site map: [llms.txt](/llms.txt)

Previous: [GeoJSON](/reference/formats-and-languages/geojson.md)

Next: [Geo functions](/reference/formats-and-languages/expr-lang/geo-functions.md)
