Struct redis::Cmd

source · []
pub struct Cmd { /* private fields */ }
Expand description

Represents redis commands.

Implementations

A command acts as a builder interface to creating encoded redis requests. This allows you to easiy assemble a packed command by chaining arguments together.

Basic example:

redis::Cmd::new().arg("SET").arg("my_key").arg(42);

There is also a helper function called cmd which makes it a tiny bit shorter:

redis::cmd("SET").arg("my_key").arg(42);

Because currently rust’s currently does not have an ideal system for lifetimes of temporaries, sometimes you need to hold on to the initially generated command:

let mut cmd = redis::cmd("SMEMBERS");
let mut iter : redis::Iter<i32> = cmd.arg("my_set").clone().iter(&mut con).unwrap();

Creates a new empty command.

Appends an argument to the command. The argument passed must be a type that implements ToRedisArgs. Most primitive types as well as vectors of primitive types implement it.

For instance all of the following are valid:

redis::cmd("SET").arg(&["my_key", "my_value"]);
redis::cmd("SET").arg("my_key").arg(42);
redis::cmd("SET").arg("my_key").arg(b"my_value");

Works similar to arg but adds a cursor argument. This is always an integer and also flips the command implementation to support a different mode for the iterators where the iterator will ask for another batch of items when the local data is exhausted.

let mut cmd = redis::cmd("SSCAN");
let mut iter : redis::Iter<isize> =
    cmd.arg("my_set").cursor_arg(0).clone().iter(&mut con).unwrap();
for x in iter {
    // do something with the item
}

Returns the packed command as a byte vector.

Returns true if the command is in scan mode.

Sends the command as query to the connection and converts the result to the target redis value. This is the general way how you can retrieve data.

Async version of query.

Similar to query() but returns an iterator over the items of the bulk result or iterator. In normal mode this is not in any way more efficient than just querying into a Vec<T> as it’s internally implemented as buffering into a vector. This however is useful when cursor_arg was used in which case the iterator will query for more items until the server side cursor is exhausted.

This is useful for commands such as SSCAN, SCAN and others.

One speciality of this function is that it will check if the response looks like a cursor or not and always just looks at the payload. This way you can use the function the same for responses in the format of KEYS (just a list) as well as SSCAN (which returns a tuple of cursor and list).

Similar to iter() but returns an AsyncIter over the items of the bulk result or iterator. A futures::Stream can be obtained by calling stream() on the AsyncIter. In normal mode this is not in any way more efficient than just querying into a Vec<T> as it’s internally implemented as buffering into a vector. This however is useful when cursor_arg was used in which case the stream will query for more items until the server side cursor is exhausted.

This is useful for commands such as SSCAN, SCAN and others in async contexts.

One speciality of this function is that it will check if the response looks like a cursor or not and always just looks at the payload. This way you can use the function the same for responses in the format of KEYS (just a list) as well as SSCAN (which returns a tuple of cursor and list).

This is a shortcut to query() that does not return a value and will fail the task if the query fails because of an error. This is mainly useful in examples and for simple commands like setting keys.

This is equivalent to a call of query like this:

let _ : () = redis::cmd("PING").query(&mut con).unwrap();

Returns an iterator over the arguments in this command (including the command name itself)

Get the value of a key. If key is a vec this becomes an MGET.

Gets all keys matching pattern

Set the string value of a key.

Sets multiple keys to their values.

Set the value and expiration of a key.

Set the value and expiration in milliseconds of a key.

Set the value of a key, only if the key does not exist

Sets multiple keys to their values failing if at least one already exists.

Set the string value of a key and return its old value.

Get a range of bytes/substring from the value of a key. Negative values provide an offset from the end of the value.

Overwrite the part of the value stored in key at the specified offset.

Delete one or more keys.

Determine if a key exists.

Set a key’s time to live in seconds.

Set the expiration for a key as a UNIX timestamp.

Set a key’s time to live in milliseconds.

Set the expiration for a key as a UNIX timestamp in milliseconds.

Remove the expiration from a key.

Get the expiration time of a key.

Get the expiration time of a key in milliseconds.

Rename a key.

Rename a key, only if the new key does not exist.

Unlink one or more keys.

Append a value to a key.

Increment the numeric value of a key by the given amount. This issues a INCRBY or INCRBYFLOAT depending on the type.

Decrement the numeric value of a key by the given amount.

Sets or clears the bit at offset in the string value stored at key.

Returns the bit value at offset in the string value stored at key.

Count set bits in a string.

Count set bits in a string in a range.

Perform a bitwise AND between multiple keys (containing string values) and store the result in the destination key.

