PR 8 No SQL
PR 8 No SQL
(4360704) 216010307044
PRACTICAL NO : 08
OBJECTIVE
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 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.
- 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 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 supports a variety of data structures, each designed to serve specific use cases. Here'san
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:
- 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.
1. Enable WSL2:
start
terminal: redis-cli
3. Additional Tips:
Configuration
While Redis itself doesn't have an official Windows configuration tool, there are two main
approaches for configuring Redis on Windows machines:
If you followed the steps to install Redis using WSL2, configuration involves editing the
configuration file within the Linux environment. Here's how:
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.
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:
- 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:
- 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.
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.
This command sets the username field to "john_doe" within the hash associated with
the key "user:1001".
2. HGET key field:
This command would return the value "john_doe" associated with the username field in
HGET user:1001 username
the hash.
3. HGETALL key:
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:
This command inserts the values "apple," "banana," and "cherry" at the beginning of the
list associated with the key "mylist."
This command appends the values "date" and "fig" to the end of the list associated
with the key "mylist."
5. Set Operations:
- 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:
This command returns all members of the set associated with the key "myset."
3. SINTER key1 key2 ...:
This command adds players to the "highscores" sorted set with corresponding scores.
2. ZRANGE key start stop:
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.
- 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.
- 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."
8. Pub/Sub (Publish/Subscribe):
- 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.
9. Transactions:
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.
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.
- 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:
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
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.
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.
- 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:
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.
- 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:
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.
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.
seconds`)
if(!is_login_success) {
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.
if(price_detail != null){
break
break
"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.
Generate OTP
Verify OTP
Redis can be leveraged to build an OTP system. Below is pseudocode that demonstrateshow
Redis can be used to develop an OTP system:
Example-: Waiting List in Help Desk System (Redis for Job Queue)
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:
while (true) {
if(request_id == null) {
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:
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:
P a g e 21
Introduction to NoSQL (4360704) Enrollment No : 216010307044
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:
(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.)
(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:
(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:
(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:
(5) Add the elements present in both sets "setA" and "setB" to a new set named
"common_elements":
After 70 seconds, the TTL should show -2 (key does not exist) if the key has expired.
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.)
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