No-SQL Unit 3 & 4: Practice Questions
NoSQL Practice Questions PDF -> Generated and Prepared By Thiruselvan (ThiruXD)
1. Define a key-value store. Explain with two real-world examples.
Answer:
A key-value store is a type of NoSQL database that stores data as simple key-value pairs. Each key is unique and is used to retrieve the associated value. It is highly scalable, fast, and works well for simple lookups.
How It Works:
| Key | Value |
|---|---|
user:101 | { "name": "Ananya", "age": 25 } |
product:200 | { "name": "Laptop", "price": 55000 } |
session:abc | "token_9382xyz" |
cart:500 | [ "item1", "item2", "item3" ] |
Real-World Examples:
1. E-commerce — Shopping Cart: Key-value stores are often used to store shopping cart data for each user. The user ID can be the key, and the cart items can be the value.
Key: cart:user123
Value: ["item1", "item2", "item3"]2. Caching — User Sessions: Key-value stores are widely used for caching user session data in web applications. The session ID is the key and the session information is the value.
Key: session:abc123
Value: { "user_id": 101, "status": "active" }Advantages:
- Simple model
- High performance (fast reads/writes)
- Scalable
- Flexible (values can be any data type)
- Simple O(1) lookups
2. What is CQL? Write basic commands to create a keyspace and table.
Answer:
CQL (Cassandra Query Language) is the query language used to interact with Apache Cassandra. It is similar to SQL, but designed for distributed, scalable, NoSQL data storage. CQL allows us to define the data structure (keyspaces, tables) and perform operations like insert, select, update, and delete.
CQL vs SQL (Quick Comparison):
| CQL (Cassandra) | SQL (Relational DB) |
|---|---|
| Keyspace | Database |
| Table | Table |
| PRIMARY KEY | Primary Key |
| Designed for distributed systems | Designed for single server |
| No JOINs | Supports JOINs |
| Eventual consistency | Strong consistency |
Basic CQL Commands:
a) Create a Keyspace:
CREATE KEYSPACE university
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 3
};- Keyspace name:
university - Replication strategy:
SimpleStrategy - Replication factor: 3 (number of copies stored across nodes)
b) Use a Keyspace:
USE university;c) Create a Table:
CREATE TABLE students (
student_id int,
name text,
department text,
age int,
PRIMARY KEY (student_id)
);- Table name:
students student_idis the primary key (which uniquely identifies each row)
d) Insert Data:
INSERT INTO students (student_id, name, department, age)
VALUES (1, 'Ananya', 'CSE', 20);e) Query Data:
SELECT * FROM students;
SELECT * FROM students WHERE student_id = 1;f) Verify the Creation:
DESCRIBE KEYSPACES;
DESCRIBE TABLES;
DESCRIBE TABLE students;Tip: Always create a keyspace first and then create tables inside it.
3. List and explain any five Redis core data structures.
Answer:
Redis supports multiple data structures beyond simple strings. The five core data structures are:
1. String
A simple key-value pair where the value is a string (text, number, or binary data).
SET user:101 "Ananya"
GET user:101 # Returns "Ananya"
INCR counter # Increase by 1
DECR counter # Decrease by 1Use Case: Store user names, configuration settings, counters.
2. List
An ordered collection of string elements that allows insertion and removal from both ends (like a queue or stack).
Left ← [A] [B] [C] [D] → RightLPUSH notifications "msg1" # Add to left
LPUSH notifications "msg2"
RPUSH notifications "msg3" # Add to right
LRANGE notifications 0 -1 # Get all
# Returns ["msg2", "msg1", "msg3"]
LPOP notifications # Remove from left
RPOP notifications # Remove from rightUse Case: Maintain recent activity logs, message queues, notification lists.
3. Set
An unordered collection of unique string elements (no duplicate values).
A
B CSADD tags "redis"
SADD tags "nosql"
SADD tags "database"
SMEMBERS tags # Returns all
# ["redis", "nosql", "database"]
SISMEMBER tags "redis" # Check membership
SINTER tags otherSet # IntersectionUse Case: Store unique items such as tags, user IDs, or followers.
4. Hash
A collection of field-value pairs (like a dictionary or map) suitable for storing objects.
Key: user:101
┌──────────┬──────────────────┐
│ Field │ Value │
├──────────┼──────────────────┤
│ name │ Ananya │
│ age │ 25 │
│ email │ ananya@gcu.edu │
│ role │ faculty │
└──────────┴──────────────────┘HSET user:101 name "Ananya"
HSET user:101 age 25
HGET user:101 name # Returns "Ananya"
HGETALL user:101 # Get all fields
HINCRBY user:101 age 1 # Increment numeric fieldUse Case: Store user profiles, product details, or application settings.
5. Sorted Set (ZSet)
A collection of unique elements, each with an associated score. Elements are automatically ordered by their score.
┌─────────┬───────┐
│ Member │ Score │
├─────────┼───────┤
│ Charlie │ 60 │
│ Bob │ 80 │
│ Alice │ 100 │
└─────────┴───────┘ZADD leaderboard 100 "Alice"
ZADD leaderboard 80 "Bob"
ZADD leaderboard 60 "Charlie"
ZRANGE leaderboard 0 -1 WITHSCORES
# Returns ["Charlie", 60, "Bob", 80, "Alice", 100]
ZREVRANGE leaderboard 0 -1 # Descending order
ZSCORE leaderboard "Alice" # Get scoreUse Case: Leaderboards, rankings, priority queues, or scheduling.
Bonus — Stream: An append-only log-like structure for events (XADD, XREAD, XRANGE).
4. Define graph database. Explain nodes, relationships and properties with an example.
Answer:
A graph database is a type of NoSQL database that stores and represents data as a graph, using nodes, relationships, and properties. It is designed to efficiently manage and query highly connected data, where the relationships between entities are as important as the entities themselves.
Core Components:
Nodes
- Represent an entity or object in the database
- Can have a label (type) and properties
- Examples: Person, Product, Company, City, Movie
Relationships
- Represent a connection between two nodes
- Usually directed and has a type
- Can also have properties
- Examples: FRIEND_OF, WORKS_AT, LIKES, PURCHASED, LIVES_IN
Properties
- Key-value pairs that store additional information about nodes or relationships
- Both nodes and relationships can have properties
- Examples:
(name: "Alice", age: 25),(since: 2020)
Example — Social Network:
Person Node (Alice) Person Node (Bob)
Properties: Properties:
name: "Alice" name: "Bob"
age: 25 age: 27
city: "Bangalore" city: "Mumbai"
│ │
│ FRIEND_OF (since: 2020) │
└────────────────────────────────┘
│ │
│ LIVES_IN │ WORKS_AT
↓ ↓
City Node (Bangalore) Company Node (ABC Corp)
Properties: Properties:
name: "Bangalore" name: "ABC Corp"
country: "India" industry: "IT"
location: "Bangalore"In Simple Terms:
Nodes = Things
Relationships = Connections
Properties = Details about things/connectionsWhy Graph Databases:
- Relationships are first-class citizens
- Fast traversal of connected data
- Flexible schema
- Ideal for social networks, recommendations, fraud detection
5. What is meant by schema flexibility in NoSQL databases? Explain its importance with a suitable example.
Answer:
Schema flexibility means that a NoSQL database does not require a fixed, predefined schema. Data can be stored without first defining all fields, and different records can have different structures. The schema can evolve over time without requiring migrations.
Importance of Schema Flexibility:
| # | Importance | Explanation |
|---|---|---|
| 1 | Rapid Development | Start storing data without designing a full schema |
| 2 | Evolving Data | Add new fields without altering existing records |
| 3 | Heterogeneous Data | Store different structures in the same collection |
| 4 | No Migrations | Avoid expensive ALTER TABLE operations |
| 5 | Agile Adaptation | Respond quickly to changing business requirements |
Suitable Example — Product Catalog:
In an e-commerce application, different products have different attributes:
Relational Database (Fixed Schema):
| id | name | price | size | color | author | ISBN |
|---|---|---|---|---|---|---|
| 1 | T-Shirt | 500 | M | Red | NULL | NULL |
| 2 | Laptop | 55000 | NULL | NULL | NULL | NULL |
| 3 | Book | 300 | NULL | NULL | R. Sharma | 978-… |
Problem: Many NULLs; adding new attributes requires schema changes.
NoSQL Document Store (Flexible Schema):
// Product 1 - Clothing
{ "id": 1, "name": "T-Shirt", "price": 500, "size": "M", "color": "Red" }
// Product 2 - Electronics
{ "id": 2, "name": "Laptop", "price": 55000, "ram": "16GB", "storage": "512GB" }
// Product 3 - Book
{ "id": 3, "name": "Book", "price": 300, "author": "R. Sharma", "isbn": "978-..." }Each document has its own structure. No NULLs. New attributes can be added anytime.
Graph Database (Flexible Schema):
In a graph database, nodes can have different labels and properties without a fixed schema:
:Person {name: "Alice", age: 25}
:Person {name: "Bob", age: 27, city: "Mumbai", hobbies: ["reading", "cycling"]}
:Company {name: "ABC Corp", industry: "IT", founded: 2010}Conclusion: Schema flexibility is a key advantage of NoSQL databases, enabling rapid development, easy evolution, and handling of diverse data without costly migrations.
6. Write Redis commands to create a key, read it, set expiry and check TTL.
Answer:
1. Create a Key (SET):
SET username "Ananya"
# 127.0.0.1:6379> SET username "Ananya"
# OKIf the key already exists, SET will update its value.
2. Read a Key (GET):
GET username
# 127.0.0.1:6379> GET username
# "Ananya"Returns the value stored at the key. If the key does not exist, returns (nil).
3. Set Expiry (EXPIRE):
EXPIRE username 60
# 127.0.0.1:6379> EXPIRE username 60
# (integer) 1The key will be automatically deleted after the specified time (in this case, 60 seconds).
4. Check TTL (TTL):
TTL username
# 127.0.0.1:6379> TTL username
# (integer) 42Returns the remaining time in seconds.
1: key exists but has no expiry2: key does not exist
5. Set with Expiry in One Command (SETEX):
SETEX session:abc 3600 "token_xyz"6. Remove Expiry (PERSIST):
PERSIST username7. Delete Key (DEL):
DEL usernameCommon Key Commands Summary:
| Command | Purpose |
|---|---|
SET key value | Create/update key |
GET key | Retrieve value |
DEL key | Delete key |
EXISTS key | Check existence |
EXPIRE key seconds | Set TTL |
TTL key | Check remaining TTL |
PERSIST key | Remove TTL |
SETEX key seconds value | Set with TTL |
Use Cases: Session management, cache entries, rate limiting, temporary tokens, distributed locks.
7. Differentiate between relational databases and graph databases.
Answer:
| Aspect | Relational Database | Graph Database |
|---|---|---|
| Data Model | Tables with rows and columns | Nodes (entities), relationships (edges), properties |
| Schema | Predefined schema (fixed structure) | Flexible schema (schema optional, can evolve) |
| Relationships | Represented using foreign keys and joins | First-class citizens (stored directly as relationships) |
| Best Suited For | Structured data with well-defined schema | Highly connected data with complex relationships |
| Query Language | SQL (MySQL, PostgreSQL, Oracle) | Graph query languages (Cypher, Gremlin, SPARQL) |
| Performance | Joins can be expensive for complex relationships | Fast traversal of relationships, efficient for connected data |
| Scalability | Typically vertically scalable (scale-up) | Horizontally scalable (designed for clusters) |
| Joins | Supports joins, normalization | No joins (denormalized data model) |
| Use Cases | Banking, ERP, inventory, transaction processing | Social networks, recommendation systems, fraud detection, knowledge graphs |
| Examples | MySQL, PostgreSQL, Oracle, SQL Server | Neo4j, Amazon Neptune, JanusGraph, ArangoDB |
| Consistency | Strong consistency (ACID) | Eventual consistency (typically) |
Example — Student Data:
Relational Database — Student Table:
| ID | Name | Age | Department |
|---|---|---|---|
| 1 | Alice | 23 | CSE |
| 2 | Bob | 24 | ECE |
| 3 | Carol | 22 | ME |
Graph Database — Student Graph:
Alice ──FRIEND_OF──→ Bob
│ │
│ STUDIES_AT │ STUDIES_AT
↓ ↓
ABC University ←───────┘Key Difference:
“Relational databases store data in tables. Graph databases store data as connected entities, making relationships easier and faster to work with.”
8. Explain the concept of a key-value database. Describe two practical applications where key-value stores are commonly used.
Answer:
A key-value database is a type of NoSQL database that stores data as simple key-value pairs. Each key is unique and is used to retrieve the associated value. It is highly scalable, fast, and works well for simple lookups.
How It Works:
| Key | Value |
|---|---|
user:101 | { "name": "Ananya", "age": 25 } |
product:200 | { "name": "Laptop", "price": 55000 } |
session:abc | "token_9382xyz" |
cart:500 | [ "item1", "item2", "item3" ] |
Characteristics:
- Simple key → value mapping
- O(1) access time
- Highly scalable
- Flexible values (strings, JSON, lists)
- No complex queries or joins
- Eventually consistent (typically)
Two Practical Applications:
1. E-commerce — Shopping Cart
Key-value stores are often used to store shopping cart data for each user. The user ID can be the key, and the cart items can be the value.
Key: cart:user123
Value: ["item1", "item2", "item3"]Advantages:
- Fast retrieval of cart contents
- Session-independent cart storage
- Easy to scale with user growth
- Simple to add/remove items
2. Caching — User Sessions
Key-value stores are widely used for caching user session data in web applications. The session ID is the key and the session information is the value.
Key: session:abc123
Value: { "user_id": 101, "status": "active" }Advantages:
- Fast session lookup
- TTL for automatic expiry
- Reduces database load
- Improves application performance
Other Applications:
- User profiles
- Product catalogs
- Configuration settings
- Real-time counters
- Message queues
- Distributed locks
Popular Key-Value Stores: Redis, Amazon DynamoDB, Riak, Memcached.
9. Describe any five fundamental data types supported by Redis and explain their typical uses.
Answer:
1. String
A simple key-value pair where the value is a string (text, number, or binary data).
SET user:101 "Ananya"
GET user:101 # Returns "Ananya"
INCR counter # Increase by 1
DECR counter # Decrease by 1Typical Uses:
- Caching values
- Counters (page views, likes)
- Session tokens
- Configuration settings
- Feature flags
2. List
An ordered collection of string elements that allows insertion and removal from both ends (like a queue or stack).
Left ← [A] [B] [C] [D] → RightLPUSH notifications "msg1"
RPUSH notifications "msg3"
LRANGE notifications 0 -1
LPOP notifications
RPOP notificationsTypical Uses:
- Message queues (FIFO)
- Stacks (LIFO)
- Recent activity logs
- Notification lists
- Timeline feeds
3. Set
An unordered collection of unique string elements (no duplicate values).
A
B CSADD tags "redis" "nosql" "database"
SMEMBERS tags
SISMEMBER tags "redis"
SINTER tags otherSetTypical Uses:
- Tags
- Unique user IDs
- Followers/following
- Common interests (intersection)
- Deduplication
4. Hash
A collection of field-value pairs (like a dictionary or map) suitable for storing objects.
Key: user:101
┌──────────┬──────────────────┐
│ Field │ Value │
├──────────┼──────────────────┤
│ name │ Ananya │
│ age │ 25 │
│ email │ ananya@gcu.edu │
│ role │ faculty │
└──────────┴──────────────────┘HSET user:101 name "Ananya"
HGET user:101 name
HGETALL user:101
HINCRBY user:101 age 1Typical Uses:
- User profiles
- Product details
- Application settings
- Object storage
- Grouping related fields
5. Sorted Set (ZSet)
A collection of unique elements, each with an associated score. Elements are automatically ordered by their score.
┌─────────┬───────┐
│ Member │ Score │
├─────────┼───────┤
│ Charlie │ 60 │
│ Bob │ 80 │
│ Alice │ 100 │
└─────────┴───────┘ZADD leaderboard 100 "Alice"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 -1
ZSCORE leaderboard "Alice"Typical Uses:
- Leaderboards
- Rankings
- Priority queues
- Trending content
- Recommendation scoring
Bonus — Stream: An append-only log-like structure for events (XADD, XREAD, XRANGE).
Use Case: Event sourcing, activity feeds, real-time analytics.
10. Explain the foundations of graph databases in detail. Include graph theory essentials such as nodes, edges, paths, degree, cycles and traversal.
Answer:
A graph database is a NoSQL database that stores data as a graph. It is built on graph theory concepts.
Graph Theory Essentials
1. Nodes (Vertices)
- Fundamental units representing entities
- Can have labels and properties
- Examples: Person, Product, Company
:Person {name: "Alice", age: 25}2. Edges (Relationships)
- Connections between nodes
- Usually directed
- Have types and properties
- Examples: FRIEND_OF, WORKS_AT
Alice ──FRIEND_OF (since: 2020)──→ Bob3. Paths
- A sequence of nodes connected by relationships
- Can be directed or undirected
- Used to find connections
Path: Alice → Bob → Carol → David4. Degree
- Number of relationships connected to a node
- In-degree: Number of incoming relationships
- Out-degree: Number of outgoing relationships
Alice (out-degree = 2, in-degree = 1)
Bob (out-degree = 1, in-degree = 1)5. Cycles
- A path that starts and ends at the same node
- Used in fraud detection, network analysis
Alice → Bob → Carol → Alice (cycle)6. Traversal
- Process of navigating through a graph
- Following relationships from node to node
- Can be one-hop, two-hop, or variable-length
One-hop: Alice → Bob
Two-hop: Alice → Bob → CarolGraph Database Foundations
1. Property Graph Model:
- Nodes + Relationships + Properties + Labels
2. Schema Flexibility:
- Nodes can have different properties
- No fixed schema
3. Index-Free Adjacency:
- Each node stores direct pointers to neighbors
- O(1) traversal per relationship
4. ACID Transactions:
- Some graph databases (Neo4j) support ACID
5. Query Language:
- Cypher (Neo4j), Gremlin, SPARQL
Example — Social Network
Carol
↑ FOLLOWS
│
David ←─ Alice ─→ Bob
FOLLOWS FOLLOWSAnalysis:
- Nodes: Alice, Bob, Carol, David
- Edges: FOLLOWS (directed)
- Path: Alice → Bob → Carol
- Degree: Alice (out=2, in=1)
- Cycle: None
Why Graph Databases?
| Feature | Benefit |
|---|---|
| Index-free adjacency | Fast traversal |
| Flexible schema | Evolving data |
| Relationship-first | Connected data |
| Powerful queries | Complex patterns |
Use Cases
- Social networks
- Recommendation systems
- Fraud detection
- Knowledge graphs
- Network analysis
11. Define a Graph Database. Explain the concepts of nodes, relationships, and properties with a suitable example.
Answer:
A graph database is a type of NoSQL database that stores and represents data as a graph, using nodes, relationships, and properties. It is designed to efficiently manage and query highly connected data, where the relationships between entities are as important as the entities themselves.
Core Concepts
1. Nodes
- Represent an entity or object in the database
- Can have a label (type) and properties
- Examples: Person, Product, Company, City, Movie
2. Relationships
- Represent a connection between two nodes
- Usually directed and has a type
- Can also have properties
- Examples: FRIEND_OF, WORKS_AT, LIKES, PURCHASED, LIVES_IN
3. Properties
- Key-value pairs that store additional information about nodes or relationships
- Both nodes and relationships can have properties
- Examples:
(name: "Alice", age: 25),(since: 2020)
Example — Social Network
Person Node (Alice) Person Node (Bob)
Properties: Properties:
name: "Alice" name: "Bob"
age: 25 age: 27
city: "Bangalore" city: "Mumbai"
│ │
│ FRIEND_OF (since: 2020) │
└────────────────────────────────┘
│ │
│ LIVES_IN │ WORKS_AT
↓ ↓
City Node (Bangalore) Company Node (ABC Corp)
Properties: Properties:
name: "Bangalore" name: "ABC Corp"
country: "India" industry: "IT"
location: "Bangalore"In Simple Terms
Nodes = Things
Relationships = Connections
Properties = Details about things/connectionsCypher Query Example
// Create nodes
CREATE (a:Person {name: 'Alice', age: 25, city: 'Bangalore'})
CREATE (b:Person {name: 'Bob', age: 27, city: 'Mumbai'})
// Create relationship
CREATE (a)-[:FRIEND_OF {since: 2020}]->(b)
// Query
MATCH (a:Person {name: 'Alice'})-[:FRIEND_OF]->(b:Person)
RETURN b.name, b.city;Key Takeaways
- Nodes represent entities
- Relationships represent connections
- Properties store details
- Labels categorize nodes
- Graph databases excel at connected data
12. Explain the five core data structures of Redis with suitable examples.
Answer:
1. String
A simple key-value pair where the value is a string (text, number, or binary data).
SET user:101 "Ananya"
GET user:101 # Returns "Ananya"
INCR counter # Increase by 1
DECR counter # Decrease by 1Use Case: Store user names, configuration settings, counters.
2. List
An ordered collection of string elements that allows insertion and removal from both ends (like a queue or stack).
Left ← [A] [B] [C] [D] → RightLPUSH notifications "msg1" # Add to left
LPUSH notifications "msg2"
RPUSH notifications "msg3" # Add to right
LRANGE notifications 0 -1 # Get all
# Returns ["msg2", "msg1", "msg3"]
LPOP notifications # Remove from left
RPOP notifications # Remove from rightUse Case: Maintain recent activity logs, message queues, notification lists.
3. Set
An unordered collection of unique string elements (no duplicate values).
A
B CSADD tags "redis"
SADD tags "nosql"
SADD tags "database"
SMEMBERS tags # Returns all
# ["redis", "nosql", "database"]
SISMEMBER tags "redis" # Check membership
SINTER tags otherSet # IntersectionUse Case: Store unique items such as tags, user IDs, or followers.
4. Hash
A collection of field-value pairs (like a dictionary or map) suitable for storing objects.
Key: user:101
┌──────────┬──────────────────┐
│ Field │ Value │
├──────────┼──────────────────┤
│ name │ Ananya │
│ age │ 25 │
│ email │ ananya@gcu.edu │
│ role │ faculty │
└──────────┴──────────────────┘HSET user:101 name "Ananya"
HSET user:101 age 25
HGET user:101 name # Returns "Ananya"
HGETALL user:101 # Get all fields
HINCRBY user:101 age 1 # Increment numeric fieldUse Case: Store user profiles, product details, or application settings.
5. Sorted Set (ZSet)
A collection of unique elements, each with an associated score. Elements are automatically ordered by their score.
┌─────────┬───────┐
│ Member │ Score │
├─────────┼───────┤
│ Charlie │ 60 │
│ Bob │ 80 │
│ Alice │ 100 │
└─────────┴───────┘ZADD leaderboard 100 "Alice"
ZADD leaderboard 80 "Bob"
ZADD leaderboard 60 "Charlie"
ZRANGE leaderboard 0 -1 WITHSCORES
# Returns ["Charlie", 60, "Bob", 80, "Alice", 100]
ZREVRANGE leaderboard 0 -1 # Descending order
ZSCORE leaderboard "Alice" # Get scoreUse Case: Leaderboards, rankings, priority queues, or scheduling.
Bonus — Stream: An append-only log-like structure for events (XADD, XREAD, XRANGE).
Use Case: Event sourcing, activity feeds, real-time analytics.
13. Differentiate between CREATE and MERGE commands in Cypher with suitable examples.
Answer:
CREATE
- Always creates new nodes or relationships
- Does not check if the data already exists
- Can result in duplicate nodes/relationships if run multiple times
- Useful when you are sure the data does not exist
Example:
CREATE (p:Person {name: 'Alice', age: 25})
RETURN p;Run twice → Two separate nodes (duplicates):
:Person (Alice) :Person (Alice)
name: "Alice" name: "Alice"
age: 25 age: 25MERGE
- Creates a node or relationship only if it does not exist
- If it exists, it matches the existing one
- Helps avoid duplicate data
- Commonly used to ensure uniqueness
Example:
MERGE (p:Person {name: 'Alice', age: 25})
RETURN p;Run twice → Only one node created:
:Person (Alice)
name: "Alice"
age: 25Comparison Table
| Aspect | CREATE | MERGE |
|---|---|---|
| Behaviour | Always creates new data | Creates only if not exists; otherwise matches |
| Duplicate Data | Can create duplicates | Prevents duplicates |
| Use Case | When you want to always create a new node/relationship | When you want to ensure uniqueness |
| Result on Repeated Execution | Multiple identical nodes/relationships | Single node/relationship (existing one returned) |
Key Takeaway
“Use CREATE when you want to always create. Use MERGE when you want to create only if it doesn’t exist (otherwise match).”
Practical Example
// CREATE — always creates
CREATE (a:Person {name: 'Alice'})
CREATE (b:Person {name: 'Bob'})
CREATE (a)-[:FOLLOWS]->(b)
// MERGE — creates only if not exists
MERGE (a:Person {name: 'Alice'})
MERGE (b:Person {name: 'Bob'})
MERGE (a)-[:FOLLOWS]->(b)14. Explain the Cache-Aside (Lazy Loading) strategy. Describe the cache hit and cache miss flow with an example.
Answer:
Cache-Aside Strategy (Lazy Loading)
The application is responsible for loading data into the cache. Data is fetched from the cache first; if not found, it is loaded from the database and then stored in the cache for future requests.
How It Works
1. Application checks the cache for the data.
2. If the data is found (cache hit), return it directly from the cache.
3. If the data is not found (cache miss), fetch it from the database.
4. Store the data in the cache (for a defined TTL) and return it to the client.Read Flow (Cache Miss)
Client → Application → Redis Cache → (not found) → Database
↓
Store in cache (with TTL)
↓
Return data to clientAfter the first request, the data is cached, so subsequent requests will be faster.
Read Flow (Cache Hit)
Client → Application → Redis Cache → (found) → Return data (fast response)Write Flow (Cache-Aside)
Application → Update database → Invalidate/delete cache entryOn write, the application updates the database first, then invalidates (or deletes) the cache entry so the next read will load fresh data.
Example: E-commerce Product Details
When a user views a product (e.g., product ID 101), the application first checks Redis. If not found, it fetches the product details from the database, stores it in Redis (e.g., for 5 minutes), and returns it to the user.
Product ID: 101
Name: Running Shoes
Price: ₹2,999
Stock: 50
Cached for 5 minutesCode Example (Pseudocode)
def get_product(product_id):
key = f"product:{product_id}"
# Check cache
cached = redis.get(key)
if cached:
return cached # Cache hit
# Cache miss — fetch from DB
product = db.query("SELECT * FROM products WHERE id = ?", product_id)
# Store in cache with TTL
redis.setex(key, 300, product) # 5 minutes
return product
def update_product(product_id, data):
# Update database
db.update("products", product_id, data)
# Invalidate cache
redis.delete(f"product:{product_id}")Key Benefits
- Reduces database load
- Improves application performance
- Simple to implement
- Works well for read-heavy applications
- Gives control to the application
Things to Consider
- First request is slower (cache miss)
- Need to handle cache invalidation on data updates
- Possibility of stale data (until invalidated)
- Choose an appropriate TTL
15. Explain the key terms in Apache Cassandra: Node, Cluster, Keyspace, Partition, and Replication Factor.
Answer:
1. Node
A node is a single instance of Cassandra running on a machine (physical or virtual). Each node stores a portion of the data (data partitions). Nodes are equal — there is no master or slave.
┌─────────────────────┐
│ Node │
│ (Cassandra instance)│
└─────────────────────┘2. Cluster
A cluster is a group of nodes that work together to store and manage data. All nodes in a cluster are peer-to-peer (equal). Provides high availability, fault tolerance, and horizontal scalability.
Cassandra Cluster
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│Node 1│ │Node 2│ │Node 3│ ... │Node N│
└──────┘ └──────┘ └──────┘ └──────┘3. Keyspace
A keyspace is a top-level container (similar to a database in relational systems). It defines replication settings and contains one or more tables (column families). You must create a keyspace before creating tables.
CREATE KEYSPACE university
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 3
};Keyspace: ecom
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Table │ │ Table │ │ Table │
│ users │ │ orders │ │ products │
└──────────┘ └──────────┘ └──────────┘4. Partition
A partition is a subset of the total data, identified by a partition key. Rows with the same partition key are stored together in the same partition. Cassandra distributes (hashes) partitions across nodes in the cluster.
Partition Key (e.g., user_id = 101)
↓
┌─────────────────┐
│ Partition │
│ Row 1 │
│ Row 2 │
│ Row 3 │
└─────────────────┘5. Replication Factor (RF)
The replication factor defines how many copies of each partition are stored across different nodes in the cluster. Helps with fault tolerance and high availability.
Example: If RF = 3, each partition is stored on 3 different nodes (ideally in different racks/data centers). You can set the replication factor at the keyspace level.
Node 1 (Replica)
↑
┌──────┴──────┐
Node 4 │ RF = 3 │ Node 2 (Replica)
(Other │3 copies of│
data) │each part. │
└──────┬──────┘
↓
Node 3 (Replica)Data Model Hierarchy
Cluster → Keyspace → TableSummary Table
| Term | Definition |
|---|---|
| Node | Single Cassandra instance on a machine |
| Cluster | Group of nodes working together |
| Keyspace | Top-level container (like database) |
| Partition | Subset of data identified by partition key |
| Replication Factor | Number of copies of each partition |
16. Explain the Property Graph Model. Discuss nodes, labels, relationship types, and properties with an example.
Answer:
The property graph model is a graph data model in which data is represented using nodes and relationships, and both nodes and relationships can have properties in the form of key-value pairs.
1. Nodes
- Represent entities or objects in the real world
- Can have one or more labels
- Contain a set of properties (key-value pairs)
- Examples: a person, a student, a course, a company
2. Labels
- A label identifies the type or category of a node
- A node can have a single label or multiple labels
- Labels help to group and query nodes
- Examples:
Student,Teacher,Course,Company - Example of multiple labels:
{Student:Scholar {name: "Alice"}}
3. Relationship Types
- A relationship type describes the nature of the connection between two nodes
- Relationships are usually directed (from one node to another)
- Can also have properties (key-value pairs)
- Examples:
ENROLLED_IN,FRIEND_OF,WORKS_AT,TEACHES,PURCHASED
4. Properties
- Key-value pairs that store additional information
- Both nodes and relationships can have properties
- Examples:
(name: "Alice", age: 25),(since: 2020)
Example: University Graph
:Student (Alice) :Course (NoSQL)
{id: 1, name: "Alice", age: 20} {id: 101, name: "NoSQL", credits: 4}
│ │
│ ENROLLED_IN (year: 2026) │ TAUGHT_BY (semester: "Fall 2026")
└─────────────────────────────────────┘
│ │
│ WORKS_AT (since: 2023) │
↓ ↓
:Company (ABC Corp) :Teacher (Dr. Kumar)
{id: 201, name: "ABC Corp", {id: 301, name: "Dr. Kumar",
industry: "IT"} department: "CSE"}Legend
| Symbol | Meaning |
|---|---|
| ○ | Node |
| → | Relationship (with direction) |
| {…} | Properties (key-value pairs) |
:Label | Node label |
Key Takeaway
In the property graph model, labels tell us what a node is, while relationship types tell us how two nodes are connected.
Cypher Example
// Create nodes with labels and properties
CREATE (a:Student {id: 1, name: 'Alice', age: 20})
CREATE (c:Course {id: 101, name: 'NoSQL', credits: 4})
// Create relationship with properties
CREATE (a)-[:ENROLLED_IN {year: 2026}]->(c)
// Query
MATCH (s:Student)-[r:ENROLLED_IN]->(c:Course)
RETURN s.name, c.name, r.year;17. Explain the Redis commands SET, GET, EXPIRE, and TTL with examples.
Answer:
1. SET — Create/Update a Key
Stores a value at a key. If the key exists, it overwrites the value.
SET username "Ananya"
# 127.0.0.1:6379> SET username "Ananya"
# OKOptions:
SET username "Ananya" EX 60 # Set with 60-second TTL
SET username "Ananya" NX # Set only if key does not exist
SET username "Ananya" XX # Set only if key exists2. GET — Retrieve a Value
Returns the value stored at the key. If the key does not exist, returns (nil).
GET username
# 127.0.0.1:6379> GET username
# "Ananya"3. EXPIRE — Set Time-to-Live
Sets a time-to-live (TTL) for a key (in seconds). The key is automatically deleted after the specified time.
EXPIRE username 60
# 127.0.0.1:6379> EXPIRE username 60
# (integer) 1Related:
PEXPIRE username 60000 # TTL in milliseconds
PERSIST username # Remove TTL4. TTL — Check Remaining Time
Returns the remaining time (in seconds) for a key.
TTL username
# 127.0.0.1:6379> TTL username
# (integer) 42Return Values:
| Return | Meaning |
|---|---|
| Positive number | Remaining seconds |
| -1 | Key exists but has no expiry |
| -2 | Key does not exist |
Complete Example
# Create key
SET session:abc "token_xyz"
# OK
# Read value
GET session:abc
# "token_xyz"
# Set 1-hour expiry
EXPIRE session:abc 3600
# (integer) 1
# Check remaining time
TTL session:abc
# (integer) 3595
# After 1 hour, key is automatically deleted
GET session:abc
# (nil)Common Use Cases
| Command | Use Case |
|---|---|
| SET | Store session tokens, cache values |
| GET | Retrieve cached data |
| EXPIRE | Auto-expire sessions, rate limiting |
| TTL | Monitor cache lifetime |
18. Explain graph traversal techniques in Neo4j. Discuss direct traversal, friends-of-friends traversal, and variable-length traversal.
Answer:
Graph traversal is the process of navigating through a graph by following relationships (edges) from one node to another to find connected nodes. In Neo4j, traversals are performed using Cypher pattern matching.
Example Graph: Social Network
Carol
↑ FOLLOWS
│
David ←─ Alice ─→ Bob
FOLLOWS FOLLOWS1. Direct Traversal (One-Hop)
Find the immediate neighbors (directly connected nodes) from a given node.
Cypher Query:
MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->(b:Person)
RETURN b.name;Result:
b.name
Bob
CarolFrom Alice, the direct traversal returns Bob and Carol (nodes directly connected to Alice).
2. Friends-of-Friends Traversal (Two-Hop)
Find nodes that are two relationships away from a given node.
Cypher Query:
MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->()-[:FOLLOWS]->(c:Person)
RETURN c.name;Result:
c.name
DavidFrom Alice, the two-hop traversal returns David (a node that is two steps away: Alice → Bob → David).
3. Variable-Length Traversal
Find nodes reachable within a variable number of hops.
Cypher Query:
MATCH (a:Person {name: 'Alice'})-[:FOLLOWS*1..3]->(p:Person)
RETURN DISTINCT p.name;Result:
p.name
Bob
Carol
DavidThe *1..3 syntax specifies a variable-length traversal of 1 to 3 hops.
4. Shortest Path Query
Find the shortest path between two nodes.
Cypher Query:
MATCH p = shortestPath(
(a:Person {name: 'Alice'})-[:FOLLOWS*]-(e:Person {name: 'Eve'})
)
RETURN [n in nodes(p) | n.name] AS path;Result:
path
["Alice", "Carol", "Eve"]Other Traversal Techniques
| Technique | Description | Example Use Case |
|---|---|---|
| Depth-First Traversal (DFS) | Explores as far as possible along each branch | Path exploration, hierarchy traversal |
| Breadth-First Traversal (BFS) | Explores all neighbors level by level | Finding shortest paths, social networks |
| Filtered Traversal | Use WHERE to apply conditions | Find friends in a specific location |
| Multi-relationship Traversal | Traverse multiple relationship types | Find people who follow or like a user |
| Bidirectional Traversal | Use undirected patterns | Find any connection between two nodes |
Filtered Traversal Example
Find people Alice follows since 2023:
MATCH (a:Person {name: 'Alice'})-[r:FOLLOWS]->(b:Person)
WHERE r.since >= 2023
RETURN b.name, r.since;Result:
name since
Bob 2023Key Takeaways
- Neo4j stores data as nodes and relationships, making traversals natural and efficient
- Cypher provides a powerful and expressive way to perform graph traversals
- Use relationship-based patterns, variable-length traversals, and shortest path functions to explore and analyze connected data
- Graph traversals enable real-world applications such as friend suggestions, recommendations, fraud detection, and network analysis
19. Explain the four major categories of graph algorithms used in Neo4j: Centrality, Community Detection, Path Finding, and Similarity algorithms.
Answer:
Graph algorithms analyze the structure and relationships in a graph to find meaningful patterns. Neo4j Graph Data Science (GDS) provides four major categories.
1. Centrality Algorithms
Measure the importance of nodes based on their position and connections. Help identify key individuals, items, or entities in a network.
Examples:
- PageRank
- Degree Centrality
- Betweenness Centrality
- Closeness Centrality
Example — PageRank:
Measures the importance of nodes based on the number and quality of incoming links. A node is important if it is linked by other important nodes.
A → C ← B
↑
D
↑
EPageRank Scores:
| Node | PageRank Score |
|---|---|
| C | 0.42 |
| A | 0.21 |
| D | 0.18 |
| B | 0.12 |
| E | 0.07 |
Use Case: Finding influential users in a social network.
2. Community Detection Algorithms
Partition the graph into communities where nodes are more connected within the group than with outside nodes. Useful for finding natural groups, such as social circles or customer segments.
Examples:
- Louvain
- Leiden
- Label Propagation
- Weakly Connected Components
Example:
Community 1 (Friends) Community 2 (Colleagues)
B ── C D ── E
│ │ │ │
A ───┘ F ───┘The graph is divided into communities using the Louvain/Leiden algorithm.
Use Case: Detecting groups of users with similar interests.
3. Path Finding Algorithms
Find paths or shortest routes between nodes. Determine paths based on distance, cost, or other criteria.
Examples:
- Dijkstra’s Shortest Path
- A* Shortest Path
- Breadth-First Search (BFS)
- Depth-First Search (DFS)
Example:
B
2 ↗ ↘ 5
A → 1 → C → 2 → E
4 ↘ ↗ 1
DShortest path from A to E: A → C → E (total cost = 3)
Use Case: Finding the shortest route between two cities.
4. Similarity Algorithms
Measure how similar two nodes are, typically based on shared neighbors or attributes. Useful for recommendations, fraud detection, and finding similar items or users.
Examples:
- Node Similarity
- K-Nearest Neighbors (KNN)
- Jaccard Similarity
- Cosine Similarity
Example:
Item A
↗ ↘
U1 U2
↘ ↗
Item B
↗ ↘
U1 U2
↘ ↗
Item CU1 and U2 are similar because they are connected to the same items (Item A, Item B, Item C).
Similarity Scores:
| Node Pair | Similarity Score |
|---|---|
| A – B | 0.80 |
| A – C | 0.65 |
| B – D | 0.60 |
Use Case: Recommending similar products or suggesting friends.
Summary Table
| Category | Purpose | Examples |
|---|---|---|
| Centrality | Measure importance of nodes | PageRank, Degree, Betweenness, Closeness |
| Community Detection | Find groups of densely connected nodes | Louvain, Leiden, Label Propagation |
| Path Finding | Find routes between nodes | Dijkstra, A*, BFS, DFS |
| Similarity | Measure how similar two nodes are | Node Similarity, KNN, Jaccard, Cosine |
Key Takeaway
Graph algorithms turn connected data into actionable insights — helping us find what is important, how things are related, what groups exist, and what is similar, enabling smarter decisions in real-world applications.
20. Explain Redis transactions and describe the functions of MULTI, EXEC, and WATCH.
Answer:
A Redis transaction groups multiple commands into a single atomic unit. Commands are queued and executed together.
1. MULTI — Start a Transaction
MULTI puts Redis into transaction mode. All subsequent commands are queued instead of being executed immediately. Redis replies with “QUEUED” for each command.
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET user:1 "Ananya"
QUEUED
127.0.0.1:6379(TX)> INCR login_count
QUEUED
127.0.0.1:6379(TX)> EXPIRE user:1 3600
QUEUED2. EXEC — Execute All Queued Commands
EXEC executes all the queued commands in the order they were added. All commands are executed as a single atomic unit. Returns an array with the result of each command.
127.0.0.1:6379(TX)> EXEC
1) OK
2) (integer) 1
3) (integer) 1Important: If EXEC is called, all queued commands are executed, even if one of them fails (runtime errors do not rollback).
3. WATCH — Optimistic Locking
WATCH monitors one or more keys for changes by other clients. If any watched key is modified before EXEC, the transaction is aborted (EXEC returns nil). Useful for implementing optimistic locking.
127.0.0.1:6379> WATCH balance:100
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> DECRBY balance:100 50
QUEUED
127.0.0.1:6379(TX)> EXEC
(nil) # if balance:100 was modified by another client4. DISCARD — Cancel Transaction
127.0.0.1:6379(TX)> DISCARD
OKUse Case Example — Money Transfer
Transfer money between two accounts (ensure both debit and credit happen together).
WATCH account:A account:B
MULTI
DECRBY account:A 1000
INCRBY account:B 1000
EXECCommand Summary
| Command | Purpose |
|---|---|
| MULTI | Starts the transaction |
| EXEC | Executes all queued commands |
| DISCARD | Cancels the transaction |
| WATCH | Detects changes; prevents lost updates |
| UNWATCH | Stops watching keys |
Key Takeaways
- MULTI starts the transaction
- EXEC executes all queued commands
- WATCH helps detect changes and prevents lost updates
- Redis transactions provide atomicity, but do not rollback on runtime errors
- They are simple, fast, and useful for ensuring data consistency
Summary Table
| Q# | Topic | Key Answer |
|---|---|---|
| 1 | Key-value store | Simple key-value pairs; e-commerce cart, session caching |
| 2 | CQL | Cassandra Query Language; CREATE KEYSPACE, CREATE TABLE |
| 3 | Redis data structures | String, List, Set, Hash, Sorted Set |
| 4 | Graph database | Nodes, relationships, properties; social network example |
| 5 | Schema flexibility | No fixed schema; evolving data; product catalog example |
| 6 | Redis commands | SET, GET, EXPIRE, TTL |
| 7 | Relational vs Graph | Tables vs connected entities |
| 8 | Key-value database | Key-value pairs; shopping cart, session caching |
| 9 | Redis data types | String, List, Set, Hash, Sorted Set with uses |
| 10 | Graph foundations | Nodes, edges, paths, degree, cycles, traversal |
| 11 | Graph database | Nodes, relationships, properties; Cypher example |
| 12 | Redis core structures | String, List, Set, Hash, Sorted Set with examples |
| 13 | CREATE vs MERGE | Always create vs create-if-not-exists |
| 14 | Cache-Aside | Lazy loading; cache hit/miss flow; e-commerce example |
| 15 | Cassandra terms | Node, Cluster, Keyspace, Partition, Replication Factor |
| 16 | Property Graph Model | Nodes, labels, relationship types, properties; university example |
| 17 | Redis commands | SET, GET, EXPIRE, TTL with examples |
| 18 | Graph traversal | Direct, friends-of-friends, variable-length |
| 19 | Graph algorithms | Centrality, Community Detection, Path Finding, Similarity |
| 20 | Redis transactions | MULTI, EXEC, WATCH, DISCARD |