Perform a bitwise OR between multiple keys (containing string values) and store the result in the destination key.

Perform a bitwise XOR between multiple keys (containing string values) and store the result in the destination key.

Perform a bitwise NOT of the key (containing string values) and store the result in the destination key.

Get the length of the value stored in a key.

Gets a single (or multiple) fields from a hash.

Deletes a single (or multiple) fields from a hash.

Sets a single field in a hash.

Sets a single field in a hash if it does not exist.

Sets a multiple fields in a hash.

Increments a value.

Checks if a field in a hash exists.

Gets all the keys in a hash.

Gets all the values in a hash.

Gets all the fields and values in a hash.

Gets the length of a hash.

Pop an element from a list, push it to another list and return it; or block until one is available

Pops count elements from the first non-empty list key from the list of provided key names; or blocks until one is available.

Remove and get the first element in a list, or block until one is available.

Remove and get the last element in a list, or block until one is available.

Pop a value from a list, push it to another list and return it; or block until one is available.

Get an element from a list by its index.

Insert an element before another element in a list.

Insert an element after another element in a list.

Returns the length of the list stored at key.

Pop an element a list, push it to another list and return it

Pops count elements from the first non-empty list key from the list of provided key names.

Removes and returns the up to count first elements of the list stored at key.

If count is not specified, then defaults to first element.

Returns the index of the first matching value of the list stored at key.

Insert all the specified values at the head of the list stored at key.

Inserts a value at the head of the list stored at key, only if key already exists and holds a list.

Returns the specified elements of the list stored at key.

Removes the first count occurrences of elements equal to value from the list stored at key.

Trim an existing list so that it will contain only the specified range of elements specified.

Sets the list element at index to value

Removes and returns the up to count last elements of the list stored at key

If count is not specified, then defaults to last element.

Pop a value from a list, push it to another list and return it.

Insert all the specified values at the tail of the list stored at key.

Inserts value at the tail of the list stored at key, only if key already exists and holds a list.

Add one or more members to a set.

Get the number of members in a set.

Subtract multiple sets.

Subtract multiple sets and store the resulting set in a key.

Intersect multiple sets.

Intersect multiple sets and store the resulting set in a key.

Determine if a given value is a member of a set.

Get all the members in a set.

Move a member from one set to another.

Remove and return a random member from a set.

Get one random member from a set.

Get multiple random members from a set.

Remove one or more members from a set.

Add multiple sets.

Add multiple sets and store the resulting set in a key.

Add one member to a sorted set, or update its score if it already exists.

Add multiple members to a sorted set, or update its score if it already exists.

Get the number of members in a sorted set.

Count the members in a sorted set with scores within the given values.

Increments the member in a sorted set at key by delta. If the member does not exist, it is added with delta as its score.

Intersect multiple sorted sets and store the resulting sorted set in a new key using SUM as aggregation function.

Intersect multiple sorted sets and store the resulting sorted set in a new key using MIN as aggregation function.

Intersect multiple sorted sets and store the resulting sorted set in a new key using MAX as aggregation function.

Count the number of members in a sorted set between a given lexicographical range.

Removes and returns up to count members with the highest scores in a sorted set

Removes and returns up to count members with the lowest scores in a sorted set

Return up to count random members in a sorted set (or 1 if count == None)

Return up to count random members in a sorted set with scores

Return a range of members in a sorted set, by index

Return a range of members in a sorted set, by index with scores.

Return a range of members in a sorted set, by lexicographical range.

Return a range of members in a sorted set, by lexicographical range with offset and limit.

Return a range of members in a sorted set, by lexicographical range.

Return a range of members in a sorted set, by lexicographical range with offset and limit.

Return a range of members in a sorted set, by score.

Return a range of members in a sorted set, by score with scores.

Return a range of members in a sorted set, by score with limit.

Return a range of members in a sorted set, by score with limit with scores.

Determine the index of a member in a sorted set.

Remove one or more members from a sorted set.

Remove all members in a sorted set between the given lexicographical range.

Remove all members in a sorted set within the given indexes.

Remove all members in a sorted set within the given scores.

Return a range of members in a sorted set, by index, with scores ordered from high to low.

Return a range of members in a sorted set, by index, with scores ordered from high to low.

Return a range of members in a sorted set, by score.

Return a range of members in a sorted set, by score with scores.

Return a range of members in a sorted set, by score with limit.

Return a range of members in a sorted set, by score with limit with scores.

Determine the index of a member in a sorted set, with scores ordered from high to low.

Get the score associated with the given member in a sorted set.

Get the scores associated with multiple members in a sorted set.

