BTCE | 5th Sem
No-SQL SubjectExtra Questions

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:

KeyValue
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:

  1. Simple model
  2. High performance (fast reads/writes)
  3. Scalable
  4. Flexible (values can be any data type)
  5. 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)
KeyspaceDatabase
TableTable
PRIMARY KEYPrimary Key
Designed for distributed systemsDesigned for single server
No JOINsSupports JOINs
Eventual consistencyStrong 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_id is 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 1

Use 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] → Right
LPUSH 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 right

Use Case: Maintain recent activity logs, message queues, notification lists.

3. Set

An unordered collection of unique string elements (no duplicate values).

    A
  B   C
SADD tags "redis"
SADD tags "nosql"
SADD tags "database"
SMEMBERS tags                   # Returns all
# ["redis", "nosql", "database"]
SISMEMBER tags "redis"          # Check membership
SINTER tags otherSet            # Intersection

Use 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 field

Use 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 score

Use 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/connections

Why 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:

#ImportanceExplanation
1Rapid DevelopmentStart storing data without designing a full schema
2Evolving DataAdd new fields without altering existing records
3Heterogeneous DataStore different structures in the same collection
4No MigrationsAvoid expensive ALTER TABLE operations
5Agile AdaptationRespond quickly to changing business requirements

Suitable Example — Product Catalog:

In an e-commerce application, different products have different attributes:

Relational Database (Fixed Schema):

idnamepricesizecolorauthorISBN
1T-Shirt500MRedNULLNULL
2Laptop55000NULLNULLNULLNULL
3Book300NULLNULLR. Sharma978-…

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"
# OK

If 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) 1

The 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) 42

Returns the remaining time in seconds.

  • 1: key exists but has no expiry
  • 2: key does not exist

5. Set with Expiry in One Command (SETEX):

SETEX session:abc 3600 "token_xyz"

6. Remove Expiry (PERSIST):

PERSIST username

7. Delete Key (DEL):

DEL username

Common Key Commands Summary:

CommandPurpose
SET key valueCreate/update key
GET keyRetrieve value
DEL keyDelete key
EXISTS keyCheck existence
EXPIRE key secondsSet TTL
TTL keyCheck remaining TTL
PERSIST keyRemove TTL
SETEX key seconds valueSet with TTL

Use Cases: Session management, cache entries, rate limiting, temporary tokens, distributed locks.


7. Differentiate between relational databases and graph databases.

Answer:

AspectRelational DatabaseGraph Database
Data ModelTables with rows and columnsNodes (entities), relationships (edges), properties
SchemaPredefined schema (fixed structure)Flexible schema (schema optional, can evolve)
RelationshipsRepresented using foreign keys and joinsFirst-class citizens (stored directly as relationships)
Best Suited ForStructured data with well-defined schemaHighly connected data with complex relationships
Query LanguageSQL (MySQL, PostgreSQL, Oracle)Graph query languages (Cypher, Gremlin, SPARQL)
PerformanceJoins can be expensive for complex relationshipsFast traversal of relationships, efficient for connected data
ScalabilityTypically vertically scalable (scale-up)Horizontally scalable (designed for clusters)
JoinsSupports joins, normalizationNo joins (denormalized data model)
Use CasesBanking, ERP, inventory, transaction processingSocial networks, recommendation systems, fraud detection, knowledge graphs
ExamplesMySQL, PostgreSQL, Oracle, SQL ServerNeo4j, Amazon Neptune, JanusGraph, ArangoDB
ConsistencyStrong consistency (ACID)Eventual consistency (typically)

Example — Student Data:

Relational Database — Student Table:

IDNameAgeDepartment
1Alice23CSE
2Bob24ECE
3Carol22ME

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:

KeyValue
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 1

Typical 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] → Right
LPUSH notifications "msg1"
RPUSH notifications "msg3"
LRANGE notifications 0 -1
LPOP notifications
RPOP notifications

Typical 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   C
SADD tags "redis" "nosql" "database"
SMEMBERS tags
SISMEMBER tags "redis"
SINTER tags otherSet

Typical 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 1

Typical 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)──→ Bob

3. Paths

  • A sequence of nodes connected by relationships
  • Can be directed or undirected
  • Used to find connections
Path: Alice → Bob → Carol → David

4. 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 → Carol

Graph 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         FOLLOWS

Analysis:

  • Nodes: Alice, Bob, Carol, David
  • Edges: FOLLOWS (directed)
  • Path: Alice → Bob → Carol
  • Degree: Alice (out=2, in=1)
  • Cycle: None

Why Graph Databases?

FeatureBenefit
Index-free adjacencyFast traversal
Flexible schemaEvolving data
Relationship-firstConnected data
Powerful queriesComplex patterns

