0% found this document useful (0 votes)
25 views25 pages

PR 8 No SQL

The document provides an overview of Redis, including its architecture, data structures, and basic commands. Redis is an open-source in-memory database that follows a key-value model and supports various data structures like strings, hashes, lists, sets and sorted sets. It can be installed on Windows using WSL2 and configured through editing the configuration file or using third-party tools.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views25 pages

PR 8 No SQL

The document provides an overview of Redis, including its architecture, data structures, and basic commands. Redis is an open-source in-memory database that follows a key-value model and supports various data structures like strings, hashes, lists, sets and sorted sets. It can be installed on Windows using WSL2 and configured through editing the configuration file or using third-party tools.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction to NoSQL Enrollment No :

(4360704) 216010307044
PRACTICAL NO : 08

Aim: Redis Basics: Introduction and Key-Value Operations

OBJECTIVE

To provide a comprehensive understanding of Redis, covering its overview, key data


structures, real-world applications, essential commands, and advanced features, integrated with
diverse technologies. This approach ensures students acquire hands-on proficiency in
employing Redis for optimal data operations and exploring its broader utility in contemporary
tech ecosystems.

Prerequisite Theory

Overview of Redis

Redis is a NoSQL database which follows the principle of key-value store. The key-value
store provides ability to store some data called a value, inside a key. You can recieve this data
later only if you know the exact key used to store it.

Redis, an open-source (BSD licensed) in-memory data structure store, serves as a


versatile solution functioning as a database, cache, and message broker. Classified as a NoSQL
database, Redis offers the flexibility to store substantial volumes of data without the constraints
typically associated with relational databases.

Redis Architecture:

Redis follows a client-server architecture and is known for its simplicity and efficiency.
The key components in Redis architecture are the Redis client and the Redis server.

Redis Server : responsible for storing data and serving

Redis Console Client


Send & receive Data
Datastore

A.Y.DADA BHAI TECHNICAL Page 1


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
1. Redis Client:

- The Redis client is any application or program that interacts with the Redis server to
perform read and write operations.

- Clients can be written in various programming languages, and Redis provides official client
libraries for several languages, including Python, Java, Ruby, and more.

- Clients communicate with the Redis server using the Redis protocol, a lightweight binary
protocol optimized for performance.

2. Redis Server:

- The Redis server is the core component responsible for storing and managing data in-
memory.

- It operates as a daemon process, running independently on a server, and listens for client
connections on a specified port (default is 6379).

- The server manages various data structures, processes commands, and responds to client
requests.

- Redis can be configured to run in different modes, such as as a standalone instance, as a


master in a replication setup, or as a node in a clustered environment.

Key Characteristics of Redis Architecture:

- Redis stores all data in RAM, providing fast read and write operations. This makes it ideal
for use cases where low-latency access to data is crucial.

- Redis is single-threaded, meaning it processes one command at a time. While this may
seem like a limitation, it simplifies the design and allows for better predictability and
consistency.
While Redis is an in-memory database, it provides options for persistence. Data can be
periodically saved to disk or written to an append-only file, ensuring data durability
- Redis supports master-slave replication, allowing data to be replicated across multiple
nodes. This enhances data availability and provides fault tolerance.

- Redis can be horizontally scaled through partitioning, enabling large datasets to be


distributed across multiple nodes.

- Redis processes commands atomically, ensuring that operations either succeed


completely or fail, maintaining data consistency.

Redis data structures

Redis supports a variety of data structures, each designed to serve specific use cases. Here'san

A.Y.DADA BHAI TECHNICAL Page 2


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
overview of the main data structures supported by Redis:

1. Strings:

- Strings are the simplest and most basic data type in Redis. They can contain any kind of
data, such as text, binary data, or serialized objects.

- Redis provides various operations on strings, including set, get, append, increment,
decrement, and more.

2. Hashes:

- Hashes are maps between string field names and string values, so they are useful for
representing objects with multiple attributes.

- Hashes in Redis are particularly suitable for storing and retrieving objects with a small
number of fields.

3. Lists:

- Lists are collections of ordered elements, where each element can be any data type.

- Redis provides powerful operations on lists, such as push, pop, index-based access,
range retrieval, and blocking pop operations.

