Log In

Redis: Getting Started and Basic Commands

Redis: Getting Started and Basic Commands
03.04.2024
Reading time: 7 min
Hostman Team
Technical writer

Redis is one of the most popular modern DBMSs (database management systems). In this Redis beginner tutorial, we will discuss the Redis basics: main features, data types, and commands, and we will also discuss the advantages of data caching using this DBMS.

Getting to know Redis

Redis is a non-relational DBMS, which means it works not only with table values but also with other data types, such as strings, lists, hashes, and sets. Data processing is implemented using the key-value principle. There is no SQL language in Redis, but you can use Lua scripts. This DBMS also features increased performance since data is stored directly in the server's RAM (in-memory), allowing you to perform more operations.

Redis use cases

The Redis DBMS is designed primarily to perform the following tasks (but is not limited to them):

  • Storing user sessions, including fragments of website pages and several other elements (for example, the contents of an online store's cart, so when you return to the site and see that there are still items in the cart, it is probably implemented using Redis).

  • Storing such data types as messages on users' "walls" on social networks, voting, results in tabular form, etc.

  • Creating news feeds, group chats, blogs.

  • Data caching which allows you to significantly reduce the load on a relational DBMS if it is used along with Redis.

  • Storing data that needs to be quickly accessed, such as analytical, commercial, and other important information. Thus, using Redis, you can implement data transfer from various sensors that take and transmit readings from industrial equipment in real time.

Getting started with Redis

To run Redis, you first need to download it. The latest version of the DBMS is available on the official page. By default, Redis only supports Ubuntu and MacOS, but running on Windows is also possible and can be done in different ways, for example, using Docker or with the Chocolatey package manager. (After installing Chocolatey, you can easily search for the required version of Redis.)

Redis itself is launched using the redis-server command. Then you can check that the installation is successful by using redis-cli.

This output indicates that the DBMS is installed correctly:

127.0.0.1:6379> ping
PONG

Redis Basics: Data Types and Commands

In this part, we will examine the main data types and commands used when working with Redis. This DBMS contains quite a few of them, so let's get acquainted with the most important ones. First, let's discuss the "building blocks" that form the basis of the entire system: the keys.

Keys

Keys in Redis are unique identifiers of the values associated with them. Values can be different: integers, strings, and even objects containing other nested values. Keys are used as pointers indicating where data is stored. We can draw an analogy with lockers where people can temporarily put things. The value is what is in this locker, and to access it, you need a specific key.

Strings

Let's move on to data types. String is the base data type that contains all other data. Strings in Redis are similar in function to strings in programming languages. The maximum allowed string size in Redis is 512 MB.

Lists

A list is a sequence of values that are arranged in a list in the order they were created. To create a list, let's get acquainted with some commands. LPUSH adds an element and LRANGE is used to display a list on the left. Enter the commands indicating list elements:

LPUSH obj1 element1
(integer) 1

LPUSH obj1 element2 (integer) 2
LPUSH obj1 element3 (integer) 3
LRANGE obj1 0 -1

And we get the following output:

1) "element3"
2) "element2"
3) "element1"

Hashes

The essence of hashes or hash tables will be immediately clear to those who have programmed in Python or JavaScript. Dictionaries are very similar to hashes in Python, and objects are very similar to hashes in JavaScript. Redis uses the HSET command to write a value to a hash, and to read it, HGET. Example:

HSET obj att1 val1
(integer) 1

HSET obj att2 val2 (integer) 1
HGET obj att1 "val1"

If you need to get all the values, use the HGETALL instruction:

HGETALL obj
1) "att1" 2) "val1" 3) "att2" 4) "val2"

Sets

In Redis, a set is an unordered collection of unique elements. To add another element there, enter the SADD command:

SADD objects object1
(integer) 1

SADD objects object2 (integer) 1
SADD objects object3 (integer) 1
SADD objects object1 (integer) 0

Now, to get all the elements, you need to enter the SMEMBERS instruction:

SMEMBERS objects
1) "object2" 2) "object3" 3) "object1"

There are also other Redis commands for working with sets. For example, SUNION allows you to combine them.

Sorted sets

To add an element to a sorted set, use the ZADD command:

ZADD objects 1230 val1
(integer) 1

ZADD objects 1231 val2 (integer) 1
ZADD objects 1232 val3 (integer) 1

Now, using the ZRANGE command, we get a slice:

ZRANGE objects 0 -1

1) "val1" 2) "val2" 3) "val3"

Other Redis commands

The following commands will also be helpful for Redis beginners to work with keys:

  • The HKEYS command prints all the keys recorded in the hash. Let's first write the values into a hash and then output the keys:

HSET object1 type "table"
(integer) 1

HSET object1 dimensions 75-50-50 (integer) 1
HKEYS object1 1) "type" 2) "dimensions"
  • If we need to display all the values, the HVALS command will help:

HVALS object1

1) "table" 2) "75-50-50"
  • The EXISTS command is used to check the existence of a key. If it exists, 1 is output, if not, then 0. For example:

EXISTS dimensions
(integer) 1

EXISTS instructions (integer) 0
  • To rename a key, use the RENAME command. First, enter the key that should be renamed and then its new name:

RENAME dimensions profile
OK

HKEYS object1 1) "type" 2) "profile"
  • And to delete a key (along with its value), use the DEL command:

DEL profile
(integer) 1

HKEYS object1 1) "type"

Caching in Redis

One of the problems that Redis solves is efficient data caching. Redis is often used together with relational DBMSs, such as PostgreSQL. Caching allows you to quickly load small objects that are frequently updated while minimizing the risk of information loss. Redis serves as a buffer DBMS and checks the key in response to a user request without affecting the main database. This significantly reduces the load on resources with high traffic (from several thousand users per hour).

To organize caching, you need to include the appropriate libraries, and you can use various programming languages. For example, in Python this is done through the import function:

import redis
import sqlite

Then the connection to the SQL database is configured:

def get_my_friends():
connection = sqlite.connect(database="database.db")
cursor = connection.cursor()

And then the DBMS is asked for the presence of the key:

redis_client = redis.Redis()

Pub/Sub Channels in Redis

Redis has a subscription mechanism which is implemented using channels. Published messages can be read by clients who have subscribed to the channel. Technically, this is similar to a regular chat, which can be useful for a group of developers. However, there is no guarantee that messages sent through such a channel will be read. Subscription to a channel is made using the SUBSCRIBE command, followed by the name of the channel, for example:

SUBSCRIBE hostman_channel

Messages are published using the PUBLISH command:

PUBLISH hostman_channel "Hello, we have launched a new channel!"

(integer) 2

The returned value (2) is the number of subscribers who received the message.

Conclusion

In this article, we have discussed how Redis works, learned the basic commands, and how to work with several types of data and special features, such as caching and channels. For a more in-depth study of Redis' capabilities, we recommend reading the official documentation. You can also find books and free guides online that describe advanced methods for working with Redis.

Share