Struct r

Source
pub struct r;
Expand description

The top-level ReQL namespace

§Example

Set up your top-level namespace.

use unreql::r;

Implementations§

Source§

impl r

Source

pub fn grant( self, username: impl Serialize + 'static, opts: impl Opt<GrantOptions>, ) -> Command

Grant or deny access permissions for a user account, globally or on a per-database or per-table basis.

See details in javascript documentation.

Source§

impl r

Source

pub fn wait( self, table_or_database: impl Serialize + 'static, opts: impl Opt<WaitOptions>, ) -> Command

Wait for a table or all the tables in a database to be ready

See details in javascript documentation.

Source§

impl r

Source

pub fn group(self, field_or_function: impl ManyArgs<GroupOptions>) -> Command

Takes a stream and partitions it into multiple groups based on the fields or functions provided.

With the multi flag single documents can be assigned to multiple groups, similar to the behavior of multi-indexes. When multi is true and the grouping value is an array, documents will be placed in each group that corresponds to the elements of the array. If the array is empty the row will be ignored.

Suppose that the table games has the following data:

[
    {"id": 2, "player": "Bob", "points": 15, "type": "ranked"},
    {"id": 5, "player": "Alice", "points": 7, "type": "free"},
    {"id": 11, "player": "Bob", "points": 10, "type": "free"},
    {"id": 12, "player": "Alice", "points": 2, "type": "free"}
]
§Example

Group games by player.

r.table("games").group("player").run(conn)

Result:

[
    {
        "group": "Alice",
        "values": [
            {"id": 5, "player": "Alice", "points": 7, "type": "free"},
            {"id": 12, "player": "Alice", "points": 2, "type": "free"}
        ]
    },
    {
        "group": "Bob",
        "values": [
            {"id": 2, "player": "Bob", "points": 15, "type": "ranked"},
            {"id": 11, "player": "Bob", "points": 10, "type": "free"}
        ]
    }
]

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)

Result:

[
    {
        "group": "Alice",
        "values": {"id": 5, "player": "Alice", "points": 7, "type": "free"}
    },
    {
        "group": "Bob",
        "values": {"id": 2, "player": "Bob", "points": 15, "type": "ranked"}
    }
]

Commands chained onto grouped data will operate on each grouped datum, producing more grouped data.

§Example

What is the maximum number of points scored by each player?

r.table("games").group("player").max("points").g("points").run(conn)

Result:

[
    {
        "group": "Alice",
        "values": 7
    },
    {
        "group": "Bob",
        "values": 15
    }
]

You can also group by more than one field.

§Example

What is the maximum number of points scored by each player for each game type?

r.table("games")
  .group(r.args(("player", "type")))
  .max("points")
  .g("points")
  .run(conn)

Result:

[
    {
        "group": ["Alice", "free"],
        "values": 7
    },
    {
        "group": ["Bob", "free"],
        "values": 10
    },
    {
        "group": ["Bob", "ranked"],
        "values": 15
    }
]

You can also group by a function.

§Example

What is the maximum number of points scored by each player for each game type?

r.table("games")
  .group(func!(|game| {
    game.pluck(r.args(("player", "type")))
  }))
  .max("points")
  .g("points")
  .run(conn)

Result:

[
    {
        "group": {"player": "Alice", "type": "free"},
        "values": 7
    },
    {
        "group": {"player": "Bob", "type": "free"},
        "values": 10
    },
    {
        "group": {"player": "Bob", "type": "ranked"},
        "values": 15
    }
]

Using a function, you can also group by date on a ReQL date field.

§Example

How many matches have been played this year by month?

r.table("matches")
  .group([r.row().g("date").year(), r.row().g("date").month()])
  .count(())
  .run(conn)

Result:

[
    {
        "group": [2014, 2],
        "values": 2
    },
    {
        "group": [2014, 3],
        "values": 2
    },
    {
        "group": [2014, 4],
        "values": 1
    },
    {
        "group": [2014, 5],
        "values": 3
    }
]

You can also group on an index (primary key or secondary).

§Example

What is the maximum number of points scored by game type?

r.table("games")
  .group(r.index("type"))
  .max("points")
  .g("points")
  .run(conn)

Result:

[
    {
        "group": "free",
        "values": 10
    },
    {
        "group": "ranked",
        "values": 15
    }
]

See more details on the javascript api documentation.

§More Examples
§Example

What is the maximum number of points scored by each player in free games?

r.table("games")
  .filter(r.row().g("type").eq("free"))
  .group("player")
  .max("points")
  .g("points")
  .run(conn)

Result:

[
    {
        "group": "Alice",
        "values": 7
    },
    {
        "group": "Bob",
        "values": 10
    }
]
§Example

What is each player’s highest even and odd score?

r.table("games")
  .group(r.args((
    "name",
    func!(|game| game.g("points").mod_(2))
  )))
  .max("points")
  .g("points")
  .run(conn)

Result:

[
    {
        "group": ["Alice", 1],
        "values": 7
    },
    {
        "group": ["Bob", 0],
        "values": 10
    },
    {
        "group": ["Bob", 1],
        "values": 15
    }
]
Source§

impl r

Source

pub fn ungroup(self) -> Command

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.

The format of the array returned by ungroup is the same as the default native format of grouped data in the javascript driver and data explorer.

Suppose that the table games has the following data:

[
    {"id": 2, "player": "Bob", "points": 15, "type": "ranked"},
    {"id": 5, "player": "Alice", "points": 7, "type": "free"},
    {"id": 11, "player": "Bob", "points": 10, "type": "free"},
    {"id": 12, "player": "Alice", "points": 2, "type": "free"}
]
§Example

What is the maximum number of points scored by each player, with the highest scorers first?

r.table("games")
  .group("player")
  .max("points")
  .g("points")
  .ungroup()
  .order_by(r.desc("reduction"))
  .run(conn)

Result:

[
    {
        "group": "Bob",
        "reduction": 15
    },
    {
        "group": "Alice",
        "reduction": 7
    }
]
§Example

Select one random player and all their games.

r.table("games").group("player").ungroup().sample(1).run(conn)

Result:

[
    {
        "group": "Bob",
        "reduction": 15
    },
    {
        "group": "Alice",
        "reduction": 7
    }
]

Note that if you didn’t call ungroup, you would instead select one random game from each player:

r.table("games").group("player").sample(1).run(conn)

Result: (Note this is a JSON representation of a List; see the group documentation for more details.)

[
    {
        "group": "Alice",
        "values": [
            {"id": 5, "player": "Alice", "points": 7, "type": "free"}
        ]
    },
    {
        "group": "Bob",
        "values": [
            {"id": 11, "player": "Bob", "points": 10, "type": "free"}
        ]
    }
]
§Example

Finding the arithmetic mode of an array of values:

r.expr([1,2,2,2,3,3])
  .group(r.row())
  .count(())
  .ungroup()
  .order_by("reduction")
  .nth(-1)
  .g("group")
  .run(conn)
// Result: 2
§Example

Types!

// Returns "GROUPED_STREAM"
r.table("games").group("player").type_of().run(conn)

// Returns "ARRAY"
r.table("games").group("player").ungroup().type_of().run(conn)

// Returns "GROUPED_DATA"
r.table("games").group("player").avg("points").run(conn)

// Returns "ARRAY"
r.table("games").group("player").avg("points").ungroup().run(conn)
Source§

impl r

Source

pub fn reduce( self, sequence: impl Serialize + 'static, function: impl Serialize + 'static, ) -> Command

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

See reduce in Command.

Source§

impl r

Source

pub fn fold( self, base: impl Serialize + 'static, function: impl Serialize + 'static, opt: impl Opt<FoldOptions>, ) -> Command

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.

In its first form, fold operates like reduce, returning a value by applying a combining function to each element in a sequence. The combining function takes two parameters: the previous reduction result (the accumulator) and the current element. However, fold has the following differences from reduce:

  • it is guaranteed to proceed through the sequence from first element to last.
  • it passes an initial base value to the function with the first element in place of the previous reduction result.

combiningFunction(accumulator | base, element) → newAccumulator

In its second form, fold operates like concat_map, returning a new sequence rather than a single value. When an emit function is provided, fold will:

  • proceed through the sequence in order and take an initial base value, as above.
  • for each element in the sequence, call both the combining function and a separate emitting function. The emitting function takes three parameters: the previous reduction result (the accumulator), the current element, and the output from the combining function (the new value of the accumulator).

If provided, the emitting function must return a list.

emit(previousAccumulator, element, accumulator) → array

A final_emit function may also be provided, which will be called at the end of the sequence. It takes a single parameter: the result of the last reduction through the iteration (the accumulator), or the original base value if the input sequence was empty. This function must return a list, which will be appended to fold’s output stream.

final_emit(accumulator | base) → array

§Example

Concatenate words from a list.

r.table("words")
  .order_by("id")
  .fold("", func!(|acc, word| {
    acc.clone().add(r.branch(acc.eq(""), "", ", ")).add(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.)

§Example

Return every other row in a table.

r.table("even_things")
  .order_by("id")
  .fold(
    0,
    func!(|acc, row| {
      acc.add(1)
    }),
    FoldOptions::new().emit(func!(|acc, row, new_acc| {
      r.branch(new_acc.mod_(2).eq(0), [row], rjson!([]))
    }))
  )
  .run(conn)

The first function increments the accumulator each time it’s called, starting at 0; the second function, the emitting function, alternates between returning a single-item list containing the current row or an empty list. The fold command will return a concatenated list of each emitted value.

§Example

Compute a five-day running average for a weight tracker.

r.table("tracker")
  .filter(rjson!({"name": "bob"}))
  .order_by("date")
  .g("weight")
  .fold(
    rjson!([]),
    func!(|acc, row| {
      r.expr([row]).add(acc).limit(5)
    }),
    FoldOptions::new().emit(func!(|acc, row, new_acc| {
      r.branch(new_acc.clone().count(()).eq(5), [new_acc.avg(())], rjson!([]))
    }))
  )
  .run(conn)
Source§

impl r

Source

pub fn count(self, value: impl ManyArgs<()>) -> Command

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.

When count is called on a sequence with a predicate value or function, it returns the number of elements in the sequence equal to that value or where the function returns true. On a binary object, count returns the size of the object in bytes; on strings, count returns the string’s length. This is determined by counting the number of Unicode codepoints in the string, counting combining codepoints separately.

§Example

Count the number of users.

r.table("users").count(()).run(conn)
§Example

Count the number of 18 year old users.

r.table("users").g("age").count(18).run(conn)
§Example

Count the number of users over 18.

r.table("users").g("age").count(func!(|age| age.gt(18))).run(conn)
r.table("users").count(func!(|user| user.g("age").gt(18))).run(conn)
§Example

Return the length of a Unicode string.

r.expr("こんにちは").count(()).run(conn)
// Return: 5
§Example

Return the length of an array.

r.expr(["0","1","2"]).count(()).run(conn)
// Return: 3
Source§

impl r

Source

pub fn sum( self, sequence: impl Serialize + 'static, field: impl Serialize + 'static, ) -> Command

Sums all the elements of a sequence.

See sum in Command.

Source§

impl r

Source

pub fn avg( self, sequence: impl Serialize + 'static, field: impl Serialize + 'static, ) -> Command

Averages all the elements of a sequence.

See avg in Command.

Source§

impl r

Source

pub fn min( self, sequence: impl Serialize + 'static, field: impl Arg<Index>, ) -> Command

Finds the minimum element of a sequence.

See min in Command.

Source§

impl r

Source

pub fn max( self, sequence: impl Serialize + 'static, field: impl Arg<Index>, ) -> Command

Finds the maximum element of a sequence.

See max in Command.

Source§

impl r

Source

pub fn distinct(self, arg: impl ManyArgs<Index>) -> Command

Removes duplicates from elements in a sequence.

The distinct command can be called on any sequence or table with an index.

Note. While distinct can be called on a table without an index, the only effect will be to convert the table into a stream; the content of the stream will not be affected.

§Example

Which unique villains have been vanquished by Marvel heroes?

r.table("marvel")
  .concat_map(func!(|hero| hero.g("villainList")))
  .distinct(())
  .run(conn)
§Example: Topics in a table of messages have a secondary index on them,

and more than one message can have the same topic. What are the unique topics in the table?

r.table("messages").distinct(r.index("topics")).run(conn)

The above structure is functionally identical to:

r.table("messages").g("topics").distinct(()).run(conn)

However, the first form (passing the index as an argument to distinct) is faster, and won’t run into array limit issues since it’s returning a stream.

Source§

impl r

Source

pub fn contains(self, value: impl ManyArgs<()>) -> Command

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.

Values and predicates may be mixed freely in the argument list.

§Example

Has Iron Man ever fought Superman?

r.table("marvel").get("ironman").g("opponents").contains("superman").run(conn)
§Example

Has Iron Man ever defeated Superman in battle?

r.table("marvel").get("ironman").g("battles").contains(func!(|battle| {
  battle.clone().g("winner").eq("ironman").and(battle.g("loser").eq("superman"))
})).run(conn)
§Example

Return all heroes who have fought both Loki and the Hulk.

r.table("marvel").filter(func!(|hero| {
  hero.g("opponents").contains(r.args(("loki", "hulk")))
})).run(conn)
§Example

Use contains with a predicate function to simulate an or. Return the Marvel superheroes who live in Detroit, Chicago or Hoboken.

r.table("marvel").filter(func!(|hero| {
  r.expr(["Detroit", "Chicago", "Hoboken"]).contains(hero.g("city"))
})).run(conn)
Source§

impl r

Source

pub fn db_list(self) -> Command

List all database names in the system. The result is a list of strings.

§Example
r.db_list().run(conn)
Source§

impl r

Source

pub fn db_create(self, db_name: impl Serialize + 'static) -> Command

Create a database. A RethinkDB database is a collection of tables, similar to relational databases.

If successful, the command returns an object with two fields:

  • dbs_created: always 1.
  • config_changes: a list containing one object with two fields, old_val and new_val:
    • old_val: always null.
    • new_val: the database’s new config value.

If a database with the same name already exists, the command throws ReqlRuntimeError.

Note: Only alphanumeric characters, hyphens and underscores are valid for the database name.

§Example

Create a database named ‘superheroes’.

r.db_create("superheroes").run(conn)
Source§

impl r

Source

pub fn db_drop(self, db_name: impl Serialize + 'static) -> Command

Drop a database. The database, all its tables, and corresponding data will be deleted.

If successful, the command returns an object with two fields:

  • dbs_dropped: always 1.
  • tables_dropped: the number of tables in the dropped database.
  • config_changes: a list containing one two-field object, old_val and new_val:
    • old_val: the database’s original config value.
    • new_val: always null.

If the given database does not exist, the command throws ReqlRuntimeError.

§Example

Drop a database named ‘superheroes’.

r.db_drop("superheroes").run(conn)
Source§

impl r

Source

pub fn now(self) -> Command

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(rjson!({
  "name": "John",
  "subscription_date": r.now(),
})).run(conn)
Source§

impl r

Source

pub fn time( self, year: impl Serialize + 'static, month: impl Serialize + 'static, day: impl Serialize + 'static, timezone: impl Serialize + 'static, ) -> Command

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.
  • timezone can be 'Z' (for UTC) or a string with the format ±[hh]:[mm].

To use hour, minutes and seconds see time_ext command.

§Example

Update the birthdate of the user “John” to November 3rd, 1986 UTC.

r.table("users").get("John").update(rjson!({
  "birthdate": r.time(1986, 11, 3, "Z"),
})).run(conn)
Source§

impl r

Source

pub fn time_ext( self, year: impl Serialize + 'static, month: impl Serialize + 'static, day: impl Serialize + 'static, hour: impl Serialize + 'static, minutes: impl Serialize + 'static, seconds: impl Serialize + 'static, timezone: impl Serialize + 'static, ) -> Command

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].
Source§

impl r

Source

pub fn epoch_time(self, number: impl Serialize + 'static) -> Command

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("users").get("John").update(rjson!({
  "birthdate": r.epoch_time(531360000),
})).run(conn)
Source§

impl r

Source

pub fn iso_8601(self, string: impl Serialize + 'static) -> Command

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("users").get("John").update(rjson!({
  "birthdate": r.iso_8601("1986-11-03T08:30:00-07:00"),
})).run(conn)
Source§

impl r

Source

pub fn time_of_day(self) -> Command

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("users").filter(
  r.row().g("date").time_of_day().le(12*60*60)
).run(conn)
Source§

impl r

Source

pub fn year(self) -> Command

Return the year of a time object.

§Example

Retrieve all the users born in 1986.

r.table("users").filter(
  r.row().g("birthdate").year().eq(1986)
).run(conn)
Source§

impl r

Source

pub fn month(self) -> Command

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().g("birthdate").month().eq(11)
).run(conn)
§Example

Retrieve all the users who were born in November.

r.table("users").filter(
  r.row().g("birthdate").month().eq(r.november())
).run(conn)
Source§

impl r

Source

pub fn day(self) -> Command

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().g("birthdate").day().eq(24)
).run(conn)
Source§

impl r

Source

pub fn monday(self) -> Command

Source§

impl r

Source

pub fn tuesday(self) -> Command

Source§

impl r

Source

pub fn wednesday(self) -> Command

Source§

impl r

Source

pub fn thursday(self) -> Command

Source§

impl r

Source

pub fn friday(self) -> Command

Source§

impl r

Source

pub fn saturday(self) -> Command

Source§

impl r

Source

pub fn sunday(self) -> Command

Source§

impl r

Source

pub fn january(self) -> Command

Source§

impl r

Source

pub fn february(self) -> Command

Source§

impl r

Source

pub fn march(self) -> Command

Source§

impl r

Source

pub fn april(self) -> Command

Source§

impl r

Source

pub fn may(self) -> Command

Source§

impl r

Source

pub fn june(self) -> Command

Source§

impl r

Source

pub fn july(self) -> Command

Source§

impl r

Source

pub fn august(self) -> Command

Source§

impl r

Source

pub fn september(self) -> Command

Source§

impl r

Source

pub fn october(self) -> Command

Source§

impl r

Source

pub fn november(self) -> Command

Source§

impl r

Source

pub fn december(self) -> Command

Source§

impl r

Source

pub fn row(self) -> Command

Returns the currently visited document.

Note that row does not work within subqueries to access nested documents; you should use anonymous functions to access those documents instead. (See the last example.)

§Example

Get all users whose age is greater than 5.

r.table("users").filter(r.row().g("age").gt(5)).run(conn)
§Example

Access the attribute ‘child’ of an embedded document.

r.table("users").filter(r.row().g("embedded_doc").g("child").gt(5)).run(conn)
§Example

Add 1 to every element of an array.

r.expr([1, 2, 3]).map(r.row().add(1)).run(conn)
§Example

For nested queries, use functions instead of row.

r.table("users").filter(func!(|doc| {
  doc.g("name").eq(r.table("prizes").get("winner"))
})).run(conn)
Source§

impl r

Source

pub fn append(self, value: impl Serialize + 'static) -> Command

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").g("equipment").append("newBoots").run(conn)
Source§

impl r

Source

pub fn prepend(self, value: impl Serialize + 'static) -> Command

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").g("equipment").prepend("newBoots").run(conn)
Source§

impl r

Source

pub fn difference(self, array: impl Serialize + 'static) -> Command

Remove the elements of one array from another array.

§Example

Retrieve Iron Man’s equipment list without boots.

r.table("marvel").get("IronMan").g("equipment").difference(["Boots"]).run(conn)
§Example

Remove Iron Man’s boots from his equipment.

r.table("marvel")
  .get("IronMan")
  .update(rjson!({ "equipment": r.row().g("equipment").difference(["Boots"]) }))
  .run(conn)
Source§

impl r

Source

pub fn set_insert(self, value: impl Serialize + 'static) -> Command

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").g("equipment").set_insert("newBoots").run(conn)
Source§

impl r

Source

pub fn set_union(self, array: impl Serialize + 'static) -> Command

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").g("equipment").set_union(["newBoots", "arc_reactor"]).run(conn)
Source§

impl r

Source

pub fn set_intersection(self, array: impl Serialize + 'static) -> Command

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").g("equipment").set_intersection(["newBoots", "arc_reactor"]).run(conn)
Source§

impl r

Source

pub fn set_difference(self, array: impl Serialize + 'static) -> Command

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").g("equipment").set_difference(["newBoots", "arc_reactor"]).run(conn)
Source§

impl r

Source

pub fn bracket(self, attr_or_index: impl Serialize + 'static) -> Command

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.

Note: Under most circumstances, you’ll want to use get_field (or its shorthand g) or nth rather than bracket. The bracket term may be useful in situations where you are unsure of the data type returned by the term you are calling bracket on.

§Example

What was Iron Man’s first appearance in a comic?

r.table("marvel").get("IronMan").bracket("firstAppearance").run(conn)

The bracket command also accepts integer arguments as array offsets, like the nth command.

§Example

Get the fourth element in a sequence. (The first element is position 0, so the fourth element is position 3.)

r.expr([10, 20, 30, 40, 50]).bracket(3).run(conn)
Source§

impl r

Source

pub fn g(self, attr: impl Serialize + 'static) -> Command

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.

You may use either get_field or its shorthand, g.

§Example

What was Iron Man’s first appearance in a comic?

r.table("marvel").get("IronMan").g("firstAppearance").run(conn)
Source§

impl r

Source

pub fn get_field(self, attr: impl Serialize + 'static) -> Command

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.

You may use either get_field or its shorthand, g.

§Example

What was Iron Man’s first appearance in a comic?

r.table("marvel").get("IronMan").g("firstAppearance").run(conn)
Source§

impl r

Source

pub fn literal(self, object: impl Serialize + 'static) -> Command

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.

Assume your users table has this structure:

[
    {
        "id": 1,
        "name": "Alice",
        "data": {
            "age": 18,
            "city": "Dallas"
        }
    }
    ...
]

Using update to modify the data field will normally merge the nested documents:

r.table("users").get(1).update(rjson!({ "data": { "age": 19, "job": "Engineer" } })).run(conn)

Result:

{
    "id": 1,
    "name": "Alice",
    "data": {
        "age": 19,
        "city": "Dallas",
        "job": "Engineer"
    }
}

That will preserve city and other existing fields. But to replace the entire data document with a new object, use literal.

§Example

Replace one nested document with another rather than merging the fields.

r.table("users")
  .get(1)
  .update(rjson!({ "data": r.literal(rjson!({ "age": 19, "job": "Engineer" })) }))
  .run(conn)

Result:

{
    "id": 1,
    "name": "Alice",
    "data": {
        "age": 19,
        "job": "Engineer"
    }
}
§Example

Use literal to remove a field from a document.

r.table("users")
  .get(1)
  .merge(rjson!({ "data": r.literal(()) }))
  .run(conn)

Result:

{
    "id": 1,
    "name": "Alice"
}
Source§

impl r

Source

pub fn object(self, key_value: impl ManyArgs<()>) -> Command

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(r.args(("id", 5, "data", ["foo", "bar"]))).run(conn)
// Result: {"data": ["foo", "bar"], "id": 5}

or for many args, use array of serde_json::Value:

r.object(r.args([rjson!("id"), rjson!(5), rjson!("data"), rjson!(["foo", "bar"])])).run(conn)
// Result: {"data": ["foo", "bar"], "id": 5}
Source§

impl r

Source

pub fn circle(self, point_radius: impl ManyArgs<CircleOptions>) -> Command

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

The center may be specified either by two floating point numbers, the latitude (−90 to 90) and longitude (−180 to 180) of the point on a perfect sphere (see Geospatial support for more information on ReQL’s coordinate system), or by a point object. The radius is a floating point number whose units are meters by default, although that may be changed with the unit argument.

§Example

Define a circle.

r.table("geo").insert(rjson!({
    "id": 300,
    "name": "Hayes Valley",
    "neighborhood": r.circle(r.args(([-122.423246,37.779388], 1000)))
})).run(conn)
Source§

impl r

Source

pub fn distance( self, point1: impl Serialize + 'static, point2: impl Serialize + 'static, opts: impl Opt<DistanceOptions>, ) -> Command

Compute the distance between a point and another geometry object.

At least one of the geometry objects specified must be a point.

If one of the objects is a polygon or a line, the point will be projected onto the line or polygon assuming a perfect sphere model before the distance is computed (using the model specified with geoSystem). As a consequence, if the polygon or line is extremely large compared to Earth’s radius and the distance is being computed with the default WGS84 model, the results of distance should be considered approximate due to the deviation between the ellipsoid and spherical models.

§Example

Compute the distance between two points on the Earth in kilometers.

let point1 = r.point(-122.423246, 37.779388);
let point2 = r.point(-117.220406, 32.719464);
let opts = DistanceOptions::new().unit("km".into());
r.distance(point1, point2, opts).run(conn)
// Result: 734.1252496021841
Source§

impl r

Source

pub fn geojson(self, geojson: impl Serialize + 'static) -> Command

Convert a GeoJSON object to a ReQL geometry object.

RethinkDB only allows conversion of GeoJSON objects which have ReQL equivalents: Point, LineString, and Polygon. MultiPoint, MultiLineString, and MultiPolygon are not supported. (You could, however, store multiple points, lines and polygons in an array and use a geospatial multi index with them.)

Only longitude/latitude coordinates are supported. GeoJSON objects that use Cartesian coordinates, specify an altitude, or specify their own coordinate reference system will be rejected.

§Example

Convert a GeoJSON object to a ReQL geometry object.

let geojson = rjson!({
    "type": "Point",
    "coordinates": [ -122.423246, 37.779388 ]
});
r.table("geo").insert(rjson!({
    "id": "sfo",
    "name": "San Francisco",
    "location": r.geojson(geojson),
})).run(conn)
Source§

impl r

Source

pub fn get_intersecting( self, geometry: impl Serialize + 'static, opts: impl Opt<Index>, ) -> Command

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

The index argument is mandatory. This command returns the same results as table.filter(r.row().g("index").intersects(geometry)). The total number of results is limited to the array size limit which defaults to 100,000, but can be changed with the arrayLimit option to run.

§Example

Which of the locations in a list of parks intersect circle1?

let unit = CircleOptions::new().unit("mi".into());
let circle1 = r.circle(r.with_opt(r.args(([-117.220406,32.719464], 10)), unit));
r.table("parks").get_intersecting(circle1, r.index("area")).run(conn)
Source§

impl r

Source

pub fn get_nearest( self, point: impl Serialize + 'static, opts: impl Opt<GetNearestOptions>, ) -> Command

Return a list of documents closest to a specified point based on a geospatial index, sorted in order of increasing distance.

The index argument is mandatory.

The return value will be an array of two-item objects with the keys dist and doc, set to the distance between the specified point and the document (in the units specified with unit, defaulting to meters) and the document itself, respectively. The array will be sorted by the values of dist.

§Example

Return a list of the closest 25 enemy hideouts to the secret base.

let secret_base = r.point(-122.422876,37.777128);
let opts = GetNearestOptions::new()
    .index("area".into())
    .max_results(25);
r.table("hideouts").get_nearest(secret_base, opts).run(conn)

Note: If you wish to find all points within a certain radius of another point, it’s often faster to use getIntersecting with circle, as long as the approximation of a circle that circle generates is sufficient.

Source§

impl r

Source

pub fn includes(self, geometry: impl Serialize + 'static) -> Command

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?

let point1 = r.point(-122.423246, 37.779388);
let point2 = r.point(-117.220406, 32.719464);
r.circle(r.args((point1, 2000))).includes(point2).run(conn)
// Result: true
Source§

impl r

Source

pub fn intersects( self, sequence_or_geometry: impl Serialize + 'static, geometry: impl Serialize + 'static, ) -> Command

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?

let point1 = r.point(-122.423246, 37.779388);
let point2 = r.point(-117.220406, 32.719464);
r.circle(r.args((point1, 2000))).intersects(point2).run(conn)
// Result: true
Source§

impl r

Source

pub fn line(self, points: impl ManyArgs<()>) -> Command

Construct a geometry object of type Line.

The line can be specified in one of two ways:

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

Longitude (−180 to 180) and latitude (−90 to 90) of vertices are plotted on a perfect sphere. See Geospatial support for more information on ReQL’s coordinate system.

§Example

Define a line.

r.table("geo").insert(rjson!({
    "id": 101,
    "route": r.line(r.args([[-122.423246,37.779388], [-121.886420,37.329898]]))
})).run(conn)
§Example

Define a line using an array of points. You can use the args command to pass an array of Point objects (or latitude-longitude pairs) to line.

let route = [
    [-122.423246, 37.779388],
    [-121.886420, 37.329898],
];
r.table("geo").insert(rjson!({
    "id": 102,
    "route": r.line(r.args(route)),
})).run(conn)
Source§

impl r

Source

pub fn point( self, longitude: impl Serialize + 'static, latitude: impl Serialize + 'static, ) -> Command

ruct 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(rjson!({
    "id": 1,
    "name": "San Francisco",
    "location": r.point(-122.423246, 37.779388)
})).run(conn)
Source§

impl r

Source

pub fn polygon(self, points: impl ManyArgs<()>) -> Command

Construct a geometry object of type Polygon.

The Polygon can be specified in one of two ways:

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

Longitude (−180 to 180) and latitude (−90 to 90) of vertices are plotted on a perfect sphere. See Geospatial support for more information on ReQL’s coordinate system.

If the last point does not specify the same coordinates as the first point, polygon will close the polygon by connecting them. You cannot directly construct a polygon with holes in it using polygon, but you can use polygonSub to use a second polygon within the interior of the first to define a hole.

§Example

Define a polygon.

r.table("geo").insert(rjson!({
    "id": 101,
    "rectangle": r.polygon(r.args([
        [-122.423246,37.779388],
        [-122.423246,37.329898],
        [-121.886420,37.329898],
        [-121.886420,37.779388]
    ]))
})).run(conn)
Source§

impl r

Source

pub fn polygon_sub(self, polygon2: impl Serialize + 'static) -> Command

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.

let outer_polygon = r.polygon(r.args([
    [-122.4,37.7],
    [-122.4,37.3],
    [-121.8,37.3],
    [-121.8,37.7]
]));
let inner_polygon = r.polygon(r.args([
    [-122.3,37.4],
    [-122.3,37.6],
    [-122.0,37.6],
    [-122.0,37.4]
]));
outer_polygon.polygon_sub(inner_polygon).run(conn)
Source§

impl r

Source

pub fn and(self, boolean: impl ManyArgs<()>) -> Command

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

The and command can be used as an infix operator after its first argument (r.expr(true).and(false)) or given all of its arguments as parameters (r.and(true,false)).

Calling and with zero arguments will return true.

§Example

Return whether both a and b evaluate to true.

let a = true;
let b = false;
r.expr(a).and(b).run(conn)
// Result: false
Source§

impl r

Source

pub fn or(self, boolean: impl ManyArgs<()>) -> Command

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

The or command can be used as an infix operator after its first argument (r.expr(true).or(false)) or given all of its arguments as parameters (r.or(true,false)).

Calling or with zero arguments will return false.

§Example

Return whether either a or b evaluate to true.

let a = true;
let b = false;
r.expr(a).or(b).run(conn)
// Result: true
§Example

Return whether any of a or b evaluate to true.

let a = false;
let b = false;
r.or(r.args([a, b])).run(conn)
// Result: false

Note: When using or inside a filter predicate to test the values of fields that may not exist on the documents being tested, you should use the default command with those fields so they explicitly return false.

r.table("posts").filter(
  r.row().g("category").default("foo").eq("article")
    .or(r.row().g("category").default("foo").eq("mystery"))
).run(conn)
Source§

impl r

Source

pub fn eq(self, value: impl ManyArgs<()>) -> Command

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).g("role").eq("administrator").run(conn)
§Example

See if three variables contain equal values.

r.eq(r.args([a, b, c])).run(conn)
Source§

impl r

Source

pub fn ne(self, value: impl ManyArgs<()>) -> Command

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).g("role").ne("administrator").run(conn)
§Example

See if three variables do not contain equal values.

r.ne(r.args([a, b, c])).run(conn)
Source§

impl r

Source

pub fn gt(self, value: impl ManyArgs<()>) -> Command

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).g("score").gt(10).run(conn)
§Example

Test if variables are ordered from lowest to highest, with no values being equal to one another.

let (a, b, c) = (15, 20, 15);
r.gt(r.args([a, b, c])).run(conn)

This is the equivalent of the following:

r.gt(r.args([a, b])).and(r.gt(r.args([b, c]))).run(conn)
Source§

impl r

Source

pub fn ge(self, value: impl ManyArgs<()>) -> Command

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).g("score").ge(10).run(conn)
Source§

impl r

Source

pub fn lt(self, value: impl ManyArgs<()>) -> Command

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).g("score").lt(10).run(conn)
Source§

impl r

Source

pub fn le(self, value: impl ManyArgs<()>) -> Command

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).g("score").le(10).run(conn)
Source§

impl r

Source

pub fn not(self, boolean: impl Serialize + 'static) -> Command

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. All values that are not false or null will be converted to true.

§Example

Not true is false.

r.not(true).run(conn)
// Result: false
§Example

Return all the users that do not have a “flag” field.

use unreql::func;
r.table("users").filter(func!(|user| {
  r.not(user.has_fields("flag"))
})).run(conn)
Source§

impl r

Source

pub fn random(self, numbers: impl ManyArgs<RandomOptions>) -> Command

Generate a random number between given (or implied) bounds. random takes zero, one or two arguments.

  • With zero arguments, the result will be a floating-point number in the range [0,1) (from 0 up to but not including 1).
  • With one argument x, the result will be in the range [0,x), and will be integer unless {float: true} is given as an option. Specifying a floating point number without the float option will raise an error.
  • With two arguments x and y, the result will be in the range [x,y), and will be integer unless {float: true} is given as an option. If x and y are equal an error will occur, unless the floating-point option has been specified, in which case x will be returned. Specifying a floating point number without the float option will raise an error.

Note: The last argument given will always be the ‘open’ side of the range, but when generating a floating-point number, the ‘open’ side may be less than the ‘closed’ side.

§Example

Generate a random number in the range [0,1)

r.random(()).run(conn)
§Example

Generate a random integer in the range [0,100)

r.random(100).run(conn)
r.random(r.args([0, 100])).run(conn)
§Example

Generate a random number in the range (-2.24,1.59]

let opts = RandomOptions::new().float(true);
r.random(r.with_opt(r.args([1.59, -2.24]), opts)).run(conn)
Source§

impl r

Source

pub fn round(self, number: impl Serialize + 'static) -> Command

Rounds the given value to the nearest whole integer.

For example, values of 1.0 up to but not including 1.5 will return 1.0, similar to floor; values of 1.5 up to 2.0 will return 2.0, similar to ceil.

§Example

Round 12.345 to the nearest integer.

r.round(12.345).run(conn)
// Result: 12.0
Source§

impl r

Source

pub fn ceil(self, number: impl Serialize + 'static) -> Command

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)
// Result: 13.0

The ceil command can also be chained after an expression.

Source§

impl r

Source

pub fn floor(self, number: impl Serialize + 'static) -> Command

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)
// Result: 12.0

The floor command can also be chained after an expression.

Source§

impl r

Source

pub fn bit_and(self, number: impl ManyArgs<()>) -> Command

A bitwise AND is a binary operation that takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits, which is equivalent to multiplying them. Thus, if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0).

§Example
r.expr(5).bit_and(3).run(conn)
// Result: 1
Source§

impl r

Source

pub fn bit_or(self, number: impl ManyArgs<()>) -> Command

A bitwise OR is a binary operation that takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of corresponding bits. The result in each position is 0 if both bits are 0, while otherwise the result is 1.

§Example
r.expr(5).bit_or(3).run(conn)
// Result: 7
Source§

impl r

Source

pub fn bit_xor(self, number: impl ManyArgs<()>) -> Command

A bitwise XOR is a binary operation that takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same.

§Example
r.expr(6).bit_xor(4).run(conn)
// Result: 2
Source§

impl r

Source

pub fn bit_not(self) -> Command

A bitwise NOT, or complement, is a unary operation that performs logical negation on each bit, forming the ones’ complement of the given binary value. Bits that are 0 become 1, and those that are 1 become 0.

§Example
r.expr(7).bit_not().run(conn)
// Result: -8
Source§

impl r

Source

pub fn bit_sal(self, number: impl ManyArgs<()>) -> Command

In an arithmetic shift (also referred to as signed shift), like a logical shift, the bits that slide off the end disappear (except for the last, which goes into the carry flag). But in an arithmetic shift, the spaces are filled in such a way to preserve the sign of the number being slid. For this reason, arithmetic shifts are better suited for signed numbers in two’s complement format.

Note: SHL and SAL are the same, and differentiation only happens because SAR and SHR (right shifting) has differences in their implementation.

§Example
r.expr(5).bit_sal(4).run(conn)
// Result: 80
Source§

impl r

Source

pub fn bit_sar(self, number: impl ManyArgs<()>) -> Command

In an arithmetic shift (also referred to as signed shift), like a logical shift, the bits that slide off the end disappear (except for the last, which goes into the carry flag). But in an arithmetic shift, the spaces are filled in such a way to preserve the sign of the number being slid. For this reason, arithmetic shifts are better suited for signed numbers in two’s complement format.

§Example
r.expr(32).bit_sal(3).run(conn)
// Result: 4
Source§

impl r

Source

pub fn minval(self) -> Command

Source§

impl r

Source

pub fn maxval(self) -> Command

Source§

impl r

Source

pub fn asc(self, key: impl Serialize + 'static) -> Command

Source§

impl r

Source

pub fn desc(self, key: impl Serialize + 'static) -> Command

Source§

impl r

Source

pub fn array(self, arg: impl Serialize + 'static) -> Command

Array

Source§

impl r

Source

pub fn index(self, arg: impl Serialize + 'static) -> Index

Source§

impl r

Source

pub fn db(self, db_name: impl Serialize + 'static) -> Command

Reference a database.

The db command is optional. If it is not present in a query, the query will run against the default database for the connection, specified in the db argument to connect.

§Example

Explicitly specify a database for a query

r.db("heroes").table("marvel").run(conn)
Source§

impl r

Source

pub fn table(self, name: impl Arg<TableOptions>) -> Command

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.

There are two optional arguments.

  • readMode: One of three possible values affecting the consistency guarantee for the table read:
    • single returns values that are in memory (but not necessarily written to disk) on the primary replica. This is the default.
    • majority will only return values that are safely committed on disk on a majority of replicas. This requires sending a message to every replica on each read, so it is the slowest but most consistent.
    • outdated will return values that are in memory on an arbitrarily-selected replica. This is the fastest but least consistent.
  • identifierFormat: possible values are name and uuid, with a default of name. If set to uuid, then system tables will refer to servers, databases and tables by UUID rather than name. (This only has an effect when used with system tables.)
§Example

Return all documents in the table ‘marvel’ of the default database.

r.table("marvel").run(conn)
§Example

Allow potentially out-of-date data in exchange for faster reads

let opts = TableOptions {
  read_mode: Some(ReadMode::Outdated),
  ..Default::default()
};
r.db("heroes").table(r.with_opt("marvel", opts)).run(conn)
Source§

impl r

Source

pub fn split(self, separator_and_max_splits: impl ManyArgs<()>) -> Command

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)
// Result: ["foo", "bar", "bax"]
§Example

Split the entries in a CSV file.

r.expr("12,37,,22,").split(",").run(conn)
// Result: ["12", "37", "", "22", ""]
§Example

Split a string into characters.

r.expr("mlucy").split("").run(conn)
// Result: ["m", "l", "u", "c", "y"]
§Example

Split the entries in a CSV file, but only at most 3 times.

r.expr("12,37,,22,").split(r.args((",", 3))).run(conn)
// Result: ["12", "37", "", "22,"]
§Example

Split on whitespace at most once (i.e. get the first word).

r.expr("foo  bar bax").split(r.args((rjson!(null), 1))).run(conn)
// Result: ["foo", "bar bax"]
Source§

impl r

Source

pub fn upcase(self) -> Command

Uppercases a string.

§Example
r.expr("Sentence about LaTeX.").upcase().run(conn)
// Result: "SENTENCE ABOUT LATEX."

Note: upcase and downcase only affect ASCII characters.

Source§

impl r

Source

pub fn downcase(self) -> Command

Lowercases a string.

§Example
r.expr("Sentence about LaTeX.").upcase().run(conn)
// Result: "sentence about latex."

Note: upcase and downcase only affect ASCII characters.

Source§

impl r

Source

pub fn binary(self, arg: impl Serialize + 'static) -> Command

Encapsulate binary data within a query.

The type of data binary accepts depends on the client language.

Only a limited subset of ReQL commands may be chained after binary:

  • coerce_to can coerce binary objects to string types
  • count will return the number of bytes in the object
  • slice will treat bytes like array indexes (i.e., slice(10,20) will return bytes 10–19)
  • type_of returns PTYPE
  • info will return information on a binary object.

TODO

Source§

impl r

Source

pub fn do_(self, args: impl DoArgs) -> Command

Call an anonymous function using return values from other ReQL commands or queries as arguments.

The last argument to do_ (or, in some forms, the only argument) is an expression or an anonymous function which receives values from either the previous arguments or from prefixed commands chained before do_. The do_ command is essentially a single-element map, letting you map a function over just one document. This allows you to bind a query result to a local variable within the scope of do_, letting you compute the result just once and reuse it in a complex expression or in a series of ReQL commands.

Arguments passed to the do_ function must be basic data types, and cannot be streams or selections. (Read about ReQL data types.) While the arguments will all be evaluated before the function is executed, they may be evaluated in any order, so their values should not be dependent on one another. The type of do_’s result is the type of the value returned from the function or last expression.

§Example

Compute a golfer’s net score for a game.

r.table("players").get(3).do_(func!(|player| {
  player.clone().g("gross_score").sub(player.g("course_handicap"))
})).run(conn)
§Example

Return the best scoring player in a two-player golf match.

r.do_(
  r.args((
    r.table("players").get(1),
    r.table("players").get(2),
    func!(|player1, player2| {
      r.branch(
        player1.clone().g("gross_score").lt(player2.clone().g("gross_score")),
        player1,
        player2
      )
    })
  ))
).run(conn)

Note that branch, the ReQL conditional command, must be used instead of if. See the branch documentation for more.

§Example

Take different actions based on the result of a ReQL insert command.

let new_data = rjson!({
  "id": 100,
  "name": "Agatha",
  "gross_score": 57,
  "course_handicap": 4,
});
r.table("players").insert(new_data).do_(func!(|doc| {
  r.branch(
    doc.clone().g("inserted").ne(0),
    r.table("log").insert(rjson!({"time": r.now(), "response": doc.clone(), "result": "ok"})),
    r.table("log").insert(rjson!({"time": r.now(), "response": doc, "result": "error"})),
  )
})).run(conn)
Source§

impl r

Source

pub fn branch( self, test: impl Serialize + 'static, true_action: impl Serialize + 'static, false_action: impl Serialize + 'static, ) -> Command

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.

See branch_ext for use more test cases.

§Example

Test the value of x.

let x = 10;
r.branch(r.expr(x).gt(5), "big", "small").run(conn)
§Example

Test the value of x.

let x = 10;
r.expr(x).gt(5).branch("big", "small").run(conn)
Source§

impl r

Source

pub fn branch_ext(self, test_then_actions: impl ManyArgs<()>) -> Command

Perform a branching conditional equivalent to if-then-else.

§Example

Categorize heroes by victory counts.

r.table("marvel").map(
  r.branch_ext(r.args([
    r.row().g("victories").gt(100),
    r.row().g("name").add(" is a superhero"),
    r.row().g("victories").gt(10),
    r.row().g("name").add(" is a hero"),
    r.row().g("name").add(" is a very nice")
  ]))
).run(conn)

To use for simple if-then-else see branch.

Source§

impl r

Source

pub fn range(self, start_end_values: impl ManyArgs<()>) -> Command

Generate a stream of sequential integers in a specified range.

range takes 0, 1 or 2 arguments:

  • With no arguments, range returns an “infinite” stream from 0 up to and including the maximum integer value;
  • With one argument, range returns a stream from 0 up to but not including the end value;
  • With two arguments, range returns a stream from the start value up to but not including the end value.

Note that the left bound (including the implied left bound of 0 in the 0- and 1-argument form) is always closed and the right bound is always open: the start value will always be included in the returned range and the end value will not be included in the returned range.

Any specified arguments must be integers, or a ReqlRuntimeError will be thrown. If the start value is equal or to higher than the end value, no error will be thrown but a zero-element stream will be returned.

§Example

Return a four-element range of [0, 1, 2, 3].

r.range(4).run(conn)
// Result: [0, 1, 2, 3]

You can also use the limit command with the no-argument variant to achieve the same result in this case:

r.range(()).limit(4).run(conn)
// Result: [0, 1, 2, 3]
§Example

Return a range from -5 through 5.

r.range(r.args([-5, 6])).run(conn)
// Result: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
Source§

impl r

Source

pub fn error(self, message: impl Serialize + 'static) -> Command

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_(func!(|ironman| {
    r.branch(
        ironman.clone().g("victories").lt(ironman.clone().g("battles")),
        r.error("impossible code path"),
        ironman
    )
})).run(conn)
Source§

impl r

Source

pub fn js(self, js_string: impl Arg<JsOptions>) -> Command

Create a javascript expression.

timeout is the number of seconds before r.js times out. The default value is 5 seconds.

Note: Whenever possible, you should use native ReQL commands rather than r.js for better performance.

§Example

Concatenate two strings using JavaScript.

r.js("'str1' + 'str2'").run(conn)
§Example

Select all documents where the ‘magazines’ field is greater than 5 by running JavaScript on the server.

r.table("marvel").filter(
    r.js("(function (row) { return row.magazines.length > 5; })")
).run(conn)
§Example

You may also specify a timeout in seconds (defaults to 5).

r.js(r.with_opt("while(true) {}", JsOptions::new().timeout(1.3))).run(conn)
Source§

impl r

Source

pub fn info(self, any: impl Serialize + 'static) -> Command

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)
Source§

impl r

Source

pub fn json(self, json_string: impl Serialize + 'static) -> Command

Parse a JSON string on the server.

§Example

Send an array to the server.

r.json("[1,2,3]").run(conn)
Source§

impl r

Source

pub fn http(self, url: impl Arg<HttpOptions>) -> Command

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

See the tutorial on r.http for more examples on how to use this command.

Source§

impl r

Source

pub fn uuid(self, string: impl Arg<()>) -> Command

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.

RethinkDB’s UUIDs are standards-compliant. Without the optional argument, a version 4 random UUID will be generated; with that argument, a version 5 UUID will be generated, using a fixed namespace UUID of 91461c99-f89d-49d2-af96-d8e2e14e9b58. For more information, read Wikipedia’s UUID article.

Note Please take into consideration when you generating version 5 UUIDs can’t be considered guaranteed unique if they’re computing based on user data because they use SHA-1 algorithm.

§Example

Generate a UUID.

r.uuid(()).run(conn)
// Result: "27961a0e-f4e8-4eb3-bf95-c5203e1d87b9"
§Example

Generate a UUID based on a string.

r.uuid("slava@example.com").run(conn)
// Result: "90691cbc-b5ea-5826-ae98-951e30fc3b2d"
Source§

impl r

Source

pub fn table_list(self) -> Command

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)
Source§

impl r

Source

pub fn table_create(self, table_name: impl Arg<TableCreateOptions>) -> Command

Create a table. A RethinkDB table is a collection of JSON documents.

If successful, the command returns an object with two fields:

  • tables_created: always 1.
  • config_changes: a list containing one two-field object, old_val and new_val:
    • old_val: always null.
    • new_val: the table’s new config value.

If a table with the same name already exists, the command throws ReqlOpFailedError.

Note: Only alphanumeric characters and underscores are valid for the table name.

Invoking tableCreate without specifying a database using db creates a table in the database specified in connect, or test if no database was specified.

When creating a table you can specify the following options:

  • primaryKey: the name of the primary key. The default primary key is id.
  • durability: if set to soft, writes will be acknowledged by the server immediately and flushed to disk in the background. The default is hard: acknowledgment of writes happens after data has been written to disk.
  • shards: the number of shards, an integer from 1-64. Defaults to 1.
  • replicas: either an integer or a mapping object. Defaults to 1.
    • If replicas is an integer, it specifies the number of replicas per shard. Specifying more replicas than there are servers will return an error.
    • If replicas is an object, it specifies key-value pairs of server tags and the number of replicas to assign to those servers: {tag1: 2, tag2: 4, tag3: 2, ...}.
  • primaryReplicaTag: the primary server specified by its server tag. Required if replicas is an object; the tag must be in the object. This must not be specified if replicas is an integer.

The data type of a primary key is usually a string (like a UUID) or a number, but it can also be a time, binary object, boolean or an array. Data types can be mixed in the primary key field, but all values must be unique. Using an array as a primary key causes the primary key to behave like a compound index; read the documentation on compound secondary indexes for more information, as it applies to primary keys as well. (Note that the primary index still only covers a single field, while compound secondary indexes can cover multiple fields in a single index.) Primary keys cannot be objects.

§Example

Create a table named ‘dc_universe’ with the default settings.

r.db("heroes").table_create("dc_universe").run(conn)
§Example

Create a table named ‘dc_universe’ using the field ‘name’ as primary key.

let opts = TableCreateOptions::new().primary_key("name");
r.db("test").table_create(r.with_opt("dc_universe", opts)).run(conn)
§Example

Create a table set up for two shards and three replicas per shard. This requires three available servers.

let opts = TableCreateOptions::new()
  .primary_key("name")
  .replicas(Replicas::Int(3));
r.db("test").table_create(r.with_opt("dc_universe", opts)).run(conn)

Read Sharding and replication for a complete discussion of the subject, including advanced topics.

Source§

impl r

Source

pub fn table_drop(self, table_name: impl Serialize + 'static) -> Command

Drop a table from a database. The table and all its data will be deleted.

If successful, the command returns an object with two fields:

  • tables_dropped: always 1.
  • config_changes: a list containing one two-field object, old_val and new_val:
    • old_val: the dropped table’s config value.
    • new_val: always null.

If the given table does not exist in the database, the command throws ReqlRuntimeError.

§Example

Drop a table named ‘dc_universe’.

r.db("test").table_drop("dc_universe").run(conn)
Source§

impl r

Source

pub fn map(self, function: impl ManyArgs<()>) -> Command

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.

Note that map can only be applied to sequences, not single values. If you wish to apply a function to a single value/selection (including an array), use the do_ command.

Example Return the first five squares.

r.expr([1, 2, 3, 4, 5])
  .map(func!(|val| val.clone().mul(val)))
  .run(conn)
// Result: [1, 4, 9, 16, 25]

Example Sum the elements of three sequences.

let sequence1 = [100, 200, 300, 400];
let sequence2 = [10, 20, 30, 40];
let sequence3 = [1, 2, 3, 4];
r.map(r.args((sequence1, sequence2, sequence3, func!(|val1, val2, val3| {
    val1.add(val2).add(val3)
  }))))
  .run(conn)
// Result: [1, 4, 9, 16, 25]
§Example

Rename a field when retrieving documents using map and merge.

This example renames the field id to userId when retrieving documents from the table users.

r.table("users").map(func!(|doc| {
    doc.clone().merge(rjson!({"userId": doc.g("id")})).without("id")
  }))
  .run(conn)

Note that in this case, row may be used as an alternative to writing an anonymous function, as it returns the same value as the function parameter receives:

r.table("users").map(
    r.row().merge(rjson!({"userId": r.row().g("id")})).without("id")
).run(conn)
§Example

Assign every superhero an archenemy.

r.table("heroes").map(r.args((r.table("villains"), func!(|hero, villain| {
    hero.merge(rjson!({"villain": villain}))
  }))))
  .run(conn)
Source§

impl r

Source

pub fn union(self, sequence: impl ManyArgs<UnionOptions>) -> Command

Merge two or more sequences.

The optional interleave argument controls how the sequences will be merged:

  • true: results will be mixed together; this is the fastest setting, but ordering of elements is not guaranteed. (This is the default.)
  • false: input sequences will be appended to one another, left to right.
  • "field_name": a string will be taken as the name of a field to perform a merge-sort on. The input sequences must be ordered before being passed to union.
  • function: the interleave argument can take a function whose argument is the current row, and whose return value is a value to perform a merge-sort on.
§Example

Construct a stream of all heroes.

r.table("marvel").union(r.table("dc")).run(conn)
§Example

Combine four arrays into one.

r.expr([1, 2]).union(r.args(([3, 4], [5, 6], [7, 8, 9]))).run(conn)
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
§Example

Create a changefeed from the first example.

r.table("marvel").union(r.table("dc")).changes(()).run(conn)

Now, when any heroes are added, modified or deleted from either table, a change notification will be sent out.

§Example

Merge-sort the tables of heroes, ordered by name.

r.table("marvel")
  .order_by("name")
  .union(r.with_opt(
    r.table("dc").order_by("name"),
    UnionOptions::new().interleave("name".into())
  ))
  .run(conn)
Source§

impl r

Source

pub async fn connect<T>(self, options: T) -> Result<Session>
where T: Arg,

Create a new connection to the database server

§Example

Open a connection using the default host and port, specifying the default database.

use unreql::{r, cmd::connect::Options};

let session = r.connect(Options::new().db("marvel")).await?;

Read more about this command connect

Source

pub fn expr(self, arg: impl Serialize) -> Command

Construct a ReQL JSON object from a native object.

§Example

Objects wrapped with expr can then be manipulated by ReQL API functions.

r.expr(json!({"a":"b"})).merge(json!({"b":[1,2,3]})).run(conn)
Source

pub fn args<T>(self, arg: T) -> Args<T>

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.

It is also the basic term for passing parameters to many driver methods in Rust. It allows you to accept an arbitrary number of arguments for commands that can have 0, 1 or more optional arguments

§Example

Get Alice and Bob from the table people.

r.table("people").get_all(r.args(["Alice", "Bob"])).run(conn)
§Example

Get all of Alice’s children from the table people.

// r.table('people').get('Alice') returns {id: 'Alice', children: ['Bob', 'Carol']}
r.table("people")
  .get_all(r.args(r.table("people").get("Alice").g("children")))
  .run(conn)
Source

pub fn with_opt<T, P>(self, arg: T, opt: P) -> ArgsWithOpt<T, P>

The term with_opt is used in conjunction with args to pass optional options to the command

§Example

Fetch all heroes by secondary index

r.table("heroes")
  .get_all(r.with_opt(r.args([1, 2]), r.index("secondary")))
  .run(conn)

Trait Implementations§

Source§

impl Clone for r

Source§

fn clone(&self) -> r

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for r

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Copy for r

Auto Trait Implementations§

§

impl Freeze for r

§

impl RefUnwindSafe for r

§

impl Send for r

§

impl Sync for r

§

impl Unpin for r

§

impl UnwindSafe for r

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more