Unions multiple sorted sets and store the resulting sorted set in a new key using SUM as aggregation function.

Unions multiple sorted sets and store the resulting sorted set in a new key using MIN as aggregation function.

Unions multiple sorted sets and store the resulting sorted set in a new key using MAX as aggregation function.

Adds the specified elements to the specified HyperLogLog.

Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).

Merge N different HyperLogLogs into a single one.

Posts a message to the given channel.

Available on crate feature acl only.

When Redis is configured to use an ACL file (with the aclfile configuration option), this command will reload the ACLs from the file, replacing all the current ACL rules with the ones defined in the file.

Available on crate feature acl only.

When Redis is configured to use an ACL file (with the aclfile configuration option), this command will save the currently defined ACLs from the server memory to the ACL file.

Available on crate feature acl only.

Shows the currently active ACL rules in the Redis server.

Available on crate feature acl only.

Shows a list of all the usernames of the currently configured users in the Redis ACL system.

Available on crate feature acl only.

Returns all the rules defined for an existing ACL user.

Available on crate feature acl only.

Creates an ACL user without any privilege.

Available on crate feature acl only.

Creates an ACL user with the specified rules or modify the rules of an existing user.

Available on crate feature acl only.

Delete all the specified ACL users and terminate all the connections that are authenticated with such users.

Available on crate feature acl only.

Shows the available ACL categories.

Available on crate feature acl only.

Shows all the Redis commands in the specified category.

Available on crate feature acl only.

Generates a 256-bits password starting from /dev/urandom if available.

Available on crate feature acl only.

Generates a 1-to-1024-bits password starting from /dev/urandom if available.

Available on crate feature acl only.

Returns the username the current connection is authenticated with.

Available on crate feature acl only.

Shows a list of recent ACL security events

Available on crate feature acl only.

Clears the ACL log.

Available on crate feature acl only.

Returns a helpful text describing the different subcommands.

Available on crate feature geospatial only.

Adds the specified geospatial items to the specified key.

Every member has to be written as a tuple of (longitude, latitude, member_name). It can be a single tuple, or a vector of tuples.

longitude, latitude can be set using redis::geo::Coord.

Returns the number of elements added to the sorted set, not including elements already existing for which the score was updated.

Example
use redis::{Commands, Connection, RedisResult};
use redis::geo::Coord;

fn add_point(con: &mut Connection) -> RedisResult<isize> {
    con.geo_add("my_gis", (Coord::lon_lat(13.361389, 38.115556), "Palermo"))
}

fn add_point_with_tuples(con: &mut Connection) -> RedisResult<isize> {
    con.geo_add("my_gis", ("13.361389", "38.115556", "Palermo"))
}

fn add_many_points(con: &mut Connection) -> RedisResult<isize> {
    con.geo_add("my_gis", &[
        ("13.361389", "38.115556", "Palermo"),
        ("15.087269", "37.502669", "Catania")
    ])
}
Available on crate feature geospatial only.

Return the distance between two members in the geospatial index represented by the sorted set.

If one or both the members are missing, the command returns NULL, so it may be convenient to parse its response as either Option<f64> or Option<String>.

Example
use redis::{Commands, RedisResult};
use redis::geo::Unit;

fn get_dists(con: &mut redis::Connection) {
    let x: RedisResult<f64> = con.geo_dist(
        "my_gis",
        "Palermo",
        "Catania",
        Unit::Kilometers
    );
    // x is Ok(166.2742)

    let x: RedisResult<Option<f64>> = con.geo_dist(
        "my_gis",
        "Palermo",
        "Atlantis",
        Unit::Meters
    );
    // x is Ok(None)
}
Available on crate feature geospatial only.

Return valid Geohash strings representing the position of one or more members of the geospatial index represented by the sorted set at key.

Example
use redis::{Commands, RedisResult};

fn get_hash(con: &mut redis::Connection) {
    let x: RedisResult<Vec<String>> = con.geo_hash("my_gis", "Palermo");
    // x is vec!["sqc8b49rny0"]

    let x: RedisResult<Vec<String>> = con.geo_hash("my_gis", &["Palermo", "Catania"]);
    // x is vec!["sqc8b49rny0", "sqdtr74hyu0"]
}
Available on crate feature geospatial only.

Return the positions of all the specified members of the geospatial index represented by the sorted set at key.

Every position is a pair of (longitude, latitude). redis::geo::Coord can be used to convert these value in a struct.

Example
use redis::{Commands, RedisResult};
use redis::geo::Coord;

