# ReQL Functions

> Source: https://docs.recombee.com/reql_functions

> For the complete documentation index, see [llms.txt](/llms.txt).

**Table of contents**

* [Quick Overview](#quick-overview)
* [Context Functions](#context-functions)  
   * [Context Item Function](#context-item-function)  
         * [Definition](#context-item-function-definition)  
         * [Examples](#context-item-function-examples)  
                  * [Example 1](#context-item-function-example-1)  
                  * [Example 2 - Up-Sell](#context-item-function-example-2-up-sell)  
   * [Context User Function](#context-user-function)  
         * [Definition](#context-user-function-definition)  
         * [Example](#context-user-function-example)  
   * [Context Segment Function](#context-segment-function)  
         * [Definition](#context-segment-function-definition)  
         * [Examples](#context-segment-function-examples)
* [Miscellaneous Functions](#miscellaneous-functions)  
   * [Now](#now)  
         * [Definition](#now-definition)  
         * [Example](#now-example)  
   * [Random](#random)  
         * [Definition](#random-definition)  
   * [Size](#size)  
         * [Definition](#size-definition)  
         * [Examples](#size-examples)  
   * [Item Values](#item-values)  
         * [Definition](#item-values-definition)  
         * [Example](#item-values-example)  
   * [Reduce](#reduce)  
         * [Definition](#reduce-definition)  
         * [Example](#reduce-example)
* [Lambda Functions](#lambda-functions)  
   * [Map](#map)  
         * [Definition](#map-definition)  
         * [Examples](#map-examples)  
   * [Select](#select)  
         * [Definition](#select-definition)  
         * [Examples](#select-examples)  
   * [Exists](#exists)  
         * [Definition](#exists-definition)  
         * [Examples](#exists-examples)
* [Type Conversion Functions](#type-conversion-functions)  
   * [Boolean Conversion Function](#boolean-conversion-function)  
         * [Definition](#boolean-conversion-function-definition)  
         * [Examples](#boolean-conversion-function-examples)  
   * [Number Conversion Function](#number-conversion-function)  
         * [Definition](#number-conversion-function-definition)  
         * [Examples](#number-conversion-function-examples)  
   * [String Conversion Function](#string-conversion-function)  
         * [Definition](#string-conversion-function-definition)  
         * [Examples](#string-conversion-function-examples)  
   * [Timestamp Conversion Function](#timestamp-conversion-function)  
         * [Definition](#timestamp-conversion-function-definition)  
         * [Examples](#timestamp-conversion-function-examples)
* [Math Functions](#math-functions)  
   * [Max](#max)  
         * [Definition](#max-definition)  
         * [Example](#max-example)  
   * [Min](#min)  
         * [Definition](#min-definition)  
         * [Example](#min-example)  
   * [Avg](#avg)  
         * [Definition](#avg-definition)  
         * [Example](#avg-example)  
   * [Round](#round)  
         * [Definition](#round-definition)  
         * [Example](#round-example)  
   * [Floor](#floor)  
         * [Definition](#floor-definition)  
         * [Example](#floor-example)  
   * [Ceil](#ceil)  
         * [Definition](#ceil-definition)  
         * [Example](#ceil-example)  
   * [Absolute Value](#absolute-value)  
         * [Definition](#absolute-value-definition)  
         * [Example](#absolute-value-example)  
   * [Square Root](#square-root)  
         * [Definition](#square-root-definition)  
         * [Example](#square-root-example)  
   * [Power Function](#power-function)  
         * [Definition](#power-function-definition)  
         * [Example](#power-function-example)  
   * [Logarithm](#logarithm)  
         * [Definition](#logarithm-definition)  
         * [Example](#logarithm-example)
* [String Functions](#string-functions)  
   * [Convert to Upper Case](#convert-to-upper-case)  
         * [Definition](#convert-to-upper-case-definition)  
         * [Example](#convert-to-upper-case-example)  
   * [Convert to Lower Case](#convert-to-lower-case)  
         * [Definition](#convert-to-lower-case-definition)  
         * [Example](#convert-to-lower-case-example)  
   * [Split String](#split-string)  
         * [Definition](#split-string-definition)  
         * [Example](#split-string-example)
* [Interactions Listing Functions](#interactions-listing-functions)  
   * [User Interactions](#user-interactions)  
         * [Definition](#user-interactions-definition)  
         * [Example](#user-interactions-example)
* [Interactions Statistics Functions](#interactions-statistics-functions)  
   * [Number of Bookmarks](#number-of-bookmarks)  
         * [Definition](#number-of-bookmarks-definition)  
         * [Example](#number-of-bookmarks-example)  
   * [Number of Detail Views](#number-of-detail-views)  
         * [Definition](#number-of-detail-views-definition)  
         * [Example](#number-of-detail-views-example)  
   * [Number of Purchases](#number-of-purchases)  
         * [Definition](#number-of-purchases-definition)  
         * [Example](#number-of-purchases-example)  
   * [Number of Ratings](#number-of-ratings)  
         * [Definition](#number-of-ratings-definition)  
         * [Example](#number-of-ratings-example)
* [Item Segments Handling Functions](#item-segments-handling-functions)  
   * [Items in a Segment](#items-in-a-segment)  
         * [Definition](#segment-items-definition)  
         * [Example](#segment-items-example)  
   * [Item Segments of an Item](#item-segments-of-an-item)  
         * [Definition](#item-segments-definition)  
         * [Example](#item-segments-example)
* [Geographical Functions](#geographical-functions)  
   * [Earth Distance](#earth-distance)  
         * [Definition](#earth-distance-definition)  
         * [Example](#earth-distance-example)  
   * [Geographical Point](#geographical-point)  
   * [Geographical Polygon](#geographical-polygon)  
         * [Definition](#geographical-polygon-definition)  
         * [Example](#geographical-polygon-example)  
   * [Geographical Radius](#geographical-radius)  
         * [Definition](#geographical-radius-definition)  
         * [Example](#geographical-radius-example)  
   * [Geographical Containment](#geographical-containment)  
         * [Examples](#geographical-containment-examples)

# ReQL Functions

Functions may be used to enhance your [ReQL](/reql) queries – for example[up-sell](/reql_functions#reql-func-context-item) or [getting nearby items](/reql_functions#reql-func-earth-distance) can be achieved easily by functions.

There are various functions like [math functions](/reql_functions#math-functions) (rounding, computing square root …), [string functions](/reql_functions#string-functions) (converting case), function for [getting size of set or string](/reql_functions#reql-func-size), [getting current timestamp](/reql_functions#reql-func-timestamp), functions for [conversions between types](/reql_functions#type-conversion-functions) (for example conversion between date in a text representation and timestamp) or even [lambda functions](/reql_functions#lambda-functions). If you are missing some function that you would like to use, please let us know.

ReQL function can take arguments and returns a single value. Arguments are placed between parentheses and are separated by commas – for example computing base 2 logarithm of 8 looks like this: `log(8,2)`. If the function takes no arguments the parentheses may be omitted (for e.g. `now`). If the function is given wrong number of arguments, or the arguments have unsupported type, an error is produced. If any of the arguments is null, then result is also a null value.

## Quick Overview

**[Context Functions](#context-functions)**

| Name                                           | Description                                                                        | Example                         |
| ---------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------- |
| [context\_item](#reql-func-context-item)       | Retrieves property value of the item, that is currently viewed by the user.        | context\_item\["price"\]        |
| [context\_user](#reql-func-context-user)       | Retrieves property value of the user, that is about to obtain the recommendations. | context\_user\["country"\]      |
| [context\_segment](#reql-func-context-segment) | Retrieves the Segment on which the recommendations are based.                      | context\_segment\["segmentId"\] |

**[Miscellaneous Functions](#miscellaneous-functions)**

| Name                                   | Description                                                  | Example                                   |
| -------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- |
| [now](#reql-func-now)                  | Returns current timestamp                                    | now() > timestamp("2015-06-24T17:35:50Z") |
| [random](#reql-func-random)            | Returns a random number between 0 and 1                      | 1\>=random()>=0                           |
| [size](#reql-func-size)                | Returns the length of a string or number of objects in a set | size("Recombee") == 8                     |
| [item\_values](#reql-func-item-values) | Returns property values of a particular item as a dictionary | item\_values("item-42")\["description"\]  |
| [reduce](#reql-func-reduce)            | Reduces a set into a single value using an operator          | reduce("+", {1, 2, 3}) == 6               |

**[Lambda Functions](#lambda-functions)**

| Name                        | Description                                                                                | Example                                                  |
| --------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
| [map](#reql-func-map)       | Applies the lambda expression to every member of a set                                     | map(lambda 'x': 2\*'x', {1, 2, 3}) == {2, 4, 6}          |
| [select](#reql-func-select) | Returns only those values of input set for which the lambda expression returns true        | select(lambda 'x': 'x' \> 5, {10, 2, 13, 1}) == {10, 13} |
| [exists](#reql-func-exists) | Returns _true_ if lambda expression is satisfied for at least one element of the input set | exists(lambda 'x': 'x' \> 5, {2, 13, 4})                 |

**[Type Conversion Functions](#type-conversion-functions)**

| Name                              | Description                        | Example                                                    |
| --------------------------------- | ---------------------------------- | ---------------------------------------------------------- |
| [boolean](#reql-func-boolean)     | Converts the argument to boolean   | boolean("") == False                                       |
| [number](#reql-func-number)       | Converts the argument to number    | number("456") == 456                                       |
| [string](#reql-func-string)       | Converts the argument to string    | string(123) == "123"                                       |
| [timestamp](#reql-func-timestamp) | Converts the argument to timestamp | timestamp("2015-06-25T11:08:44Z") == timestamp(1435230524) |

**[Math Functions](#math-functions)**

| Name                      | Description                                                           | Example                 |
| ------------------------- | --------------------------------------------------------------------- | ----------------------- |
| [max](#reql-func-max)     | Returns the maximum of _n_ arguments                                  | max(147,42,81.9) == 147 |
| [min](#reql-func-min)     | Returns the minimum of _n_ arguments                                  | min(147,42,81.9) == 42  |
| [avg](#reql-func-avg)     | Returns the average of _n_ numbers                                    | avg(2, 4) == 3          |
| [round](#reql-func-round) | Returns closest integer                                               | round(4.5) == 5         |
| [floor](#reql-func-floor) | Returns largest preceding integer                                     | floor(4.3) == 4         |
| [ceil](#reql-func-ceil)   | Returns smallest following integer                                    | ceil(4.3) == 5          |
| [abs](#reql-func-abs)     | Returns non-negative value of the argument without regard to its sign | abs(-4.3) == 4.3        |
| [sqrt](#reql-func-sqrt)   | Returns the square root of the argument                               | sqrt(4) == 2            |
| [pow](#reql-func-pow)     | Returns 𝑓𝑖𝑟𝑠𝑡\_𝑎𝑟𝑔𝑢𝑚𝑒𝑛𝑡𝑠𝑒𝑐𝑜𝑛𝑑\_𝑎𝑟𝑔𝑢𝑚𝑒𝑛𝑡    | pow(10,3) == 1000       |
| [log](#reql-func-log)     | Returns the logarithm of the argument                                 | log(1000) == 3          |

**[String Functions](#string-functions)**

| Name                      | Description                                        | Example                                              |
| ------------------------- | -------------------------------------------------- | ---------------------------------------------------- |
| [upper](#reql-func-upper) | Converts all letters to the capital letters        | upper("AbCdefG") == "ABCDEFG"                        |
| [lower](#reql-func-lower) | Converts all letters to the small letters          | lower("AbCdefG") == "abcdefg                         |
| [split](#reql-func-split) | Splits a string into sub-strings using a separator | split("abc,def,ghi", ",") == \["abc", "def", "ghi"\] |

**[Interactions Listing Functions](#interactions-listing-functions)**

| Name                                               | Description                                       | Example                                                      |
| -------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------ |
| [user\_interactions](#reql-func-user-interactions) | Returns list of interactions by a particular user | user\_interactions(context\_user\["userId"\], {"purchases"}) |

**[Interactions Statistics Functions](#interactions-statistics-functions)**

| Name                                                         | Description                                   | Example                                       |
| ------------------------------------------------------------ | --------------------------------------------- | --------------------------------------------- |
| [num\_item\_bookmarks](#reql-func-num-item-bookmarks)        | Returns the number of bookmarks of an item    | num\_item\_bookmarks('itemId') < 10           |
| [num\_item\_detail\_views](#reql-func-num-item-detail-views) | Returns the number of detail views of an item | num\_item\_detail\_views('itemId') < 10       |
| [num\_item\_purchases](#reql-func-num-item-purchases)        | Returns the number of purchases of an item    | num\_item\_purchases('itemId') < 10           |
| [num\_item\_ratings](#reql-func-num-item-ratings)            | Returns the number of ratings of an item      | num\_item\_ratings('itemId', "negative") < 10 |

**[Item Segments Handling Functions](#item-segments-handling-functions)**

| Name                                       | Description                                 | Example                                          |
| ------------------------------------------ | ------------------------------------------- | ------------------------------------------------ |
| [segment\_items](#reql-func-segment-items) | Get items in a Segment                      | 'itemId' in segment\_items("genres", "thriller") |
| [item\_segments](#reql-func-item-segments) | Get Item Segments to which the item belongs | "thriller" in item\_segments("genres", 'itemId') |

**[Geographical Functions](#geographical-functions)**

| Name                                         | Description                                                                                                      | Example                                                                                              |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| [earth\_distance](#reql-func-earth-distance) | Returns the orthodromic distance between two points (given as their latitude and longitude in degrees) in meters | earth\_distance(50.075538,14.437800,52.520007,13.404954) < 282000                                    |
| [geo\_polygon](#reql-func-geo-polygon)       | Creates a spherical polygon represented by points with geographical coordinates                                  | geo\_polygon(\[\[40.800, -73.957\], \[40.767, -73.981\], \[40.764, -73.972\], \[40.796, -73.949\]\]) |
| [geo\_radius](#reql-func-geo-radius)         | Creates a spherical cap represented by a center with geographical coordinates and a radius in km                 | geo\_radius(\[40.689167, -74.044444\], 10)                                                           |

## Context Functions

| Name                                           | Description                                                                        | Example                         |
| ---------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------- |
| [context\_item](#reql-func-context-item)       | Retrieves property value of the item, that is currently viewed by the user.        | context\_item\["price"\]        |
| [context\_user](#reql-func-context-user)       | Retrieves property value of the user, that is about to obtain the recommendations. | context\_user\["country"\]      |
| [context\_segment](#reql-func-context-segment) | Retrieves the Segment on which the recommendations are based                       | context\_segment\["segmentId"\] |

### Context Item Function

Context item function is used in [Recommend Items to Item](/api#request-recommend-items-to-item) and [Recommend Item Segments to Item](/api#request-recommend-item-segments-to-item)for retrieving property values of the item, that is currently viewed by the user.

#### Definition

```
context_item[property_name]
```

| Key            | Type   | Meaning                                                                                          |
| -------------- | ------ | ------------------------------------------------------------------------------------------------ |
| property\_name | string | Name of property to be retrieved. If property of this name does not exist, an error is produced. |

_(Note that Context item function is a bit special function – it takes no arguments and returns a map `name of property -> value` representing the context item. `propertyname` placed in square brackets is the key to this map.)_

#### Examples

Consider following sample items.

| name String         | price Number | category String |
| ------------------- | ------------ | --------------- |
| "television-42"     | 369          | "television"    |
| "television-49"     | 449          | "television"    |
| "remote-control-13" | 25           | remote-control  |

##### Example 1

Suppose that the user is currently viewing `television-42`. Then the following expression returns `369`, because that is the price of the context item.

```
context_item["price"]
```

##### Example 2 - Up-Sell

Suppose that the user is currently viewing `television-42`. You can recommend him products from the same category with higher price. The _filter_ would look like this:

```
'price' > context_item["price"] and 'category' == context_item["category"]
```

Considering the sample items above, only `television-49` will pass the filter.

If you don’t want to be so restrictive about the cheaper products, you shall use _booster_ instead of _filter_ and boost the products with higher price. The _booster_ could look like this:

```
if 'category' != context_item["category"] then 0.1 else if  'price' > context_item["price"] then 1 else 0.5
```

### Context User Function

Context user function is used for retrieving property values of the user that the recommendations are for.

#### Definition

```
context_user[property_name]
```

| Key            | Type   | Meaning                                                                                          |
| -------------- | ------ | ------------------------------------------------------------------------------------------------ |
| property\_name | string | Name of property to be retrieved. If property of this name does not exist, an error is produced. |

_(Note that Context user function is a bit special function – it takes no arguments and returns a map `name of property -> value` representing the context user. `propertyname` placed in square brackets is the key to this map.)_

#### Example

Consider following sample users, which have specified languages they understand:

| userId String | languages Set  |
| ------------- | -------------- |
| "user-27"     | \["EN"\]       |
| "user-29"     | \["EN", "FR"\] |

And sample items, which are some movies:

| itemId String                         | language String |
| ------------------------------------- | --------------- |
| "Pulp Fiction"                        | "EN"            |
| "Le fabuleux destin d Amelie Poulain" | "FR"            |
| "Fight Club"                          | "EN"            |
| "Kolja"                               | "CS"            |

Suppose that I want to recommend movies to users, but only movies that the users can understand. I can use the following filter:

```
'language' in context_user["languages"]
```

For _user-27_ (which can speak only english) _Pulp Fiction_ or _Fight Club_ can be recommended.

For _user-29_ (which can speak english and french) _Pulp Fiction, Fight Club_ or _Le fabuleux destin d Amelie Poulain_ can be recommended.

### Context Segment Function

Context Segment function is used in [Recommend Item Segments to Item Segment](/api#request-recommend-item-segments-to-item-segment)for retrieving the [Item Segment](/segmentations) to which is being recommended.

#### Definition

```
context_segment[property_name]
```

| Key            | Type   | Meaning                                                                  |
| -------------- | ------ | ------------------------------------------------------------------------ |
| property\_name | string | Name of property to be retrieved. Currently only segmentId is supported. |

#### Examples

```
// If the context Segment is "fairy tales"
// then explicitly disallow "tabloid news" Segment to be ever recommended

if context_segment["segmentId"] == "fairy tales"
	then 'segmentId' != "tabloid news"
	else true
```

## Miscellaneous Functions

| Name                                   | Description                                                  | Example                                   |
| -------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- |
| [now](#reql-func-now)                  | Returns current timestamp                                    | now() > timestamp("2015-06-24T17:35:50Z") |
| [random](#reql-func-random)            | Returns a random number between 0 and 1                      | 1\>=random()>=0                           |
| [size](#reql-func-size)                | Returns the length of a string or number of objects in a set | size("Recombee") == 8                     |
| [item\_values](#reql-func-item-values) | Returns property values of a particular item as a dictionary | item\_values("item-42")\["description"\]  |
| [reduce](#reql-func-reduce)            | Reduces a set into a single value using an operator          | reduce("+", {1, 2, 3}) == 6               |

### Now

Returns current timestamp.

#### Definition

```
now()
```

#### Example

The following expression results in `true`:

```
now() > timestamp("2015-06-24T17:35:50Z")
```

### Random

Returns a random number between 0 and 1.

#### Definition

```
random()
```

### Size

Returns the length of a string or number of objects in a set.

#### Definition

```
size(value)
```

| Argument | Type       |
| -------- | ---------- |
| value    | string set |

#### Examples

All the following expressions result in `true`:

```
size("Recombee") == 8

size("") == 0

size({"abc", 4, {} } ) == 3

// Objects in nested set are not counted
size({ {1,2,3} } ) == 1
```

### Item Values

Returns property values of a particular item as a dictionary.

#### Definition

```
item_values(item_id)
```

| Argument | Type   | Meaning       |
| -------- | ------ | ------------- |
| value    | string | ID of an item |

#### Example

```
// Returns value of property "category" for item with ID "item-42"
item_values("item-42")["category"]
```

### Reduce

Reduces a set into a single value using an operator.

#### Definition

```
reduce(operator, input_set, initial_value)
```

| Argument       | Type                               | Meaning                                                         |
| -------------- | ---------------------------------- | --------------------------------------------------------------- |
| operator       | string                             | One of +, \*, &, and, or                                        |
| input\_set     | set                                | Set that will be reduced                                        |
| initial\_value | Same type as members of input\_set | _Optional._ Value used as left operand for the first operation. |

#### Example

All the following expressions result in `true`:

```
reduce("+", {2, 3, 4}) == 9

reduce("+", {2, 3, 4}, 1) == 10

reduce("*", {2, 3, 4}) == 24

reduce("and", {true, false, true}) == false

reduce("or", {true, false, true}) == true
```

## Lambda Functions

ReQL Lambda functions can be used for computations on sets of values.

Lambda functions take two arguments: a lambda expression and a set.

Lambda functions evaluate the lambda expression on every element of the set. The lambda expression can be any valid ReQL expression, and therefore can contain for example item properties or functions.

| Name                        | Description                                                                                | Example                                                  |
| --------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
| [map](#reql-func-map)       | Applies the lambda expression to every member of a set                                     | map(lambda 'x': 2\*'x', {1, 2, 3}) == {2, 4, 6}          |
| [select](#reql-func-select) | Returns only those values of input set for which the lambda expression returns true        | select(lambda 'x': 'x' \> 5, {10, 2, 13, 1}) == {10, 13} |
| [exists](#reql-func-exists) | Returns _true_ if lambda expression is satisfied for at least one element of the input set | exists(lambda 'x': 'x' \> 5, {2, 13, 4})                 |

### Map

Map applies the expression to every element and returns the result as set.

#### Definition

```
map(lambda 'x': EXPRESSION, input_set)
```

| Argument          | Type              |
| ----------------- | ----------------- |
| lambda expression | lambda expression |
| input\_set        | set               |

#### Examples

All the following expressions result in `true`:

```
// Multiplies every element of the input set by two
map(lambda 'x': 2\*'x', {1, 2, 3}) == {2, 4, 6}

// Converts every element from the input set to number
map(lambda 'x': number('x'), {"1", "2", "3"}) == {1, 2, 3}

// Map applied on empty set is empty set
map(lambda 'x': 'x'*'x', {}) == {}
```

### Select

Select returns only those values of input set for which the lambda expression returns true. The lambda expression have to return a boolean.

#### Definition

```
select(lambda 'x': EXPRESSION, input_set)
```

| Argument          | Type                                |
| ----------------- | ----------------------------------- |
| lambda expression | lambda expression returning boolean |
| input\_set        | set                                 |

#### Examples

All the following expressions result in `true`:

```
// Selects only the values that are greater than five
select(lambda 'x': 'x'>5, {10, 2, 13, 8, 3, 4, 7}) == {10, 13, 8, 7}

// ''true'' is satisfied for every element
select(lambda 'x': true , {1, "a", {}}) == {1, "a", {}}

// Selects only the strings, that are lowercase
select(lambda 'x': lower('x') == 'x', {"HELLO", "hello", "Hello", "a"}) == {"hello", "a"}

// No element represents a number with value less then 100
select(lambda 'x': number('x')<100 , {"125", "123", "251"}) == {}
```

### Exists

Exists returns _true_ if lambda expression returns _true_ for at least one element of the input set. Otherwise returns _false_.

`exists(lambda 'x': ...)` can be though as shorthand for `size(select(lambda 'x': ...)) > 0.`

#### Definition

```
exists(lambda 'x': EXPRESSION, input_set)
```

| Argument          | Type                                |
| ----------------- | ----------------------------------- |
| lambda expression | lambda expression returning boolean |
| input\_set        | set                                 |

#### Examples

All the following expressions result in `true`:

```
// Returns true, as 13 > 5
exists(lambda 'x': 'x'>5, {2, 13, 4})

// None of the elements is larger than 5
exists(lambda 'x': 'x'>5, {2, 1, 4}) == false
```

## Type Conversion Functions

| Name                              | Description                        | Example                                                    |
| --------------------------------- | ---------------------------------- | ---------------------------------------------------------- |
| [boolean](#reql-func-boolean)     | Converts the argument to boolean   | boolean("") == False                                       |
| [number](#reql-func-number)       | Converts the argument to number    | number("456") == 456                                       |
| [string](#reql-func-string)       | Converts the argument to string    | string(123) == "123"                                       |
| [timestamp](#reql-func-timestamp) | Converts the argument to timestamp | timestamp("2015-06-25T11:08:44Z") == timestamp(1435230524) |

### Boolean Conversion Function

Boolean conversion function is used for getting the truth value of any expression.

#### Definition

```
boolean(value_to_be_converted)
```

| Argument                 | Type     | Meaning                              |
| ------------------------ | -------- | ------------------------------------ |
| value\_to\_be\_converted | any type | Value to be converted into a boolean |

#### Examples

All the following expressions result in `true`:

```
boolean("Recombee") == true

boolean("") == False

boolean(42) == true

boolean(0) == False

boolean({""}) == true

boolean({}) == False
```

### Number Conversion Function

Number conversion function is used for converting strings, booleans and timestamps into numbers.

#### Definition

```
number(value_to_be_converted)
```

| Argument                 | Type                            | Meaning                             |
| ------------------------ | ------------------------------- | ----------------------------------- |
| value\_to\_be\_converted | string boolean timestamp number | Value to be converted into a number |

#### Examples

All the following expressions result in `true`:

```
number("456") == 456

number("1E4") == 10000

number(true) == 1

// String "Recombee" cannot be converted into a number
number("Recombee") == null
```

### String Conversion Function

String conversion function is used for converting numbers, booleans, sets and timestamps into their textual representations.

#### Definition

```
string(value_to_be_converted [, date_time_format (only if value_to_be_converted is a timestamp)])
```

| Argument                 | Type                                | Meaning                                                                                                                                                                                                                                                                                                                                        |
| ------------------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| value\_to\_be\_converted | string boolean timestamp set number | Value to be converted into a string                                                                                                                                                                                                                                                                                                            |
| date\_time\_format       | string                              | _(Optional and only if value\_to\_be\_converted is a timestamp)_ String specifying the format of textual representation of the timestamp after conversion. [See supported date and time format specifiers](/time_specifiers). If date\_time\_format is not specified, [ISO 8601](https://en.wikipedia.org/?title=ISO_8601) format is used. |

#### Examples

All the following expressions result in `true`:

```
string(123) == "123"

string(true) == "true"

// Suppose that 'time' is a timestamp with value 1435230524. No format string is specified, so ISO 8601 is used.
string('time') == "2015-06-25T11:08:44Z"

// Suppose that 'time' is a timestamp with value 1435230524.
string('time', "%d.%m.%Y %H:%M:%S") == "25.06.2015 11:08:44"
```

### Timestamp Conversion Function

Timestamp conversion function is used for converting numbers and strings into timestamps.

#### Definition

```
timestamp(value_to_be_converted [, date_time_format (only if value_to_be_converted is a string) ] )
```

| Argument                 | Type                    | Meaning                                                                                                                                                                                                                                                                                                     |
| ------------------------ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| value\_to\_be\_converted | string number timestamp | Value to be converted into a string                                                                                                                                                                                                                                                                         |
| date\_time\_format       | string                  | _(Optional and only if value\_to\_be\_converted is a string)_ String specifying the format of value\_to\_be\_converted. [See supported date and time format specifiers](/time_specifiers). If date\_time\_format is not specified, [ISO 8601](https://en.wikipedia.org/?title=ISO_8601) format is used. |

#### Examples

All the following expressions result in `true`:

```
// No format string is specified, so ISO 8601 is used.
timestamp("2015-06-25T11:08:44Z") == timestamp(1435230524)

timestamp("25.06.2015 11:08:44", "%d.%m.%Y %H:%M:%S") == timestamp(1435230524)
```

## Math Functions

| Name                      | Description                                                           | Example                 |
| ------------------------- | --------------------------------------------------------------------- | ----------------------- |
| [max](#reql-func-max)     | Returns the maximum of _n_ arguments                                  | max(147,42,81.9) == 147 |
| [min](#reql-func-min)     | Returns the minimum of _n_ arguments                                  | min(147,42,81.9) == 42  |
| [avg](#reql-func-avg)     | Returns the average of _n_ numbers                                    | avg(2, 4) == 3          |
| [round](#reql-func-round) | Returns closest integer                                               | round(4.5) == 5         |
| [floor](#reql-func-floor) | Returns largest preceding integer                                     | floor(4.3) == 4         |
| [ceil](#reql-func-ceil)   | Returns smallest following integer                                    | ceil(4.3) == 5          |
| [abs](#reql-func-abs)     | Returns non-negative value of the argument without regard to its sign | abs(-4.3) == 4.3        |
| [sqrt](#reql-func-sqrt)   | Returns the square root of the argument                               | sqrt(4) == 2            |
| [pow](#reql-func-pow)     | Returns 𝑓𝑖𝑟𝑠𝑡\_𝑎𝑟𝑔𝑢𝑚𝑒𝑛𝑡𝑠𝑒𝑐𝑜𝑛𝑑\_𝑎𝑟𝑔𝑢𝑚𝑒𝑛𝑡    | pow(10,3) == 1000       |
| [log](#reql-func-log)     | Returns the logarithm of the argument                                 | log(1000) == 3          |

### Max

Returns the maximum of n arguments.

Alternatively, if you provide a single set/array, it returns the maximum of its values.

The arguments must be comparable using `>`.

#### Definition

```
max(val1, val2, [val3, val4 ...])

max(set/array value)
```

| Argument | Type |
| -------- | ---- |
| val1     | any  |
| val2     | any  |
| ...      |      |

#### Example

```
max(147,42,81.9) == 147
max("abc", "bac") == "bac"
max({5}, {}) == {5}

max({147,42,81.9}) == 147
```

### Min

Returns the minimum of _n_ arguments.

Alternatively, if you provide a single set/array, it returns the minimum of its values.

The arguments must be comparable using `<`.

#### Definition

```
min(val1, val2, [val3, val4 ...])

min(set/array value)
```

| Argument | Type |
| -------- | ---- |
| val1     | any  |
| val2     | any  |
| ...      |      |

#### Example

```
min(147,42,81.9) == 42
min("abc", "bac") == "abc"
min({5}, {}) == {}

min({147,42,81.9}) == 42
```

### Avg

Returns the average of _n_ numbers.

Alternatively, if you provide a single set/array of values, it returns the average of its values.

#### Definition

```
avg(val1, val2, [val3, val4 ...])

avg(set/array value)
```

| Argument | Type |
| -------- | ---- |
| val1     | any  |
| val2     | any  |
| ...      |      |

#### Example

```
avg(2, 1, 5) == 4
avg({2, 1, 5}) == 4
```

### Round

#### Definition

```
round(x)
```

| Argument         | Type   | Meaning              |
| ---------------- | ------ | -------------------- |
| x                | number |                      |
| **Return value** | number | Integer closest to x |

#### Example

All the following expressions result in `true`:

```
round(4.3) == 4

round(4.5) == 5
```

### Floor

#### Definition

```
floor(x)
```

| Argument         | Type   | Meaning                     |
| ---------------- | ------ | --------------------------- |
| x                | number |                             |
| **Return value** | number | Largest integer preceding x |

#### Example

All the following expressions result in `true`:

```
floor(4.3) == 4

floor(4.5) == 4
```

### Ceil

#### Definition

```
ceil(x)
```

| Argument         | Type   | Meaning                      |
| ---------------- | ------ | ---------------------------- |
| x                | number |                              |
| **Return value** | number | Smallest integer following x |

#### Example

All the following expressions result in `true`:

```
ceil(4.3) == 5

ceil(4.5) == 5
```

### Absolute Value

#### Definition

```
abs(x)
```

| Argument         | Type   | Meaning                                            |
| ---------------- | ------ | -------------------------------------------------- |
| x                | number |                                                    |
| **Return value** | number | Non-negative value of x without regard to its sign |

#### Example

All the following expressions result in `true`:

```
abs(-4.3) == 4.3

abs(4.3) == 4.3
```

### Square Root

#### Definition

```
sqrt(x)
```

| Argument         | Type                | Meaning                      |
| ---------------- | ------------------- | ---------------------------- |
| x                | Non-negative number |                              |
| **Return value** | number              | Number 𝑎, such that 𝑎2\=𝑥 |

#### Example

All the following expressions result in `true`:

```
sqrt(4) == 2

// Square root is defined only for non-negative numbers
sqrt(-16) == null
```

### Power Function

#### Definition

```
pow(base, exponent)
```

| Argument         | Type   | Meaning                                                      |
| ---------------- | ------ | ------------------------------------------------------------ |
| base             | number |                                                              |
| exponent         | number |                                                              |
| **Return value** | number | Base raised to the power exponent (𝑏𝑎𝑠𝑒𝑒𝑥𝑝𝑜𝑛𝑒𝑛𝑡) |

#### Example

All the following expressions result in `true`:

```
pow(10,3) == 1000

pow(5,-2) == 0.04

pow(-2,5) == -32
```

### Logarithm

#### Definition

```
log(x [, base])
```

| Argument         | Type                | Meaning                              |
| ---------------- | ------------------- | ------------------------------------ |
| x                | Non-negative number |                                      |
| base             | Non-negative number | _Optional._ Default base is decadic. |
| **Return value** | number              | Number 𝑦, such that 𝑏𝑎𝑠𝑒𝑦\=𝑥  |

#### Example

All the following expressions result in `true`:

```
log(1000) == 3

log(16,2) == 4

// Logarithm is defined only for non-negative numbers
log(-2) == null
```

## String Functions

| Name                      | Description                                        | Example                                              |
| ------------------------- | -------------------------------------------------- | ---------------------------------------------------- |
| [upper](#reql-func-upper) | Converts all letters to the capital letters        | upper("AbCdefG") == "ABCDEFG"                        |
| [lower](#reql-func-lower) | Converts all letters to the small letters          | lower("AbCdefG") == "abcdefg                         |
| [split](#reql-func-split) | Splits a string into sub-strings using a separator | split("abc,def,ghi", ",") == \["abc", "def", "ghi"\] |

### Convert to Upper Case

Converts all letters to the capital letters.

#### Definition

```
upper(str)
```

| Argument | Type   |
| -------- | ------ |
| str      | string |

#### Example

All the following expressions result in `true`:

```
upper("AbCdefG") == "ABCDEFG"

upper("7b&*#č汉字") == "7B&*#Č汉字"
```

### Convert to Lower Case

Converts all letters to small letters.

#### Definition

```
lower(str)
```

| Argument | Type   |
| -------- | ------ |
| str      | string |

#### Example

All the following expressions result in `true`:

```
lower("AbCdefG") == "abcdefg"

lower("7B&*#Č汉字") == "7b&*#č汉字"
```

### Split String

Splits a string into sub-strings using a separator.

#### Definition

```
split(str, separator)
```

| Argument  | Type   | Meaning            |
| --------- | ------ | ------------------ |
| str       | string | String to be split |
| separator | string | Separator          |

#### Example

All the following expressions result in `true`:

```
split("abc,def,ghi", ",") == ["abc", "def", "ghi"]
```

## Interactions Listing Functions

Note

These functions are not enabled by default due to higher resource consumption. Contact [support@recombee.com](mailto:support@recombee.com) if you need to enable them, and please specify the types of interactions needed in your request.

| Name                                               | Description                                       | Example                                                      |
| -------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------ |
| [user\_interactions](#reql-func-user-interactions) | Returns list of interactions by a particular user | user\_interactions(context\_user\["userId"\], {"purchases"}) |

### User Interactions

Returns a list of interactions by a particular user.

These interactions are of given `interaction_types` and are ordered by timestamp from the oldest to the most recent.

Each interaction is a dictionary with the following fields:

```
{
  "userId": string,
  "itemId": string,
  "timestamp": timestamp,
  "type": string
}
```

#### Definition

```
user_interactions(user_id, interaction_types, num_interactions)
```

| Argument           | Type                 | Meaning                                                                  |
| ------------------ | -------------------- | ------------------------------------------------------------------------ |
| user\_id           | string               | Id of a user                                                             |
| interaction\_types | set                  | [Interaction types](/api#user-item-interactions) that should be returned |
| num\_interactions  | Non negative integer | _Optional._ Return only that number of latest interactions.              |

#### Example

```
// Get IDs of items that the user purchased or viewed
map(lambda 'it': 'it'["itemId"], user_interactions(context_user["userId"], {"detail_views", "purchases"}))

// Returns true if the user consumed some content in French
exists(lambda 'it': item_values('it'["itemId"])["language"] == "FR",
			user_interactions(context_user["userId"], {"purchases"}))
```

## Interactions Statistics Functions

Note

These functions are not enabled by default due to higher resource consumption.. Contact[support@recombee.com](mailto:support@recombee.com) if you need to enable them.

| Name                                                         | Description                                   | Example                                       |
| ------------------------------------------------------------ | --------------------------------------------- | --------------------------------------------- |
| [num\_item\_bookmarks](#reql-func-num-item-bookmarks)        | Returns the number of bookmarks of an item    | num\_item\_bookmarks('itemId') < 10           |
| [num\_item\_detail\_views](#reql-func-num-item-detail-views) | Returns the number of detail views of an item | num\_item\_detail\_views('itemId') < 10       |
| [num\_item\_purchases](#reql-func-num-item-purchases)        | Returns the number of purchases of an item    | num\_item\_purchases('itemId') < 10           |
| [num\_item\_ratings](#reql-func-num-item-ratings)            | Returns the number of ratings of an item      | num\_item\_ratings('itemId', "negative") < 10 |

### Number of Bookmarks

Returns number of bookmarks of an item specified by its ID.

#### Definition

```
num_item_bookmarks(id)
```

| Argument | Type   | Meaning       |
| -------- | ------ | ------------- |
| id       | string | ID of an item |

#### Example

```
// Only items with less than 5 bookmarks pass the filter
num_item_bookmarks('itemId') < 5
```

### Number of Detail Views

Returns number of detail views of an item specified by its ID.

#### Definition

```
num_item_detail_views(id)
```

| Argument | Type   | Meaning       |
| -------- | ------ | ------------- |
| id       | string | ID of an item |

#### Example

```
// Only items with less than 5 detail views pass the filter
num_item_detail_views('itemId') < 5
```

### Number of Purchases

Returns number of purchases of an item specified by its ID.

You can use this function for example for recommending only items that have just few purchases and you need to sell them.

#### Definition

```
num_item_purchases(id)
```

| Argument | Type   | Meaning       |
| -------- | ------ | ------------- |
| id       | string | ID of an item |

#### Example

```
// Only items with less than 5 purchases pass the filter
num_item_purchases('itemId') < 5
```

### Number of Ratings

Returns number of ratings of an item specified by its ID.

Optionally you can get number of only the `positive` ratings (> 0) or `negative` (< 0) ratings.

You can use this function for example for recommending only items that have already a certain number of positive ratings.

#### Definition

```
num_item_ratings(id, rating_type)
```

| Argument     | Type   | Meaning                                                                |
| ------------ | ------ | ---------------------------------------------------------------------- |
| id           | string | ID of an item                                                          |
| rating\_type | string | _Optional._ Take into consideration only positive or negative ratings. |

#### Example

```
// Only items with more than 5 positive ratings pass the filter
num_item_ratings('itemId', "positive") > 5
```

## Item Segments Handling Functions

| Name                                       | Description                                 | Example                                          |
| ------------------------------------------ | ------------------------------------------- | ------------------------------------------------ |
| [segment\_items](#reql-func-segment-items) | Get items in a Segment                      | 'itemId' in segment\_items("genres", "thriller") |
| [item\_segments](#reql-func-item-segments) | Get Item Segments to which the item belongs | "thriller" in item\_segments("genres", 'itemId') |

### Items in a Segment

Gets Items belonging to an [Item Segment](/segmentations) 

#### Definition

```
segment_items(segmentation_id, segment_id)
```

| Argument         | Type   | Meaning                                     |
| ---------------- | ------ | ------------------------------------------- |
| segmentation\_id | string | ID of an Item Segmentation                  |
| segment\_id      | string | ID of a Segment from the given Segmentation |

#### Example

```
// Allow only thrillers
'itemId' in segment_items("genres", "thriller")
```

### Item Segments of an Item

Given an [Item Segmentation](/segmentations) and an Item, get a set of Item Segments to which the Item belongs

#### Definition

```
item_segments(segmentation_id, item_id)
```

| Argument         | Type   | Meaning                    |
| ---------------- | ------ | -------------------------- |
| segmentation\_id | string | ID of an Item Segmentation |
| item\_id         | string | ID of an Item              |

#### Example

```
// Allow only thrillers
"thriller" in item_segments("genres", 'itemId')
```

## Geographical Functions

| Name                                         | Description                                                                                                      | Example                                                                                              |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| [earth\_distance](#reql-func-earth-distance) | Returns the orthodromic distance between two points (given as their latitude and longitude in degrees) in meters | earth\_distance(50.075538,14.437800,52.520007,13.404954) < 282000                                    |
| [geo\_polygon](#reql-func-geo-polygon)       | Creates a spherical polygon represented by points with geographical coordinates                                  | geo\_polygon(\[\[40.800, -73.957\], \[40.767, -73.981\], \[40.764, -73.972\], \[40.796, -73.949\]\]) |
| [geo\_radius](#reql-func-geo-radius)         | Creates a spherical cap represented by a center with geographical coordinates and a radius in km                 | geo\_radius(\[40.689167, -74.044444\], 10)                                                           |

Geographical functions `geo_polygon` and `geo_radius` construct geographical values, on which queries for testing geographic containment may be applied. For a detailed description and examples of usage, see the [Geographical Containment section](/reql_functions#reql-func-geo-containment).

### Earth Distance

Returns the orthodromic distance in meters between two points specified by their latitude and longitude in degrees.

#### Definition

```
earth_distance(lat1,lon1,lat2,lon2)
```

| Argument | Type   | Meaning                                  |
| -------- | ------ | ---------------------------------------- |
| lat1     | number | Latitude of the first point in degrees   |
| lon1     | number | Longitude of the first point in degrees  |
| lat2     | number | Latitude of the second point in degrees  |
| lon2     | number | Longitude of the second point in degrees |

#### Example

All the following expressions result in `true`:

```
earth_distance(10,10,10,10) == 0

// Distance between Prague (50.075538,14.437800) and Berlin (52.520007,13.404954)
281000 < earth_distance(50.075538,14.437800,52.520007,13.404954) < 282000
```

### Geographical Point

To specify a point with geographical coordinates, use an[array](/reql_filtering_and_boosting#arrays) of length two, which contains number values latitude and longitude as its elements, respectively:

```
// Geographical coordinates of One World Trade Center
[40.713056, -74.013333]
```

### Geographical Polygon

Creates a spherical polygon represented by [points](#reql-func-geo-point) with geographical coordinates, on which queries of testing for [geographical containment](#reql-func-geo-containment) may be applied.

#### Definition

```
geo_polygon(polygon points, strict)
```

| Argument       | Type                                    | Meaning                                                                                                     |
| -------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| polygon points | array of [points](#reql-func-geo-point) | The boundary of the polygon                                                                                 |
| strict         | boolean                                 | _Optional._ Boolean specifying if any non-valid polygon results in an error. Default if not provided: false |

* A polygon is specified as an array of geographical coordinates of at least 3 [points](#reql-func-geo-point)
* The points of a polygon can be specified in both CW and CCW orders
* The interior of a polygon is such that the polygon encloses at most half of the sphere (from two possible interpretations of a polygon, the one with the smaller area is considered). The interior does not include the boundary, except for the points

To avoid ambiguity of the requests, the following requirements should be kept:

* No two points of a polygon may share coordinates (the first and the last point are presumed to be connected automatically),
* Edges of a polygon may not cross anywhere but in the points

By default, if any of the requirements above are not fulfilled, the geo containment query will be handled on a best-effort basis.

Should you want to enable strict checking, set the boolean parameter `strict` to `true`. In that case, any failure to comply with the requirements will result in an error.

#### Example

```
// A geo_polygon roughly encompassing NYC's Manhattan
geo_polygon([[40.878273, -73.925268], [40.711673, -74.027338], [40.698674, -73.984877], [40.761036, -73.957467], [40.794154, -73.913269], [40.834948, -73.934384], [40.872342, -73.908634]])

// A geo_polygon roughly encompassing NYC's Manhattan with strict checking
geo_polygon([[40.878273, -73.925268], [40.711673, -74.027338], [40.698674, -73.984877], [40.761036, -73.957467], [40.794154, -73.913269], [40.834948, -73.934384], [40.872342, -73.908634]], true)
```

### Geographical Radius

Creates a spherical cap represented by a center [point](#reql-func-geo-point) with geographical coordinates and a radius in km, on which queries of testing for [geographical containment](#reql-func-geo-containment) may be applied.

#### Definition

```
geo_radius(center point, radius)
```

| Argument     | Type                          | Meaning                                      |
| ------------ | ----------------------------- | -------------------------------------------- |
| center point | [point](#reql-func-geo-point) | Coordinates of the center of the geo\_radius |
| radius       | number                        | Length of the geo\_radius radius in km       |

Everything that is within the orthodromic distance of a given radius to the center point is contained within the `geo_radius` (inclusively).

Nothing is contained within a `geo_radius` with a negative radius, and everything is contained within a `geo_radius` with a radius larger than half of the Earth Equator’s length.

#### Example

```
// A geo_radius of 10km around Statue of Liberty
geo_radius([40.689167, -74.044444], 10)
```

### Geographical Containment

Geographical values `geo_polygon` and `geo_radius` support the `in` operator for checking containtment of a [geographical point](#reql-func-geo-point). The result of the operator is truthy if the [point](#reql-func-geo-point) is contained within the given geographical value. The syntax of such a query is: `point` in `geographical value`.

#### Examples

All the following expressions result in `true`:

```
// One World Trade Center is contained within a geo_polygon roughly encompassing NYC's Manhattan
[40.713056, -74.013333] in geo_polygon([[40.878273, -73.925268], [40.711673, -74.027338], [40.698674, -73.984877], [40.761036, -73.957467], [40.794154, -73.913269], [40.834948, -73.934384], [40.872342, -73.908634]])

// One World Trade Center is contained within a geo_radius of 10km around Statue of Liberty
[40.713056, -74.013333] in geo_radius([40.689167, -74.044444], 10)
```