4. Sets:

- Sets are collections of unique elements with no specific order.

- Set operations include adding, removing, and checking for the existence of members.
Redis also supports set operations like union, intersection, and difference between sets.

5. Sorted Sets:

- Sorted sets are similar to sets, but each element in a sorted set is associated with a score.

- Elements in a sorted set are kept sorted based on their scores, allowing for efficient range
queries and ranking of elements.

Redis features efficient Bitmaps for binary flag representation, HyperLogLogs for estimating
unique element cardinality with minimal memory usage, and Geospatial Indexes for location-
based storage and retrieval. These data structures, coupled with Redis's in-memory storage
and atomic operations, make it a powerful tool for applications like caching, real-time
analytics, and messaging systems. Understanding the distinct characteristics of each data
structure is vital for maximizing Redis's effectiveness in various scenarios.

A.Y.DADA BHAI TECHNICAL Page 3


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
Redis isn't officially supported on Windows itself, but you can install it on Windows 10 (version
2004 or later) and Windows 11 using the Windows Subsystem for Linux (WSL2). Here's a step-
by-step guide:

1. Enable WSL2:

 Open PowerShell as Administrator.


 Run the following command to enable WSL2:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

 Restart your machine after running this command.

2. Start and Connect to Redis:

 Start the Redis server:

sudo service redis-server

start

 Verify the installation by connecting to the Redis server from the

terminal: redis-cli

 You should see a redis> prompt, indicating a successful connection.

3. Additional Tips:

 To stop the Redis

server: sudo service redis-

server stop Redis -

Configuration

While Redis itself doesn't have an official Windows configuration tool, there are two main
approaches for configuring Redis on Windows machines:

1. Using WSL2 (Windows Subsystem for Linux):

If you followed the steps to install Redis using WSL2, configuration involves editing the
configuration file within the Linux environment. Here's how:

A.Y.DADA BHAI TECHNICAL Page 4


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
 Locate the configuration file: The default location for the Redis configuration file on
WSL2 is typically /etc/redis/redis.conf.
 Edit the file: Use a text editor like nano or vim within the Linux terminal to modify the
configuration options.

A.Y.DADA BHAI TECHNICAL Page 5


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
 Common configurations: Some common configuration options you might adjust
include:
o port: The port on which Redis listens for connections (default: 6379).
o bind: IP address to bind the server to (default: 127.0.0.1 for localhost).
o maxmemory: Maximum memory allocated for storing data.
o loglevel: Verbosity level for logging information.
 Restart the service: After making changes, save the file and restart the Redis server
using the command:

sudo service redis-server restart

2. Using Third-Party Tools (Unofficial):

There are some third-party tools that attempt to provide a Windows interface for managing
Redis, but keep in mind these are not officially supported by Redis. Proceed with caution and
research the specific tool before using it.

Here are some alternatives to consider:

 Redis Desktop Manager (third-party tool)


 Chocolatey package manager (might offer Redis packages with configuration options)

Basic commands and operations

Redis commands are used to perform some operations on Redis server.

To run commands on Redis server, you need a Redis client. Redis client is available in Redis
package, which we have installed earlier.

Redis provides a rich set of commands and operations to interact with its various data
structures. Here are some basic Redis commands and operations:

1. Key-Value Operations:

Indeed, these key-value operations are fundamental to working with Redis. Let's delve into
these commands:

1. SET key value:

- This command sets the value associated with a given key. If the key already exists, it
updates the existing value; otherwise, it creates a new key-value pair.

2. GET key:
- Used to retrieve the value associated with a specific key. It is a fundamental readoperation
in Redis.

GET mykey
A.Y.DADA BHAI TECHNICAL INSTITUDE Page 5
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
This would return `"Hello, Redis!"` if the previous SET command was executed.

3. DEL key:

- Deletes a key and its associated value from the Redis database.

After executing this command, the key "mykey" and its value will be removed from the
database.
These key-value operations form the basis for many Redis use cases, allowing efficient
storage and retrieval of data. They are commonly used for caching, session management, and
various other scenarios where quick and direct access to data is essential.

2. STRING OPERATIONS:

Certainly, let's delve into these string operations in Redis:

