DEV Community

Cover image for Redis for Beginners (Part 2 of 2)
topeogunleye
topeogunleye

Posted on

Redis for Beginners (Part 2 of 2)

Welcome back to the second part of our Redis for Beginners series. In Part 1, we covered some basic setups of a Redis database and a couple of fundamental commands. In this second part, we will further explore advanced options for commands while deeply focusing on the difference between lists and sets in Redis.

Command Options

Not all commands have options, but a few, for example, SET, have certain added features that can be essential.

  • EX seconds: Sets an expiration time in seconds (must be a positive integer).
  • PX milliseconds: Sets an expiration time in milliseconds (must be a positive integer).
  • EXAT timestamp-seconds: Sets a specific Unix timestamp for expiration (must be a positive integer).
  • NX: Sets the key only if it does not already exist.
  • XX: Sets the key only if it already exists.

Note: You can't use NX and XX together because they will conflict with each other. Also, you can use only one option for expiration (EX or PX) at a time.

To learn more about the SET command visit here to check out the Redis documentation page.


Example: SET Command Using the EX Option

When executing the following at your workbench, you will define a key with an expiration in Redis:

SET key value EX seconds

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the key that contains the string and value with the new value you would like to store. Replace seconds with the amount of time, in seconds, after which the key should expire.

For example: if you want to set your name value to "Yoshi", and you want it to expire after 7 seconds, run:

SET name carint EX 7

Enter fullscreen mode Exit fullscreen mode

This command updates the value of name to "Yoshi" and sets an expiration of 7 seconds from the time the command is executed.


Example: SET Command with NX and XX Options

You can set the key conditionally concerning its existence in Redis by using the options NX, which stands for Not eXists, and XX, which stands for eXists, in the SET command:

Using NX (Not eXists) Option:

SET key value NX

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the key you want to set and value with the value you want to store in the key. This command sets the value of key to value only if key does not already exist. If key already exists, the command will not perform any action.

Example:

If you want to set a new key username to "alice" only if username does not already exist, you would use:

SET username alice NX
Enter fullscreen mode Exit fullscreen mode

Using XX (eXists) Option:

SET key value XX

Enter fullscreen mode Exit fullscreen mode

This command sets the value of key to value only if key already exists. If key does not exist, the command will not perform any action.

Example:

If you want to update the value of an existing key username to "bob" only if username already exists, you would use:

SET username bob XX

Enter fullscreen mode Exit fullscreen mode

Lists vs. Sets

Lists

  • An ordered collection of strings.
  • Supports operations like adding elements to the head or tail, trimming based on ranges, etc.
  • Useful for maintaining ordered data structures.
  • Commands: RPUSH, LPUSH, LRANGE, LPOP, RPOP, etc.

Sets

  • An unordered collection of unique strings.
  • Supports operations like adding, removing, and checking membership.
  • Useful for storing unique items and performing set operations.
  • Commands: SADD, SREM, SMEMBERS, SISMEMBER, etc.

When deciding between lists and sets, consider the order requirements and the need for uniqueness in your data.


RPUSH: Adding Elements to the End of a List

To add one or more elements to the end of a list, use the RPUSH command. Here’s how to use it in your workbench:

RPUSH key element [element ...]

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the list, and element with the elements you want to add.

For example:

  1. Create a list named fruits and add elements to it:
RPUSH fruits apple banana cherry

Enter fullscreen mode Exit fullscreen mode

This will add "apple", "banana", and "cherry" to the end of the fruits list.


LPUSH: Adding Elements to the Beginning of a List

To add one or more elements to the beginning of a list, use the LPUSH command. Here’s how to use it in your workbench:

LPUSH key element [element ...]

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the list, and element with the elements you want to add.

For example:

  1. Add elements to the beginning of the fruits list:
LPUSH fruits mango orange

Enter fullscreen mode Exit fullscreen mode

This will add "mango" and "orange" to the beginning of the fruits list.


LRANGE: Retrieving Elements from a List

To retrieve a range of elements from a list, use the LRANGE command. Here’s how to use it in your workbench:

LRANGE key start stop

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the list, start with the starting index, and stop with the ending index.

For example:

  1. Retrieve elements from the fruits list:
LRANGE fruits 0 2

Enter fullscreen mode Exit fullscreen mode

This will return the first three elements: "mango", "orange", and "apple".


LPOP: Removing the First Element from a List

