layout | title | active | no_footer | permalink | alias | language |
---|---|---|---|---|---|---|
api |
ReQL command reference |
api |
true |
api/javascript/ |
api/ |
JavaScript |
{% apisection Accessing ReQL %} All ReQL queries begin from the top-level module.
{% apibody %} r → r {% endapibody %}
The top-level ReQL namespace.
Example: Set up your top-level namespace.
require_once('rdb/rdb.php');
{% apibody %} r\connect(host, port=28015[, db[, authKey[, timeout]]]) → connection {% endapibody %}
Create a new connection to the database server.
Example: Open a connection using the default host and port, specifying the default database.
$conn = r\connect('localhost', 28015, "myDb")
Read more about this command →
{% apibody %} conn->close(noreplyWait=true) {% endapibody %}
Close an open connection.
Example: Close an open connection, waiting for noreply writes to finish.
$conn->close()
Read more about this command →
{% apibody %} conn->reconnect(noreplyWait=true) {% endapibody %}
Close and reopen a connection.
Example: Cancel outstanding requests/queries that are no longer needed.
$conn->reconnect(false)
Read more about this command →
{% apibody %} conn->useDb(dbName) {% endapibody %}
Change the default database on this connection.
Example: Change the default database so that we don't need to specify the database when referencing a table.
$conn->useDb('marvel')
r\table('heroes')->run($conn) // refers to r\db('marvel').table('heroes')
{% apibody %} query->run(conn[, options]) → cursor query->run(conn[, options]) → datum {% endapibody %}
Run a query on a connection.
Returns either a single result or a cursor, depending on the query.
Example: Run a query on the connection conn
and log each row in
the result to the console.
$cursor = r\table('marvel')->run($conn)
foreach ($cursor as $x) { print_r($x); }
Read more about this command →
{% apibody %} conn->noreplyWait() {% endapibody %}
noreplyWait
ensures that previous queries with the noreply
flag have been processed
by the server. Note that this guarantee only applies to queries run on the given connection.
Example: We have previously run queries with the noreply
argument set to true
. Now
wait until the server has processed them.
$conn->noreplyWait()
{% apibody %} conn->server() conn->server() → promise {% endapibody %}
Return the server name and server UUID being used by a connection.
Example: Return the server name and UUID.
$conn->server();
// Result
array( "id" => "404bef53-4b2c-433f-9184-bc3f7bda4a15", "name" => "amadeus" )
{% apibody %} cursor->toArray() → array {% endapibody %}
Retrieve all results and return them as an array.
Example: For small result sets it may be more convenient to process them at once as an array.
$fullResult = $cursor->toArray()
Read more about this command →
{% apibody %} cursor->close() {% endapibody %}
Close a cursor. Closing a cursor cancels the corresponding query and frees the memory associated with the open request.
Example: Close a cursor.
$cursor->close()
{% apibody %} cursor->addListener(event, listener) cursor->on(event, listener) cursor->once(event, listener) cursor->removeListener(event, listener) cursor->removeAllListeners([event]) cursor->setMaxListeners(n) cursor->listeners(event) cursor->emit(event, [arg1], [arg2], [...]) {% endapibody %}
Cursors and feeds implement the same interface as Node's EventEmitter.
Read more about this command →
{% endapisection %}
{% apisection Manipulating databases %}
{% apibody %} r\dbCreate(dbName) → object {% endapibody %}
Create a database. A RethinkDB database is a collection of tables, similar to relational databases.
If successful, the operation returns an object: {created: 1}
. If a database with the
same name already exists the operation throws ReqlRuntimeError
.
Note: that you can only use alphanumeric characters and underscores for the database name.
Example: Create a database named 'superheroes'.
r\dbCreate('superheroes')->run($conn)
{% apibody %} r\dbDrop(dbName) → object {% endapibody %}
Drop a database. The database, all its tables, and corresponding data will be deleted.
If successful, the operation returns the object {dropped: 1}
. If the specified database
doesn't exist a ReqlRuntimeError
is thrown.
Example: Drop a database named 'superheroes'.
r\dbDrop('superheroes')->run($conn)
{% apibody %} r\dbList() → array {% endapibody %}
List all database names in the system. The result is a list of strings.
Example: List all databases.
r\dbList()->run($conn)
{% endapisection %}
{% apisection Manipulating tables %}
{% apibody %} db->tableCreate(tableName[, options]) → object r\tableCreate(tableName[, options]) → object {% endapibody %}
Create a table. A RethinkDB table is a collection of JSON documents.
Example: Create a table named 'dc_universe' with the default settings.
r\db('heroes')->tableCreate('dc_universe')->run($conn)
Read more about this command →
{% apibody %} db->tableDrop(tableName) → object {% endapibody %}
Drop a table. The table and all its data will be deleted.
Example: Drop a table named 'dc_universe'.
r\db('test')->tableDrop('dc_universe')->run($conn)
Read more about this command →
{% apibody %} db->tableList() → array {% endapibody %}
List all table names in a database. The result is a list of strings.
Example: List all tables of the 'test' database.
r\db('test')->tableList()->run($conn)
{% apibody %} table->indexCreate(indexName[, indexFunction]) → object table->indexCreateMulti(indexName[, indexFunction]) → object table->indexCreateGeo(indexName[, indexFunction]) → object table->indexCreateMultiGeo(indexName[, indexFunction]) → object {% endapibody %}
Create a new secondary index on a table.
The index can be either a regular index, a multi index, a geo index, or a multi geo index.
Example: Create a simple index based on the field postId
.
r\table('comments')->indexCreate('postId')->run($conn)
Read more about this command →
{% apibody %} table->indexDrop(indexName) → object {% endapibody %}
Delete a previously created secondary index of this table.
Example: Drop a secondary index named 'code_name'.
r\table('dc')->indexDrop('code_name')->run($conn)
{% apibody %} table->indexList() → array {% endapibody %}
List all the secondary indexes of this table.
Example: List the available secondary indexes for this table.
r\table('marvel')->indexList()->run($conn)
{% apibody %} table->indexRename(oldIndexName, newIndexName[, array('overwrite' => false)]) → object {% endapibody %}
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.
Example: Rename an index on the comments table.
r\table('comments')->indexRename('postId', 'messageId')->run($conn)
{% apibody %} table->indexStatus() → array table->indexStatus(index) → array table->indexStatus(array(index, ...)) → array {% endapibody %}
Get the status of the specified indexes on this table, or the status of all indexes on this table if no indexes are specified.
Example: Get the status of all the indexes on test
:
r\table('test')->indexStatus()->run($conn)
Example: Get the status of the timestamp
index:
r\table('test')->indexStatus('timestamp')->run($conn)
{% apibody %} table->indexWait() → array table->indexWait(index) → array table->indexWait(array(index, ...)) → array {% endapibody %}
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.
Example: Wait for all indexes on the table test
to be ready:
r\table('test')->indexWait()->run($conn)
Example: Wait for the index timestamp
to be ready:
r\table('test')->indexWait('timestamp')->run($conn)
{% apibody %} stream->changes([options]) → stream singleSelection->changes([options]) → stream {% endapibody %}
Return a changefeed, an infinite stream of objects representing changes to a query. A changefeed may return changes to a table or an individual document (a "point" changefeed), and document transformation commands such as filter
or map
may be used before the changes
command to affect the output.
Example: Subscribe to the changes on a table.
$feed = r\table('games')->changes()->run($conn);
foreach ($feed as $change) {
print_r($change);
}
Read more about this command →
{% endapisection %}
{% apisection Writing data %}
{% apibody %} table->insert(object | array(object, ...)[, array('durability' => "hard", 'return_changes' => false, 'conflict' => "error")]) → object {% endapibody %}
Insert JSON documents into a table. Accepts a single JSON document or an array of documents.
Example: Insert a document into the table posts
.
r\table("posts")->insert(array(
'id' => 1,
'title' => "Lorem ipsum",
'content' => "Dolor sit amet"
))->run($conn)
Read more about this command →
{% apibody %} table->update(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object selection->update(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object singleSelection->update(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object {% endapibody %}
Update JSON documents in a table. Accepts a JSON document, a ReQL expression, or a
combination of the two. You can pass options like return_changes
that will return the old
and new values of the row you have modified.
Example: Update the status of the post with id
of 1
to published
.
r\table("posts")->get(1)->update(array('status' => "published"))->run($conn)
Read more about this command →
{% apibody %} table->replace(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object selection->replace(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object singleSelection->replace(object | function [, array('durability' => "hard", 'return_changes' => false, 'non_atomic' => false)]) → object
{% endapibody %}
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.
Example: Replace the document with the primary key 1
.
r\table("posts")->get(1)->replace(array(
'id' => 1,
'title' => "Lorem ipsum",
'content' => "Aleas jacta est",
'status' => "draft"
))->run($conn)
Read more about this command →
{% apibody %} table->delete([array('durability' => "hard", 'return_changes' => false)]) → object selection->delete([array('durability' => "hard", 'return_changes' => false)]) → object singleSelection->delete([array('durability' => "hard", 'return_changes' => false)]) → object {% endapibody %}
Delete one or more documents from a table.
Example: Delete a single document from the table comments
.
r\table("comments")->get("7eab9e63-73f1-4f33-8ce4-95cbea626f59")->delete()->run($conn)
Read more about this command →
{% apibody %} table->sync() → object {% endapibody %}
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.
Example: After having updated multiple heroes with soft durability, we now want to wait until these changes are persisted.
r\table('marvel')->sync()->run($conn)
{% endapisection %}
{% apisection Selecting data %}
{% apibody %} r\db(dbName) → db {% endapibody %}
Reference a database.
Example: Explicitly specify a database for a query.
r\db('heroes')->table('marvel')->run($conn)
Read more about this command →
{% apibody %} db->table(name[, array('readMode' => 'single', 'identifierFormat' => 'name')]) → table {% endapibody %}
Select all documents in a table. This command can be chained with other commands to do further processing on the data.
Example: Return all documents in the table 'marvel' of the default database.
r\table('marvel')->run($conn)
Read more about this command →
{% apibody %} table->get(key) → singleRowSelection {% endapibody %}
Get a document by primary key.
If no document exists with that primary key, get
will return null
.
Example: Find a document by UUID.
r\table('posts')->get('a9849eef-7176-4411-935b-79a6e3c56a74')->run($conn)
Read more about this command →
{% apibody %} table->getAll(key[, array('index' =>'id')]) → selection table->getMultiple(array(key, ...)[, array('index' =>'id')]) → selection {% endapibody %}
Get all documents where the given value matches the value of the requested index.
Use getMultiple
for retrieving documents under multiple keys at once.
Example: Secondary index keys are not guaranteed to be unique so we cannot query via get when using a secondary index.
r\table('marvel')->getAll('man_of_steel', array('index' =>'code_name'))->run($conn)
Read more about this command →
{% apibody %} table->between(lowerKey, upperKey[, options]) → table_slice table_slice->between(lowerKey, upperKey[, options]) → table_slice {% endapibody %}
Get all documents between two keys. Accepts three optional arguments: index
,
left_bound
, and right_bound
. If index
is set to the name of a secondary 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 right_bound
may be set to open
or closed
to indicate whether or not to include that endpoint of the range (by default,
left_bound
is closed and right_bound
is open).
Example: Find all users with primary key >= 10 and < 20 (a normal half-open interval).
r\table('marvel')->between(10, 20)->run($conn)
Read more about this command →
{% apibody %} selection->filter(predicate_function[, array(default => false)]) → selection stream->filter(predicate_function[, array(default => false)]) → stream array->filter(predicate_function[, array(default => false)]) → array {% endapibody %}
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.
The body of every filter is wrapped in an implicit .default(false)
, which means that
if a non-existence errors is thrown (when you try to access a field that does not exist
in a document), RethinkDB will just ignore the document.
The default
value can be changed by passing an object with a default
field.
Setting this optional argument to r.error()
will cause any non-existence errors to
return a ReqlRuntimeError
.
Example: Get all the users that are 30 years old.
r\table('users')->filter(array('age' => 30))->run($conn)
Read more about this command →
{% endapisection %}
{% apisection Joins %} These commands allow the combination of multiple sequences into a single sequence
{% apibody %} sequence->innerJoin(otherSequence, predicate_function) → stream array->innerJoin(otherSequence, predicate_function) → array {% endapibody %}
Returns an inner join of two sequences.
Example: Return a list of all matchups between Marvel and DC heroes in which the DC hero could beat the Marvel hero in a fight.
r\table('marvel')->innerJoin(r\table('dc'), function($marvelRow, $dcRow) {
return $marvelRow('strength')->lt($dcRow('strength'));
})->zip()->run($conn)
Read more about this command →
{% apibody %} sequence->outerJoin(otherSequence, predicate_function) → stream array->outerJoin(otherSequence, predicate_function) → array {% endapibody %}
Returns a left outer join of two sequences.
Example: Return a list of all Marvel heroes, paired with any DC heroes who could beat them in a fight.
r\table('marvel')->outerJoin(r\table('dc'), function($marvelRow, $dcRow) {
return $marvelRow('strength')->lt($dcRow('strength'));
})->run($conn)
Read more about this command →
{% apibody %} sequence->eqJoin(leftField, rightTable[, array('index' =>'id')]) → sequence sequence->eqJoin(predicate_function, rightTable[, array('index' =>'id')]) → sequence {% endapibody %}
Join tables using a field or function on the left-hand sequence matching primary keys or secondary indexes on the right-hand table. eqJoin
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.
Example: Match players with the games they've played against one another.
r\table('players')->eqJoin('gameId', r\table('games'))->run($conn)
Read more about this command →
{% apibody %} stream->zip() → stream array->zip() → array {% endapibody %}
Used to 'zip' up the result of a join by merging the 'right' fields into 'left' fields of each member of the sequence.
Example: 'zips up' the sequence by merging the left and right fields produced by a join.
r\table('marvel')->eqJoin('main_dc_collaborator', r\table('dc'))
->zip()->run($conn)
{% endapisection %}
{% apisection Transformations %} These commands are used to transform data in a sequence.
{% apibody %} sequence->map(mappingFunction) → stream array->map(mappingFunction) → array sequence1->mapMultiple(array(sequence2, ...), mappingFunction) → stream array1->mapMultiple(array(array2, ...), mappingFunction) → array r\mapMultiple(array(sequence1, sequence2, ...), mappingFunction) → stream r\mapMultiple(array(array1, array2, ...), mappingFunction) → array {% endapibody %}
Transform each element of one or more sequences by applying a mapping function to them. For mapping over multiple sequences, mapMultiple
must be used. mapMultiple
will iterate for as many items as there are in the shortest sequence.
Example: Return the first five squares.
$result = r\expr(array(1, 2, 3, 4, 5))->map(function ($val) {
return $val->mul($val);
})->run($conn);
// Result
array(1, 4, 9, 16, 25)
Read more about this command →
{% apibody %} sequence->withFields(selector | array(selector1, selector2...)) → stream array->withFields(selector | array(selector1, selector2...)) → array {% endapibody %}
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 hasFields
followed by pluck
on a sequence.
Example: Get a list of users and their posts, excluding any users who have not made any posts.
r\table('users')->withFields(array('id', 'username', 'posts'))->run($conn)
Read more about this command →
{% apibody %} stream->concatMap(function) → stream array->concatMap(function) → array {% endapibody %}
Concatenate one or more elements into a single sequence using a mapping function.
Example: Construct a sequence of all monsters defeated by Marvel heroes. The field "defeatedMonsters" is an array of one or more monster names.
r\table('marvel')->concatMap(function($hero) {
return $hero('defeatedMonsters');
})->run($conn)
Read more about this command →
{% apibody %} table->orderBy(keyOrFunction2 | array(keyOrFunction2, ...), array('index' => index_name)) → table_slice selection->orderBy(keyOrFunction | array(keyOrFunction1, ,,,)) → selection sequence->orderBy(keyOrFunction | array(keyOrFunction1, ...)) → array {% endapibody %}
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.
Example: Order all the posts using the index date
.
r\table('posts')->orderBy(array('index' => 'date'))->run($conn)
The index must have been previously created with indexCreate.
r\table('posts')->indexCreate('date')->run($conn)
You can also select a descending ordering:
r\table('posts')->orderBy(array('index' => r\desc('date')))->run($conn)
Read more about this command →
{% apibody %} sequence->skip(n) → stream array->skip(n) → array {% endapibody %}
Skip a number of elements from the head of the sequence.
Example: Here in conjunction with orderBy
we choose to ignore the most successful heroes.
r\table('marvel')->orderBy('successMetric')->skip(10)->run($conn)
{% apibody %} sequence->limit(n) → stream array->limit(n) → array {% endapibody %}
End the sequence after the given number of elements.
Example: Only so many can fit in our Pantheon of heroes.
r\table('marvel')->orderBy('belovedness')->limit(10)->run($conn)
{% apibody %} selection->slice(startIndex[, endIndex, array('left_bound' =>'closed', 'right_bound' =>'open')]) → selection stream->slice(startIndex[, endIndex, array('left_bound' =>'closed', 'right_bound' =>'open')]) → stream array->slice(startIndex[, endIndex, array('left_bound' =>'closed', 'right_bound' =>'open')]) → array binary->slice(startIndex[, endIndex, array('left_bound' =>'closed', 'right_bound' =>'open')]) → binary {% endapibody %}
Return the elements of a sequence within the specified range.
Example: Return the fourth, fifth and sixth youngest players. (The youngest player is at index 0, so those are elements 3–5.)
r\table('players')->orderBy(array('index' => 'age'))->slice(3,6)->run($conn)
{% apibody %} sequence->nth(index) → object selection->nth(index) → selection<object> {% endapibody %}
Get the nth element of a sequence, counting from zero. If the argument is negative, count from the last element.
Example: Select the second element in the array.
r\expr(array(1,2,3))->nth(1)->run($conn)
{% apibody %} sequence->offsetsOf(datum | predicate_function) → array {% endapibody %}
Get the indexes of an element in a sequence. If the argument is a predicate, get the indexes of all elements matching it.
Example: Find the position of the letter 'c'.
r\expr(array('a','b','c'))->offsetsOf('c')->run($conn)
Read more about this command →
{% apibody %} sequence->isEmpty() → bool {% endapibody %}
Test if a sequence is empty.
Example: Are there any documents in the marvel table?
r\table('marvel')->isEmpty()->run($conn)
{% apibody %} stream->union(sequence) → stream array->union(sequence) → array {% endapibody %}
Merge two sequences. (Note that ordering is not guaranteed by union
.)
Example: Construct a stream of all heroes.
r\table('marvel')->union(r\table('dc'))->run($conn);
{% apibody %} sequence->sample(number) → selection stream->sample(number) → array array->sample(number) → array {% endapibody %}
Select a given number of elements from a sequence with uniform random distribution. Selection is done without replacement.
Example: Select 3 random heroes.
r\table('marvel')->sample(3)->run($conn)
{% endapisection %}
{% apisection Aggregation %} These commands are used to compute smaller values from large sequences.
{% apibody %} sequence->group(fieldOrFunction[, array('index' => "indexName", 'multi' => false)]) → grouped_stream {% endapibody %}
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.
Example: What is each player's best game?
r\table('games')->group('player')->max('points')->run($conn)
Read more about this command →
{% apibody %} grouped_stream->ungroup() → array grouped_data->ungroup() → array {% endapibody %}
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.
Example: What is the maximum number of points scored by each player, with the highest scorers first?
r\table('games')
->group('player')->max('points')->getField('points')
->ungroup()->orderBy(r\desc('reduction'))->run($conn)
Read more about this command →
{% apibody %} sequence->reduce(function) → value {% endapibody %}
Produce a single value from a sequence through repeated application of a reduction function.
Example: Return the number of documents in the table `posts.
r\table("posts")->map(function($doc) {
return 1;
})->reduce(function($left, $right) {
return $left->add($right);
})->run($conn);
Read more about this command →
{% apibody %} sequence->count([value | predicate_function]) → number binary->count() → number {% endapibody %}
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.
Example: Just how many super heroes are there?
r\table('marvel')->count()->add(r\table('dc')->count())->run($conn)
Read more about this command →
{% apibody %} sequence->sum([field | function]) → number {% endapibody %}
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
null
or a non-existence error.
Example: What's 3 + 5 + 7?
r\expr(array(3, 5, 7))->sum()->run($conn)
Read more about this command →
{% apibody %} sequence->avg([field | function]) → number {% endapibody %}
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 null
or a non-existence error.
Example: What's the average of 3, 5, and 7?
r\expr(array(3, 5, 7))->avg()->run($conn)
Read more about this command →
{% apibody %} sequence->min(field | function) → element sequence->min(array('index' => )) → element {% endapibody %}
Finds the minimum element of a sequence.
Example: Return the minimum value in the list [3, 5, 7]
.
r\expr(array(3, 5, 7))->min()->run($conn);
Read more about this command →
{% apibody %} sequence->max(field | function) → element sequence->max(array('index' => )) → element {% endapibody %}
Finds the maximum element of a sequence.
Example: Return the maximum value in the list [3, 5, 7]
.
r\expr(array(3, 5, 7))->max()->run($conn);
Read more about this command →
{% apibody %} sequence->distinct() → array table->distinct([array('index' => )]) → stream {% endapibody %}
Remove duplicate elements from the sequence.
Example: Which unique villains have been vanquished by marvel heroes?
r\table('marvel')->concatMap(function($hero) {
return $hero('villainList');
})->distinct()->run($conn)
Read more about this command →
{% apibody %} sequence->contains(value | function) → bool {% endapibody %}
Returns whether or not a sequence contains the specified value, or if functions are provided instead, returns whether or not a sequence contains values matching the specified function.
Example: Has Iron Man ever fought Superman?
r\table('marvel')->get('ironman')->getField('opponents')->contains('superman')->run($conn)
Read more about this command →
{% endapisection %}
{% apisection Document manipulation %}
{% apibody %} r\row([field]) → value {% endapibody %}
Returns the currently visited document.
Example: Get all users whose age is greater than 5.
r\table('users')->filter(r\row('age')->gt(5))->run($conn)
Read more about this command →
{% apibody %} sequence->pluck(selector | array(selector1, selector2...)) → stream array->pluck(selector | array(selector1, selector2...)) → array object->pluck(selector | array(selector1, selector2...)) → object singleSelection->pluck(selector | array(selector1, selector2...)) → object {% endapibody %}
Plucks out one or more attributes from either an object or a sequence of objects (projection).
Example: We just need information about IronMan's reactor and not the rest of the document.
r\table('marvel')->get('IronMan')->pluck(array('reactorState', 'reactorPower'))->run($conn)
Read more about this command →
{% apibody %} sequence->without(selector | array(selector1, selector2...)) → stream array->without(selector | array(selector1, selector2...)) → array singleSelection->without(selector | array(selector1, selector2...)) → object object->without(selector | array(selector1, selector2...)) → object {% endapibody %}
The opposite of pluck; takes an object or a sequence of objects, and returns them with the specified paths removed.
Example: Since we don't need it for this computation we'll save bandwidth and leave out the list of IronMan's romantic conquests.
r\table('marvel')->get('IronMan')->without('personalVictoriesList')->run($conn)
Read more about this command →
{% apibody %} singleSelection->merge([object | function, object | function, ...]) → object object->merge([object | function, object | function, ...]) → object sequence->merge([object | function, object | function, ...]) → stream array->merge([object | function, object | function, ...]) → array {% endapibody %}
Merge two or more objects together to construct a new object with properties from all. When there is a conflict between field names, preference is given to fields in the rightmost object in the argument list.
Example: Equip Thor for battle.
r\table('marvel')->get('thor')->merge(
r\table('equipment')->get('hammer'),
r\table('equipment')->get('pimento_sandwich')
)->run($conn)
Read more about this command →
{% apibody %} array->append(value) → array {% endapibody %}
Append a value to an array.
Example: Retrieve Iron Man's equipment list with the addition of some new boots.
r\table('marvel')->get('IronMan')->getField('equipment')->append('newBoots')->run($conn)
{% apibody %} array->prepend(value) → array {% endapibody %}
Prepend a value to an array.
Example: Retrieve Iron Man's equipment list with the addition of some new boots.
r\table('marvel')->get('IronMan')->getField('equipment')->prepend('newBoots')->run($conn)
{% apibody %} array->difference(array) → array {% endapibody %}
Remove the elements of one array from another array.
Example: Retrieve Iron Man's equipment list without boots.
r\table('marvel')->get('IronMan')->getField('equipment')->difference(array('Boots'))->run($conn)
{% apibody %} array->setInsert(value) → array {% endapibody %}
Add a value to an array and return it as a set (an array with distinct values).
Example: Retrieve Iron Man's equipment list with the addition of some new boots.
r\table('marvel')->get('IronMan')->getField('equipment')->setInsert('newBoots')->run($conn)
{% apibody %} array->setUnion(array) → array {% endapibody %}
Add a several values to an array and return it as a set (an array with distinct values).
Example: Retrieve Iron Man's equipment list with the addition of some new boots and an arc reactor.
r\table('marvel')->get('IronMan')->getField('equipment')->setUnion(array('newBoots', 'arc_reactor'))->run($conn)
{% apibody %} array->setIntersection(array) → array {% endapibody %}
Intersect two arrays returning values that occur in both of them as a set (an array with distinct values).
Example: Check which pieces of equipment Iron Man has from a fixed list.
r\table('marvel')->get('IronMan')->getField('equipment')->setIntersection(array('newBoots', 'arc_reactor'))->run($conn)
{% apibody %} array->setDifference(array) → array {% endapibody %}
Remove the elements of one array from another and return them as a set (an array with distinct values).
Example: Check which pieces of equipment Iron Man has, excluding a fixed list.
r\table('marvel')->get('IronMan')->getField('equipment')->setDifference(array('newBoots', 'arc_reactor'))->run($conn)
{% apibody %} sequence(attr) → sequence singleSelection(attr) → value object(attr) → value array(index) → value {% endapibody %}
Get a single field from an object or a single element from a sequence.
Example: What was Iron Man's first appearance in a comic?
$ironMan = r\table('marvel')->get('IronMan');
$ironMan('firstAppearance')->run($conn)
Read more about this command →
{% apibody %} sequence->getField(attr) → sequence singleSelection->getField(attr) → value object->getField(attr) → value {% endapibody %}
Get a single field from an object. If called on a sequence, gets that field from every object in the sequence, skipping objects that lack it.
Example: What was Iron Man's first appearance in a comic?
r\table('marvel')->get('IronMan')->getField('firstAppearance')->run($conn)
{% apibody %} sequence->hasFields(selector | array(selector1, selector2...)) → stream array->hasFields(selector | array(selector1, selector2...)) → array object->hasFields(selector | array(selector1, selector2...)) → boolean {% endapibody %}
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. For instance, the object {'a': 1,'b': 2,'c': null}
has the fields a
and b
.
Example: Return the players who have won games.
r\table('players')->hasFields('games_won')->run($conn)
Read more about this command →
{% apibody %} array->insertAt(index, value) → array {% endapibody %}
Insert a value in to an array at a given index. Returns the modified array.
Example: Hulk decides to join the avengers.
r\expr(array("Iron Man", "Spider-Man"))->insertAt(1, "Hulk")->run($conn)
{% apibody %} array->spliceAt(index, array) → array {% endapibody %}
Insert several values in to an array at a given index. Returns the modified array.
Example: Hulk and Thor decide to join the avengers.
r\expr(array("Iron Man", "Spider-Man"))->spliceAt(1, array("Hulk", "Thor"))->run($conn)
{% apibody %} array->deleteAt(index [,endIndex]) → array {% endapibody %}
Remove one or more elements from an array at a given index. Returns the modified array.
Example: Delete the second element of an array.
> r(array('a','b','c','d','e','f'))->deleteAt(1)->run($conn)
// result
array('a', 'c', 'd', 'e', 'f')
Read more about this command →
{% apibody %} array->changeAt(index, value) → array {% endapibody %}
Change a value in an array at a given index. Returns the modified array.
Example: Bruce Banner hulks out.
r\expr(array("Iron Man", "Bruce", "Spider-Man"))->changeAt(1, "Hulk")->run($conn)
{% apibody %} singleSelection->keys() → array object->keys() → array {% endapibody %}
Return an array containing all of an object's keys. Note that the keys will be sorted as described in ReQL data types (for strings, lexicographically).
Example: Get all the keys from a table row.
// row: { id: 1, mail: "[email protected]", name: "fred" }
r\table('users')->get(1)->keys()->run($conn);
// Result
array( "id", "mail", "name" )
{% apibody %} singleSelection->values() → array object->values() → array {% endapibody %}
Return an array containing all of an object's values. values()
guarantees the values will come out in the same order as keys.
Example: Get all of the values from a table row.
// row: { id: 1, mail: "[email protected]", name: "fred" }
r\table('users')->get(1)->values()->run($conn);
// Result
array( 1, "[email protected]", "fred" )
{% apibody %} r\literal(object) → special {% endapibody %}
Replace an object in a field instead of merging it with an existing object in a merge
or update
operation.
r\table('users')->get(1)->update(array( 'data' => r\literal(array( 'age' => 19, 'job' => 'Engineer' )) ))->run($conn)
Read more about this command →
{% apibody %} r\object(array(key, value,...)) → object {% endapibody %}
Creates an object from a list of key-value pairs, where the keys must
be strings. r.object(array(A, B, C, D))
is equivalent to
r.expr([[A, B], [C, D]]).coerce_to('OBJECT')
.
Example: Create a simple object.
r\object(r.array('id', 5, 'data', array('foo', 'bar')))->run($conn)
{% endapisection %}
{% apisection String manipulation %} These commands provide string operators.
{% apibody %} string->match(regexp) → null/object {% endapibody %}
Matches against a regular expression. If there is a match, returns an object with the fields:
str
: The matched stringstart
: The matched string's startend
: The matched string's endgroups
: The capture groups defined with parentheses
If no match is found, returns null
.
Example: Get all users whose name starts with "A".
r\table('users')->filter(function($doc){
return $doc('name')->match("^A");
})->run($conn)
Read more about this command →
{% apibody %} string->split([separator, [max_splits]]) → array {% endapibody %}
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 null
as the separator if you want to split on whitespace
while still specifying max_splits
.)
Mimics the behavior of Python's string.split
in edge cases, except
for splitting on the empty string, which instead produces an array of
single-character strings.
Example: Split on whitespace.
r\expr("foo bar bax")->split()->run($conn)
Read more about this command →
{% apibody %} string->upcase() → string {% endapibody %}
Uppercases a string.
Example:
r\expr("Sentence about LaTeX.")->upcase()->run($conn)
{% apibody %} string->downcase() → string {% endapibody %}
Lowercases a string.
Example:
r\expr("Sentence about LaTeX.")->downcase()->run($conn)
{% endapisection %}
{% apisection Math and logic %}
{% apibody %} value->add(value[, value, ...]) → value time->add(number[, number, ...]) → time {% endapibody %}
Sum two or more numbers, or concatenate two or more strings or arrays.
Example: It's as easy as 2 + 2 = 4.
r\expr(2)->add(2)->run($conn)
Read more about this command →
{% apibody %} number->sub(number[, number, ...]) → number time->sub(number[, number, ...]) → time time->sub(time) → number {% endapibody %}
Subtract two numbers.
Example: It's as easy as 2 - 2 = 0.
r\expr(2)->sub(2)->run($conn)
Read more about this command →
{% apibody %} number->mul(number[, number, ...]) → number array->mul(number[, number, ...]) → array {% endapibody %}
Multiply two numbers, or make a periodic array.
Example: It's as easy as 2 * 2 = 4.
r\expr(2)->mul(2)->run($conn)
Read more about this command →
{% apibody %} number->div(number[, number ...]) → number {% endapibody %}
Divide two numbers.
Example: It's as easy as 2 / 2 = 1.
r\expr(2)->div(2)->run($conn)
{% apibody %} number->mod(number) → number {% endapibody %}
Find the remainder when dividing two numbers.
Example: It's as easy as 2 % 2 = 0.
r\expr(2)->mod(2)->run($conn)
{% apibody %} bool->rAnd(bool) → bool r\rAnd(bool, bool) → bool {% endapibody %}
Compute the logical "and" of two values.
Example: Return whether both a
and b
evaluate to true.
var $a = true, $b = false;
r\expr($a)->rAnd($b)->run($conn);
// result
false
{% apibody %} bool->rOr(bool) → bool r\rOr(bool, bool) → bool {% endapibody %}
Compute the logical "or" of two values.
Example: Return whether either a
or b
evaluate to true.
var $a = true, $b = false;
r\expr($a)->rOr($b)->run($conn);
// result
true
{% apibody %} value->eq(value[, value, ...]) → bool {% endapibody %}
Test if two or more values are equal.
Example: See if a user's role
field is set to administrator
.
r\table('users')->get(1)->getField('role')->eq('administrator')->run($conn);
{% apibody %} value->ne(value[, value, ...]) → bool {% endapibody %}
Test if two or more values are not equal.
Example: See if a user's role
field is not set to administrator
.
r\table('users')->get(1)->getField('role')->ne('administrator')->run($conn);
{% apibody %} value->gt(value[, value, ...]) → bool {% endapibody %}
Compare values, testing if the left-hand value is greater than the right-hand.
Example: Test if a player has scored more than 10 points.
r\table('players')->get(1)->getField('score')->gt(10)->run($conn);
{% apibody %} value->ge(value[, value, ...]) → bool {% endapibody %}
Compare values, testing if the left-hand value is greater than or equal to the right-hand.
Example: Test if a player has scored 10 points or more.
r\table('players')->get(1)->getField('score')->ge(10)->run($conn);
{% apibody %} value->lt(value[, value, ...]) → bool {% endapibody %}
Compare values, testing if the left-hand value is less than the right-hand.
Example: Test if a player has scored less than 10 points.
r\table('players')->get(1)->getField('score')->lt(10)->run($conn);
{% apibody %} value->le(value[, value, ...]) → bool {% endapibody %}
Compare values, testing if the left-hand value is less than or equal to the right-hand.
Example: Test if a player has scored 10 points or less.
r\table('players')->get(1)->getField('score')->le(10)->run($conn);
{% apibody %} bool->not() → bool not(bool) → bool {% endapibody %}
Compute the logical inverse (not) of an expression.
not
can be called either via method chaining, immediately after an expression that evaluates as a boolean value, or by passing the expression as a parameter to not
.
Example: Not true is false.
r(true)->not()->run($conn)
r\not(true)->run($conn)
Read more about this command →
{% apibody %} r\random() → number r\random(number[, number], array(float => true)) → number r\random(integer[, integer]) → integer {% endapibody %}
Generate a random number between given (or implied) bounds. random
takes zero, one or two arguments.
Example: Generate a random number in the range [0,1)
r\random()->run($conn)
Read more about this command →
{% apibody %} r\round(number) → number number->round() → number {% endapibody %}
Rounds the given value to the nearest whole integer.
Example: Round 12.345 to the nearest integer.
> r\round(12.345)->run($conn);
12.0
{% apibody %} r\ceil(number) → number number->ceil() → number {% endapibody %}
Rounds the given value up, returning the smallest integer value greater than or equal to the given value (the value's ceiling).
Example: Return the ceiling of 12.345.
> r\ceil(12.345)->run($conn);
13.0
{% apibody %} r\floor(number) → number number->floor() → number {% endapibody %}
Rounds the given value down, returning the largest integer value less than or equal to the given value (the value's floor).
Example: Return the floor of 12.345.
> r\floor(12.345)->run($conn);
12.0
{% endapisection %}
{% apisection Dates and times %}
{% apibody %} r\now() → time {% endapibody %}
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 r.now() will always return the same time inside a query.
Example: Add a new user with the time at which he subscribed.
r\table("users")->insert(array(
'name' => "John",
'subscription_date' => r\now()
))->run($conn)
{% apibody %} r\time(year, month, day[, hour, minute, second], timezone) → time {% endapibody %}
Create a time object for a specific time.
A few restrictions exist on the arguments:
year
is an integer between 1400 and 9,999.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]
.
Example: Update the birthdate of the user "John" to November 3rd, 1986 UTC.
r\table("user")->get("John")->update(array('birthdate' => r\time(1986, 11, 3, 'Z')))
->run($conn)
{% apibody %} r\epochTime(number) → time {% endapibody %}
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).
Example: Update the birthdate of the user "John" to November 3rd, 1986.
r\table("user")->get("John")->update(array('birthdate' => r\epochTime(531360000)))
->run($conn)
{% apibody %} r\ISO8601(string[, array('default_timezone' =>'')]) → time {% endapibody %}
Create a time object based on an ISO 8601 date-time string (e.g. '2013-01-01T01:01:01+00:00'). RethinkDB supports all valid ISO 8601 formats except for week dates. Read more about the ISO 8601 format at Wikipedia.
If you pass an ISO 8601 string without a time zone, you must specify the time zone with the default_timezone
argument.
Example: Update the time of John's birth.
r\table("user")->get("John")->update(array('birth' => r\ISO8601('1986-11-03T08:30:00-07:00')))->run($conn)
{% apibody %} time->inTimezone(timezone) → time {% endapibody %}
Return a new time object with a different timezone. While the time stays the same, the results returned by methods such as hours() will change since they take the timezone into account. The timezone argument has to be of the ISO 8601 format.
Example: Hour of the day in San Francisco (UTC/GMT -8, without daylight saving time).
r\now()->inTimezone('-08:00')->hours()->run($conn)
{% apibody %} time->timezone() → string {% endapibody %}
Return the timezone of the time object.
Example: Return all the users in the "-07:00" timezone.
r\table("users")->filter( function($user) {
return user("subscriptionDate")->timezone()->eq("-07:00")
})
{% apibody %} time->during(startTime, endTime[, options]) → bool {% endapibody %}
Return if a time is between two other times (by default, inclusive for the start, exclusive for the end).
Example: Retrieve all the posts that were posted between December 1st, 2013 (inclusive) and December 10th, 2013 (exclusive).
r\table("posts")->filter(
r\row('date')->during(r\time(2013, 12, 1), r\time(2013, 12, 10))
)->run($conn)
Read more about this command →
{% apibody %} time->date() → time {% endapibody %}
Return a new time object only based on the day, month and year (ie. the same day at 00:00).
Example: Retrieve all the users whose birthday is today.
r\table("users")->filter(function($user) {
return user("birthdate")->date()->eq(r\now()->date())
})->run($conn)
{% apibody %} time->timeOfDay() → number {% endapibody %}
Return the number of seconds elapsed since the beginning of the day stored in the time object.
Example: Retrieve posts that were submitted before noon.
r\table("posts")->filter(
r\row("date")->timeOfDay()->le(12*60*60)
)->run($conn)
{% apibody %} time->year() → number {% endapibody %}
Return the year of a time object.
Example: Retrieve all the users born in 1986.
r\table("users")->filter(function($user) {
return user("birthdate")->year()->eq(1986)
})->run($conn)
{% apibody %} time->month() → number {% endapibody %}
Return the month of a time object as a number between 1 and 12. For your convenience, the terms r.january, r.february etc. are defined and map to the appropriate integer.
Example: Retrieve all the users who were born in November.
r\table("users")->filter(
r\row("birthdate")->month()->eq(11)
)
Read more about this command →
{% apibody %} time->day() → number {% endapibody %}
Return the day of a time object as a number between 1 and 31.
Example: Return the users born on the 24th of any month.
r\table("users")->filter(
r\row("birthdate")->day()->eq(24)
)->run($conn)
{% apibody %} time->dayOfWeek() → number {% endapibody %}
Return the day of week of a time object as a number between 1 and 7 (following ISO 8601 standard). For your convenience, the terms r.monday, r.tuesday etc. are defined and map to the appropriate integer.
Example: Return today's day of week.
r\now()->dayOfWeek()->run($conn)
Read more about this command →
{% apibody %} time->dayOfYear() → number {% endapibody %}
Return the day of the year of a time object as a number between 1 and 366 (following ISO 8601 standard).
Example: Retrieve all the users who were born the first day of a year.
r\table("users")->filter(
r\row("birthdate")->dayOfYear()->eq(1)
)
{% apibody %} time->hours() → number {% endapibody %}
Return the hour in a time object as a number between 0 and 23.
Example: Return all the posts submitted after midnight and before 4am.
r\table("posts")->filter(function($post) {
return post("date")->hours()->lt(4)
})
{% apibody %} time->minutes() → number {% endapibody %}
Return the minute in a time object as a number between 0 and 59.
Example: Return all the posts submitted during the first 10 minutes of every hour.
r\table("posts")->filter(function($post) {
return post("date")->minutes()->lt(10)
})
{% apibody %} time->seconds() → number {% endapibody %}
Return the seconds in a time object as a number between 0 and 59.999 (double precision).
Example: Return the post submitted during the first 30 seconds of every minute.
r\table("posts")->filter(function($post) {
return post("date")->seconds()->lt(30)
})
{% apibody %} time->toISO8601() → string {% endapibody %}
Convert a time object to a string in ISO 8601 format.
Example: Return the current ISO 8601 time.
r\now()->toISO8601()->run($conn)
// Result
"2015-04-20T18:37:52.690+00:00"
{% apibody %} time->toEpochTime() → number {% endapibody %}
Convert a time object to its epoch time.
Example: Return the current time in seconds since the Unix Epoch with millisecond-precision.
r\now()->toEpochTime()
{% endapisection %}
{% apisection Control structures %}
{% apibody %} r\binary(data) → binary {% endapibody %}
Encapsulate binary data within a query.
Example: Save an avatar image to a existing user record.
$avatarImage = file_get_contents('./defaultAvatar.png');
r\table('users')->get(100)->update(array(
'avatar' => r\binary($avatarImage)
))->run($conn)
Read more about this command →
{% apibody %} any->rDo(function) → any r\rDo(arg | array(arg,...), function) → any any->rDo(expr) → any r\rDo(arg | array(arg,...), expr) → any {% endapibody %}
Call an anonymous function using return values from other ReQL commands or queries as arguments.
Example: Compute a golfer's net score for a game.
r\table('players')->get('f19b5f16-ef14-468f-bd48-e194761df255')->rDo(
function ($player) {
return $player('gross_score')->sub($player('course_handicap'));
}
)->run($conn);
Read more about this command →
{% apibody %} r\branch(test, true_action[, test2, else_action, ...], false_action) → any {% endapibody %}
Perform a branching conditional equivalent to if-then-else
.
The branch
command takes 2n+1 arguments: pairs of conditional expressions and commands to be executed if the conditionals return any value but false
or null
(i.e., "truthy" values), with a final "else" command to be evaluated if all of the conditionals are false
or null
.
Example: Test the value of x.
var $x = 10;
r\branch(r\expr($x)->gt(5), 'big', 'small')->run($conn);
// Result
"big"
Read more about this command →
{% apibody %} sequence->rForeach(write_function) → object {% endapibody %}
Loop over a sequence, evaluating the given write query for each element.
Example: Now that our heroes have defeated their villains, we can safely remove them from the villain table.
r\table('marvel')->rForeach(function($hero) {
return r\table('villains')->get($hero('villainDefeated'))->delete()
})->run($conn)
{% apibody %} r\range() → stream r\range([startValue, ]endValue) → stream {% endapibody %}
Generate a stream of sequential integers in a specified range.
Example: Return a four-element range of [0, 1, 2, 3]
.
> r\range(4)->run($conn)
array(0, 1, 2, 3)
{% apibody %} r\error(message) → error {% endapibody %}
Throw a runtime error. If called with no arguments inside the second argument to default
, re-throw the current error.
Example: Iron Man can't possibly have lost a battle:
r\table('marvel')->get('IronMan')->do(function($ironman) {
return r\branch($ironman('victories')->lt($ironman('battles')),
r\error('impossible code path'),
$ironman)
})->run($conn)
{% apibody %} value->default(default_value | function) → any sequence->default(default_value | function) → any {% endapibody %}
Provide a default value in case of non-existence errors. The default
command 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 function that returns a value.
Example: Retrieve the titles and authors of the table posts
.
In the case where the author field is missing or null
, we want to retrieve the string
Anonymous
.
r\table("posts")->map(function ($post) {
return array(
'title' => $post("title"),
'author' => $post("author")->default("Anonymous")
)
})->run($conn);
Read more about this command →
{% apibody %} r\expr(value) → value {% endapibody %}
Construct a ReQL JSON object from a native object.
Example: Objects wrapped with expr
can then be manipulated by ReQL API functions.
r\expr(array('a' => 'b'))->merge(array('b' => array(1,2,3)))->run($conn)
Read more about this command →
{% apibody %} r\js(jsString[, array('timeout' => )]) → value {% endapibody %}
Create a javascript expression.
Example: Concatenate two strings using JavaScript.
r\js("'str1' + 'str2'")->run($conn)
Read more about this command →
{% apibody %} sequence->coerceTo('array') → array value->coerceTo('string') → string string->coerceTo('number') → number array->coerceTo('object') → object sequence->coerceTo('object') → object object->coerceTo('array') → array binary->coerceTo('string') → string string->coerceTo('binary') → binary {% endapibody %}
Convert a value of one type into another.
Example: Coerce a stream to an array.
r\table('posts')->map(function ($post) {
return $post->merge(array( 'comments' => r\table('comments')->getAll(post('id'), array('index' => 'postId'))->coerceTo('array')));
})->run($conn)
Read more about this command →
{% apibody %} any->typeOf() → string {% endapibody %}
Gets the type of a value.
Example: Get the type of a string.
r\expr("foo")->typeOf()->run($conn)
{% apibody %} any->info() → object r\info(any) → object {% endapibody %}
Get information about a ReQL value.
Example: Get information about a table such as primary key, or cache size.
r\table('marvel')->info()->run($conn)
{% apibody %} r\json(json_string) → value {% endapibody %}
Parse a JSON string on the server.
Example: Send an array to the server.
r\json("[1,2,3]")->run($conn)
{% apibody %} value->toJsonString() → string {% endapibody %}
Convert a ReQL value or object to a JSON string.
Example: Get a ReQL document as a JSON string.
> r\table('hero')->get(1)->toJsonString()
// result
'{"id": 1, "name": "Batman", "city": "Gotham", "powers": ["martial arts", "cinematic entrances"]}'
{% apibody %} r\http(url [, options]) → value {% endapibody %}
Retrieve data from the specified URL over HTTP. The return type depends on the resultFormat
option, which checks the Content-Type
of the response by default.
Example: Perform a simple HTTP GET
request, and store the result in a table.
r\table('posts')->insert(r\http('http://httpbin.org/get'))->run($conn)
Read more about this command →
{% apibody %} r\uuid([string]) → string {% endapibody %}
Return a UUID (universally unique identifier), a string that can be used as a unique ID. If a string is passed to uuid
as an argument, the UUID will be deterministic, derived from the string's SHA-1 hash.
Example: Generate a UUID.
> r\uuid()->run($conn)
// result
"27961a0e-f4e8-4eb3-bf95-c5203e1d87b9"
Read more about this command →
{% endapisection %}
{% apisection Geospatial commands %}
{% apibody %} r\circle(array(longitude, latitude), radius[, array('num_vertices' => 32, 'geo_system' => 'WGS84', 'unit' => 'm', 'fill' => true)]) → geometry r\circle(point, radius[, array('num_vertices' => 32, 'geo_system' => 'WGS84', 'unit' => 'm', 'fill' => true)]) → geometry {% endapibody %}
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).
Example: Define a circle.
r\table('geo')->insert(array(
'id' => 300,
'name' => 'Hayes Valley',
'neighborhood' => r\circle(array(-122.423246,37.779388), 1000)
))->run($conn);
Read more about this command →
{% apibody %} geometry->distance(geometry[, array('geo_system' => 'WGS84', 'unit' => 'm')]) → number r\distance(geometry, geometry[, array('geo_system' => 'WGS84', 'unit' => 'm')]) → number {% endapibody %}
Compute the distance between a point and another geometry object. At least one of the geometry objects specified must be a point.
Example: Compute the distance between two points on the Earth in kilometers.
var $point1 = r\point(-122.423246,37.779388);
var $point2 = r\point(-117.220406,32.719464);
r\distance($point1, $point2, array('unit' => 'km'))->run($conn);
// result
734.1252496021841
Read more about this command →
{% apibody %} line->fill() → polygon {% endapibody %}
Convert a Line object into a Polygon object. If the last point does not specify the same coordinates as the first point, polygon
will close the polygon by connecting them.
Example: Create a line object and then convert it to a polygon.
r\table('geo')->insert(array(
'id' => 201,
'rectangle' => r\line(array(
array(-122.423246,37.779388),
array(-122.423246,37.329898),
array(-121.886420,37.329898),
array(-121.886420,37.779388)
))
))->run($conn);
r\table('geo')->get(201)->update(array(
'rectangle' => r\row('rectangle')->fill()
), array('non_atomic' => true))->run($conn);
Read more about this command →
{% apibody %} r\geojson(geojson) → geometry {% endapibody %}
Convert a GeoJSON object to a ReQL geometry object.
Example: Convert a GeoJSON object to a ReQL geometry object.
var $geoJson = array(
'type' => 'Point',
'coordinates' => array( -122.423246, 37.779388 )
);
r\table('geo')->insert(array(
'id' => 'sfo',
'name' => 'San Francisco',
'location' => r\geojson($geoJson)
))->run($conn);
Read more about this command →
{% apibody %} geometry->toGeojson() → object {% endapibody %}
Convert a ReQL geometry object to a GeoJSON object.
Example: Convert a ReQL geometry object to a GeoJSON object.
r\table('geo')->get('sfo')->getField('location')->toGeojson()->run($conn);
// result
array(
'type' => 'Point',
'coordinates' => array( -122.423246, 37.779388 )
)
Read more about this command →
{% apibody %} table->getIntersecting(geometry, array('index' => 'indexname')) → selection {% endapibody %}
Get all documents where the given geometry object intersects the geometry object of the requested geospatial index.
Example: Which of the locations in a list of parks intersect circle1
?
$circle1 = r\circle(array(-117.220406,32.719464), 10, array('unit' => 'mi'));
r\table('parks')->getIntersecting($circle1, array('index' => 'area'))->run($conn);
Read more about this command →
{% apibody %} table->getNearest(point, array('index' => 'indexname'[, 'maxResults' => 100, 'maxDist' => 100000, 'unit' => 'm', 'geo_system' => 'WGS84'])) → selection {% endapibody %}
Get all documents where the specified geospatial index is within a certain distance of the specified point (default 100 kilometers).
Example: Return a list of enemy hideouts within 5000 meters of the secret base.
$secretBase = r\point(-122.422876,37.777128);
r\table('hideouts')->getNearest($secretBase,
array('index' => 'location', 'maxDist' => 5000)
)->run($conn)
Read more about this command →
{% apibody %} sequence->includes(geometry) → sequence geometry->includes(geometry) → bool {% endapibody %}
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.
Example: Is point2
included within a 2000-meter circle around point1
?
var $point1 = r\point(-117.220406,32.719464);
var $point2 = r\point(-117.206201,32.725186);
r\circle($point1, 2000)->includes($point2)->run($conn);
// result
true
Read more about this command →
{% apibody %} sequence->intersects(geometry) → sequence geometry->intersects(geometry) → bool r\intersects(sequence, geometry) → sequence r\intersects(geometry, geometry) → bool {% endapibody %}
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.
Example: Is point2
within a 2000-meter circle around point1
?
var $point1 = r\point(-117.220406,32.719464);
var $point2 = r\point(-117.206201,32.725186);
r\circle($point1, 2000)->intersects($point2)->run($conn);
// result
true
Read more about this command →
{% apibody %} r\line(array(array(lon1, lat1), array(lon2, lat2), ...)) → line r\line(array(point1, point2, ...)) → line {% endapibody %}
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.
Example: Define a line.
r\table('geo')->insert(array(
'id' => 101,
'route' => r\line(array(array(-122.423246,37.779388), array(-121.886420,37.329898)))
))->run($conn);
Read more about this command →
{% apibody %} r\point(longitude, latitude) → point {% endapibody %}
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.
Example: Define a point.
r\table('geo')->insert(array(
'id' => 1,
'name' => 'San Francisco',
'location' => r\point(-122.423246,37.779388)
))->run($conn);
Read more about this command →
{% apibody %} r\polygon(array(array(lon1, lat1), array(lon2, lat2), ...)) → polygon r\polygon(array(point1, point2, ...)) → polygon {% endapibody %}
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.
Example: Define a polygon.
r\table('geo')->insert(array(
'id' => 101,
'rectangle' => r\polygon(array(
array(-122.423246,37.779388),
array(-122.423246,37.329898),
array(-121.886420,37.329898),
array(-121.886420,37.779388)
))
))->run($conn);
Read more about this command →
{% apibody %} polygon1->polygonSub(polygon2) → polygon {% endapibody %}
Use polygon2
to "punch out" a hole in polygon1
. polygon2
must be completely contained within polygon1
and must have no holes itself (it must not be the output of polygonSub
itself).
Example: Define a polygon with a hole punched in it.
var $outerPolygon = r\polygon(array(
array(-122.4,37.7),
array(-122.4,37.3),
array(-121.8,37.3),
array(-121.8,37.7)
));
var $innerPolygon = r\polygon(array(
array(-122.3,37.4),
array(-122.3,37.6),
array(-122.0,37.6),
array(-122.0,37.4)
));
$outerPolygon->polygonSub($innerpolygon)->run($conn);
Read more about this command →
{% endapisection %}
{% apisection Administration %}
{% apibody %} table->config() → selection<object> database->config() → selection<object> {% endapibody %}
Query (read and/or update) the configurations for individual tables or databases.
Example: Get the configuration for the users
table.
> r\table('users')->config()->run($conn);
Read more about this command →
{% apibody %} table->rebalance() → object database->rebalance() → object {% endapibody %}
Rebalances the shards of a table. When called on a database, all the tables in that database will be rebalanced.
Example: Rebalance a table.
> r\table('superheroes')->rebalance()->run($conn);
Read more about this command →
{% apibody %}
table->reconfigure(array('shards' => , 'replicas' => [, 'primary_replica_tag' => , 'dry_run' => false)]) → object
database->reconfigure(array('shards' => , 'replicas' => [, 'primary_replica_tag' => , 'dry_run' => false)]) → object
{% endapibody %}
Reconfigure a table's sharding and replication.
Example: Reconfigure a table.
> r\table('superheroes')->reconfigure(array('shards' => 2, 'replicas' => 1))->run($conn);
Read more about this command →
{% apibody %} table->status() → selection<object> {% endapibody %}
Return the status of a table.
Example: Get a table's status.
> r\table('superheroes')->status()->run($conn);
Read more about this command →
{% apibody %} table->wait([array('wait_for' => 'ready_for_writes', 'timeout' => )]) → object database->wait([array('wait_for' => 'ready_for_writes', 'timeout' => )]) → object r\wait([array('wait_for' => 'ready_for_writes', 'timeout' => )]) → object {% endapibody %}
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.
Example: Wait for a table to be ready.
> r\table('superheroes')->wait()->run($conn);
Read more about this command →
{% endapisection %}