paint-brush
Useful Redis Commands You Should Knowby@mka342
144 reads

Useful Redis Commands You Should Know

by Mohsen KhosroanjamNovember 12th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Once you are connected to the command-line (CLI) of the Redis, you are able to use some commands to work with the keys. In this article, I want to share these commands with a brief explanation for you.
featured image - Useful Redis Commands You Should Know
Mohsen Khosroanjam HackerNoon profile picture

As you may know, Redis is basically a data-structure store that uses key-value pairs to store the data and supports strings, integers, sets, lists, hashes, and so on. To access the data faster, we can implement Redis.


Once you are connected to the command-line (CLI) of the Redis, you are able to use some commands to work with the keys. In this article, I want to share these commands with a brief explanation for you.

select {database_number}

This command will connect you to the database of {database_number} in Redis.

keys *

This command shows all available keys in Redis (note that: when the TTL of a key finishes, the key is automatically destroyed).

type {key_name}

Use this command with the key's name. It shows the type of the key. For example, if the type of the key is hash, the command returns a hash.

lindex {key_name} {index}

If the key is a list of values, you can use this command to get the value of each index. You may know that in lists, the index starts from "0" to "length of the list-1". For example, lindex {key_name} 1, will return the value of index 1 in list {key_name}.

del {key_name1} {key_name2} …

This command deletes the given keys with {key_name1} {key_name2} and so on.

hgetall {key_name}

If the key is hash and you want to get all fields and the related values in the key, you can use this command. For example, if a key is hash and has two fields "a" and "b" with values of ‘x’ and ‘y’ respectively; if you use this command, you will get "a", x, "b", and y in response.

hget {key_name} {field}

If the type of the key is hash and you want to get the value of a specific field in the key, you can use this command. For example, imagine a key is hash and has two fields "a" and "b". The value of field “a” is ‘x’.


To get x, you can use: hget {key_name} a

get {key_name}

This command returns the value that the key holds. It works when the type of the key is not hash or list.

flushdb

This command deletes all keys in Redis.

ttl {key_name}

This command returns the TTL of the key in seconds.

set {key_name} {value}

This command creates a key named {key_name} with a value in Redis. This command works when you want to create a key that is not a list or hash.