Learn Redis · 2/15

Redis Fundamentals: Mastering Strings and Numbers

8 min read

Redis Fundamentals: Mastering Strings and Numbers redis

Welcome to the foundational guide on Redis, where we'll explore the simplest yet most powerful data types: Strings and Numbers. Think of Redis as a super-fast, in-memory data store, like a highly organized and lightning-quick short-term memory for your applications.

What are Redis Strings?

In Redis, a "String" is the most basic kind of value you can have. But don't let the simplicity fool you! A Redis string can hold any kind of data, from a simple text message to a serialized object or even an image, up to a whopping 512 megabytes. This makes them incredibly versatile.

At its core, Redis is a key-value store. This means that for every piece of data (the value), there's a unique name you use to identify it (the key). Since keys in Redis are also strings, when you use the string data type, you are essentially mapping one string to another.

The Problem: Imagine you're building a website and need to store user session information or frequently accessed data from a database. Constantly fetching this data from a traditional database can be slow and create a bottleneck.

The Solution: Redis strings provide a simple and incredibly fast way to cache this data. By storing it in memory, you can retrieve it almost instantly, dramatically speeding up your application.


1. Setting and Getting Values: The Basics of Key-Value Storage básico

The most fundamental operations you'll perform with Redis strings are setting a value for a key and then getting it back.

SET: Storing Your Data

The SET command is your go-to for storing a string value. If the key doesn't exist, Redis creates it. If the key already exists, its value is overwritten with the new one.

How it works:

gams
SET key value

Let's try it out in the Redis Command Line Interface (CLI). If you don't have it installed, you can find instructions for various operating systems in the official documentation.

shell
127.0.0.1:6379> SET username "SuperCoder"
OK

That "OK" tells you everything went smoothly. You've just stored the value "SuperCoder" under the key username.

GET: Retrieving Your Data

Now, to get that value back, you use the GET command.

How it works:

routeros
GET key

Let's retrieve the username we just set:

shell
127.0.0.1:6379> GET username
"SuperCoder"

What if you ask for a key that doesn't exist?

shell
127.0.0.1:6379> GET non_existent_key
(nil)

Redis returns (nil) (which is like null in many programming languages) instead of an error. This is by design to keep things fast; Redis assumes you know what you're looking for.

Real-World Scenario: User Session Management 👤💬

Imagine a user logs into your e-commerce site. You can store their session ID and user information in Redis.

shell
127.0.0.1:6379> SET session:12345 "{\"userId\": 789, \"username\": \"Shopaholic\", \"cartItems\": 3}"
OK

Now, every time "Shopaholic" clicks on a new page, your application can quickly fetch their session data using GET session:12345 without hitting the main database.

Fun Fact: The SET command has some cool options. For instance, you can make a key expire after a certain time using EX. This is perfect for caching data that should be refreshed periodically.

shell
127.0.0.1:6379> SET temporary_deal "50% off!" EX 60
OK

This key will automatically disappear after 60 seconds!


2. Managing Counters: INCR and DECR Operations 🔢

A surprisingly common and powerful use case for Redis strings is managing counters. Even though we're dealing with the "string" data type, Redis is smart enough to treat strings that look like integers as numbers.

The Problem: Let's say you want to count the number of visitors to your website, likes on a post, or items in stock. Doing this with a traditional database can be inefficient, especially with high traffic, as it often involves reading a value, modifying it, and writing it back, which can lead to issues if multiple users are doing it at the same time.

The Solution: Redis provides atomic operations INCR and DECR that make managing counters a breeze. "Atomic" means the operation is all-or-nothing, ensuring that even with many simultaneous requests, the counter will be updated correctly.

INCR: Incrementing a Counter

The INCR command increases the number stored at a key by one.

How it works:

ebnf
INCR key

If the key doesn't exist, Redis sets it to 0 and then increments it, so the first INCR on a new key will result in 1.

Let's track page views:

shell
127.0.0.1:6379> INCR page_views
(integer) 1
127.0.0.1:6379> INCR page_views
(integer) 2

If you need to increment by a different amount, you can use INCRBY:

shell
127.0.0.1:6379> INCRBY page_views 10
(integer) 12

DECR: Decrementing a Counter

Similarly, the DECR command decreases the number stored at a key by one.

How it works:

ebnf
DECR key

And DECRBY lets you decrement by a specific amount.

Real-World Scenario: Inventory Management 📦

Imagine you're running an online store. You can use Redis to keep track of the stock for a popular item.

shell
127.0.0.1:6379> SET product:101:stock 50
OK

When a customer buys an item:

shell
127.0.0.1:6379> DECR product:101:stock
(integer) 49

This is incredibly fast and reliable, preventing you from overselling products.

An interesting tidbit: What happens if you try to increment a string that isn't a number?

shell
127.0.0.1:6379> SET mykey "hello"
OK
127.0.0.1:6379> INCR mykey
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Redis will give you an error because it can't convert "hello" into an integer.