fn get_position(con: &mut redis::Connection) {
    let x: RedisResult<Vec<Vec<f64>>> = con.geo_pos("my_gis", &["Palermo", "Catania"]);
    // x is [ [ 13.361389, 38.115556 ], [ 15.087269, 37.502669 ] ];

    let x: Vec<Coord<f64>> = con.geo_pos("my_gis", "Palermo").unwrap();
    // x[0].longitude is 13.361389
    // x[0].latitude is 38.115556
}
Available on crate feature geospatial only.

Return the members of a sorted set populated with geospatial information using geo_add, which are within the borders of the area specified with the center location and the maximum distance from the center (the radius).

Every item in the result can be read with redis::geo::RadiusSearchResult, which support the multiple formats returned by GEORADIUS.

use redis::{Commands, RedisResult};
use redis::geo::{RadiusOptions, RadiusSearchResult, RadiusOrder, Unit};

fn radius(con: &mut redis::Connection) -> Vec<RadiusSearchResult> {
    let opts = RadiusOptions::default().with_dist().order(RadiusOrder::Asc);
    con.geo_radius("my_gis", 15.90, 37.21, 51.39, Unit::Kilometers, opts).unwrap()
}
Available on crate feature geospatial only.

Retrieve members selected by distance with the center of member. The member itself is always contained in the results.

Available on crate feature streams only.

Ack pending stream messages checked out by a consumer.

XACK <key> <group> <id> <id> ... <id>
Available on crate feature streams only.

Add a stream message by key. Use * as the id for the current timestamp.

XADD key <ID or *> [field value] [field value] ...
Available on crate feature streams only.

BTreeMap variant for adding a stream message by key. Use * as the id for the current timestamp.

XADD key <ID or *> [rust BTreeMap] ...
Available on crate feature streams only.

Add a stream message while capping the stream at a maxlength.

XADD key [MAXLEN [~|=] <count>] <ID or *> [field value] [field value] ...
Available on crate feature streams only.

BTreeMap variant for adding a stream message while capping the stream at a maxlength.

XADD key [MAXLEN [~|=] <count>] <ID or *> [rust BTreeMap] ...
Available on crate feature streams only.

Claim pending, unacked messages, after some period of time, currently checked out by another consumer.

This method only accepts the must-have arguments for claiming messages. If optional arguments are required, see xclaim_options below.

XCLAIM <key> <group> <consumer> <min-idle-time> [<ID-1> <ID-2>]
Available on crate feature streams only.

This is the optional arguments version for claiming unacked, pending messages currently checked out by another consumer.

use redis::{Connection,Commands,RedisResult};
use redis::streams::{StreamClaimOptions,StreamClaimReply};
let client = redis::Client::open("redis://127.0.0.1/0").unwrap();
let mut con = client.get_connection().unwrap();

// Claim all pending messages for key "k1",
// from group "g1", checked out by consumer "c1"
// for 10ms with RETRYCOUNT 2 and FORCE

let opts = StreamClaimOptions::default()
    .with_force()
    .retry(2);
let results: RedisResult<StreamClaimReply> =
    con.xclaim_options("k1", "g1", "c1", 10, &["0"], opts);

// All optional arguments return a `Result<StreamClaimReply>` with one exception:
// Passing JUSTID returns only the message `id` and omits the HashMap for each message.

let opts = StreamClaimOptions::default()
    .with_justid();
let results: RedisResult<Vec<String>> =
    con.xclaim_options("k1", "g1", "c1", 10, &["0"], opts);
XCLAIM <key> <group> <consumer> <min-idle-time> <ID-1> <ID-2>
    [IDLE <milliseconds>] [TIME <mstime>] [RETRYCOUNT <count>]
    [FORCE] [JUSTID]
Available on crate feature streams only.

Deletes a list of ids for a given stream key.

XDEL <key> [<ID1> <ID2> ... <IDN>]
Available on crate feature streams only.

This command is used for creating a consumer group. It expects the stream key to already exist. Otherwise, use xgroup_create_mkstream if it doesn’t. The id is the starting message id all consumers should read from. Use $ If you want all consumers to read from the last message added to stream.

XGROUP CREATE <key> <groupname> <id or $>
Available on crate feature streams only.

This is the alternate version for creating a consumer group which makes the stream if it doesn’t exist.

XGROUP CREATE <key> <groupname> <id or $> [MKSTREAM]
Available on crate feature streams only.

Alter which id you want consumers to begin reading from an existing consumer group.

XGROUP SETID <key> <groupname> <id or $>
Available on crate feature streams only.

Destroy an existing consumer group for a given stream key

XGROUP SETID <key> <groupname> <id or $>
Available on crate feature streams only.

