Recombee Docs
Visit recombee.comStart Free
docs20User Documentation
adminuiAdmin UI
reql32ReQL
codeAPI Clients & Integrations
cookhatScenario Recipes
suitcaseMisc
Table of contents

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 Functions

NameDescriptionExample
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_segment

Retrieves the Segment on which the recommendations are based.

context_segment["segmentId"]

Miscellaneous Functions

NameDescriptionExample
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

NameDescriptionExample
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

NameDescriptionExample
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

NameDescriptionExample
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
avg
Returns the average of n numbers
avg(2, 4) == 3
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 π‘“π‘–π‘Ÿπ‘ π‘‘_π‘Žπ‘Ÿπ‘”π‘’π‘šπ‘’π‘›π‘‘π‘ π‘’π‘π‘œπ‘›π‘‘_π‘Žπ‘Ÿπ‘”π‘’π‘šπ‘’π‘›π‘‘
pow(10,3) == 1000
log
Returns the logarithm of the argument
log(1000) == 3

String Functions

NameDescriptionExample
upper

Converts all letters to the capital letters

upper("AbCdefG") == "ABCDEFG"
lower

Converts all letters to the small letters

lower("AbCdefG") == "abcdefg
split

Splits a string into sub-strings using a separator

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

Interactions Listing Functions

NameDescriptionExample
user_interactions

Returns list of interactions by a particular user

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

Interactions Statistics Functions

NameDescriptionExample
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
num_item_ratings

Returns the number of ratings of an item

num_item_ratings('itemId', "negative") < 10

Item Segments Handling Functions

NameDescriptionExample
segment_items

Get items in a Segment

'itemId' in segment_items("genres", "thriller")
item_segments

Get Item Segments to which the item belongs

"thriller" in item_segments("genres", 'itemId')

Geographical Functions

NameDescriptionExample
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

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

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

NameDescriptionExample
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_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 and Recommend Item Segments to Item for retrieving property values of the item, that is currently viewed by the user.

Definition

context_item[property_name]
KeyTypeMeaning
property_namestring

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]
KeyTypeMeaning
property_namestring

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.

Context Segment Function

Context Segment function is used in Recommend Item Segments to Item Segment for retrieving the Item Segment to which is being recommended.

Definition

context_segment[property_name]
KeyTypeMeaning
property_namestring

Name of property to be retrieved. Currently only segmentId is supported.

Examples

# If the context Segment is "fairy tales" then explicitly dissalow "tabloid news" Segment to be ever recommended

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

Miscellaneous Functions

NameDescriptionExample
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

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)
ArgumentType
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)
ArgumentTypeMeaning
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)
ArgumentTypeMeaning
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.

NameDescriptionExample
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)
ArgumentType
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)
ArgumentType
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)
ArgumentType
lambda expression

lambda expression returning boolean

input_set

set

Examples

All the following expressions result in true:

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

NameDescriptionExample
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)
ArgumentTypeMeaning
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)
ArgumentTypeMeaning
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)])
ArgumentTypeMeaning
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) ] )
ArgumentTypeMeaning
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

NameDescriptionExample
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
avg
Returns the average of n numbers
avg(2, 4) == 3
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 π‘“π‘–π‘Ÿπ‘ π‘‘_π‘Žπ‘Ÿπ‘”π‘’π‘šπ‘’π‘›π‘‘π‘ π‘’π‘π‘œπ‘›π‘‘_π‘Žπ‘Ÿπ‘”π‘’π‘šπ‘’π‘›π‘‘
pow(10,3) == 1000
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)
ArgumentType
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)
ArgumentType
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)
ArgumentType
val1

any

val2

any

...

Example

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

Round

Definition

round(x)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

x

Non-negative number

Return value

number

Number π‘Ž, such that π‘Ž2=π‘₯

Example

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)
ArgumentTypeMeaning

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])
ArgumentTypeMeaning

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

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

String Functions

NameDescriptionExample
upper

Converts all letters to the capital letters

upper("AbCdefG") == "ABCDEFG"
lower

Converts all letters to the small letters

lower("AbCdefG") == "abcdefg
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)
ArgumentType

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)
ArgumentType

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)
ArgumentTypeMeaning

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

note20
Note

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

NameDescriptionExample
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 following fields:

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

Definition

user_interactions(user_id, interaction_types, num_interactions)
ArgumentTypeMeaning

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.

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

note20
Note

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

NameDescriptionExample
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
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)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

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)
ArgumentTypeMeaning

id

string

ID of an item

Example

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

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)
ArgumentTypeMeaning

id

string

ID of an item

rating_type

string

Optional. Take into consideration only positive or negative ratings.

Example

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

Item Segments Handling Functions

NameDescriptionExample
segment_items

Get items in a Segment

'itemId' in segment_items("genres", "thriller")
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

Definition

segment_items(segmentation_id, segment_id)
ArgumentTypeMeaning

segmentation_id

string

ID of an Item Segmentation

segment_id

string

ID of a Segment from the given Segmentation

Example

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

Item Segments of an Item

Given an Item Segmentation and an Item, get a set of Item Segments to which the Item belongs

Definition

item_segments(segmentation_id, item_id)
ArgumentTypeMeaning

segmentation_id

string

ID of an Item Segmentation

item_id

string

ID of an Item

Example

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

Geographical Functions

NameDescriptionExample
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

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

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.

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)
ArgumentTypeMeaning

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

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)

Geographical Point

To specify a point with geographical coordinates, use an array of length two, which contains number values latitude and longitude as its elements, respectively:

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

Geographical Polygon

Creates a spherical polygon represented by points with geographical coordinates, on which queries of testing for geographical containment may be applied.

Definition

geo_polygon(polygon points, strict)
ArgumentTypeMeaning

polygon points

array of points

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
  • 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]], tru

Geographical Radius

Creates a spherical cap represented by a center point with geographical coordinates and a radius in km, on which queries of testing for geographical containment may be applied.

Definition

geo_radius(center point, radius)
ArgumentTypeMeaning

center point

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. The result of the operator is truthy if the 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)
Β© Copyright 2024, Recombee s.r.o
docs.recombee.com