3. Working with Multiple Strings: MSET and MGET 💨

Sometimes you need to set or get multiple key-value pairs at once.

The Problem: Making a separate network request for each key can be slow and inefficient, especially when dealing with a large number of keys.

The Solution: Redis provides MSET and MGET to handle multiple keys in a single command, reducing network latency and improving performance.

MSET: Setting Multiple Key-Value Pairs

The MSET command allows you to set multiple keys to their respective values in one go.

How it works:

gams
MSET key1 value1 key2 value2 ...

Let's set up a user profile:

shell
127.0.0.1:6379> MSET user:1:name "Alice" user:1:email "[email protected]" user:1:city "Wonderland"
OK

MGET: Getting Multiple Values

The MGET command retrieves the values for a list of keys.

How it works:

gams
MGET key1 key2 ...

Let's get Alice's profile details:

shell
127.0.0.1:6379> MGET user:1:name user:1:email user:1:city
1) "Alice"
2) "[email protected]"
3) "Wonderland"

The values are returned in the same order as the keys you requested. If a key doesn't exist, you'll get (nil) in its place.

A note on Redis Cluster: In a clustered Redis setup, where data is split across multiple nodes, MSET and MGET by default only work if all the keys are in the same "hash slot". A common practice to ensure this is to use "hash tags" in your keys, where a part of the key in curly braces {} determines the slot. For example, user:{1}:name and user:{1}:email would be in the same slot.


4. Modifying Strings: Appending and Substring Operations ✏️

Beyond simply setting and getting entire strings, Redis allows for more granular modifications.

APPEND: Adding to a String

The APPEND command adds a value to the end of an existing string.

The Problem: You have a log or a long string of text and you need to add more information to it without retrieving the entire string, modifying it, and setting it again.

The Solution: APPEND efficiently adds the new data to the end of the existing value.

How it works:

dos
APPEND key value

If the key doesn't exist, it's created, so APPEND acts like SET in that case.

shell
127.0.0.1:6379> SET my_log "User logged in. "
OK
127.0.0.1:6379> APPEND my_log "Viewed dashboard."
(integer) 34

The command returns the new length of the string. Let's see the result:

shell
127.0.0.1:6379> GET my_log
"User logged in. Viewed dashboard."

GETRANGE: Getting a Substring

GETRANGE allows you to retrieve a portion of a string.

The Problem: You have a large string value and you only need a small piece of it. Fetching the whole string is a waste of resources.

The Solution: GETRANGE lets you specify the start and end offsets to get just the substring you need.

How it works:

xquery
GETRANGE key start end

The offsets are zero-based. You can also use negative offsets to count from the end of the string, where -1 is the last character.

Let's get the first part of our log:

shell
127.0.0.1:6379> GETRANGE my_log 0 15
"User logged in."

Humorous exaggeration: Imagine if every time you wanted a slice of a giant birthday cake, you had to take the whole cake back to your table. GETRANGE is like being able to just cut out the slice you want right there!


Further Reading and References 📚

Challenge

Challenge: E-commerce Inventory and Session Management

You are the backend developer for a new e-commerce platform. You need to use Redis string commands to manage product inventory, a flash sale promotion, and user session data.

Write the sequence of Redis commands required to perform the following operations in the specified order:

  1. Initial Inventory Setup: In a single, atomic operation, set the initial stock for the following three products:

    • Product ID product:sku:a101 has a stock of 150 units.
    • Product ID product:sku:b202 has a stock of 80 units.
    • Product ID product:sku:c303 has a stock of 200 units.
  2. Flash Sale Promotion: Create a special promotion key, promo:flash_sale:active, and set its value to 1. This key must automatically expire in exactly one hour (3600 seconds).

  3. User Purchase: A customer purchases 10 units of product product:sku:a101 and 5 units of product product:sku:c303. Atomically decrement the stock for these products.

  4. Audit Trail: Append a log entry to the key log:audit:q4. The value to append is the string "--user_purchase:sku:a101:10;sku:c303:5".

  5. Stock Restock: A new shipment has arrived. Atomically increase the stock of product product:sku:b202 by 50 units.

  6. Data Retrieval: In a single command, retrieve the final stock counts for all three products (product:sku:a101, product:sku:b202, product:sku:c303).

Expected result

Your solution should be a sequence of six Redis commands that correctly perform the requested operations in order.

  1. MSET product:sku:a101 150 product:sku:b202 80 product:sku:c303 200
  2. SET promo:flash_sale:active 1 EX 3600
  3. DECRBY product:sku:a101 10
  4. DECRBY product:sku:c303 5
  5. APPEND log:audit:q4 "--user_purchase:sku:a101:10;sku:c303:5"
  6. INCRBY product:sku:b202 50
  7. MGET product:sku:a101 product:sku:b202 product:sku:c303

After these operations, the values for the product keys would be:

  • product:sku:a101: 140
  • product:sku:b202: 130
  • product:sku:c303: 195
redis

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.