BONUS! Redis Commands Cheat Sheet Part 4 - Transactions, Bit Data, Pub/Sub and Geospatial Data
Hrittik Bhattacharjee
Posted on February 5, 2023
Following are some of the commonly used Redis commands and data structures, use this list as a quick cheat sheet or a ready reference for your day-to-day Redis usage as needed 😄
This is a BONUS Part 4 of this series, containing commands pertaining to Transactions, Bit Data, Pub/Sub and Geospatial Data in Redis!
Transactions
# each transaction is atomic - either it completes, nor not
# command execution is single threaded in redis
# new command will execute after previous command is completed and will wait till it is either finished or failed
# but there are exceptions - e.g. async non-blocking commands like `UNLINK`
# transaction: a set of commands that are guaranteed to be atomic
# all commands in a transaction are serialized and executed sequentially
# this guarantees that all the commands are executed in a single, isolated operation
# another connectoin cannot make a change during the execution of a transaction
# in transaction, all commands are executed or none are
# commands:
# mark the start of a transaction block
# Subsequent commands will be queued for atomic execution using EXEC
> MULTI
# executes all previously queued commands (issued after MULTI) in a transaction and restores the connection state to normal
> EXEC
# flushes all previously queued commands (issued after MULTI) in a transaction and restores the connection state to normal
> DISCARD
# example:
> MULTI
OK
> ...command 1
QUEUED
> ...command 2
QUEUED
> ...command 3
QUEUED
> EXEC
# optimistic concurrency control or optimistic blocking:
# observe changes in one/more keys
# abort transaction if observed key(s) have changed
# declare interest in one/more keys
> WATCH key [key ...]
# when EXEC is called, the transaction will fail if any 'watched' keys have been modified
# WATCH has to be called before the transaction is started, i.e. before MULTI
# multiple WATCH commands can be called subsequently, the effects are cumulative
# watches are local to the current client connection
# all keys are automatically 'unwatched' after EXEC (EXEC will return (nil))
# forget about all 'watched' keys
> UNWATCH
Bit Data
Bit Fields:
# bit fields can be used to get, set or increment a value in a bit field
# bitfield commands allows manipulation of one/more variable length integers within a string datatype
> BITFIELD key
[GET type offset]
[SET type offset value]
[INCRBY type offset increment]
[OVERFLOW WRAP | SAT | FAIL]
# 'type' can be - i (signed) or u (unsigned), followed by the size
# e.g. u8, i16, etc.
# can have a max size of i63 and u64
# set an unsigned 8-bit value, at bit offset 0, to 42
> BITFIELD mykey SET u8 0 42
# get the unsigned 8-bit value, at bit offset 0
> BITFIELD mykey GET u8 0
1) (integer) 42
# BITFIELD can also be used to increment values
> BITFIELD myfield incrby u8 0 1
2) (integer) 43
> TYPE mykey
string
> OBJECT ENCODING mykey
"raw" # not "embstr"
Bit Arrays:
# bit arrays allow manipulation of individual bits within a string datatype
> GETBIT key offset
> SETBIT key offset value
# no need to specify 'type' for bit array commands
# bitfields are preferred over bit arrays, since commands have greated flexibility
# count the no. of "set" bits within a range
> BITCOUNT key [start end]
# BITCOUNT uses a "byte offset" not "bit offset" unlike all the other commands
# perform AND/OR/XOR/NOT and store the result at a new 'destination' key
> BITOP operation destination key [key...]
# find the index of the first set/unset bit within a given offset range
> BITPOS key bit [start end]
Pub/Sub
# simple pub/sub
# post a message to the given channel
> PUBLISH channel message
# when a message is published with the PUBLISH command, redis guaranteeS the order of messages in a single node
# listen for messgaes on a channel(s)
> SUBSCRIBE channel [channel ...]
# stop listening for messgaes on a channel(s)
> UNSUBSCRIBE [channel [channel ...]]
# patterned pub/sub
# subscribes the client to the given patterns
# Supported glob-style patterns:
# h?llo subscribes to hello, hallo and hxllo
# h*llo subscribes to hllo and heeeello
# h[ae]llo subscribes to hello and hallo, but not hillo
> PSUBSCRIBE pattern [pattern ...]
# un-subscribes the client from the given patterns
# when no patterns are specified, the client is unsubscribed from all the previously subscribed patterns
> PUNSUBSCRIBE [pattern [pattern ...]]
# introspection/admin of the pub-sub mechanism can be done using the PUBSUB command
> PUBSUB subcommand [argument [argument ...]]
# list currently active channels
# if no pattern is specified, all the channels are listed
> PUBSUB CHANNELS [pattern]
# return the number of "unique" patterns that are subscribed to by clients (that are performed using the PSUBSCRIBE command)
# note that this isn't the count of clients subscribed to patterns, but the total number of unique patterns all the clients are subscribed to
> PUBSUB NUMPAT
# return the number of subscribers (exclusive of clients subscribed to patterns) for the specified channels
> PUBSUB NUMSUB [channel [channel ...]]
# list the currently active shard channels
# an active shard channel is a Pub/Sub shard channel with one or more subscribers
> PUBSUB SHARDCHANNELS [pattern]
Geospatial data
# we can create a geo-spatial index, using a "key" and the "value" comprising of - *unique name of point (member)*, *latitude* and *longitude*
# geo-spatial data is encoded as "geo-hash" - 52 bit integer value
# geo-spatial data is stored as sorted sets
# commands:
# add one or more geospatial items to the geospatial index (key)
# adds the specified geospatial items (longitude, latitude, name) to the specified key
# options:
# XX: only update elements that already exist, never add elements
# NX: don't update already existing elements, always add new elements
> GEOADD key [NX | XX] longitude latitude member [longitude latitude member ...]
> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
# data is stored into the key as a sorted set, in a way that makes it possible to query the items with the GEOSEARCH command
# there is no GEODEL command because you can use ZREM to remove elements
# see all the computed geo-hashes for a given geospatial index (key) i.e. the computed 52-bit integer values
> ZRANGE key 0 -1 WITHSCORES
# see the geo-hashes for specific member(s) in a given geospatial index
# the command returns 11-character geo-hash strings, not the 52-bit integers
> GEOHASH key member [member ...]
# see the longitude and latitude for specific member(s) in a given geospatial index
> GEOPOS key member [member ...]
# query a geospatial index to fetch members inside an area of a box or a circle
> GEOSEARCH key
<FROMMEMBER member | FROMLONLAT longitude latitude>
<BYRADIUS radius <M | KM | FT | MI> | BYBOX width height <M | KM | FT | MI>>
[ASC | DESC] [COUNT count [ANY]] [WITHCOORD] [WITHDIST] [WITHHASH]
# The query's center point is provided by one of these mandatory options:
# FROMMEMBER: use the position of the given existing <member> in the sorted set
# FROMLONLAT: use the given <longitude> and <latitude> position
# the query's shape is provided by one of these mandatory options:
# BYRADIUS: similar to GEORADIUS, search inside circular area according to given <radius>
# BYBOX: search inside an axis-aligned rectangle, determined by <height> and <width>
# matching items are returned unsorted by default, to sort them, use one of the following two options: ASC or DESC
# all matching items are returned by default, to limit the results to the first N matching items, use the COUNT <count> option
# the command optionally returns additional information using the following options:
# WITHDIST: also return the distance of the returned items from the specified center point, the distance is returned in the same unit as specified for the radius or height and width arguments
# WITHCOORD: also return the longitude and latitude of the matching items
# WITHHASH: also return the raw geohash-encoded sorted set score of the item
# GEOSEARCHSTORE is similR GEOSEARCH, but stores the result in destination key
> GEOSEARCHSTORE destination source
<FROMMEMBER member | FROMLONLAT longitude latitude>
<BYRADIUS radius <M | KM | FT | MI> | BYBOX width height <M | KM | FT | MI>>
[ASC | DESC] [COUNT count [ANY]] [STOREDIST]
# return the distance between two members in the geospatial index
> GEODIST key member1 member2 [M | KM | FT | MI]
💖 💪 🙅 🚩
Hrittik Bhattacharjee
Posted on February 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.