Skip to the workspace
Pebellslearn by building
Strings  ›  Capstone Project

More String Commands

More Commands 12 minMSET and MGET move many string keys in one round trip, INCRBY and INCRBYFLOAT change a number by any amount, and GETRANGE reads part of a string.

redis / More String Commands

Explore each scene at your own pace.

01 · The rule

The rule

More String Commands

The Wordcraft home screen shows the coin totals of four friends. Four GET commands mean four trips across the network, and each trip usually costs far more time than Redis spends answering. A handful of extra string commands save those trips and cover the cases SET, GET and INCR do not.

The rule

One command, many keys: batch the trips, not just the work.

MSET and MGET set or read several string keys in a single command.

127.0.0.1:6379> MSET coins:asha 120 coins:ravi 75 coins:tom 300
OK
127.0.0.1:6379> MGET coins:asha coins:ravi coins:meera coins:tom
1) "120"
2) "75"
3) (nil)
4) "300"

The reply has one entry per key, in the order you asked. A key that is missing (or holds a non-string type) gives (nil) in its slot, so positions always line up. MSET replies OK and, like SET, replaces old values.

INCRBY and INCRBYFLOAT change a number by any amount. INCRBY takes whole numbers (negative ones too); INCRBYFLOAT handles decimals and replies with the result as a string:

127.0.0.1:6379> SET rating:asha 4.5
OK
127.0.0.1:6379> INCRBYFLOAT rating:asha 0.25
"4.75"

GETRANGE key start end reads part of a string by byte positions, counting from 0, with both ends included. Negative positions count from the end, so -1 is the last byte.

127.0.0.1:6379> SET word:today planet
OK
127.0.0.1:6379> GETRANGE word:today 0 2
"pla"
127.0.0.1:6379> GETRANGE word:today -3 -1
"net"

GETDEL key returns the value and deletes the key in one step, useful for one-time codes. SETRANGE overwrites bytes from a position, and MSETNX sets several keys only if none of them exist.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.