rethinkdb.query

Public interface to clj-rethinkdb. You should only need to require this namespace.

Priority of databases used in queries: 1. If a database is explicitly specified as part of a query it will always be used. 2. If there is no database used in the query AND a database is set on the database at connection time (with the :db parameter), then this will be used. 3. If there is no database in the query or connection, then RethinkDB will fall back to using the “test” database (You probably don’t want this).

N.B. Database names are validated at query time, not connection time.

add

(add & args)

Sum numbers, concatenate strings or concatenate arrays.

all

and

(and & bools)

Compute the logical “and” of two or more values.

any

append

(append sq x)

Append a value to an array.

args

(args sq)

asc

(asc field-name)

Specify ascending order.

avg

(avg sq)(avg sq field-or-func)

Averages all the elements of a sequence. If called with a field name, averages all the values of that field in the sequence, skipping elements of the sequence that lack that field. If called with a function, calls that function on every element of the sequence and averages the results, skipping elements of the sequence where that function returns nil or a non-existence error.

between

(between sel lower-key upper-key & [optargs])

Get all documents between two keys. Accepts three optional arguments: index,

index, ```between``` will return all documents where that index's value is in the
specified range (it uses the primary key by default). ```left-bound``` or

include that endpoint of the range (by default, left-bound is closed and right-bound is open).

branch

(branch bool true-branch false-branch)

If the bool expression returns false or nil, the false-branch will be evaluated. Otherwise, the true-branch will be evaluated.

ceil

(ceil n)

Rounds the given value up, returning the smallest integer value greater than or equal to the given value (the value’s ceiling).

change-at

(change-at sq n x)

Change a value in an array at a given index. Returns the modified array.

changes

(changes xs)(changes xs optargs)

Return an infinite stream of objects representing changes to a table, sequence, or a document.

circle

(circle point radius & [optargs])

Construct a circular line or polygon. A circle in RethinkDB is a polygon or line approximating a circle of a given radius around a given center, consisting of a specified number of vertices (default 32).

close

(close cursor)

coerce-to

(coerce-to x s)

Convert a value of one type into another.

concat-map

(concat-map sel func)

Concatenate one or more elements into a single sequence using a mapping function.

config

(config table-or-db)

Query (read and/or update) the configurations for individual tables or databases.

connect

Creates a database connection to a RethinkDB host [& {:keys [host port token auth-key db] :or {host “127.0.0.1” port 28015 token 0 auth-key "" db nil}}

contains

(contains sq x-or-func)

Returns whether or not a sequence contains all the specified values, or if functions are provided instead, returns whether or not a sequence contains values matching all the specified functions.

count

(count sq)(count sq x-or-func)

Count the number of elements in the sequence. With a single argument, count the number of elements equal to it. If the argument is a function, it is equivalent to calling filter before count.

date

(date time-obj)

Return a new time object only based on the day, month and year (i.e. the same day at 00:00).

day

(day time-obj)

Return the day of a time object as a number between 1 and 31.

day-of-week

(day-of-week time-obj)

Return the day of week of a time object as a number between 1 and 7 (following ISO 8601 standard).

day-of-year

(day-of-year time-obj)

Return the day of the year of a time object as a number between 1 and 366 (following ISO 8601 standard).

db

(db db-name)

Reference a database.

db-create

(db-create db-name)

Creates a database.

db-drop

(db-drop db-name)

Drops a database.

db-list

(db-list)

List all database names in the system.

default

(default any default)

Provide a default value in case of non-existence errors. default evaluates its first argument (the value it’s chained to). If that argument returns null or a non-existence error is thrown in evaluation, then default returns its second argument. The second argument is usually a default value, but it can be a RethinkDB function that returns a value.

delete

(delete obj-or-sq & [optargs])

Delete one or more documents from a table.

delete-at

(delete-at sq idx)(delete-at sq idx end-idx)

Remove one or more elements from an array at a given index. Returns the modified array.

desc

(desc field-name)

Specify descending order.

difference

(difference sq1 sq2)

Remove the elements of one array from another array.

distance

(distance point1 point2 & [optargs])

Compute the distance between a point and another geometry object. At least one of the geometry objects specified must be a point.

distinct

(distinct sq)

Remove duplicate elements from the sequence.

div

(div & args)

Divide numbers.

do

(do args fun)

Evaluate an expression and pass its values as arguments to a function or to an expression.

downcase

(downcase s)

Lowercases a string.

during

(during time-obj start-time end-time & [optargs])

Return if a time is between two other times (by default, inclusive for the start, exclusive for the end).

epoch-time

(epoch-time i)

Create a time object based on seconds since epoch. The first argument is a double and will be rounded to three decimal places (millisecond-precision).

eq

(eq & args)

Test if values are equal.

eq-join

(eq-join sq index-name table & [optargs])

Join tables using a field on the left-hand sequence matching primary keys or secondary indexes on the right-hand table. eq-join is more efficient than other ReQL join types, and operates much faster. Documents in the result set consist of pairs of left-hand and right-hand documents, matched when the field on the left-hand side exists and is non-null and an entry with that field’s value exists in the specified index on the right-hand side.

error

(error)(error s)

Throw a runtime error.

fill

(fill point)

Convert a Line object into a Polygon object. If the last point does not specify the same coordinates as the first point, fill will close the polygon by connecting them.

filter

(filter sq obj-or-func & [optargs])

Get all the documents for which the given predicate is true.

Filter can be called on a sequence, selection, or a field containing an array of elements. The return type is the same as the type on which the function was called on.

Passing a :default optional argument can change the handling of documents with missing fields.

  • {:default true} will return documents with missing fields, rather than ignore them.
  • {:default (r/error)) will cause any non-existence error to raise an exception.
  • {:default false} (the default) will ignore documents where a specified field is missing.

floor

(floor n)

Rounds the given value down, returning the largest integer value less than or equal to the given value (the value’s floor).

fn

macro

(fn args & [body])

for-each

(for-each sq func)

Loop over a sequence, evaluating the given write query for each element.

func

(func args terms)

Unsweetened alternative to fn. The fn macro has the benefit of providing a syntax that mirrors the native clojure fn, but oftentimes it’s necessary to have the added versatility of a definition that accepts pure data.

Args is a vector of keywords. Terms is a term map. e.g. (func [::my-arg] terms)

ge

(ge & args)

Test if every value is greater than or equal to the following

geojson

(geojson obj)

Convert a GeoJSON object to a ReQL geometry object.

get

(get table id)

Get a document by primary key.

If no document exists with that primary key, get will return nil

get-all

(get-all table ids & [optargs])

Get all documents where the given value matches the value of the requested index.

get-field

(get-field sel field-name)

Get a single field from an object.

get-intersecting

(get-intersecting table geo & [optargs])

Get all documents where the given geometry object intersects the geometry object of the requested geospatial index.

get-nearest

(get-nearest table geo & [optargs])

Get all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).

group

(group sq field-or-index-or-optargs)

Takes a stream and partitions it into multiple groups based on the fields or functions provided. Commands chained after group will be called on each of these grouped sub-streams, producing grouped data.

gt

(gt & args)

Test if every value is greater than the following.

has-fields

(has-fields obj-or-sq x)

Test if an object has one or more fields. An object has a field if it has that key and the key has a non-null value.

hours

(hours time-obj)

Return the hour in a time object as a number between 0 and 23.

http

(http url & [optargs])

Retrieve data from the specified URL over HTTP. The return type depends on the result-format option, which checks the Content-Type of the response by default.

in-timezone

(in-timezone time-obj s)

Return a new time object with a different timezone. While the time stays the same, the results returned by functions such as hours will change since they take the timezone into account. The timezone argument has to be of the ISO 8601 format.

includes

(includes geo1 geo2)

Tests whether a geometry object is completely contained within another. When applied to a sequence of geometry objects, includes acts as a filter, returning a sequence of objects from the sequence that include the argument.

index-create

(index-create table index-name & [func optargs])