This deletes a consumer from an existing consumer group for given stream `key.

XGROUP DELCONSUMER <key> <groupname> <consumername>
Available on crate feature streams only.

This returns all info details about which consumers have read messages for given consumer group. Take note of the StreamInfoConsumersReply return type.

It’s possible this return value might not contain new fields added by Redis in future versions.

XINFO CONSUMERS <key> <group>
Available on crate feature streams only.

Returns all consumer groups created for a given stream key. Take note of the StreamInfoGroupsReply return type.

It’s possible this return value might not contain new fields added by Redis in future versions.

XINFO GROUPS <key>
Available on crate feature streams only.

Returns info about high-level stream details (first & last message id, length, number of groups, etc.) Take note of the StreamInfoStreamReply return type.

It’s possible this return value might not contain new fields added by Redis in future versions.

XINFO STREAM <key>
Available on crate feature streams only.

Returns the number of messages for a given stream key.

XLEN <key>
Available on crate feature streams only.

This is a basic version of making XPENDING command calls which only passes a stream key and consumer group and it returns details about which consumers have pending messages that haven’t been acked.

You can use this method along with xclaim or xclaim_options for determining which messages need to be retried.

Take note of the StreamPendingReply return type.

XPENDING <key> <group> [<start> <stop> <count> [<consumer>]]
Available on crate feature streams only.

This XPENDING version returns a list of all messages over the range. You can use this for paginating pending messages (but without the message HashMap).

Start and end follow the same rules xrange args. Set start to - and end to + for the entire stream.

Take note of the StreamPendingCountReply return type.

XPENDING <key> <group> <start> <stop> <count>
Available on crate feature streams only.

An alternate version of xpending_count which filters by consumer name.

Start and end follow the same rules xrange args. Set start to - and end to + for the entire stream.

Take note of the StreamPendingCountReply return type.

XPENDING <key> <group> <start> <stop> <count> <consumer>
Available on crate feature streams only.

Returns a range of messages in a given stream key.

Set start to - to begin at the first message. Set end to + to end the most recent message. You can pass message id to both start and end.

Take note of the StreamRangeReply return type.

XRANGE key start end
Available on crate feature streams only.

A helper method for automatically returning all messages in a stream by key. Use with caution!

XRANGE key - +
Available on crate feature streams only.

A method for paginating a stream by key.

XRANGE key start end [COUNT <n>]
Available on crate feature streams only.

Read a list of ids for each stream key. This is the basic form of reading streams. For more advanced control, like blocking, limiting, or reading by consumer group, see xread_options.

XREAD STREAMS key_1 key_2 ... key_N ID_1 ID_2 ... ID_N
Available on crate feature streams only.

This method handles setting optional arguments for XREAD or XREADGROUP Redis commands.

use redis::{Connection,RedisResult,Commands};
use redis::streams::{StreamReadOptions,StreamReadReply};
let client = redis::Client::open("redis://127.0.0.1/0").unwrap();
let mut con = client.get_connection().unwrap();

// Read 10 messages from the start of the stream,
// without registering as a consumer group.

let opts = StreamReadOptions::default()
    .count(10);
let results: RedisResult<StreamReadReply> =
    con.xread_options(&["k1"], &["0"], &opts);

// Read all undelivered messages for a given
// consumer group. Be advised: the consumer group must already
// exist before making this call. Also note: we're passing
// '>' as the id here, which means all undelivered messages.

let opts = StreamReadOptions::default()
    .group("group-1", "consumer-1");
let results: RedisResult<StreamReadReply> =
    con.xread_options(&["k1"], &[">"], &opts);
XREAD [BLOCK <milliseconds>] [COUNT <count>]
    STREAMS key_1 key_2 ... key_N
    ID_1 ID_2 ... ID_N

XREADGROUP [BLOCK <milliseconds>] [COUNT <count>] [NOACK] [GROUP group-name consumer-name]
    STREAMS key_1 key_2 ... key_N
    ID_1 ID_2 ... ID_N
Available on crate feature streams only.

This is the reverse version of xrange. The same rules apply for start and end here.

XREVRANGE key end start

This is the reverse version of xrange_all. The same rules apply for start and end here.

XREVRANGE key + -
Available on crate feature streams only.

This is the reverse version of xrange_count. The same rules apply for start and end here.

XREVRANGE key end start [COUNT <n>]
Available on crate feature streams only.

Trim a stream key to a MAXLEN count.

XTRIM <key> MAXLEN [~|=] <count>  (Same as XADD MAXLEN option)

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Returns the “default value” for a type. Read more

Accepts a serialized redis command.

Accepts a serialized redis command.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

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

Calls U::from(self).

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

The resulting type after obtaining ownership.

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

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

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

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