Skip to content

Instantly share code, notes, and snippets.

@sangdth
Last active December 14, 2023 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangdth/f1faaef25de8721498ebc15aac00202e to your computer and use it in GitHub Desktop.
Save sangdth/f1faaef25de8721498ebc15aac00202e to your computer and use it in GitHub Desktop.
My list of most used Redis commands

Useful links

Getting Started

If Redis is running on the same machine, it will connect to the default Redis server localhost on port 6379.

redis-cli

STRING

Set value

> SET my:key myvalue
OK

Get value

> GET my:key
"myvalue"

Rename a key

> RENAME my:key my:newkey
OK

Get all keys in a namespace

> KEYS my:*
1) "my:newky"
2) "my:key"

Note: Source

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length. All redis commands are single thread and will block the server. The only difference is that keys has the potential of blocking server for longer when querying a large data set.

So, with version 2.8 or later, use scan is a superior alternative to keys because it does not block the server nor does it consume significant resources.

redis-cli --scan --pattern '*'

SET

Creating Sets

> SADD my:set hello world
(integer) 2

Retrieve Sets members

> SMEMBERS my:set
1) "hello"
2) "world"

spop, srem, and smove.

  • spop randomly selects a specified number then deletes them
  • srem allows you to remove one or more specific members
  • Use smove to move a member from one set to another.

Read more from here.

HASH

Set or create new Hash

> HSET person name Sang
(integer) 1

Get the value of a field

> HGET person name
"Sang"

Get all fields

> HGETALL person
1) "name"
2) "Sang"

Delete a field

> HDEL person name
(integer) 1

Read more about Hash group commands here.

Others

Returns the time to live (seconds)

> TTL my:key
(integer) -1

Set time to live (seconds)

> EXPIRE my:key 10
(integer) 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment