# ReQL functions¶

Functions may be used to enhance your ReQL queries – for example up-sell or getting nearby items can be achieved easily by functions.

There are various functions like math functions (rounding, computing square root …), string functions (converting case), function for getting size of set or string, getting current timestamp, functions for conversions between types (for example conversion between date in a text representation and timestamp) or even 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 item function Name of the function Description Example context_item Retrieves property value of the item, that is currently viewed by the user context_item["price"] context_user Retrieves property value of the user, that is about to obtain the recommendations context_user["country"] Miscellaneous functions Name of the function Description Example 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 now Returns current timestamp now() > timestamp("2015-06-24T17:35:50Z") random Returns a random number between 0 and 1 1>=random()>=0 size Returns the length of a string or number of objects in a set size("Recombee") == 8 item_values Returns property values of a particular item as a dictionary item_values("item-42")["description"] reduce Reduces a set into a single value using an operator reduce("+", {1, 2, 3}) == 6 Lambda functions Name of the function Description Example map Applies the lambda expression to every member of a set map(lambda 'x': 2*'x', {1, 2, 3}) == {2, 4, 6} 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 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 Name of the function Description Example boolean Converts the argument to boolean boolean("") == False number Converts the argument to number number("456") == 456 string Converts the argument to string string(123) == "123" timestamp Converts the argument to timestamp timestamp("2015-06-25T11:08:44Z") == timestamp(1435230524) Math functions Name of the function Description Example max Returns the maximum of n arguments max(147,42,81.9) == 147 min Returns the minimum of n arguments min(147,42,81.9) == 42 round Returns closest integer round(4.5) == 5 floor Returns largest preceding integer floor(4.3) == 4 ceil Returns smallest following integer ceil(4.3) == 5 abs Returns non-negative value of the argument without regard to its sign abs(-4.3) == 4.3 sqrt Returns the square root of the argument sqrt(4) == 2 pow Returns $${first\_argument}^{second\_argument}$$ pow(10,3) == 1000 log Returns the logarithm of the argument log(1000) == 3 String functions Name of the function Description Example upper Converts all letters to the capital letters upper("AbCdefG") == "ABCDEFG" lower Converts all letters to the small letters lower("AbCdefG") == "abcdefg Interactions handling functions Name of the function Description Example user_interactions Returns list of interactions by a particular user user_interactions(context_user["userId"], {"purchases"}) num_item_bookmarks Returns the number of bookmarks of an item num_item_bookmarks('itemId') < 10 num_item_detail_views Returns the number of detail views of an item num_item_detail_views('itemId') < 10 num_item_purchases Returns the number of purchases of an item num_item_purchases('itemId') < 10

## Context functions¶

 Context item function Name of the function Description Example context_item Retrieves property value of the item, that is currently viewed by the user context_item["price"] context_user Retrieves property value of the user, that is about to obtain the recommendations context_user["country"]

### Context item function¶

Context item function is used in Recommend items 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. property_name 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. property_name 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 such movies, that the users can understand them. I can use 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.

## Miscellaneous functions¶

Name of the function

Description

Example

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

now

Returns current timestamp

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

random

Returns a random number between 0 and 1

1>=random()>=0

size

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

size("Recombee") == 8

item_values

Returns property values of a particular item as a dictionary

item_values("item-42")["description"]

reduce

Reduces a set into a single value using an operator

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

### 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

#### Examples¶

All the following expressions result in true:

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

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


### 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

Meaning

value

string set

#### Examples¶

All the following expressions result in true:

size("Recombee") == 8

size("") == 0

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

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


### Item Values¶

Returns property values of a particular item as a dictionary

#### Definition¶

item_values(item_id)


Argument

Type

Meaning

item_id

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 of the function

Description

Example

map

Applies the lambda expression to every member of a set

map(lambda 'x': 2*'x', {1, 2, 3}) == {2, 4, 6}

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

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

Meaning

lambda expression

lambda expression