Create a new secondary index on a table. To create a simple index based on the value of a single field, pass the field as the index-name. If you need to pass optargs without a function, then set func to nil.

index-drop

(index-drop table index-name)

Delete a previously created secondary index.

index-list

(index-list table)

List all the secondary indexes of a table.

index-rename

(index-rename table old-name new-name & [optargs])

Rename an existing secondary index on a table. If the optional argument overwrite is specified as true, a previously existing index with the new name will be deleted and the index will be renamed. If overwrite is false (the default) an error will be raised if the new index name already exists.

index-status

(index-status table & index-names)

Get the status of the specified indexes on this table, or the status of all indexes on this table if no indexes are specified.

index-wait

(index-wait table & index-names)

Wait for the specified indexes on this table to be ready, or for all indexes on this table to be ready if no indexes are specified.

info

(info x)

Get information about a ReQL value.

inner-join

(inner-join sq1 sq2 func)

Returns an inner join of two sequences.

insert

(insert table objs & [optargs])

Insert documents into a table. Accepts a list of documents.

insert-at

(insert-at sq n x)

Insert a value in to an array at a given index. Returns the modified array.

intersects

(intersects geo1 geo2)

Tests whether two geometry objects intersect with one another. When applied to a sequence of geometry objects, intersects acts as a filter, returning a sequence of objects from the sequence that intersect with the argument.

is-empty

(is-empty sq)

Test if a sequence is empty.

iso8601

(iso8601 s & [optargs])

Create a time object based on an ISO 8601 date-time string (e.g. ‘2013-01-01T01:01:01+00:00’). We support all valid ISO 8601 formats except for week dates. If you pass an ISO 8601 date-time without a time zone, you must specify the time zone with the default-timezone argument.

json

(json s)

Parse a JSON string on the server.

keys

(keys obj)

Return an array containing all of the object’s keys.

le

(le & args)

Test if every value is less than or equal to the following

limit

(limit sq n)

End the sequence after the given number of elements.

line

(line points)

Construct a geometry object of type Line. The line can be specified in one of two ways:

  • Two or more two-item arrays, specifying longitude and latitude numbers of the line’s vertices;
  • Two or more Point objects specifying the line’s vertices.

literal

(literal x)

Replace an object in a field instead of merging it with an existing object in a merge or update operation.

lt

(lt & args)

Test if every value is less than the following

make-array

(make-array & xs)

map

(map sq obj-or-func)

Transform each element of one or more sequences by applying a mapping function to them. If map is run with two or more sequences, it will iterate for as many items as there are in the shortest sequence.

match

(match s regex-str)

Matches against a regular expression. If there is a match, returns an object with the fields:

  • str: The matched string
  • start: The matched string’s start
  • end: The matched string’s end
  • groups: The capture groups defined with parentheses

If no match is found, returns nil.

max

(max sq)(max sq field-or-func)

Finds the maximum element of a sequence.

maxval

merge

(merge & objs)

Merge one or more objects together to construct a new object with properties from all. If a key occurs in more than one object, the mapping from the latter (left-to-right) will be the mapping in the result.

min

(min sq)(min sq field-or-func)

Finds the minimum element of a sequence.

minutes

(minutes time-obj)

Return the minute in a time object as a number between 0 and 59.

minval

mod

(mod & args)

Find the remainder when dividing numbers.

month

(month time-obj)

Return the month of a time object as a number between 1 and 12.

mul

(mul & args)

Multiply numbers, or make a periodic array.

ne

(ne & args)

Test if values are not equal.

not

(not bool)

Compute the logical inverse (not) of an expression.

now

(now)

Return a time object representing the current time in UTC. The command now is computed once when the server receives the query, so multiple instances of now will always return the same time inside a query.

nth

(nth sq n)

Get the nth element of a sequence.

object

(object & key-vals)

Creates an object from a list of key-value pairs.

offsets-of

(offsets-of sq obj-or-func)

Get the indexes of an element in a sequence. If the argument is a predicate, get the indexes of all elements matching it.