Use Cases

  1. Social networks
  2. Recommendation systems
  3. Fraud detection
  4. Knowledge graphs
  5. 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/connections

Cypher 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 1

Use 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] → Right
LPUSH 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 right

Use Case: Maintain recent activity logs, message queues, notification lists.

3. Set

An unordered collection of unique string elements (no duplicate values).

    A
  B   C
SADD tags "redis"
SADD tags "nosql"
SADD tags "database"
SMEMBERS tags                   # Returns all
# ["redis", "nosql", "database"]
SISMEMBER tags "redis"          # Check membership
SINTER tags otherSet            # Intersection

Use 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 field

Use 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 score

Use 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: 25

MERGE

  • 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: 25

Comparison Table

AspectCREATEMERGE
BehaviourAlways creates new dataCreates only if not exists; otherwise matches
Duplicate DataCan create duplicatesPrevents duplicates
Use CaseWhen you want to always create a new node/relationshipWhen you want to ensure uniqueness
Result on Repeated ExecutionMultiple identical nodes/relationshipsSingle 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 client

After 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 entry

On 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 minutes

Code 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

  1. Reduces database load
  2. Improves application performance
  3. Simple to implement
  4. Works well for read-heavy applications
  5. Gives control to the application

Things to Consider

  1. First request is slower (cache miss)
  2. Need to handle cache invalidation on data updates
  3. Possibility of stale data (until invalidated)
  4. 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 → Table

Summary Table

TermDefinition
NodeSingle Cassandra instance on a machine
ClusterGroup of nodes working together
KeyspaceTop-level container (like database)
PartitionSubset of data identified by partition key
Replication FactorNumber 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

SymbolMeaning
○Node
→Relationship (with direction)
{…}Properties (key-value pairs)
:LabelNode 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"
# OK

Options:

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 exists

2. 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) 1

Related:

PEXPIRE username 60000           # TTL in milliseconds
PERSIST username                 # Remove TTL

4. TTL — Check Remaining Time

Returns the remaining time (in seconds) for a key.

TTL username
# 127.0.0.1:6379> TTL username
# (integer) 42

Return Values:

ReturnMeaning
Positive numberRemaining seconds
-1Key exists but has no expiry
-2Key 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

CommandUse Case
SETStore session tokens, cache values
GETRetrieve cached data
EXPIREAuto-expire sessions, rate limiting
TTLMonitor 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         FOLLOWS

1. 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
Carol

From 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
David

From 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
David

The *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

TechniqueDescriptionExample Use Case
Depth-First Traversal (DFS)Explores as far as possible along each branchPath exploration, hierarchy traversal
Breadth-First Traversal (BFS)Explores all neighbors level by levelFinding shortest paths, social networks
Filtered TraversalUse WHERE to apply conditionsFind friends in a specific location
Multi-relationship TraversalTraverse multiple relationship typesFind people who follow or like a user
Bidirectional TraversalUse undirected patternsFind 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     2023

Key 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
    ↑
    E

PageRank Scores:

NodePageRank Score
C0.42
A0.21
D0.18
B0.12
E0.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
        D

Shortest 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 C

U1 and U2 are similar because they are connected to the same items (Item A, Item B, Item C).

Similarity Scores:

Node PairSimilarity Score
A – B0.80
A – C0.65
B – D0.60

Use Case: Recommending similar products or suggesting friends.

Summary Table

CategoryPurposeExamples
CentralityMeasure importance of nodesPageRank, Degree, Betweenness, Closeness
Community DetectionFind groups of densely connected nodesLouvain, Leiden, Label Propagation
Path FindingFind routes between nodesDijkstra, A*, BFS, DFS
SimilarityMeasure how similar two nodes areNode 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
QUEUED

2. 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) 1

Important: 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 client

4. DISCARD — Cancel Transaction

127.0.0.1:6379(TX)> DISCARD
OK

Use 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
EXEC

Command Summary

CommandPurpose
MULTIStarts the transaction
EXECExecutes all queued commands
DISCARDCancels the transaction
WATCHDetects changes; prevents lost updates
UNWATCHStops watching keys

Key Takeaways

  1. MULTI starts the transaction
  2. EXEC executes all queued commands
  3. WATCH helps detect changes and prevents lost updates
  4. Redis transactions provide atomicity, but do not rollback on runtime errors
  5. They are simple, fast, and useful for ensuring data consistency

Summary Table