1. APPEND key value:

- This command appends the specified value to the existing value of a key. If the key
doesnot exist, a new key is created with the provided value.

SET mystring "Hello"

After executing these commands, the value of the key "mystring" would be "Hello, Redis!".

2. STRLEN key:

- Retrieves the length of the string value stored at the specified key.

This would return the length of the string in the key "mystring".
3. INCR key / DECR key:

- INCR increments the integer value stored at the specified key by 1, while DECR
decrements it by 1. If the key does not exist, a new key is created with the value set to 1.

After these commands, the value of "mycounter" would be 11.


Subsequently, the value of "mycounter" would be 10 again.
DECR mycounter
These string operations are useful for manipulating and analyzing text-based data as wellas
managing counters or numerical values in Redis.

A.Y.DADA BHAI TECHNICAL Page 6


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
3. HASH OPERATIONS:

Certainly, let's explore these hash operations in Redis:

1. HSET key field value:


- Sets the value of a field within a hash. If the hash does not exist, a new hash is createdwith
the specified key.

This command sets the username field to "john_doe" within the hash associated with
the key "user:1001".
2. HGET key field:

- Retrieves the value of a specified field within a hash.

This command would return the value "john_doe" associated with the username field in
HGET user:1001 username
the hash.

3. HGETALL key:

- Retrieves all fields and their corresponding values in a hash.

This command returns a list of field-value pairs for the hash associated with the key
"user:1001".

These hash operations are particularly useful for representing and managing structured data
within Redis. Hashes can be employed to store and retrieve information related to entities,
making them a valuable choice for scenarios where data needs to be organizedinto fields and
subfields.

4. LIST OPERATIONS:

Certainly, let's explore these list operations in Redis:

1. LPUSH key value1 value2 ...:

- Inserts one or more values at the beginning of a list.

This command inserts the values "apple," "banana," and "cherry" at the beginning of the
list associated with the key "mylist."

2. RPUSH key value1 value2 ...:

A.Y.DADA BHAI TECHNICAL Page 7


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
- Inserts one or more values at the end of a list.

This command appends the values "date" and "fig" to the end of the list associated
with the key "mylist."

3. LRANGE key start stop:


- Retrieves a range of elements from a list. The range is specified by the start and stop
indices.
This command retrieves all elements from the list associated with the key "mylist."
LRANGE mylist 0 -1
These list operations in Redis are beneficial for scenarios where data needs to be stored in an
ordered sequence. Lists are commonly used for implementing queues, managing job queues,
and storing logs where the order of events is crucial. The ability to insert and
retrieveelements from both ends of the list makes Redis lists versatile for various use cases.

5. Set Operations:

1. SADD key member1 member2 ...:

- Adds one or more members to a set. If the set does not exist, a new set is created.

This command adds the members "apple," "banana," and "orange" to the set associated
with the key "myset."

2. SMEMBERS key:

- Retrieves all members of a set.

This command returns all members of the set associated with the key "myset."
3. SINTER key1 key2 ...:

- Retrieves the intersection of multiple sets.

SINTER set1 set2


In this example, the last command returns the members "banana" and "orange," which
are common to both sets.

A.Y.DADA BHAI TECHNICAL Page 8


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
Redis sets are useful for scenarios where you need to represent a collection of unique
elements. Set operations like union, intersection, and difference provide powerful tools for
analyzing and manipulating sets in various applications.

6. Sorted Set Operations:

Certainly, let's explore these sorted set operations in Redis:

1. ZADD key score1 member1 score2 member2 ...:


- Adds members with associated scores to a sorted set. If a member already exists, itsscore
is updated.

This command adds players to the "highscores" sorted set with corresponding scores.
2. ZRANGE key start stop:

- Retrieves a range of elements from a sorted set based on their scores.

This command retrieves all members and their scores from the "highscores" sorted set.
ZRANGE highscores 0 -1 WITHSCORES
Sorted sets in Redis are particularly useful when you need to maintain a ranking or
leaderboard based on scores. These operations allow you to efficiently retrieve and update
elements based on their scores, making sorted sets suitable for scenarios such as gaming
leaderboards or any application involving ordered data.

7. Bitwise Operations (Bitmaps):