or

(or & bools)

Compute the logical “or” of two or more values.

order-by

(order-by sel field-or-ordering)

Sort the sequence by document values of the given key(s). To specify the ordering, wrap the attribute with either r.asc or r.desc (defaults to ascending).

Sorting without an index requires the server to hold the sequence in memory, and is limited to 100,000 documents (or the setting of the array-limit option for run). Sorting with an index can be done on arbitrarily large tables, or after a between command using the same index.

outer-join

(outer-join sq1 sq2 func)

Returns a left outer join of two sequences.

pluck

(pluck obj-or-sq x)

Plucks out one or more attributes from either an object or a sequence of objects (projection).

point

(point x y & [optargs])

Construct a geometry object of type Point. The point is specified by two floating point numbers, the longitude (−180 to 180) and the latitude (−90 to 90) of the point on a perfect sphere.

polygon

(polygon points)

Construct a geometry object of type Polygon. The Polygon can be specified in one of two ways:

  • Three or more two-item arrays, specifying longitude and latitude numbers of the polygon’s vertices;
  • Three or more Point objects specifying the polygon’s vertices.

polygon-sub

(polygon-sub outer-polygon inner-polygon)

Use inner-polygon to “punch out” a hole in outer-polygon. inner-polygon must be completely contained within outer-polygon and must have no holes itself (it must not be the output of polygon-sub itself).

prepend

(prepend sq x)

Prepend a value to an array.

random

(random n1 n2 & [optargs])

Generate a random number between given bounds.

range

(range)(range end-value)(range start-value end-value)

Generate a stream of sequential integers in a specified range.

rebalance

(rebalance table-or-db)

Rebalances the shards of a table. When called on a database, all the tables in that database will be rebalanced.

reconfigure

(reconfigure table-or-db optargs)

Reconfigure a database or table’s sharding and replication.

reduce

(reduce sq func)

Produce a single value from a sequence through repeated application of a reduction function.

replace

(replace sel obj-or-func & [optargs])

Replace documents in a table. Accepts a JSON document or a ReQL expression, and replaces the original document with the new one. The new document must have the same primary key as the original document.

replace-vars

(replace-vars query)

round

(round n)

Rounds the given value to the nearest whole integer. Less than n.5 rounds down, n.5 and greater rounds up.

run

(run query conn & [opts])

sample

(sample sq n)

Select a given number of elements from a sequence with uniform random distribution. Selection is done without replacement.

seconds

(seconds time-obj)

Return the seconds in a time object as a number between 0 and 59.999 (double precision).

server

(server conn)

Returns the server name and server UUID being used by a connection. Only supported by RethinkDB 2.2 and up

set-difference

(set-difference sq1 sq2)

Remove the elements of one array from another and return them as a set (an array with distinct values).

set-insert

(set-insert sq x)

Add a value to an array and return it as a set (an array with distinct values).

set-intersection

(set-intersection sq1 sq2)

Intersect two arrays returning values that occur in both of them as a set (an array with distinct values).

set-union

(set-union sq1 sq2)

Add a several values to an array and return it as a set (an array with distinct values).

skip

(skip sel n)

Skip a number of elements from the head of the sequence.

slice

(slice sq n1 n2)

Return the elements of a sequence within the specified range.

splice-at

(splice-at sq1 n sq2)

Insert several values in to an array at a given index. Returns the modified array.

split

(split s)(split s separator)(split s separator max-splits)

Splits a string into substrings. Splits on whitespace when called with no arguments. When called with a separator, splits on that separator. When called with a separator and a maximum number of splits, splits on that separator at most max-splits times. (Can be called with nil as the separator if you want to split on whitespace while still specifying max-splits.)

status

(status table)

Return the status of a table.

sub

(sub & args)

Subtract numbers.

sum

(sum sq)(sum sq field-or-func)

Sums all the elements of a sequence. If called with a field name, sums all the values of that field in the sequence, skipping elements of the sequence that lack that field. If called with a function, calls that function on every element of the sequence and sums the results, skipping elements of the sequence where that function returns nil or a non-existence error.