To remove and return the first element of a list, use the LPOP command. Here’s how to use it in your workbench:

LPOP key

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the list.

For example:

  1. Remove the first element from the fruits list:
LPOP fruits

Enter fullscreen mode Exit fullscreen mode

This will remove and return "orange".


RPOP: Removing the Last Element from a List

To remove and return the last element of a list, use the RPOP command. Here’s how to use it in your workbench:

RPOP key

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the list.

For example:

  1. Remove the last element from the fruits list:
RPOP fruits

Enter fullscreen mode Exit fullscreen mode

This will remove and return "cherry".


SADD: Adding Elements to a Set

To add one or more elements to a set, use the SADD command. Here’s how to use it in your workbench:

SADD key member [member ...]

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the set, and member with the elements you want to add.

For example:

  1. Create a set named colors and add elements to it:
SADD colors red green blue

Enter fullscreen mode Exit fullscreen mode

This will add "red", "green", and "blue" to the colors set.


SREM: Removing Elements from a Set

To remove one or more elements from a set, use the SREM command. Here’s how to use it in your workbench:

SREM key member [member ...]

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the set, and member with the elements you want to remove.

For example:

  1. Remove elements from the colors set:
SREM colors blue

Enter fullscreen mode Exit fullscreen mode

This will remove "blue" from the colors set.


SMEMBERS: Retrieving All Elements from a Set

To retrieve all the elements of a set, use the SMEMBERS command. Here’s how to use it in your workbench:

SMEMBERS key

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the set.

For example:

  1. Retrieve all elements from the colors set:
SMEMBERS colors

Enter fullscreen mode Exit fullscreen mode

This will return all elements in the colors set: "red" and “green”.


SISMEMBER: Checking if an Element Exists in a Set

To check if an element is a member of a set, use the SISMEMBER command. Here’s how to use it in your workbench:

SISMEMBER key member

Enter fullscreen mode Exit fullscreen mode

Replace key with the name of the set, and member with the element you want to check.

For example:

  1. Check if "red" is in the colors set:
SISMEMBER colors red

Enter fullscreen mode Exit fullscreen mode

This will return 1 if "red" is a member of the set, and 0 otherwise.


Hashes in Redis

In Redis, hashes are maps between string fields and string values. They are ideal for representing objects or entities with multiple attributes. Unlike sets or lists, which hold single values, hashes store key-value pairs where both the field and the value are strings.

Example: Using HSET Command for Hashes

The HSET command sets a field in the hash stored at key to a specified value. If the key does not exist, it creates an empty hash.

HSET key field value

Enter fullscreen mode Exit fullscreen mode
  • Replace key with the name of the hash.
  • Replace field with the attribute to change.
  • Replace value with the new value to assign.

Example: Setting Fields in a Hash

Create a hash user:1001 representing a user with attributes:

HSET user:1001 username alice email alice@example.com

Enter fullscreen mode Exit fullscreen mode

This command sets username to "alice" and email to "alice@example.com" in the hash user:1001.

Example: Using HGET Command for Hashes

The HGET command retrieves the value of a field from the hash stored at key.

HGET key field

Enter fullscreen mode Exit fullscreen mode
  • Replace key with the name of the hash.
  • Replace field with the specific field whose value you want to retrieve.

Example: Getting Fields from a Hash

To retrieve the username and email fields from the user:1001 hash:

HGET user:1001 username
HGET user:1001 email

Enter fullscreen mode Exit fullscreen mode

These commands will return "alice" and "alice@example.com" respectively.

Example: Using HDEL Command for Hashes

The HDEL command deletes one or more fields from the hash at key.

HDEL key field [field ...]

Enter fullscreen mode Exit fullscreen mode
  • Replace key with the name of the hash from which fields are removed.
  • Replace field with the field(s) to remove.

Example: Removing Fields from a Hash

To remove the email field from the user:1001 hash:

HDEL user:1001 email

Enter fullscreen mode Exit fullscreen mode

The email field will be removed from the user:1001 hash.

Conclusion

Redis has evolved significantly, positioning itself not just as a caching layer but as a primary database. It offers data persistence, replication for durability and availability, JSON support, and search modules for storing and querying complex data. Redis OM, an Object mapping library, simplifies usage. This series focuses on Redis's core capabilities.


This format organizes the content into sections with headings, subheadings, and clear examples, suitable for readability and reference in Notion.

Top comments (0)