Certainly, let's explore these bitwise operations with bitmaps in Redis:

1. SETBIT key offset value:

- Sets or clears the bit at a specified offset in the string value stored at a key. The value
canbe 0 or 1.
This command sets the bit at offset 5 in the bitmap associated with the key
SETBIT mybitmap 5 1
"mybitmap" to 1.

2. GETBIT key offset:

- Retrieves the bit value at a specified offset in the string value stored at a key.

This command returns the bit value at offset 5 in the bitmap associated with the key
GETBIT mybitmap 5
"mybitmap."

A.Y.DADA BHAI TECHNICAL Page 9


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
Bitwise operations in Redis are often used for scenarios where you need to efficiently
represent and manipulate sets of binary flags or indicators. Bitmaps can be employed for
tasks such as tracking user preferences, monitoring system states, or implementing compact
data structures that rely on binary representation.

8. Pub/Sub (Publish/Subscribe):

Certainly, let's explore these Pub/Sub operations in Redis:

1. PUBLISH channel message:

- Publishes a message to a specified channel. Any clients subscribed to that channel will
receive the message.

This command publishes the message "Breaking News: Redis 7.0 Released!" to the
"news_channel."
2. SUBSCRIBE channel:

- Subscribes the client to the specified channel. The client will receive messages publishedto
that channel.

This command subscribes the client to the "news_channel," allowing it to receive


messages published to that channel.
Redis Pub/Sub is commonly used for building real-time messaging systems, chat applications,
and event notification systems. Publishers broadcast messages to specific channels, and
subscribers receive messages from channels they are interested in, facilitating efficient
communication between different parts of an application.

9. Transactions:

Certainly, let's explore these transaction-related commands in Redis:

1. MULTI:

- Marks the start of a transaction block. Subsequent commands are queued up for
executionas part of the transaction.

MULTI

This command initiates a transaction block, and the subsequent SET commands will be
executed atomically.

A.Y.DADA BHAI TECHNICAL Page 10


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
2. EXEC:

- Executes all previously queued commands in a transaction. If the transaction is


successful, the changes are committed; otherwise, they are rolled back.

This command executes the queued commands within the transaction block. If
EXEC
successful, the changes are committed.
3. DISCARD:

- Discards all commands in the current transaction, effectively canceling the transaction.

DISCARD
This command discards all commands queued in the current transaction block, undoing
any changes made so far.

These transaction commands in Redis provide a way to group multiple commands into a
single atomic operation. This ensures that either all commands in the transaction are
executed, or none of them are, maintaining data consistency. Transactions are particularly
useful in scenarios where it's crucial to perform a series of operations atomically.

10. Key Expiry:

Certainly, let's explore these commands related to key expiration in Redis:

1. EXPIRE key seconds:

- Sets the time to live (TTL) of a key, indicating how long the key should be retained beforeit
is automatically deleted.

This command sets the key "mykey" to expire in 60 seconds. After this time elapses, the
key will be automatically removed from the database.
2. TTL key:

- Retrieves the remaining time to live of a key in seconds.

This command returns the remaining time to live of the key "mykey." If the key is
persistent (does not have a set expiration), TTL returns -1. If the key does not exist or has
expired, TTL returns -2.

These commands are valuable for managing the lifecycle of keys in Redis. Setting an
expiration time is useful for scenarios such as caching, where you want to automatically

A.Y.DADA BHAI TECHNICAL Page 11


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
refresh data after a certain period. The TTL command provides a convenient way to check the
remaining time before a key expires.

These are just a few examples, and Redis provides a comprehensive set of commands to
perform a wide range of operations on different data structures. Understanding these basic
commands is essential for effectively working with Redis in various applications.

Advanced features of Redis

Redis offers several advanced features that contribute to its versatility and wide range of use
cases. Here are some notable advanced features of Redis:

1. Persistence:

- Redis supports different mechanisms for persistence, allowing data to be saved to disk.
This ensures that data is not lost when Redis is restarted. Options include RDB snapshots and
AOF (Append-Only File) logs.

2. Replication:
- Redis supports master-slave replication, allowing data to be asynchronously replicated
from one Redis server (master) to one or more Redis servers (slaves). This provides data
redundancy, high availability, and scalability.