input_set

set

#### Examples¶

All the following expressions result in true:

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

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

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


### 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

Meaning

lambda expression

lambda expression returning boolean

input_set

set

#### Examples¶

All the following expressions result in true:

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

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

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

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


### 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

Meaning

lambda expression

lambda expression returning boolean

input_set

set

#### Examples¶

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

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


## Type conversion functions¶

Name of the function

Description

Example

boolean

Converts the argument to boolean

boolean("") == False

number

Converts the argument to number

number("456") == 456

string

Converts the argument to string

string(123) == "123"

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

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


### 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. If date_time_format is not specified, ISO 8601 format is used.

#### Examples¶

All the following expressions result in true:

string(123) == "123"

string(true) == "true"

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

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


### 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. If date_time_format is not specified, ISO 8601 format is used.

#### Examples¶

All the following expressions result in true:

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

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


## Math functions¶

Name of the function

Description

Example

max

Returns the maximum of n arguments

max(147,42,81.9) == 147

min

Returns the minimum of n arguments

min(147,42,81.9) == 42

round

Returns closest integer

round(4.5) == 5

floor

Returns largest preceding integer

floor(4.3) == 4

ceil

Returns smallest following integer

ceil(4.3) == 5

abs

Returns non-negative value of the argument without regard to its sign

abs(-4.3) == 4.3

sqrt

Returns the square root of the argument

sqrt(4) == 2

pow

Returns $${first\_argument}^{second\_argument}$$

pow(10,3) == 1000

log

Returns the logarithm of the argument

log(1000) == 3

### Max¶

Returns the maximum of n arguments.

The arguments must be comparable using >.

#### Definition¶

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


Argument

Type

Meaning

val1

any

val2

any

#### Example¶

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


### Min¶

Returns the minimum of n arguments.

The arguments must be comparable using <.

#### Definition¶

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


Argument

Type

Meaning

val1

any

val2

any

#### Example¶

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


### Round¶

#### Definition¶

round(x)


Argument

Type

Meaning

x

number

 Return value number Integer closest to x

#### Examples¶

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

#### Examples¶

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

#### Examples¶

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

#### Examples¶

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 $$a$$, such that $$a^2 = x$$

#### Examples¶

All the following expressions result in true:

sqrt(4) == 2

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


### Power function¶

#### Definition¶

pow(base, exponent)


Argument

Type

Meaning

base

number

exponent

number

Return value

number

Base raised to the power exponent ($${base}^{exponent}$$)

#### Examples¶

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 $$y$$, such that $${base}^{y} = x$$

#### Examples¶

All the following expressions result in true:

log(1000) == 3

log(16,2) == 4

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


## String functions¶

Name of the function

Description

Example

upper

Converts all letters to the capital letters

upper("AbCdefG") == "ABCDEFG"

lower

Converts all letters to the small letters

lower("AbCdefG") == "abcdefg

### Convert to upper case¶

Converts all letters to the capital letters

#### Definition¶

upper(str)


Argument

Type

Meaning

str

string

#### Examples¶

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

Meaning

str

string

#### Examples¶

All the following expressions result in true:

lower("AbCdefG") == "abcdefg"

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


## Interactions handling functions¶

Note

These functions are not enabled by default due to their higher resource consumption. Contact support@recombee.com if you need to use them.

Name of the function

Description

Example

user_interactions

Returns list of interactions by a particular user

user_interactions(context_user["userId"], {"purchases"})

num_item_bookmarks

Returns the number of bookmarks of an item

num_item_bookmarks('itemId') < 10

num_item_detail_views

Returns the number of detail views of an item

num_item_detail_views('itemId') < 10

num_item_purchases

Returns the number of purchases of an item

num_item_purchases('itemId') < 10

### 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 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 that should be returned

num_interactions

Non negative integer

Optional. Return only that number of latest interactions.

#### Examples¶

# 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"}))


### 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¶

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


### 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¶

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


### 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¶

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