Q#TopicKey Answer
1Key-value storeSimple key-value pairs; e-commerce cart, session caching
2CQLCassandra Query Language; CREATE KEYSPACE, CREATE TABLE
3Redis data structuresString, List, Set, Hash, Sorted Set
4Graph databaseNodes, relationships, properties; social network example
5Schema flexibilityNo fixed schema; evolving data; product catalog example
6Redis commandsSET, GET, EXPIRE, TTL
7Relational vs GraphTables vs connected entities
8Key-value databaseKey-value pairs; shopping cart, session caching
9Redis data typesString, List, Set, Hash, Sorted Set with uses
10Graph foundationsNodes, edges, paths, degree, cycles, traversal
11Graph databaseNodes, relationships, properties; Cypher example
12Redis core structuresString, List, Set, Hash, Sorted Set with examples
13CREATE vs MERGEAlways create vs create-if-not-exists
14Cache-AsideLazy loading; cache hit/miss flow; e-commerce example
15Cassandra termsNode, Cluster, Keyspace, Partition, Replication Factor
16Property Graph ModelNodes, labels, relationship types, properties; university example
17Redis commandsSET, GET, EXPIRE, TTL with examples
18Graph traversalDirect, friends-of-friends, variable-length
19Graph algorithmsCentrality, Community Detection, Path Finding, Similarity
20Redis transactionsMULTI, EXEC, WATCH, DISCARD

On this page

1. Define a key-value store. Explain with two real-world examples.2. What is CQL? Write basic commands to create a keyspace and table.3. List and explain any five Redis core data structures.1. String2. List3. Set4. Hash5. Sorted Set (ZSet)4. Define graph database. Explain nodes, relationships and properties with an example.NodesRelationshipsProperties5. What is meant by schema flexibility in NoSQL databases? Explain its importance with a suitable example.6. Write Redis commands to create a key, read it, set expiry and check TTL.7. Differentiate between relational databases and graph databases.8. Explain the concept of a key-value database. Describe two practical applications where key-value stores are commonly used.1. E-commerce — Shopping Cart2. Caching — User Sessions9. Describe any five fundamental data types supported by Redis and explain their typical uses.1. String2. List3. Set4. Hash5. Sorted Set (ZSet)10. Explain the foundations of graph databases in detail. Include graph theory essentials such as nodes, edges, paths, degree, cycles and traversal.Graph Theory Essentials1. Nodes (Vertices)2. Edges (Relationships)3. Paths4. Degree5. Cycles6. TraversalGraph Database FoundationsExample — Social NetworkWhy Graph Databases?Use Cases11. Define a Graph Database. Explain the concepts of nodes, relationships, and properties with a suitable example.Core Concepts1. Nodes2. Relationships3. PropertiesExample — Social NetworkIn Simple TermsCypher Query ExampleKey Takeaways12. Explain the five core data structures of Redis with suitable examples.1. String2. List3. Set4. Hash5. Sorted Set (ZSet)13. Differentiate between CREATE and MERGE commands in Cypher with suitable examples.CREATEMERGEComparison TableKey TakeawayPractical Example14. Explain the Cache-Aside (Lazy Loading) strategy. Describe the cache hit and cache miss flow with an example.Cache-Aside Strategy (Lazy Loading)How It WorksRead Flow (Cache Miss)Read Flow (Cache Hit)Write Flow (Cache-Aside)Example: E-commerce Product DetailsCode Example (Pseudocode)Key BenefitsThings to Consider15. Explain the key terms in Apache Cassandra: Node, Cluster, Keyspace, Partition, and Replication Factor.1. Node2. Cluster3. Keyspace4. Partition5. Replication Factor (RF)Data Model HierarchySummary Table16. Explain the Property Graph Model. Discuss nodes, labels, relationship types, and properties with an example.1. Nodes2. Labels3. Relationship Types4. PropertiesExample: University GraphLegendKey TakeawayCypher Example17. Explain the Redis commands SET, GET, EXPIRE, and TTL with examples.1. SET — Create/Update a Key2. GET — Retrieve a Value3. EXPIRE — Set Time-to-Live4. TTL — Check Remaining TimeComplete ExampleCommon Use Cases18. Explain graph traversal techniques in Neo4j. Discuss direct traversal, friends-of-friends traversal, and variable-length traversal.Example Graph: Social Network1. Direct Traversal (One-Hop)2. Friends-of-Friends Traversal (Two-Hop)3. Variable-Length Traversal4. Shortest Path QueryOther Traversal TechniquesFiltered Traversal ExampleKey Takeaways19. Explain the four major categories of graph algorithms used in Neo4j: Centrality, Community Detection, Path Finding, and Similarity algorithms.1. Centrality Algorithms2. Community Detection Algorithms3. Path Finding Algorithms4. Similarity AlgorithmsSummary TableKey Takeaway20. Explain Redis transactions and describe the functions of MULTI, EXEC, and WATCH.1. MULTI — Start a Transaction2. EXEC — Execute All Queued Commands3. WATCH — Optimistic Locking4. DISCARD — Cancel TransactionUse Case Example — Money TransferCommand SummaryKey TakeawaysSummary Table