3. Partitioning:

- Redis allows horizontal scaling through partitioning, where data is distributed across
multiple Redis instances. This helps handle large datasets and improves performance by
leveraging the capabilities of multiple servers.

4. Lua Scripting:

- Redis supports Lua scripting, allowing users to write custom scripts that can be executed
on the server. This feature enables complex operations and transactions to be executed
atomically on the server side.

5. Transactions:

- Redis supports transactions using the MULTI, EXEC, and DISCARD commands. Multiple
commands can be grouped together in a transaction, ensuring they are executed atomically.
This helps maintain data consistency.

6. Keyspace Notifications:

- Redis provides the ability to subscribe to notifications for specific keyspace events. Clients
can be notified when certain events, such as key expirations or modifications, occur in the
Redis dataset.

A.Y.DADA BHAI TECHNICAL Page 12


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
7. Bitmap Operations:

- Redis supports advanced bitmap operations, allowing efficient manipulation of sets of bits.
This is useful for scenarios such as tracking user behavior, handling flags, and implementing
efficient data structures.

8. HyperLogLogs:

- HyperLogLogs provide approximate cardinality estimation for sets of unique elements


with minimal memory usage. This feature is useful for counting distinct items in large
datasets with reduced memory requirements.

9. Geospatial Indexing:

- Redis supports geospatial data types and provides commands for storing, querying, and
manipulating data based on geographic location. This is valuable for location-based services
and applications.

10. Cluster Mode:

- Redis Cluster is a distributed implementation of Redis that provides high availability and
horizontal scaling. It divides the dataset into multiple partitions across nodes, ensuring data is
distributed and replicated for fault tolerance.
11. Security Features:

- Redis supports authentication through passwords and provides access control


mechanisms to restrict client access based on IP addresses. This helps enhance the securityof
Redis deployments.

These advanced features contribute to Redis's appeal in various use cases, including real-
time analytics, caching, messaging systems, and more. Understanding and leveraging these
features allows developers and system administrators to optimize Redis for specific
requirements and achieve better performance and reliability.

Example-: Log In Throttling

Related Command: INCRBY, EXPIRE, TTL

Authentication has many interesting use cases, one of which is preventing users from hacking
other users through brute force attacks. One of the easiest ways to achieve this is by
implementing throttling. Throttling refers to the practice of intentionally limiting the rate or
speed of a process or service. You might have seen messages such:

“There have been too many login failures. Try again in x seconds”

This is an implementation of throttling for login attempts to prevent brute force attacks. In a
simple manner, throttling involves storing the number of login attempts made by a user.

A.Y.DADA BHAI TECHNICAL Page 13


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
However, storing this data in databases like MySQL or PostgreSQL may seem overly
engineering. Additionally, databases like MySQL and PostgreSQL do not have built-in time-
based expiration, unlike Redis. Using Redis to implement throttling is a straightforward
solution. Please refer to the system design below:

var guest_session = context.GuestSession


var max_attempt = 5

