Looking for documentation for a community driver?
Find the project page
for your driver for specific ReQL documentation.
r → r
The top-level ReQL namespace.
Example: Setup your top-level namespace.
from rethinkdb import RethinkDB
r = RethinkDB()
Read more about this command →
r.connect(options) → connection
Create a new connection to the database server. The keyword arguments are:
host
: host of the RethinkDB instance. The default value is localhost
.port
: the driver port, by default 28015
.db
: the database used if not explicitly specified in a query, by default test
.user
: the user account to connect as (default admin
).password
: the password for the user account to connect as (default ''
, empty).timeout
: timeout period in seconds for the connection to be opened (default 20
).ssl
: a hash of options to support SSL connections (default None
). Currently, there is only one option available, and if the ssl
option is specified, this key is required:
ca_certs
: a path to the SSL CA certificate.If the connection cannot be established, a ReqlDriverError
exception will be thrown.
Example: Open a connection using the default host and port, specifying the default database.
conn = r.connect(db='marvel')
Read more about this command →
conn.repl()
Set the default connection to make REPL use easier. Allows calling
.run()
on queries without specifying a connection.
Example: Set the default connection for the REPL, then call
run()
without specifying the connection.
r.connect(db='marvel').repl()
r.table('heroes').run()
Read more about this command →
conn.close(noreply_wait=True)
Close an open connection.
Example: Close an open connection, waiting for noreply writes to finish.
conn.close()
Read more about this command →
conn.reconnect(noreply_wait=True)
Close and reopen a connection.
Example: Cancel outstanding requests/queries that are no longer needed.
conn.reconnect(noreply_wait=False)
Read more about this command →
conn.use(db_name)
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.use('marvel')
r.table('heroes').run(conn) # refers to r.db('marvel').table('heroes')
Read more about this command →
query.run(conn[, options]) → cursor
query.run(conn[, options]) → object
Run a query on a connection, returning either a single JSON result or a cursor, depending on the query.
Example: Run a query on the connection conn
and print out every
row in the result.
for doc in r.table('marvel').run(conn):
print doc
Read more about this command →
stream.changes([options]) → stream
singleSelection.changes([options]) → stream
Turn a query into a changefeed, an infinite stream of objects representing changes to the query’s results as they occur. A changefeed may return changes to a table or an individual document (a “point” changefeed). Commands such as filter
or map
may be used before the changes
command to transform or filter the output, and many commands that operate on sequences can be chained after changes
.
Example: Subscribe to the changes on a table.
Start monitoring the changefeed in one client:
for change in r.table('games').changes().run(conn):
print change
As these queries are performed in a second client, the first client would receive and print the following objects:
> r.table('games').insert({'id': 1}).run(conn)
{'old_val': None, 'new_val': {'id': 1}}
> r.table('games').get(1).update({'player1': 'Bob'}).run(conn)
{'old_val': {'id': 1}, 'new_val': {'id': 1, 'player1': 'Bob'}}
> r.table('games').get(1).replace({'id': 1, 'player1': 'Bob', 'player2': 'Alice'}).run(conn)
{'old_val': {'id': 1, 'player1': 'Bob'},
'new_val': {'id': 1, 'player1': 'Bob', 'player2': 'Alice'}}
> r.table('games').get(1).delete().run(conn)
{'old_val': {'id': 1, 'player1': 'Bob', 'player2': 'Alice'}, 'new_val': None}
> r.table_drop('games').run(conn)
ReqlRuntimeError: Changefeed aborted (table unavailable)
Read more about this command →
conn.noreply_wait()
noreply_wait
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.noreply_wait()
Read more about this command →
conn.server()
Return information about the server being used by a connection.
Example: Return server information.
> conn.server()
{
"id": "404bef53-4b2c-433f-9184-bc3f7bda4a15",
"name": "amadeus",
"proxy": False
}
Read more about this command →
r.set_loop_type(string)
Set an asynchronous event loop model. There are two supported models:
Example: Read a table’s data using Tornado.
r.set_loop_type("tornado")
conn = r.connect(host='localhost', port=28015)
@gen.coroutine
def use_cursor(conn):
# Print every row in the table.
cursor = yield r.table('test').order_by(index="id").run(yield conn)
while (yield cursor.fetch_next()):
item = yield cursor.next()
print(item)
For a longer discussion with both Tornado and Twisted examples, see the documentation article on Asynchronous connections.
cursor.next([wait=True])
Get the next element in the cursor.
Example: Retrieve the next element.
cursor = r.table('superheroes').run(conn)
doc = cursor.next()
Read more about this command →
for items in cursor:
for items in array:
for items in feed:
Lazily iterate over a result set one element at a time.
Example: Let’s process all the elements!
cursor = r.table('users').run(conn)
for doc in cursor:
process_row(doc)
Read more about this command →
list(cursor)
Retrieve all results as a list.
Example: For small result sets it may be more convenient to process them at once as an array.
cursor = r.table('users').run()
users = list(cursor)
process_results(users)
Read more about this command →
cursor.close()
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()
r.db_create(db_name) → object
Create a database. A RethinkDB database is a collection of tables, similar to relational databases.
Example: Create a database named ‘superheroes’.
r.db_create('superheroes').run(conn)
{
"config_changes": [
{
"new_val": {
"id": "e4689cfc-e903-4532-a0e6-2d6797a43f07",
"name": "superheroes"
},
"old_val": None
}
],
"dbs_created": 1
}
Read more about this command →
r.db_drop(db_name) → object
Drop a database. The database, all its tables, and corresponding data will be deleted.
Example: Drop a database named ‘superheroes’.
r.db_drop('superheroes').run(conn)
{
"config_changes": [
{
"old_val": {
"id": "e4689cfc-e903-4532-a0e6-2d6797a43f07",
"name": "superheroes"
},
"new_val": None
}
],
"tables_dropped": 3,
"dbs_dropped": 1
}
Read more about this command →
r.db_list() → array
List all database names in the system. The result is a list of strings.
Example: List all databases.
r.db_list().run(conn)
db.table_create(table_name[, options]) → object
r.table_create(table_name[, options]) → object
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').table_create('dc_universe').run(conn)
{
"config_changes": [
{
"new_val": {
"db": "test",
"durability": "hard",
"id": "20ea60d4-3b76-4817-8828-98a236df0297",
"name": "dc_universe",
"primary_key": "id",
"shards": [
{
"primary_replica": "rethinkdb_srv1",
"replicas": [
"rethinkdb_srv1",
"rethinkdb_srv2"
]
}
],
"write_acks": "majority"
},
"old_val": None
}
],
"tables_created": 1
}
Read more about this command →
db.table_drop(table_name) → object
Drop a table. The table and all its data will be deleted.
Example: Drop a table named ‘dc_universe’.
r.db('test').table_drop('dc_universe').run(conn)
{
"config_changes": [
{
"old_val": {
"db": "test",
"durability": "hard",
"id": "20ea60d4-3b76-4817-8828-98a236df0297",
"name": "dc_universe",
"primary_key": "id",
"shards": [
{
"primary_replica": "rethinkdb_srv1",
"replicas": [
"rethinkdb_srv1",
"rethinkdb_srv2"
]
}
],
"write_acks": "majority"
},
"new_val": None
}
],
"tables_dropped": 1
}
Read more about this command →
db.table_list() → array
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').table_list().run(conn)
Read more about this command →
table.index_create(index_name[, index_function][, multi=False, geo=False]) → object
Create a new secondary index on a table. Secondary indexes improve the speed of many read queries at the slight cost of increased storage space and decreased write performance. For more information about secondary indexes, read the article “Using secondary indexes in RethinkDB.”
Example: Create a simple index based on the field post_id
.
r.table('comments').index_create('post_id').run(conn)
Read more about this command →
table.index_drop(index_name) → object
Delete a previously created secondary index of this table.
Example: Drop a secondary index named ‘code_name’.
r.table('dc').index_drop('code_name').run(conn)
Read more about this command →
table.index_list() → array
List all the secondary indexes of this table.
Example: List the available secondary indexes for this table.
r.table('marvel').index_list().run(conn)
Read more about this command →
table.index_rename(old_index_name, new_index_name[, overwrite=False]) → object
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').index_rename('post_id', 'message_id').run(conn)
Read more about this command →
table.index_status([, index...]) → array
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').index_status().run(conn)
Read more about this command →
table.index_wait([, index...]) → array
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').index_wait().run(conn)
Read more about this command →
table.set_write_hook(function | binary | null) → object
Sets the write hook on a table or overwrites it if one already exists.
The function
can be an anonymous function with the signature (context: object, old_val: object, new_val: object) -> object
or a binary representation obtained from the function
field of get_write_hook. The function must be deterministic, and so cannot use a subquery or the r.js
command.
Read more about this command →
table.get_write_hook() → null/object
Gets the write hook of this table. If a write hook exists, the result is an object of the following form:
{
"function": <binary>,
"query": "setWriteHook(function(_var1, _var2, _var3) { return ...; })",
}
table.insert(object | [object1, object2, ...][, durability="hard", return_changes=False, conflict="error"]) → object
Insert documents into a table. Accepts a single document or an array of documents.
Example: Insert a document into the table posts
.
r.table("posts").insert({
"id": 1,
"title": "Lorem ipsum",
"content": "Dolor sit amet"
}).run(conn)
Read more about this command →
table.update(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
selection.update(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
singleSelection.update(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
Update JSON documents in a table. Accepts a JSON document, a ReQL expression, or a combination of the two.
Example: Update the status of the post with id
of 1
to published
.
r.table("posts").get(1).update({"status": "published"}).run(conn)
Read more about this command →
table.replace(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
selection.replace(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
singleSelection.replace(object | function[, durability="hard", return_changes=False, non_atomic=False]) → object
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({
"id": 1,
"title": "Lorem ipsum",
"content": "Aleas jacta est",
"status": "draft"
}).run(conn)
Read more about this command →
table.delete([durability="hard", return_changes=False]) → object
selection.delete([durability="hard", return_changes=False]) → object
singleSelection.delete([durability="hard", return_changes=False]) → object
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 →
table.sync() → object
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)
r.db(db_name) → db
Reference a database.
Example: Explicitly specify a database for a query.
r.db('heroes').table('marvel').run(conn)
Read more about this command →
db.table(name[, read_mode='single', identifier_format='name']) → table
Return all documents in a table. Other commands may be chained after table
to return a subset of documents (such as get and filter) or perform further processing.
Example: Return all documents in the table ‘marvel’ of the default database.
r.table('marvel').run(conn)
Read more about this command →
table.get(key) → singleRowSelection
Get a document by primary key.
Example: Find a document by UUID.
r.table('posts').get('a9849eef-7176-4411-935b-79a6e3c56a74').run(conn)
Read more about this command →
table.get_all([key1, key2...], [, index='id']) → selection
Get all documents where the given value matches the value of the requested index.
Example: Secondary index keys are not guaranteed to be unique so we cannot query via get when using a secondary index.
r.table('marvel').get_all('man_of_steel', index='code_name').run(conn)
Read more about this command →
table.between(lower_key, upper_key[, options]) → table_slice
table_slice.between(lower_key, upper_key[, options]) → table_slice
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 →
selection.filter(predicate_function[, default=False]) → selection
stream.filter(predicate_function[, default=False]) → stream
array.filter(predicate_function[, default=False]) → array
Return all the elements in a sequence for which the given predicate is true. The return value of filter
will be the same as the input (sequence, stream, or array). Documents can be filtered in a variety of ways—ranges, nested values, boolean conditions, and the results of anonymous functions.
Example: Get all users who are 30 years old.
r.table('users').filter({'age': 30}).run(conn)
The predicate {'age': 30}
selects documents in the users
table with an age
field whose value is 30
. Documents with an age
field set to any other value or with no age
field present are skipped.
sequence.inner_join(other_sequence, predicate_function) → stream
array.inner_join(other_sequence, predicate_function) → array
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').inner_join(r.table('dc'),
lambda marvel_row, dc_row: marvel_row['strength'] < dc_row['strength']
).zip().run(conn)
Read more about this command →
sequence.outer_join(other_sequence, predicate_function) → stream
array.outer_join(other_sequence, predicate_function) → array
Returns a left outer join of two sequences. The returned sequence represents a union of the left-hand sequence and the right-hand sequence: all documents in the left-hand sequence will be returned, each matched with a document in the right-hand sequence if one satisfies the predicate condition. In most cases, you will want to follow the join with zip to combine the left and right results.
Example: Return a list of all Marvel heroes, paired with any DC heroes who could beat them in a fight.
r.table('marvel').outer_join(r.table('dc'),
lambda marvel_row, dc_row: marvel_row['strength'] < dc_row['strength']
).zip().run(conn)
(Compare this to an inner_join with the same inputs and predicate, which would return a list only of the matchups in which the DC hero has the higher strength.)
Read more about this command →
sequence.eq_join(left_field, right_table[, index='id', ordered=False]) → sequence
sequence.eq_join(function, right_table[, index='id', ordered=False]) → sequence
Join tables using a field or function 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.
Example: Match players with the games they’ve played against one another.
Join these tables using game_id
on the player table and id
on the games table:
r.table('players').eq_join('game_id', r.table('games')).run(conn)
This will return a result set such as the following:
[
{
"left" : { "game_id" : 3, "id" : 2, "player" : "Agatha" },
"right" : { "id" : 3, "field" : "Bucklebury" }
},
{
"left" : { "game_id" : 2, "id" : 3, "player" : "Fred" },
"right" : { "id" : 2, "field" : "Rushock Bog" }
},
...
]
Read more about this command →
stream.zip() → stream
array.zip() → array
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').eq_join('main_dc_collaborator', r.table('dc')).zip().run(conn)
sequence1.map([sequence2, ...], function) → stream
array1.map([array2, ...], function) → array
r.map(sequence1[, sequence2, ...], function) → stream
r.map(array1[, array2, ...], function) → array
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.
Example: Return the first five squares.
> r.expr([1, 2, 3, 4, 5]).map(lambda val: (val * val)).run(conn)
[1, 4, 9, 16, 25]
Read more about this command →
sequence.with_fields([selector1, selector2...]) → stream
array.with_fields([selector1, selector2...]) → array
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.
Example: Get a list of users and their posts, excluding any users who have not made any posts.
Existing table structure:
[
{ 'id': 1, 'user': 'bob', 'email': 'bob@foo.com', 'posts': [ 1, 4, 5 ] },
{ 'id': 2, 'user': 'george', 'email': 'george@foo.com' },
{ 'id': 3, 'user': 'jane', 'email': 'jane@foo.com', 'posts': [ 2, 3, 6 ] }
]
Command and output:
r.table('users').with_fields('id', 'user', 'posts').run(conn)
[
{ 'id': 1, 'user': 'bob', 'posts': [ 1, 4, 5 ] },
{ 'id': 3, 'user': 'jane', 'posts': [ 2, 3, 6 ] }
]
Read more about this command →
stream.concat_map(function) → stream
array.concat_map(function) → array
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').concat_map(lambda hero: hero['defeatedMonsters']).run(conn)
Read more about this command →
table.order_by([key | function], index=index_name) → table_slice
selection.order_by(key | function[, ...]) → selection<array>
sequence.order_by(key | function[, ...]) → array
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).
Example: Order all the posts using the index date
.
r.table('posts').order_by(index='date').run(conn)
Read more about this command →
sequence.skip(n) → stream
array.skip(n) → array
Skip a number of elements from the head of the sequence.
Example: Here in conjunction with order_by we choose to ignore the most successful heroes.
r.table('marvel').order_by('successMetric').skip(10).run(conn)
Read more about this command →
sequence.limit(n) → stream
array.limit(n) → array
End the sequence after the given number of elements.
Example: Only so many can fit in our Pantheon of heroes.
r.table('marvel').order_by('belovedness').limit(10).run(conn)
Read more about this command →
selection.slice(start_offset[, end_offset, left_bound='closed', right_bound='open']) → selection
stream.slice(start_offset[, end_offset, left_bound='closed', right_bound='open']) → stream
array.slice(start_offset[, end_offset, left_bound='closed', right_bound='open']) → array
binary.slice(start_offset[, end_offset, left_bound='closed', right_bound='open']) → binary
string.slice(start_offset[, end_offset, left_bound='closed', right_bound='open']) → string
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').order_by(index='age').slice(3,6).run(conn)
Or, using Python’s slice operator:
r.table('players').filter({'class': 'amateur'})[10:20].run(conn)
Read more about this command →
sequence.nth(index) → object
selection.nth(index) → selection<object>
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([1,2,3]).nth(1).run(conn)
r.expr([1,2,3])[1].run(conn)
Read more about this command →
sequence.offsets_of(datum | predicate_function) → array
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(['a','b','c']).offsets_of('c').run(conn)
Read more about this command →
sequence.is_empty() → bool
Test if a sequence is empty.
Example: Are there any documents in the marvel table?
r.table('marvel').is_empty().run(conn)
Read more about this command →
stream.union(sequence[, sequence, ...][, interleave=True]) → stream
array.union(sequence[, sequence, ...][, interleave=True]) → array
r.union(stream, sequence[, sequence, ...][, interleave=True]) → stream
r.union(array, sequence[, sequence, ...][, interleave=True]) → array
Merge two or more sequences.
Example: Construct a stream of all heroes.
r.table('marvel').union(r.table('dc')).run(conn)
Read more about this command →
sequence.sample(number) → selection
stream.sample(number) → array
array.sample(number) → array
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)
sequence.group(field | function..., [index=<indexname>, multi=False]) → grouped_stream
r.group(sequence, field | function..., [index=<indexname>, multi=False]) → grouped_stream
Takes a stream and partitions it into multiple groups based on the fields or functions provided.
Example: Group games by player.
> r.table('games').group('player').run(conn)
{
"Alice": [
{"id": 5, "player": "Alice", "points": 7, "type": "free"},
{"id": 12, "player": "Alice", "points": 2, "type": "free"}
],
"Bob": [
{"id": 2, "player": "Bob", "points": 15, "type": "ranked"},
{"id": 11, "player": "Bob", "points": 10, "type": "free"}
]
}
Read more about this command →
grouped_stream.ungroup() → array
grouped_data.ungroup() → array
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')['points']
.ungroup().order_by(r.desc('reduction')).run(conn)
Read more about this command →
sequence.reduce(function) → value
r.reduce(sequence, function) → value
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(lambda doc: 1)
.reduce(lambda left, right: left+right)
.default(0).run(conn)
A shorter way to execute this query is to use count.
Read more about this command →
sequence.fold(base, function) → value
sequence.fold(base, function, emit=function[, final_emit=function]) → sequence
Apply a function to a sequence in order, maintaining state via an accumulator. The fold
command returns either a single value or a new sequence.
Example: Concatenate words from a list.
r.table('words').order_by('id').fold('',
lambda acc, word: acc + r.branch(acc == '', '', ', ') + word
).run(conn)
(This example could be implemented with reduce
, but fold
will preserve the order when words
is a RethinkDB table or other stream, which is not guaranteed with reduce
.)
Read more about this command →
sequence.count([value | predicate_function]) → number
binary.count() → number
string.count() → number
object.count() → number
r.count(sequence | binary | string | object[, predicate_function]) → number
Counts the number of elements in a sequence or key/value pairs in an object, or returns the size of a string or binary object.
Example: Count the number of users.
r.table('users').count().run(conn)
Read more about this command →
sequence.sum([field | function]) → number
r.sum(sequence, [field | function]) → number
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
None
or a non-existence error.
Example: What’s 3 + 5 + 7?
r.expr([3, 5, 7]).sum().run(conn)
Read more about this command →
sequence.avg([field | function]) → number
r.avg(sequence, [field | function]) → number
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 None
or a non-existence error.
Example: What’s the average of 3, 5, and 7?
r.expr([3, 5, 7]).avg().run(conn)
Read more about this command →
sequence.min(field | function) → element
sequence.min(index=<indexname>) → element
r.min(sequence, field | function) → element
r.min(sequence, index=<indexname>) → element
Finds the minimum element of a sequence.
Example: Return the minimum value in the list [3, 5, 7]
.
r.expr([3, 5, 7]).min().run(conn)
Read more about this command →
sequence.max(field | function) → element
sequence.max(index=<indexname>) → element
r.max(sequence, field | function) → element
r.max(sequence, index=<indexname>) → element
Finds the maximum element of a sequence.
Example: Return the maximum value in the list [3, 5, 7]
.
r.expr([3, 5, 7]).max().run(conn)
Read more about this command →
sequence.distinct() → array
table.distinct([index=<indexname>]) → stream
r.distinct(sequence) → array
r.distinct(table, [index=<indexname>]) → stream
Removes duplicate elements from a sequence.
Example: Which unique villains have been vanquished by Marvel heroes?
r.table('marvel').concat_map(
lambda hero: hero['villain_list']).distinct().run(conn)
Read more about this command →
sequence.contains([value | predicate_function, ...]) → bool
r.contains(sequence, [value | predicate_function, ...]) → bool
When called with values, returns True
if a sequence contains all the
specified values. When called with predicate functions, returns True
if for each predicate there exists at least one element of the stream
where that predicate returns True
.
Example: Has Iron Man ever fought Superman?
r.table('marvel').get('ironman')['opponents'].contains('superman').run(conn)
r.row → value
Returns the currently visited document.
Example: Get all users whose age is greater than 5.
r.table('users').filter(r.row['age'] > 5).run(conn)
Read more about this command →
sequence.pluck([selector1, selector2...]) → stream
array.pluck([selector1, selector2...]) → array
object.pluck([selector1, selector2...]) → object
singleSelection.pluck([selector1, selector2...]) → object
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('reactorState', 'reactorPower').run(conn)
Read more about this command →
sequence.without([selector1, selector2...]) → stream
array.without([selector1, selector2...]) → array
singleSelection.without([selector1, selector2...]) → object
object.without([selector1, selector2...]) → object
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 →
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
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 merge
also accepts a subquery function that returns an object, which will be used similarly to a map function.
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 →
array.append(value) → array
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')['equipment'].append('newBoots').run(conn)
Read more about this command →
array.prepend(value) → array
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')['equipment'].prepend('newBoots').run(conn)
Read more about this command →
array.difference(array) → array
Remove the elements of one array from another array.
Example: Retrieve Iron Man’s equipment list without boots.
r.table('marvel').get('IronMan')['equipment'].difference(['Boots']).run(conn)
Read more about this command →
array.set_insert(value) → array
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')['equipment'].set_insert('newBoots').run(conn)
Read more about this command →
array.set_union(array) → array
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')['equipment'].set_union(['newBoots', 'arc_reactor']).run(conn)
Read more about this command →
array.set_intersection(array) → array
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')['equipment'].set_intersection(['newBoots', 'arc_reactor']).run(conn)
Read more about this command →
array.set_difference(array) → array
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')['equipment'].set_difference(['newBoots', 'arc_reactor']).run(conn)
Read more about this command →
sequence[attr] → sequence
singleSelection[attr] → value
object[attr] → value
array[index] → value
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')['firstAppearance'].run(conn)
Read more about this command →
sequence.get_field(attr) → sequence
singleSelection.get_field(attr) → value
object.get_field(attr) → value
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').get_field('firstAppearance').run(conn)
Read more about this command →
sequence.has_fields([selector1, selector2...]) → stream
array.has_fields([selector1, selector2...]) → array
object.has_fields([selector1, selector2...]) → boolean
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').has_fields('games_won').run(conn)
Read more about this command →
array.insert_at(offset, value) → array
Insert a value in to an array at a given index. Returns the modified array.
Example: Hulk decides to join the avengers.
r.expr(["Iron Man", "Spider-Man"]).insert_at(1, "Hulk").run(conn)
Read more about this command →
array.splice_at(offset, array) → array
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(["Iron Man", "Spider-Man"]).splice_at(1, ["Hulk", "Thor"]).run(conn)
Read more about this command →
array.delete_at(offset [,end_offset]) → array
Remove one or more elements from an array at a given index. Returns the modified array. (Note: delete_at
operates on arrays, not documents; to delete documents, see the delete command.)
Example: Delete the second element of an array.
> r.expr(['a','b','c','d','e','f']).delete_at(1).run(conn)
['a', 'c', 'd', 'e', 'f']
Read more about this command →
array.change_at(offset, value) → array
Change a value in an array at a given index. Returns the modified array.
Example: Bruce Banner hulks out.
r.expr(["Iron Man", "Bruce", "Spider-Man"]).change_at(1, "Hulk").run(conn)
Read more about this command →
singleSelection.keys() → array
object.keys() → array
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": "fred@example.com", "name": "fred" }
r.table('users').get(1).keys().run(conn)
> [ "id", "mail", "name" ]
Read more about this command →
singleSelection.values() → array
object.values() → array
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": "fred@example.com", "name": "fred" }
r.table('users').get(1).values().run(conn)
> [ 1, "fred@example.com", "fred" ]
Read more about this command →
r.literal(object) → special
Replace an object in a field instead of merging it with an existing object in a merge
or update
operation. = Using literal
with no arguments in a merge
or update
operation will remove the corresponding field.
Example: Replace one nested document with another rather than merging the fields.
r.table('users').get(1).update({ 'data': r.literal({ 'age': 19, 'job': 'Engineer' }) }).run(conn)
{
"id": 1,
"name": "Alice",
"data": {
"age": 19,
"job": "Engineer"
}
}
Read more about this command →
r.object([key, value,]...) → object
Creates an object from a list of key-value pairs, where the keys must
be strings. r.object(A, B, C, D)
is equivalent to
r.expr([[A, B], [C, D]]).coerce_to('OBJECT')
.
Example: Create a simple object.
> r.object('id', 5, 'data', ['foo', 'bar']).run(conn)
{'data': ["foo", "bar"], 'id': 5}
string.match(regexp) → None/object
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 parenthesesIf no match is found, returns None
.
Example: Get all users whose name starts with “A”. Because None
evaluates to false
in
filter, you can just use the result of match
for the predicate.
r.table('users').filter(lambda doc:
doc['name'].match("^A")
).run(conn)
Read more about this command →
string.split([separator, [max_splits]]) → array
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 None
as the separator if you want to split on whitespace
while still specifying max_splits
.)
Example: Split on whitespace.
> r.expr("foo bar bax").split().run(conn)
["foo", "bar", "bax"]
Read more about this command →
string.upcase() → string
Uppercases a string.
Example:
> r.expr("Sentence about LaTeX.").upcase().run(conn)
"SENTENCE ABOUT LATEX."
Note: upcase
and downcase
only affect ASCII characters.
Read more about this command →
string.downcase() → string
Lowercases a string.
Example:
> r.expr("Sentence about LaTeX.").downcase().run(conn)
"sentence about latex."
Note: upcase
and downcase
only affect ASCII characters.
value + value → value
time + number → time
value.add(value[, value, ...]) → value
time.add(number[, number, ...]) → time
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) + 2).run(conn)
4
Read more about this command →
number - number → number
time - number → time
time - time → number
number.sub(number[, number, ...]) → number
time.sub(number[, number, ...]) → time
time.sub(time) → number
Subtract two numbers.
Example: It’s as easy as 2 - 2 = 0.
(r.expr(2) - 2).run(conn)
Read more about this command →
number * number → number
array * number → array
number.mul(number[, number, ...]) → number
array.mul(number[, number, ...]) → array
Multiply two numbers, or make a periodic array.
Example: It’s as easy as 2 * 2 = 4.
(r.expr(2) * 2).run(conn)
Read more about this command →
number / number → number
number.div(number[, number ...]) → number
Divide two numbers.
Example: It’s as easy as 2 / 2 = 1.
(r.expr(2) / 2).run(conn)
Read more about this command →
number % number → number
Find the remainder when dividing two numbers.
Example: It’s as easy as 2 % 2 = 0.
(r.expr(2) % 2).run(conn)
Read more about this command →
bool & bool → bool
bool.and_([bool, bool, ...]) → bool
r.and_([bool, bool, ...]) → bool
Compute the logical “and” of one or more values.
Example: Return whether both a
and b
evaluate to true.
> a = True
> b = False
> (r.expr(a) & b).run(conn)
False
Read more about this command →
bool | bool → bool
bool.or_([bool, bool, ...]) → bool
r.or_([bool, bool, ...]) → bool
Compute the logical “or” of one or more values.
Example: Return whether either a
or b
evaluate to true.
> a = True
> b = False
> (r.expr(a) | b).run(conn)
True
Read more about this command →
value.eq(value[, value, ...]) → bool
value == value → bool
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)['role'].eq('administrator').run(conn)
# alternative syntax
(r.table('users').get(1)['role'] == 'administrator').run(conn)
Read more about this command →
value.ne(value[, value, ...]) → bool
value != value → bool
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)['role'].ne('administrator').run(conn)
# alternative syntax
(r.table('users').get(1)['role'] != 'administrator').run(conn)
Read more about this command →
value.gt(value[, value, ...]) → bool
value > value → bool
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)['score'].gt(10).run(conn)
# alternative syntax
(r.table('players').get(1)['score'] > 10).run(conn)
Read more about this command →
value.ge(value[, value, ...]) → bool
value >= value → bool
Compare values, testing if the left-hand value is greater or equal to than the right-hand.
Example: Test if a player has scored 10 points or more.
r.table('players').get(1)['score'].ge(10).run(conn)
# alternative syntax
(r.table('players').get(1)['score'] >= 10).run(conn)
Read more about this command →
value.lt(value[, value, ...]) → bool
value < value → bool
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)['score'].lt(10).run(conn)
# alternative syntax
(r.table('players').get(1)['score'] < 10).run(conn)
Read more about this command →
value.le(value[, value, ...]) → bool
value <= value → bool
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)['score'].le(10).run(conn)
# alternative syntax
(r.table('players').get(1)['score'] <= 10).run(conn)
Read more about this command →
bool.not_() → bool
not_(bool) → bool
(~bool) → bool
Compute the logical inverse (not) of an expression.
Example: Not true is false.
r.not_(True).run(conn)
r.expr(True).not_().run(conn)
(~r.expr(True)).run(conn)
These evaluate to false
.
Note that when using ~
the expression is wrapped in parentheses. Without this, Python will evaluate r.expr(True)
first rather than using the ReQL operator and return an incorrect value. (~True
evaluates to −2 in Python.)
Read more about this command →
r.bit_and(number) → number
r.bit_and(number[, number, ...]) → number
Compute the arithmetic “and” of one or more values. bit_and
takes one or more arguments.
Example: Compute the arithmetic “and” of 6
and 4
r.expr(6).bit_and(4).run(conn)
Read more about this command →
r.bit_or(number) → number
r.bit_or(number[, number, ...]) → number
Compute the arithmetic “or” of one or more values. bit_or
takes one or more arguments.
Example: Compute the arithmetic “or” of 6
and 4
r.expr(6).bit_or(4).run(conn)
Read more about this command →
r.bit_xor(number) → number
r.bit_xor(number[, number, ...]) → number
Compute the arithmetic “and” of one or more values. bit_xor
takes one or more arguments.
Example: Compute the arithmetic “and” of 6
and 4
r.expr(6).bit_xor(4).run(conn)
Read more about this command →
r.bit_not() → number
Compute the arithmetic inverse (not) of an expression. bit_not
takes no arguments.
Example: Negate the arithmetice expression
r.expr(15).bit_not().run(conn)
Read more about this command →
r.bit_sal(number) → number
r.bit_sal(number[, number, ...]) → number
Compute the left arithmetic shift (left logical shift) of one or more values. bit_sal
takes one or more arguments.
Example: Compute the left arithmetic shift of 5
and 4
r.expr(5).bit_sal(4).run(conn)
Read more about this command →
r.bit_sar(number) → number
r.bit_sar(number[, number, ...]) → number
Compute the right arithmetic shift of one or more values. bit_sar
takes one or more arguments.
Example: Compute the right arithmetic shift of 32
and 3
r.expr(32).bit_sar(3).run(conn)
Read more about this command →
r.random() → number
r.random(number[, number], float=True) → number
r.random(integer[, integer]) → integer
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 →
r.round(number) → number
number.round() → number
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
The round
command can also be chained after an expression.
Read more about this command →
r.ceil(number) → number
number.ceil() → number
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
The ceil
command can also be chained after an expression.
Read more about this command →
r.floor(number) → number
number.floor() → number
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
The floor
command can also be chained after an expression.
r.now() → time
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({
"name": "John",
"subscription_date": r.now()
}).run(conn)
Read more about this command →
r.time(year, month, day[, hour, minute, second], timezone) → time
Create a time object for a specific time.
Example: Update the birthdate of the user “John” to November 3rd, 1986 UTC.
r.table("user").get("John").update({"birthdate": r.time(1986, 11, 3, 'Z')}).run(conn)
Read more about this command →
r.epoch_time(number) → time
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({"birthdate": r.epoch_time(531360000)}).run(conn)
Read more about this command →
r.iso8601(string[, default_timezone='']) → time
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.
Example: Update the time of John’s birth.
r.table("user").get("John").update({"birth": r.iso8601('1986-11-03T08:30:00-07:00')}).run(conn)
Read more about this command →
time.in_timezone(timezone) → time
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().in_timezone('-08:00').hours().run(conn)
Read more about this command →
time.timezone() → string
Return the timezone of the time object.
Example: Return all the users in the “-07:00” timezone.
r.table("users").filter(lambda user:
user["subscriptionDate"].timezone() == "-07:00"
)
Read more about this command →
time.during(start_time, end_time[, left_bound="closed", right_bound="open"]) → bool
Return whether a time is between two other times.
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, "Z"), r.time(2013, 12, 10, "Z"))
).run(conn)
Read more about this command →
time.date() → time
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(lambda user:
user["birthdate"].date() == r.now().date()
).run(conn)
Read more about this command →
time.time_of_day() → number
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"].time_of_day() <= 12*60*60
).run(conn)
Read more about this command →
time.year() → number
Return the year of a time object.
Example: Retrieve all the users born in 1986.
r.table("users").filter(lambda user:
user["birthdate"].year() == 1986
).run(conn)
Read more about this command →
time.month() → number
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() == 11
)
Read more about this command →
time.day() → number
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() == 24
)
Read more about this command →
time.day_of_week() → number
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().day_of_week().run(conn)
Read more about this command →
time.day_of_year() → number
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"].day_of_year() == 1
).run(conn)
Read more about this command →
time.hours() → number
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(lambda post:
post["date"].hours() < 4
).run(conn)
Read more about this command →
time.minutes() → number
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(lambda post:
post["date"].minutes() < 10
).run(conn)
Read more about this command →
time.seconds() → number
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(lambda post:
post["date"].seconds() < 30
).run(conn)
Read more about this command →
time.to_iso8601() → string
Convert a time object to a string in ISO 8601 format.
Example: Return the current ISO 8601 time.
> r.now().to_iso8601().run(conn)
"2015-04-20T18:37:52.690+00:00"
Read more about this command →
time.to_epoch_time() → number
Convert a time object to its epoch time.
Example: Return the current time in seconds since the Unix Epoch with millisecond-precision.
r.now().to_epoch_time()
r.args(array) → special
r.args
is a special term that’s used to splice an array of arguments
into another term. This is useful when you want to call a variadic
term such as get_all with a set of arguments produced at runtime.
Example: Get Alice and Bob from the table people
.
r.table('people').get_all('Alice', 'Bob').run(conn)
# or
r.table('people').get_all(r.args(['Alice', 'Bob'])).run(conn)
Read more about this command →
r.binary(data) → binary
Encapsulate binary data within a query.
Example: Save an avatar image to a existing user record.
f = open('./default_avatar.png', 'rb')
avatar_image = f.read()
f.close()
r.table('users').get(100).update({'avatar': r.binary(avatar_image)}).run(conn)
Read more about this command →
any.do(function) → any
r.do([args]*, function) → any
any.do(expr) → any
r.do([args]*, expr) → any
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('86be93eb-a112-48f5-a829-15b2cb49de1d').do(
lambda player: player['gross_score'] - player['course_handicap']
).run(conn)
Read more about this command →
r.branch(test, true_action[, test2, test2_action, ...], false_action) → any
test.branch(true_action[, test2, test2_action, ...], false_action) → any
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 None
(i.e., “truthy” values), with a final “else” command to be evaluated if all of the conditionals are False
or None
.
Example: Test the value of x.
x = 10
r.branch((x > 5), 'big', 'small').run(conn)
> "big"
Read more about this command →
sequence.for_each(write_function) → object
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').for_each(
lambda hero: r.table('villains').get(hero['villainDefeated']).delete()
).run(conn)
Read more about this command →
r.range() → stream
r.range([start_value, ]end_value) → stream
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)
[0, 1, 2, 3]
Read more about this command →
r.error(message) → error
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(
lambda ironman: r.branch(ironman['victories'] < ironman['battles'],
r.error('impossible code path'),
ironman)
).run(conn)
Read more about this command →
value.default(default_value | function) → any
sequence.default(default_value | function) → any
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 None
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 None
, we want to retrieve the string
Anonymous
.
r.table("posts").map(lambda post:
{
"title": post["title"],
"author": post["author"].default("Anonymous")
}
).run(conn)
Read more about this command →
r.expr(value) → value
Construct a ReQL JSON object from a native object.
Example: Objects wrapped with expr
can then be manipulated by ReQL API functions.
r.expr({'a':'b'}).merge({'b':[1,2,3]}).run(conn)
Read more about this command →
r.js(js_string[, timeout=<number>]) → value
Create a javascript expression.
Example: Concatenate two strings using JavaScript.
timeout
is the number of seconds before r.js
times out. The default value is 5 seconds.
Whenever possible, you should use native ReQL commands rather than r.js
for better performance.
r.js("'str1' + 'str2'").run(conn)
Read more about this command →
sequence.coerce_to('array') → array
value.coerce_to('string') → string
string.coerce_to('number') → number
array.coerce_to('object') → object
sequence.coerce_to('object') → object
object.coerce_to('array') → array
binary.coerce_to('string') → string
string.coerce_to('binary') → binary
Convert a value of one type into another.
Example: Coerce a stream to an array to store its output in a field. (A stream cannot be stored in a field directly.)
r.table('posts').map(lambda post: post.merge(
{ 'comments': r.table('comments').get_all(post['id'], index='post_id').coerce_to('array') }
)).run(conn)
Read more about this command →
any.type_of() → string
Gets the type of a ReQL query’s return value.
Example: Get the type of a string.
> r.expr("foo").type_of().run(conn)
"STRING"
Read more about this command →
any.info() → object
r.info(any) → object
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)
Read more about this command →
r.json(json_string) → value
Parse a JSON string on the server.
Example: Send an array to the server.
r.json("[1,2,3]").run(conn)
Read more about this command →
value.to_json_string() → string
value.to_json() → string
Convert a ReQL value or object to a JSON string. You may use either to_json_string
or to_json
.
Example: Get a ReQL document as a JSON string.
> r.table('hero').get(1).to_json()
'{"id": 1, "name": "Batman", "city": "Gotham", "powers": ["martial arts", "cinematic entrances"]}'
Read more about this command →
r.http(url[, options]) → value
r.http(url[, options]) → stream
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. Make sure that you never use this command for user provided URLs.
Example: Perform an HTTP GET
and store the result in a table.
r.table('posts').insert(r.http('http://httpbin.org/get')).run(conn)
Read more about this command →
r.uuid([string]) → string
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)
"27961a0e-f4e8-4eb3-bf95-c5203e1d87b9"
r.circle([longitude, latitude], radius[, num_vertices=32, geo_system='WGS84', unit='m', fill=True]) → geometry
r.circle(point, radius[, {num_vertices=32, geo_system='WGS84', unit='m', fill=True]) → geometry
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({
'id': 300,
'name': 'Hayes Valley',
'neighborhood': r.circle([-122.423246, 37.779388], 1000)
}).run(conn)
Read more about this command →
geometry.distance(geometry[, geo_system='WGS84', unit='m']) → number
r.distance(geometry, geometry[, geo_system='WGS84', unit='m']) → number
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.
> point1 = r.point(-122.423246, 37.779388)
> point2 = r.point(-117.220406, 32.719464)
> r.distance(point1, point2, unit='km').run(conn)
734.1252496021841
Read more about this command →
line.fill() → polygon
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({
'id': 201,
'rectangle': r.line(
[-122.423246, 37.779388],
[-122.423246, 37.329898],
[-121.886420, 37.329898],
[-121.886420, 37.779388]
)
}).run(conn)
r.table('geo').get(201).update({
'rectangle': r.row['rectangle'].fill()
}, non_atomic=True).run(conn)
Read more about this command →
r.geojson(geojson) → geometry
Convert a GeoJSON object to a ReQL geometry object.
Example: Convert a GeoJSON object to a ReQL geometry object.
geo_json = {
'type': 'Point',
'coordinates': [ -122.423246, 37.779388 ]
}
r.table('geo').insert({
'id': 'sfo',
'name': 'San Francisco',
'location': r.geojson(geo_json)
}).run(conn)
Read more about this command →
geometry.to_geojson() → object
Convert a ReQL geometry object to a GeoJSON object.
Example: Convert a ReQL geometry object to a GeoJSON object.
> r.table('geo').get('sfo')['location'].to_geojson().run(conn)
{
'type': 'Point',
'coordinates': [ -122.423246, 37.779388 ]
}
Read more about this command →
table.get_intersecting(geometry, index='indexname') → selection<stream>
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([-117.220406, 32.719464], 10, unit='mi')
r.table('parks').get_intersecting(circle1, index='area').run(conn)
Read more about this command →
table.get_nearest(point, index='indexname'[, max_results=100, max_dist=100000, unit='m', geo_system='WGS84']) → array
Return a list of documents closest to a specified point based on a geospatial index, sorted in order of increasing distance.
Example: Return a list of the closest 25 enemy hideouts to the secret base.
secret_base = r.point(-122.422876, 37.777128)
r.table('hideouts').get_nearest(secret_base, index='location',
max_results=25).run(conn)
Read more about this command →
sequence.includes(geometry) → sequence
geometry.includes(geometry) → bool
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
?
> point1 = r.point(-117.220406, 32.719464)
> point2 = r.point(-117.206201, 32.725186)
> r.circle(point1, 2000).includes(point2).run(conn)
True
Read more about this command →
sequence.intersects(geometry) → sequence
geometry.intersects(geometry) → bool
r.intersects(sequence, geometry) → sequence
r.intersects(geometry, geometry) → bool
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
?
> point1 = r.point(-117.220406, 32.719464)
> point2 = r.point(-117.206201, 32.725186)
> r.circle(point1, 2000).intersects(point2).run(conn)
True
Read more about this command →
r.line([lon1, lat1], [lon2, lat2], ...) → line
r.line(point1, point2, ...) → line
Construct a geometry object of type Line. The line can be specified in one of two ways:
Example: Define a line.
r.table('geo').insert({
'id': 101,
'route': r.line([-122.423246, 37.779388], [-121.886420, 37.329898])
}).run(conn)
Read more about this command →
r.point(longitude, latitude) → point
Construct a geometry object of type Point. The point is specified by two floating point numbers, the longitude (−180 to 180) and latitude (−90 to 90) of the point on a perfect sphere. See Geospatial support for more information on ReQL’s coordinate system.
Example: Define a point.
r.table('geo').insert({
'id': 1,
'name': 'San Francisco',
'location': r.point(-122.423246, 37.779388)
}).run(conn)
Read more about this command →
r.polygon([lon1, lat1], [lon2, lat2], [lon3, lat3], ...) → polygon
r.polygon(point1, point2, point3, ...) → polygon
Construct a geometry object of type Polygon. The Polygon can be specified in one of two ways:
Example: Define a polygon.
r.table('geo').insert({
'id': 101,
'rectangle': r.polygon(
[-122.423246, 37.779388],
[-122.423246, 37.329898],
[-121.886420, 37.329898],
[-121.886420, 37.779388]
)
}).run(conn)
Read more about this command →
polygon1.polygon_sub(polygon2) → polygon
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 polygon_sub
itself).
Example: Define a polygon with a hole punched in it.
outer_polygon = r.polygon(
[-122.4, 37.7],
[-122.4, 37.3],
[-121.8, 37.3],
[-121.8, 37.7]
)
inner_polygon = r.polygon(
[-122.3, 37.4],
[-122.3, 37.6],
[-122.0, 37.6],
[-122.0, 37.4]
)
outer_polygon.polygon_sub(inner_polygon).run(conn)
r.grant("username", {"permission": bool[, ...]}) → object
db.grant("username", {"permission": bool[, ...]}) → object
table.grant("username", {"permission": bool[, ...]}) → object
Grant or deny access permissions for a user account, globally or on a per-database or per-table basis.
Example: Grant the chatapp
user account read and write permissions on the users
database.
> r.db('users').grant('chatapp', {'read': True, 'write': True}).run(conn)
{
"granted": 1,
"permissions_changes": [
{
"new_val": { "read": true, "write": true },
"old_val": { null }
}
]
Read more about this command →
table.config() → selection<object>
database.config() → selection<object>
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 →
table.rebalance() → object
database.rebalance() → object
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 →
table.reconfigure(shards=<s>, replicas=<r>[, primary_replica_tag=<t>, dry_run=False, nonvoting_replica_tags=None]) → object
database.reconfigure(shards=<s>, replicas=<r>[, primary_replica_tag=<t>, dry_run=False, nonvoting_replica_tags=None]) → object
table.reconfigure(emergency_repair=<option>, dry_run=False) → object
Reconfigure a table’s sharding and replication.
Example: Reconfigure a table.
r.table('superheroes').reconfigure(shards=2, replicas=1).run(conn)
Read more about this command →
table.status() → selection<object>
Return the status of a table.
Example: Get a table’s status.
r.table('superheroes').status().run(conn)
Read more about this command →
table.wait([wait_for='all_replicas_ready', timeout=<sec>]) → object
database.wait([wait_for='all_replicas_ready', timeout=<sec>]) → object
r.wait(table | database, [wait_for='all_replicas_ready', timeout=<sec>]) → object
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 on a table to be ready.
r.table('superheroes').wait().run(conn)
{"ready": 1}