sync

(sync table)

sync ensures that writes on a given table are written to permanent storage. Queries that specify soft durability ({:durability "soft"}) do not give such guarantees, so sync can be used to ensure the state of these queries. A call to sync does not return until all previous writes to the table are persisted.

table

(table table-name)(table db table-name)(table db table-name optargs)

Select all documents in a table. This command can be chained with other commands to do further processing on the data. If no db is provided then precedence follows the order given in the rethinkdb.query ns documentation.

To provide optargs without explicitly passing a db (instead using the db on the connection), pass nil as the db, e.g. (table nil :authors {:read-mode :outdated})

table-create

(table-create table-name)(table-create db table-name)(table-create db table-name optargs)

Create a table.

table-drop

(table-drop table-name)(table-drop db table-name)

Drop a table. If no db is provided then precedence follows the order given in the rethinkdb.query ns documentation.

table-list

(table-list)(table-list db)

List all table names in a database. If no db is provided then precedence follows the order given in the rethinkdb.query ns documentation.

time

(time year month day)(time year month day tz)(time year month day hour minute second)(time year month day hour minute second tz)

Create a time object for a specific time.

  • year is an integer between 1400 and 9999.
  • month is an integer between 1 and 12.
  • day is an integer between 1 and 31.
  • hour is an integer.
  • minutes is an integer.
  • seconds is a double. Its value will be rounded to three decimal places (millisecond-precision). timezone can be ‘Z’ (for UTC) or a string with the format ±[hh]:[mm].

If tz is not supplied then UTC is used.

time-of-day

(time-of-day time-obj)

Return the number of seconds elapsed since the beginning of the day stored in the time object.

timezone

(timezone time-obj)

Return the timezone of the time object.

to-epoch-time

(to-epoch-time time-obj)

Convert a time object to its epoch time.

to-geojson

(to-geojson geo)

Convert a ReQL geometry object to a GeoJSON object.

to-iso8601

(to-iso8601 time-obj)

Convert a time object to its ISO 8601 format.

type-of

(type-of x)

Gets the type of a value.

ungroup

(ungroup grouped)

Takes a grouped stream or grouped data and turns it into an array of objects representing the groups. Any commands chained after ungroup will operate on this array, rather than operating on each group individually. This is useful if you want to e.g. order the groups by the value of their reduction.

union

(union & sqs)

Concatenate two sequences.

upcase

(upcase s)

Uppercases a string.

update

(update sel obj-or-func & [optargs])

Update JSON documents in a table. Accepts a JSON document, a ReQL expression, or a combination of the two.

uuid

(uuid)(uuid string)

Return a UUID (universally unique identifier), a string that can be used as a unique ID. If a string is passed, a UUID is generated based on a SHA-1 hash of the string. Passing a string is only supported by RethinkDB 2.2 and up.

values

(values obj)

Return an array containing all of an object’s values. values guarantees the values will come out in the same order as keys. Only supported by RethinkDB 2.2 and up.

wait

(wait)(wait table-or-db)(wait table-or-db optargs)

Wait for a table or all the tables in a database to be ready. A table may be temporarily unavailable after creation, rebalancing or reconfiguring. The wait command blocks until the given table (or database) is fully up to date.

If wait is called with no table or db specified, it will wait on the default db for the connection.

with-fields

(with-fields sq fields)

Plucks one or more attributes from a sequence of objects, filtering out any objects in the sequence that do not have the specified fields. Functionally, this is identical to has-fields followed by pluck on a sequence.

without

(without obj-or-sq selectors)

The opposite of pluck; takes an object or a sequence of objects, and a sequence of selectors, and returns them with the specified paths removed. Selectors can either be a single field, or a nested path to a field. See http://rethinkdb.com/api/javascript/without/ for selector examples.

year

(year time-obj)

Return the year of a time object.

zip

(zip sq)

Used to ‘zip’ up the result of a join by merging the ‘right’ fields into ‘left’ fields of each member of the sequence.