seconds`)

if(!is_login_success) {

A.Y.DADA BHAI TECHNICAL Page 14


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044

return null, errors("user not found / invalid password")

return auth_token, null

Example-4: Dynamic Pricing in Hotel Industry (Redis Distributed Locking)

Related Command: GET, SET NX EX

When working with horizontal scaling or even microservices, it becomes necessary to


implement distributed locking at the application level to address issues such as race
conditions or thundering herd problems. Redis can be leveraged for distributed locking,
offering several advantages including high scalability, fault tolerance, and strong consistency
guarantees.

Consider a scenario where you are developing a hotel booking platform that fetches dynamic
prices from a third-party API. In a situation where multiple users are requesting hotel
information for the same date, you may want to avoid overwhelming the third-party API.
Here, you can utilize Redis distributed locking to resolve this issue effectively.

A.Y.DADA BHAI TECHNICAL Page 15


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044

var price_detail = null

if(price_detail != null){
break

var current_machine_name = os.GetHostname()


{current_machine_name} NX EX 5`) if(!acquire_lock){
sleep(250) // waiting 250 ms

A.Y.DADA BHAI TECHNICAL Page 16


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
continue

price_detail = getHotelPriceFromThirdParty(hotel_id, booking_at)

break

Example-: OTP (One Time Password) using Redis

Related Command: SET NX EX, GET, DEL

"OTP" stands for "One-Time Password." It is a security measure used to authenticate usersand
verify their identity during online transactions or account logins. A one-time password is a
unique and temporary code that is typically valid for a short period of time, usually for a
single login session or transaction. Since Redis has time-based expiration using the
EXPIRE command, it is well-suited for building an OTP (One-Time Password) system.

The OTP system consists of two functions:

 Generate OTP
 Verify OTP

A.Y.DADA BHAI TECHNICAL Page 17


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044

Redis can be leveraged to build an OTP system. Below is pseudocode that demonstrateshow
Redis can be used to develop an OTP system:

A.Y.DADA BHAI TECHNICAL Page 18


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044

Example-: Waiting List in Help Desk System (Redis for Job Queue)

Related Commands: LPUSH, RPOPLPUSH, LREM, LPOS

A help desk is a system designed to manage and streamline customer support and issue
resolution processes within an organization. When the number of support request much
bigger than the number of customer support it will generate a problem.

Imagine you only have 3 customer support officer and at one time there are 100 request to
have chat support, how to solve it?

It’s a common where help desk system has waiting list mechanism. In technical, waiting list is
similar to JOB QUEUE in data structure. Redis has a powerfull command to solve job queue
problems. In a help desk system, there are at least two functions:

 Create Request (by User)


 Handle Support Request (by Customer Support)

A.Y.DADA BHAI TECHNICAL Page 19


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044

redis.Do(`LPUSH helpdesk {request_id}`)

// Notes: "RANK -1" means you reverse the sort

while (true) {

if(request_id == null) {

A.Y.DADA BHAI TECHNICAL Page 20


INSTITUDE
Introduction to NoSQL Enrollment No :
(4360704) 216010307044
Multiple-Choice Questions (MCQs):
(1) Which data structure in Redis is suitable for storing and retrieving objects with
multiple attributes?
(a) Strings (b)Hashes
(c) Lists (d)Sets
Ans:
2. What is the primary role of the Redis client in the client-server architecture?
(a) Storing and managing data (b) Executing Lua scripts
(c)Interacting with the Redis server (d) Handling key expiration
Ans:
3. Which Redis command is used to add members to a set?
(a) HSET (b)LPUSH
(c)SADD (d) ZADD
Ans:
4. What does the `PUBLISH` command do in Redis?
(a) Adds elements to a list (b)Publishes a message to a
channel (c)Sets the time to live for a key (d)Retrieves all members of a set

5. Which advanced feature in Redis provides approximate cardinality estimation for sets
of unique elements?
(a)Bitmap Operations (b)
HyperLogLogs (c)Geospatial Indexing
(d)Transactions
Ans:

6. In Redis, what does the `EXPIRE` command do?


(a) Increments the value of a key (b)Sets the time to live for a key
(c) Retrieves the length of a string (d) Retrieves all fields and values in a
hash Ans:

7. Which data structure is suitable for ordered data retrieval based on scores in Redis?
(a) Sets (b) Lists (c) Sorted Sets (d) Hashes
Ans:
8. What is the primary advantage of using Redis for caching?
(a) Unlimited storage capacity (b) Low-latency Access to data
(c) Support for complex queries (d) Automatic data indexing
Ans:

True/False Statements:

1. Redis is a relational database system.


2. Redis supports horizontal scaling through partitioning.
3. The `RPUSH` command is used to insert values at the beginning of a list in Redis.
4. HyperLogLogs in Redis provide precise cardinality estimation for sets of unique elements.
5. Redis allows the execution of multiple commands atomically using transactions.

P a g e 21
Introduction to NoSQL (4360704) Enrollment No : 216010307044

Write redis queries for following


1. Using only Redis commands, demonstrate how you can create a new key named
"counter" and set its value to 100, but only if the key doesn't already exist. If the key exists,
increment its value by 10.
2. Write a Redis query to append the string ", Redis is powerful!" to the existing value of the
key "description" only if the length of the current value is less than 50 characters.
3. Suppose you have a hash named "user:101" representing a user profile. Add a new field
"age" with a value of 25, but only if the field doesn't exist. If the field exists, increment its
value by 1.
4. Create a list named "logs" and insert the values "log_entry_1," "log_entry_2," and
"log_entry_3" at the beginning of the list. After that, trim the list to keep only the first two
elements.
5. Implement a scenario where you have two sets, "setA" and "setB." Write a query to add
the elements present in both sets to a new set named "common_elements."
6. Create a key "temporary_data" with a value "sensitive_info" and set it to expire in 60
seconds. Write a query to retrieve the value of the key and check its time to live after 70
seconds.

Here are the Redis queries for each of the requested tasks:

(1) Create a new key named "counter" and set its value to 100, but only if the key
doesn't already exist. If the key exists, increment its value by 10:

SETNX counter 100


IF (GET counter != 100) {
INCRBY counter 10
}

(Note: The above logic should be implemented in a script or within a Redis client that
supports conditional logic, as Redis itself doesn't directly support IF statements.)

Alternatively, using Lua script within Redis for atomic operation:

EVAL "if redis.call('exists', KEYS[1]) == 0 then return redis.call('set', KEYS[1], ARGV[1])


else return redis.call('incrby', KEYS[1], ARGV[2]) end" 1 counter 100 10

(2) Append the string ", Redis is powerful!" to the existing value of the key
"description" only if the length of the current value is less than 50 characters:

EVAL "if string.len(redis.call('get', KEYS[1])) < 50 then return redis.call('append', KEYS[1],


ARGV[1]) else return 0 end" 1 description ", Redis is powerful!"

(3) Add a new field "age" with a value of 25 to a hash named "user:101", but only if
the field doesn't exist. If the field exists, increment its value by 1:

HSETNX user:101 age 25


HINCRBY user:101 age 1

A Y Dadabhai Technical Institute, Page 22


Introduction to NoSQL (4360704) Enrollment No : 216010307044

(4) Create a list named "logs" and insert the values "log_entry_1," "log_entry_2," and
"log_entry_3" at the beginning of the list. Then trim the list to keep only the first two
elements:

LPUSH logs log_entry_3 log_entry_2 log_entry_1


LTRIM logs 0 1

(5) Add the elements present in both sets "setA" and "setB" to a new set named
"common_elements":

SINTERSTORE common_elements setA setB

(6)Create a key "temporary_data" with a value "sensitive_info" and set it to expire in


60 seconds. Retrieve the value of the key and check its time to live after 70 seconds:

SET temporary_data sensitive_info EX 60


GET temporary_data
TTL temporary_data

After 70 seconds, the TTL should show -2 (key does not exist) if the key has expired.

To check TTL after 70 seconds:

GET temporary_data
TTL temporary_data

(Note: After waiting for 70 seconds, the TTL will typically return -2, indicating that the key
has expired and is no longer available.)

A Y Dadabhai Technical Institute, Page 23


Introduction to NoSQL (4360704) Enrollment No : 216010307044

ASSESSMENT RUBRICS

Needs
Criteria Excellent (10) Good (7) Satisfactory
Improvement Marks
(5)
(3)
Demonstrates a Demonstrates a Struggles to
Understanding profound Shows a strong
basic grasp the
of Redis understanding understanding understanding fundamental
Overview of Redis
of Redis of Redis concepts of
overview
overview overview Redis overview
Struggles to
Knowledge of Displays an Shows a solid Demonstrates a comprehend
Redis Data excellent graspof understanding basic Redis data
Structures Redis data of Redis data understanding structures or
structures structures of Redis data
makes significant
structures
errors
Carries out Struggles to
Proficiency in Executes basic Performs basic
basic commands execute basic
Basic Redis commands and and operations commands and
Commands commands and operations with
but with some operations or
and operations with competence
errors makes significant
Operations precision
errors
Struggles to
Understanding Demonstrates a Shows a strong Demonstrates a grasp the
of Advanced profound understanding basic fundamental
Redis Features understanding of advanced understanding concepts of
of advanced Redis features of advanced
advanced Redis
Redis features Redis features
features
Average Marks

----------------
Signature with date

A Y Dadabhai Technical Institute, Page 24

You might also like