BTCE | 5th Sem
No-SQL SubjectUnit 4

No-SQL Unit 4: Questions & Answers

Unit 4: Graph Databases, Cypher, Graph Algorithms & Neo4j -> Generated and Prepared By Thiruselvan (ThiruXD)

SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)

Introduction to Graph Databases

Q1. What is a graph database?

  1. A relational database with tables
  2. A NoSQL database that stores data as nodes, relationships, and properties
  3. A document database
  4. A key-value store

Answer: B) A NoSQL database that stores data as nodes, relationships, and properties -> Explanation: A graph database stores and represents data as a graph using nodes, relationships, and properties. It is designed to efficiently manage highly connected data.


Q2. In a graph database, what does a node represent?

  1. A connection between entities
  2. An entity or object
  3. A key-value pair
  4. A table

Answer: B) An entity or object -> Explanation: Nodes represent entities or objects in the database. They can have labels and properties. Examples: Person, Product, Company, City.


Q3. In a graph database, what does a relationship represent?

  1. An entity
  2. A connection between two nodes
  3. A table
  4. A property

Answer: B) A connection between two nodes -> Explanation: Relationships represent connections between two nodes. They are usually directed and have a type. Examples: FRIEND_OF, WORKS_AT, LIKES.


Q4. What are properties in a graph database?

  1. Tables
  2. Key-value pairs storing information about nodes or relationships
  3. Connections between nodes
  4. Labels

Answer: B) Key-value pairs storing information about nodes or relationships -> Explanation: Properties are key-value pairs that store additional information about nodes or relationships. Examples: (name: “Alice”, age: 25), (since: 2020).


Q5. Which of the following is NOT a graph database?

  1. Neo4j
  2. Amazon Neptune
  3. MySQL
  4. JanusGraph

Answer: C) MySQL -> Explanation: MySQL is a relational database. Neo4j, Amazon Neptune, JanusGraph, and ArangoDB are graph databases.


Q6. Graph databases are best suited for:

  1. Transaction processing
  2. Highly connected data with complex relationships
  3. Simple key-value lookups
  4. Document storage

Answer: B) Highly connected data with complex relationships -> Explanation: Graph databases are ideal for highly connected data where relationships are as important as entities. Examples: social networks, recommendation systems, fraud detection.


Relational vs Graph Databases

Q7. In a relational database, relationships are represented using:

  1. Nodes
  2. Foreign keys and joins
  3. Properties
  4. Labels

Answer: B) Foreign keys and joins -> Explanation: In relational databases, relationships are represented using foreign keys and joins. In graph databases, relationships are first-class citizens stored directly.


Q8. Which database has a flexible schema?

  1. Relational database
  2. Graph database
  3. Both
  4. Neither

Answer: B) Graph database -> Explanation: Graph databases have a flexible schema (schema optional, can evolve). Relational databases have a predefined schema (fixed structure).


Q9. Which query language is used with Neo4j?

  1. SQL
  2. Cypher
  3. CQL
  4. Gremlin

Answer: B) Cypher -> Explanation: Cypher is the declarative, SQL-like query language used with Neo4j. Gremlin is used with other graph databases like Apache TinkerPop.


Q10. Which is a common use case for graph databases?

  1. Banking transactions
  2. Social networks
  3. Inventory management
  4. ERP systems

Answer: B) Social networks -> Explanation: Graph databases are commonly used for social networks, recommendation systems, fraud detection, and knowledge graphs. Banking, inventory, and ERP are typically relational.


Property Graph Model

Q11. What is the property graph model?

  1. A model with tables and rows
  2. A model with nodes, relationships, and properties
  3. A model with documents
  4. A model with key-value pairs

Answer: B) A model with nodes, relationships, and properties -> Explanation: The property graph model represents data using nodes and relationships, and both nodes and relationships can have properties in the form of key-value pairs.


Q12. What is a label in a graph database?

  1. A property
  2. A type or category of a node
  3. A relationship
  4. A value

Answer: B) A type or category of a node -> Explanation: A label identifies the type or category of a node. A node can have a single label or multiple labels. Examples: Student, Teacher, Course, Company.


Q13. Which of the following is a relationship type?

  1. Person
  2. FRIEND_OF
  3. name
  4. age

Answer: B) FRIEND_OF -> Explanation: FRIEND_OF is a relationship type. Person is a node label; name and age are properties.


Q14. In the property graph model, what do labels tell us?

  1. How two nodes are connected
  2. What a node is
  3. The value of a property
  4. The direction of a relationship

Answer: B) What a node is -> Explanation: In the property graph model, labels tell us what a node is, while relationship types tell us how two nodes are connected.


Q15. Can a relationship have properties in the property graph model?

  1. No, only nodes can have properties
  2. Yes, both nodes and relationships can have properties
  3. Only in some databases
  4. Only for certain relationship types

Answer: B) Yes, both nodes and relationships can have properties -> Explanation: In the property graph model, both nodes and relationships can have properties in the form of key-value pairs.


Cypher Query Language

Q16. What is Cypher?

  1. A relational database
  2. A declarative, SQL-like query language for Neo4j
  3. A programming language
  4. A data structure

Answer: B) A declarative, SQL-like query language for Neo4j -> Explanation: Cypher is a declarative, SQL-like query language used in Neo4j to create, read, update, and delete graph data.


Q17. Which Cypher command is used to create new nodes and relationships?

  1. MATCH
  2. CREATE
  3. MERGE
  4. INSERT

Answer: B) CREATE -> Explanation: CREATE is used to add new nodes and relationships. It always creates new data.


Q18. Which Cypher command creates data only if it does not exist?

  1. CREATE
  2. MERGE
  3. INSERT
  4. ADD

Answer: B) MERGE -> Explanation: MERGE creates a node or relationship only if it does not exist. If it exists, it matches the existing one.


Q19. In Cypher, nodes are written in:

  1. Square brackets [ ]
  2. Parentheses ( )
  3. Curly braces { }
  4. Angle brackets < >

Answer: B) Parentheses ( ) -> Explanation: In Cypher, nodes are written in parentheses ( ). Relationships are written in square brackets [ ].


Q20. In Cypher, relationships are written in:

  1. Parentheses ( )
  2. Square brackets [ ]
  3. Curly braces { }
  4. Angle brackets < >

Answer: B) Square brackets [ ] -> Explanation: In Cypher, relationships are written in square brackets [ ]. Example: (a)-[:FOLLOWS]->(b).


Q21. What is the correct Cypher syntax to create a relationship?

  1. CREATE (a)-[:FOLLOWS]->(b)
  2. CREATE (a)-[FOLLOWS]-(b)
  3. CREATE (a)<-[:FOLLOWS]-(b)
  4. Both A and B

Answer: A) CREATE (a)-[:FOLLOWS]->(b) -> Explanation: The correct syntax to create a directed relationship is CREATE (a)-[:FOLLOWS]->(b). The arrow shows direction.


Q22. What does the MERGE command do if the pattern already exists?

  1. Creates a duplicate
  2. Returns the existing node/relationship
  3. Throws an error
  4. Deletes the existing one

Answer: B) Returns the existing node/relationship -> Explanation: MERGE checks if the pattern exists. If it does, it returns (matches) the existing one. If not, it creates a new one.


Q23. What happens if you run CREATE twice with the same data?

  1. Only one node is created
  2. Two duplicate nodes are created
  3. An error occurs
  4. The second is ignored

Answer: B) Two duplicate nodes are created -> Explanation: CREATE always creates new data. Running it twice with the same data creates two duplicate nodes.


Q24. What happens if you run MERGE twice with the same data?

  1. Two duplicate nodes are created
  2. Only one node is created; the second run returns the existing node
  3. An error occurs
  4. The second is ignored

Answer: B) Only one node is created; the second run returns the existing node -> Explanation: MERGE creates only if not exists. Running it twice creates one node and returns the existing node on the second run.


Graph Traversal

Q25. What is graph traversal?

  1. Creating new nodes
  2. Navigating through a graph by following relationships
  3. Deleting nodes
  4. Storing data

Answer: B) Navigating through a graph by following relationships -> Explanation: Graph traversal is the process of navigating through a graph by following relationships (edges) from one node to another to find connected nodes.


Q26. What is a one-hop traversal?

  1. Finding nodes two steps away
  2. Finding immediate neighbors (directly connected nodes)
  3. Finding the shortest path
  4. Finding all nodes in the graph

Answer: B) Finding immediate neighbors (directly connected nodes) -> Explanation: A one-hop traversal finds the immediate neighbors (directly connected nodes) from a given node.


Q27. What is a two-hop traversal?

  1. Finding directly connected nodes
  2. Finding nodes that are two relationships away
  3. Finding the shortest path
  4. Finding all nodes

Answer: B) Finding nodes that are two relationships away -> Explanation: A two-hop traversal finds nodes that are two relationships away from a given node.


Q28. Which Cypher query finds nodes reachable within 1 to 3 hops?

  1. MATCH (a)-[:FOLLOWS]->(b)
  2. MATCH (a)-[:FOLLOWS*1..3]->(b)
  3. MATCH (a)-[:FOLLOWS*]->(b)
  4. MATCH (a)-[:FOLLOWS{1,3}]->(b)

Answer: B) MATCH (a)-[:FOLLOWS*1..3]->(b) -> Explanation: The *1..3 syntax specifies a variable-length traversal of 1 to 3 hops.


Q29. Which function finds the shortest path between two nodes?

  1. shortestRoute()
  2. shortestPath()
  3. minPath()
  4. findPath()

Answer: B) shortestPath() -> Explanation: shortestPath() is used to find the shortest path between two nodes in Cypher.


Q30. Which traversal technique explores as far as possible along each branch?

  1. BFS
  2. DFS
  3. Shortest path
  4. One-hop

Answer: B) DFS -> Explanation: Depth-First Search (DFS) explores as far as possible along each branch before backtracking.


Q31. Which traversal technique explores all neighbors level by level?

  1. DFS
  2. BFS
  3. Shortest path
  4. Variable-length

Answer: B) BFS -> Explanation: Breadth-First Search (BFS) explores all neighbors level by level. It is used for finding shortest paths.


Graph Algorithms

Q32. What do centrality algorithms measure?

  1. Path length
  2. Importance of nodes
  3. Community size
  4. Similarity

Answer: B) Importance of nodes -> Explanation: Centrality algorithms measure the importance of nodes based on their position and connections. Examples: PageRank, Degree, Betweenness, Closeness.


Q33. Which centrality algorithm measures importance based on incoming links?

  1. Degree Centrality
  2. PageRank
  3. Betweenness Centrality
  4. Closeness Centrality

Answer: B) PageRank -> Explanation: PageRank measures the importance of nodes based on the number and quality of incoming links. A node is important if linked by other important nodes.


Q34. What do community detection algorithms do?

  1. Find shortest paths
  2. Partition the graph into communities
  3. Measure node importance
  4. Calculate similarity

Answer: B) Partition the graph into communities -> Explanation: Community detection algorithms partition the graph into communities where nodes are more connected within the group than with outside nodes.


Q35. Which algorithm is used for community detection?

  1. PageRank
  2. Louvain
  3. Dijkstra
  4. Jaccard

Answer: B) Louvain -> Explanation: Louvain and Leiden are community detection algorithms. PageRank is centrality; Dijkstra is path finding; Jaccard is similarity.


Q36. Which algorithm finds the shortest route between nodes?

  1. PageRank
  2. Louvain
  3. Dijkstra
  4. Jaccard

Answer: C) Dijkstra -> Explanation: Dijkstra’s algorithm finds the shortest path between nodes. It is a path finding algorithm.


Q37. Which algorithm measures how similar two nodes are?

  1. PageRank
  2. Node Similarity
  3. Dijkstra
  4. Louvain

Answer: B) Node Similarity -> Explanation: Node Similarity measures how similar two nodes are based on shared neighbors or attributes. Jaccard and Cosine are also similarity measures.


Q38. Which similarity measure uses intersection over union of neighbors?

  1. Cosine Similarity
  2. Jaccard Similarity
  3. Euclidean Distance
  4. PageRank

Answer: B) Jaccard Similarity -> Explanation: Jaccard Similarity measures similarity as the intersection over union of neighbors.


Neo4j Architecture

Q39. What is Neo4j?

  1. A relational database
  2. A native graph database
  3. A document database
  4. A key-value store

Answer: B) A native graph database -> Explanation: Neo4j is a native graph database that stores data as nodes and relationships. It uses a property graph model.


Q40. Which layer of Neo4j architecture stores nodes, relationships, labels, and properties?

  1. Application layer
  2. Cypher query layer
  3. Database engine
  4. Graph storage

Answer: D) Graph storage -> Explanation: Graph storage stores nodes, relationships, labels, and properties.


Q41. What is the role of the Neo4j database engine?

  1. Store data
  2. Store, index, process, and traverse the graph
  3. Provide UI
  4. Manage users

Answer: B) Store, index, process, and traverse the graph -> Explanation: The Neo4j database engine stores, indexes, processes, and traverses the graph.


Q42. In Neo4j, relationships always have:

  1. No direction
  2. A direction (start → end)
  3. A single node
  4. No type

Answer: B) A direction (start → end) -> Explanation: Relationships in Neo4j always have a direction (start → end). They can also have types and properties.


Q43. Which of the following is a valid Neo4j node label?

  1. name
  2. Person
  3. age
  4. location

Answer: B) Person -> Explanation: Person is a node label. name, age, and location are properties.


Social Network Use Cases

Q44. Which Cypher query creates a new user?

  1. CREATE (p:Person {name: 'Alice'})
  2. INSERT (p:Person {name: 'Alice'})
  3. ADD (p:Person {name: 'Alice'})
  4. NEW (p:Person {name: 'Alice'})

Answer: A) CREATE (p:Person {name: 'Alice'}) -> Explanation: The CREATE command creates a new node with the label Person and property name.


Q45. Which Cypher query finds a user’s friends?

  1. MATCH (p:Person)-[:FRIENDS_WITH]-(f:Person) RETURN f.name
  2. SELECT friends FROM Person
  3. FIND friends OF Person
  4. GET friends FROM Person

Answer: A) MATCH (p:Person)-[:FRIENDS_WITH]-(f:Person) RETURN f.name -> Explanation: The MATCH query with FRIENDS_WITH relationship finds a user’s friends.


Q46. Which Cypher query finds popular posts?

  1. MATCH (p:Post)<-[:LIKES]-(Person) RETURN p, count(*) AS likes ORDER BY likes DESC
  2. SELECT * FROM Post ORDER BY likes
  3. FIND Post WITH MOST likes
  4. GET popular posts

Answer: A) MATCH (p:Post)<-[:LIKES]-(Person) RETURN p, count(*) AS likes ORDER BY likes DESC -> Explanation: This query matches posts and their likes, counts them, and orders by like count descending.


Q47. Which Cypher query finds friend recommendations (friends-of-friends)?

  1. MATCH (p:Person)-[:FRIENDS_WITH]-(f:Person)-[:FRIENDS_WITH]-(fof:Person) RETURN fof
  2. SELECT friends of friends
  3. FIND friends_of_friends
  4. GET recommendations

Answer: A) MATCH (p:Person)-[:FRIENDS_WITH]-(f:Person)-[:FRIENDS_WITH]-(fof:Person) RETURN fof -> Explanation: This query traverses two FRIENDS_WITH relationships to find friends-of-friends.


Q48. Which Cypher query creates a friendship between two users?

  1. MATCH (a:Person), (b:Person) MERGE (a)-[:FRIENDS_WITH]->(b)
  2. CREATE FRIENDSHIP (a, b)
  3. INSERT FRIENDSHIP
  4. ADD FRIENDSHIP

Answer: A) MATCH (a:Person), (b:Person) MERGE (a)-[:FRIENDS_WITH]->(b) -> Explanation: This query matches two Person nodes and uses MERGE to create a FRIENDS_WITH relationship between them.


Q49. Which Cypher query finds the shortest path between Alice and Eve?

  1. MATCH p = shortestPath((a:Person {name: 'Alice'})-[:FOLLOWS*]-(e:Person {name: 'Eve'})) RETURN p
  2. FIND PATH FROM Alice TO Eve
  3. SELECT shortest_path FROM Person
  4. GET shortest path

Answer: A) MATCH p = shortestPath((a:Person {name: 'Alice'})-[:FOLLOWS*]-(e:Person {name: 'Eve'})) RETURN p -> Explanation: The shortestPath() function finds the shortest path between Alice and Eve.


Q50. What does the Cypher query RETURN [n in nodes(p) | n.name] AS path do?

  1. Returns all nodes
  2. Returns node names along the path
  3. Returns relationships
  4. Returns properties

Answer: B) Returns node names along the path -> Explanation: The list comprehension [n in nodes(p) | n.name] extracts the name property from each node in the path p.


SECTION B: THEORY QUESTIONS (20)


Q1. Define a graph database. Explain its core components.

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:

ComponentDescriptionExamples
NodesRepresent an entity or object; can have a label and propertiesPerson, Product, Company, City
RelationshipsRepresent a connection between two nodes; usually directed; has a type; can have propertiesFRIEND_OF, WORKS_AT, LIKES
PropertiesKey-value pairs storing additional information(name: "Alice", age: 25), (since: 2020)

Example — Social Network:

Alice ──FRIEND_OF (since: 2020)──→ Bob
  │                                  │
  │ LIVES_IN                         │ WORKS_AT
  ↓                                  ↓
Bangalore                        ABC Corp

In Simple Terms:

Nodes = Things
Relationships = Connections
Properties = Details about things/connections

Q2. Compare relational databases and graph databases.

Answer:

AspectRelational DatabaseGraph Database
Data ModelTables with rows and columnsNodes, relationships, properties
SchemaPredefined (fixed)Flexible (schema optional)
RelationshipsForeign keys and joinsFirst-class citizens
Best Suited ForStructured data with well-defined schemaHighly connected data
Query LanguageSQLCypher, Gremlin, SPARQL
PerformanceJoins can be expensiveFast traversal
ScalabilityVertically scalableHorizontally scalable
Use CasesBanking, ERP, inventorySocial networks, recommendations, fraud detection
ExamplesMySQL, PostgreSQL, OracleNeo4j, Amazon Neptune, JanusGraph

Key Difference:

“Relational databases store data in tables. Graph databases store data as connected entities, making relationships easier and faster to work with.”


Q3. Explain the property graph model.

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
  • Can have one or more labels
  • Contain a set of properties (key-value pairs)

2. Labels:

  • Identify the type or category of a node
  • A node can have single or multiple labels
  • Examples: Student, Teacher, Course, Company

3. Relationship Types:

  • Describe the nature of connection between two nodes
  • Usually directed (from one node to another)
  • Can have properties
  • Examples: ENROLLED_IN, FRIEND_OF, WORKS_AT

Example — University Graph:

:Student (Alice)  ──ENROLLED_IN (year: 2026)──→  :Course (NoSQL)
      │                                                │
      │ WORKS_AT (since: 2023)                         │ TAUGHT_BY (semester: "Fall 2026")
      ↓                                                ↓
:Company (ABC Corp)                              :Teacher (Dr. Kumar)

Key Takeaway:

Labels tell us what a node is, while relationship types tell us how two nodes are connected.


Q4. Explain Cypher with CREATE and MERGE commands.

Answer:

Cypher is a declarative, SQL-like query language used in Neo4j to create, read, update, and delete graph data.

Cypher Pattern Syntax:

(a:Label)-[r:RELATIONSHIP_TYPE]->(b:Label)

CREATE: Always creates new nodes or relationships. Does not check if the data already exists. Can result in duplicates.

CREATE (a:Person {name: 'Alice', age: 25}),
       (b:Person {name: 'Bob', age: 27})
CREATE (a)-[:FOLLOWS]->(b)
RETURN a, b;

Run twice → Two separate nodes (duplicates)

MERGE: Creates a node or relationship only if it does not exist. If it exists, it matches the existing one. Prevents duplicates.

MERGE (p:Person {name: 'Alice', age: 25})
RETURN p;

Run twice → Only one node created

Comparison:

AspectCREATEMERGE
BehaviourAlways creates new dataCreates only if not exists
Duplicate DataCan create duplicatesPrevents duplicates
Use CaseAlways create newEnsure uniqueness
Repeated ExecutionMultiple identical nodesSingle node (existing returned)

Key Takeaway:

“Use CREATE when you want to always create. Use MERGE when you want to create only if it doesn’t exist.”


Q5. Explain graph traversal with one-hop and two-hop examples.

Answer:

Graph traversal is the process of navigating through a graph by following relationships (edges) from one node to another to find connected nodes.

Example Graph:

        Carol
          ↑ FOLLOWS
          │
David ←─ Alice ─→ Bob
  FOLLOWS         FOLLOWS

One-Hop Traversal: Find the immediate neighbors (directly connected nodes) from a given node.

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->(b:Person)
RETURN b;

Result: Bob, Carol

Two-Hop Traversal: Find nodes that are two relationships away from a given node.

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->()-[:FOLLOWS]->(c:Person)
RETURN c;

Result: David (Alice → Bob → David)

Variable-Length Traversal:

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS*1..3]->(p:Person)
RETURN DISTINCT p.name;

Result: Bob, Carol, David

Shortest Path:

MATCH p = shortestPath(
    (a:Person {name: 'Alice'})-[:FOLLOWS*]-(e:Person {name: 'Eve'})
)
RETURN [n in nodes(p) | n.name] AS path;

Result: [“Alice”, “Carol”, “Eve”]


Q6. Explain the categories of graph algorithms.

Answer:

Graph algorithms analyze the structure and relationships in a graph to find meaningful patterns.

1. Centrality Algorithms: Measure the importance of nodes based on their position and connections.

AlgorithmDescription
PageRankImportance based on incoming links
Degree CentralityNumber of connections
Betweenness CentralityHow often a node lies on shortest paths
Closeness CentralityAverage distance to other nodes

2. Community Detection Algorithms: Partition the graph into communities where nodes are more connected within the group than with outside nodes.

AlgorithmDescription
LouvainModularity-based community detection
LeidenImproved Louvain algorithm
Label PropagationFast community detection
Weakly Connected ComponentsConnected subgraphs

3. Path Finding Algorithms: Find paths or shortest routes between nodes.

AlgorithmDescription
Dijkstra’s Shortest PathShortest path by cost
A* Shortest PathHeuristic shortest path
BFSBreadth-First Search
DFSDepth-First Search

4. Similarity Algorithms: Measure how similar two nodes are.

AlgorithmDescription
Node SimilarityBased on shared neighbors
K-Nearest Neighbors (KNN)K most similar nodes
Jaccard SimilarityIntersection over union
Cosine SimilarityCosine of angle between vectors

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.


Q7. Explain PageRank and its use case.

Answer:

PageRank is a centrality algorithm that measures the importance of nodes based on the number and quality of incoming links.

Principle: A node is important if it is linked by other important nodes.

Example:

A → C ← B
    ↑
    D
    ↑
    E

PageRank Scores:

NodeScore
C0.42
A0.21
D0.18
B0.12
E0.07

Interpretation:

  • Node C has the highest PageRank because it has incoming links from multiple nodes.
  • Higher PageRank = more influence.

Use Cases:

  1. Ranking web pages
  2. Finding influential users in social networks
  3. Identifying key entities in knowledge graphs
  4. Recommendation systems

Key Takeaway:

PageRank helps identify the most important or influential nodes in a network based on incoming connections.


Q8. Explain community detection algorithms.

Answer:

Community Detection Algorithms partition the graph into communities where nodes are more connected within the group than with outside nodes.

Purpose: Find natural groups, such as social circles or customer segments.

Example:

Community 1 (Friends)     Community 2 (Colleagues)
   B ── C                    D ── E
   │    │                    │    │
   A ───┘                    F ───┘

Algorithms:

AlgorithmDescription
LouvainModularity-based; widely used
LeidenImproved Louvain; guarantees well-connected communities
Label PropagationFast; uses labels
Weakly Connected ComponentsFinds connected subgraphs

Use Cases:

  1. Social network analysis (finding groups of friends)
  2. Customer segmentation
  3. Fraud detection (finding suspicious groups)
  4. Recommendation systems
  5. Biology (protein interaction networks)

Key Takeaway:

Community detection helps discover natural groupings in networks, enabling targeted analysis and recommendations.


Q9. Explain path finding algorithms.

Answer:

Path Finding Algorithms find paths or shortest routes between nodes. Determine paths based on distance, cost, or other criteria.

Example:

        B
     2 ↗   ↘ 5
A → 1 → C → 2 → E
     4 ↘   ↗ 1
        D

Shortest path from A to E: A → C → E (total cost = 3)

Algorithms:

AlgorithmDescriptionUse Case
Dijkstra’s Shortest PathShortest path by costRoute planning
A* Shortest PathHeuristic shortest pathGPS navigation
BFSBreadth-First SearchUnweighted shortest path
DFSDepth-First SearchPath exploration

Use Cases:

  1. Route planning (maps, logistics)
  2. Network routing (data packets)
  3. Recommendation paths (user journey)
  4. Fraud detection (unusual paths)
  5. Social network analysis (degrees of separation)

Key Takeaway:

Path finding algorithms help find the most efficient routes or connections between entities in a network.


Q10. Explain similarity algorithms in graph analytics.

Answer:

Similarity Algorithms measure how similar two nodes are, typically based on shared neighbors or attributes.

Purpose: Recommendations, fraud detection, and finding similar items or users.

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 PairScore
A – B0.80
A – C0.65
B – D0.60

Algorithms:

AlgorithmDescription
Node SimilarityBased on shared neighbors
K-Nearest Neighbors (KNN)K most similar nodes
Jaccard SimilarityIntersection over union
Cosine SimilarityCosine of angle between vectors

Use Cases:

  1. Product recommendations
  2. Friend suggestions
  3. Fraud detection
  4. Finding similar users/items
  5. Link prediction

Key Takeaway:

Similarity algorithms help identify how alike two nodes are, enabling recommendations and pattern detection.


Q11. Explain Neo4j architecture.

Answer:

Neo4j is a native graph database that stores data as nodes and relationships. It uses a property graph model and provides a high-performance graph engine, Cypher query language, and tools for data management and visualization.

Architecture Layers:

┌─────────────────────────────────────────────────────┐
│  Applications     │  Cypher Query    │  Tools       │
│  (Web, Mobile)    │  Language        │  (Browser,   │
│                   │                  │   Bloom)     │
├─────────────────────────────────────────────────────┤
│           Neo4j Database Engine                     │
│  Stores, indexes, processes and traverses the graph │
├─────────────────────────────────────────────────────┤
│              Graph Storage                          │
│  Nodes │ Relationships │ Labels │ Properties        │
└─────────────────────────────────────────────────────┘

Components:

LayerPurpose
ApplicationsWeb, mobile, desktop applications
Cypher Query LanguageQuery and manipulate graph data
ToolsNeo4j Browser, Bloom, Drivers
Database EngineStores, indexes, processes, traverses
Graph StorageNodes, relationships, labels, properties

Key Features:

  1. Native graph storage
  2. Property graph model
  3. Cypher query language
  4. ACID transactions
  5. High performance
  6. Horizontal scalability
  7. Indexes on labels and properties

Use Cases:

  1. Social networks
  2. Recommendation systems
  3. Fraud detection
  4. Knowledge graphs
  5. Network analysis

Q12. Explain nodes and relationships in Neo4j.

Answer:

Nodes:

  • Represent entities (e.g., people, posts, products)
  • Can have one or more labels
  • Store properties as key-value pairs
  • Represent a real-world entity

Example:

:Person
{name: "Alice", age: 25, location: "Bangalore"}

Relationships:

  • Connect two nodes and represent how they are related
  • Always have a direction (start → end)
  • Can have a type (e.g., FRIENDS_WITH, LIKES)
  • Can store properties (e.g., since, createdAt)
  • Represent meaningful connections between entities

Example:

Alice ──:FRIENDS_WITH {since: 2020}──→ Bob

Labels and Properties:

Node Labels and Properties:

LabelExample Properties
:Personname, age, location
:Posttitle, content, createdAt
:Productname, price

Relationship Types and Properties:

TypeExample Properties
:FRIENDS_WITHsince
:LIKEScreatedAt
:CREATEDcreatedAt

Key Points:

  • Labels define the type of node or relationship
  • Properties store information as key-value pairs
  • Both labels and properties make data flexible and easy to query
  • Indexes can be created on labels and properties for faster search

Q13. Explain the Cypher query for creating a social network.

Answer:

Create a user:

CREATE (p:Person {
    userid: 'u1001',
    name: 'Alice',
    age: 25,
    location: 'Bangalore',
    joinDate: date()
});

Create a friendship:

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MERGE (a)-[:FRIENDS_WITH {since: date()}]->(b);

Find a user’s friends:

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
RETURN f.name, f.location;

Find posts by a user:

MATCH (p:Person {name: 'Alice'})-[:CREATED]->(post:Post)
RETURN post.postid, post.content, post.createdAt;

Add a tag to a post:

MERGE (t:Tag {name: 'Neo4j'})
MATCH (p:Post {postid: 'p100'})
MERGE (p)-[:HAS_TAG]->(t);

Find popular posts:

MATCH (p:Post)<-[:LIKES]-(Person)
RETURN p.postid, p.content, count(*) AS likeCount
ORDER BY likeCount DESC
LIMIT 5;

Friend recommendations (friends-of-friends):

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
WHERE NOT (p)-[:FRIENDS_WITH]-(f)
AND p <> f
RETURN DISTINCT f.name, f.location
LIMIT 10;

Q14. Explain graph traversal techniques in Neo4j.

Answer:

Graph traversal is the process of navigating through a graph by following relationships. In Neo4j, traversals are performed using Cypher pattern matching.

Cypher Pattern Syntax:

(a:Label)-[r:RELATIONSHIP_TYPE]->(b:Label)

Traversal Techniques:

TechniqueDescriptionExample Use Case
Simple RelationshipFind directly connected nodesFind people Alice follows
Variable-LengthFind nodes within a variable number of hopsFind friends-of-friends
Shortest PathFind shortest path between nodesFind connection between users
DFSExplores as far as possible along each branchPath exploration
BFSExplores all neighbors level by levelFinding shortest paths
Filtered TraversalUse WHERE to apply conditionsFind friends in a location
Multi-relationshipTraverse multiple relationship typesFind people who follow or like
BidirectionalUse undirected patternsFind any connection between nodes

Examples:

Simple Relationship:

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->(b:Person)
RETURN b.name;

Variable-Length:

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS*1..3]->(p:Person)
RETURN DISTINCT p.name;

Shortest Path:

MATCH p = shortestPath(
    (a:Person {name: 'Alice'})-[:FOLLOWS*]-(b:Person {name: 'Eve'})
)
RETURN [n in nodes(p) | n.name] AS path;

Filtered:

MATCH (a:Person {name: 'Alice'})-[r:FOLLOWS]->(b:Person)
WHERE r.since >= 2023
RETURN b.name, r.since;

Key Takeaways:

  • Neo4j stores data as nodes and relationships, making traversals natural
  • Cypher provides a powerful way to perform graph traversals
  • Use relationship patterns, variable-length, and shortest path functions
  • Traversals enable recommendations, fraud detection, and network analysis

Q15. Explain the significance of graph algorithms in real-world applications.

Answer:

Graph algorithms analyze the structure and relationships in a graph to find meaningful patterns. They help identify important nodes, discover communities, find connections, and measure similarity.

Real-World Applications:

ApplicationAlgorithm CategoryExample
Social NetworksCentrality, Community DetectionFinding influencers, groups
Recommendation SystemsSimilarityProduct recommendations
Fraud DetectionCommunity Detection, SimilaritySuspicious groups
Knowledge GraphsCentrality, Path FindingEntity importance
Network OptimizationPath FindingRoute planning
BiologyCommunity DetectionProtein interactions
CybersecurityPath Finding, SimilarityAttack paths
Supply ChainPath FindingLogistics optimization

Benefits:

  1. Identify important nodes — PageRank, Degree
  2. Discover communities — Louvain, Leiden
  3. Find connections — Shortest path, BFS
  4. Measure similarity — Jaccard, Cosine
  5. Optimize networks — Dijkstra, A*
  6. Detect anomalies — Community, Similarity

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.


Q16. Explain the difference between DFS and BFS.

Answer:

AspectDFS (Depth-First Search)BFS (Breadth-First Search)
StrategyExplores as far as possible along each branchExplores all neighbors level by level
Data StructureStackQueue
MemoryLess memoryMore memory
Shortest PathNot guaranteedGuaranteed (unweighted)
Use CasePath exploration, hierarchyShortest path, social networks
ImplementationRecursive or stackQueue
Time ComplexityO(V + E)O(V + E)
Space ComplexityO(h) — heightO(w) — width

Example Graph:

        A
       / \
      B   C
     / \   \
    D   E   F

DFS Traversal: A → B → D → E → C → F BFS Traversal: A → B → C → D → E → F

Use Cases:

  • DFS: Maze solving, topological sorting, cycle detection
  • BFS: Shortest path, social network degrees, web crawling

Q17. Explain the Cypher query for finding popular posts.

Answer:

Find top 5 posts by number of likes:

MATCH (p:Post)<-[:LIKES]-(Person)
RETURN p.postid, p.content, count(*) AS likeCount
ORDER BY likeCount DESC
LIMIT 5;

-> Explanation:

ClausePurpose
MATCH (p:Post)<-[:LIKES]-(Person)Match posts and their likes
RETURN p.postid, p.content, count(*) AS likeCountReturn post details and like count
ORDER BY likeCount DESCSort by like count descending
LIMIT 5Return top 5

Result:

postidcontentlikeCount
p100“Graph DB Rocks!”150
p101“Neo4j is amazing!”120
p102“Cypher is powerful!”95

Key Points:

  • Uses count(*) to count likes
  • ORDER BY ... DESC sorts descending
  • LIMIT restricts results

Q18. Explain friend recommendations using Cypher.

Answer:

Friend recommendations (friends-of-friends): Find users who are friends of my friends (excluding direct friends).

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
WHERE NOT (p)-[:FRIENDS_WITH]-(f)
AND p <> f
RETURN DISTINCT f.name, f.location
LIMIT 10;

-> Explanation:

ClausePurpose
MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)Find friends of Alice
WHERE NOT (p)-[:FRIENDS_WITH]-(f)Exclude direct friends
AND p <> fExclude Alice herself
RETURN DISTINCT f.name, f.locationReturn unique recommendations
LIMIT 10Return top 10

How It Works:

  1. Start with Alice
  2. Traverse FRIENDS_WITH to find her friends
  3. From those friends, traverse FRIENDS_WITH again
  4. Exclude direct friends and Alice
  5. Return unique recommendations

Example:

Alice ──FRIENDS_WITH──→ Bob ──FRIENDS_WITH──→ Carol
Alice ──FRIENDS_WITH──→ David ──FRIENDS_WITH──→ Carol

Carol is a friend-of-friend → recommend Carol to Alice.


Q19. Explain Neo4j’s property graph data model with an example.

Answer:

Neo4j’s Property Graph Data Model stores data as nodes and relationships with labels and properties.

Example:

:Person (Alice)  ←──FRIENDS_WITH──→  :Person (Bob)
{name: "Alice",                     {name: "Bob",
 age: 25,                            age: 27,
 location: "Bangalore"}              location: "Mumbai"}
      │                                    │
      │ CREATED                            │ LIKES
      ↓                                    ↓
:Post (Graph DB)                    :Post (Graph DB)
{title: "Graph DB",                 {createdAt: "2024-09-01"}
 content: "Neo4j is amazing!",
 createdAt: "2024-09-01"}

Components:

ComponentDescriptionExample
NodesEntities:Person, :Post
LabelsCategories:Person, :Post
RelationshipsConnectionsFRIENDS_WITH, CREATED, LIKES
PropertiesKey-value pairsname, age, location

Node Labels and Properties:

LabelExample Properties
:Personname, age, location
:Posttitle, content, createdAt
:Productname, price

Relationship Types and Properties:

TypeExample Properties
:FRIENDS_WITHsince
:LIKEScreatedAt
:CREATEDcreatedAt

Key Points:

  • Labels define the type of node or relationship
  • Properties store information as key-value pairs
  • Both labels and properties make data flexible
  • Indexes can be created on labels and properties

Q20. Explain the complete Cypher workflow for a social network application.

Answer:

1. Create Users:

CREATE (alice:Person {userid: 'u1001', name: 'Alice', age: 25, location: 'Bangalore'});
CREATE (bob:Person {userid: 'u1002', name: 'Bob', age: 27, location: 'Mumbai'});
CREATE (carol:Person {userid: 'u1003', name: 'Carol', age: 26, location: 'Delhi'});

2. Create Friendships:

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MERGE (a)-[:FRIENDS_WITH {since: date()}]->(b);

MATCH (a:Person {name: 'Bob'}), (c:Person {name: 'Carol'})
MERGE (a)-[:FRIENDS_WITH {since: date()}]->(c);

3. Find Friends:

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
RETURN f.name, f.location;

4. Create Posts:

MATCH (p:Person {name: 'Alice'})
CREATE (p)-[:CREATED]->(post:Post {postid: 'p100', content: 'Graph DB Rocks!', createdAt: date()});

5. Like Posts:

MATCH (p:Person {name: 'Bob'}), (post:Post {postid: 'p100'})
MERGE (p)-[:LIKES {createdAt: date()}]->(post);

6. Find Popular Posts:

MATCH (p:Post)<-[:LIKES]-(Person)
RETURN p.postid, p.content, count(*) AS likeCount
ORDER BY likeCount DESC
LIMIT 5;

7. Friend Recommendations:

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
WHERE NOT (p)-[:FRIENDS_WITH]-(f)
AND p <> f
RETURN DISTINCT f.name, f.location
LIMIT 10;

8. Shortest Path:

MATCH p = shortestPath(
    (a:Person {name: 'Alice'})-[:FRIENDS_WITH*]-(c:Person {name: 'Carol'})
)
RETURN [n in nodes(p) | n.name] AS path;

Workflow Summary:

  1. Create nodes (users, posts, tags)
  2. Create relationships (friendships, likes, created)
  3. Query data (friends, posts, popular posts)
  4. Analyze (recommendations, shortest path)

SECTION C: ANALYTICAL QUESTIONS (10)


Q1. Analyze the following Cypher commands and predict the output.

CREATE (a:Person {name: 'Alice', age: 25})
CREATE (b:Person {name: 'Bob', age: 27})
CREATE (a)-[:FOLLOWS]->(b)
RETURN a, b;

Answer:

Output:

:Person (Alice)  ──FOLLOWS──→  :Person (Bob)
name: "Alice"                  name: "Bob"
age: 25                        age: 27

Step-by-step:

  1. CREATE (a:Person {name: 'Alice', age: 25}) → creates Alice node
  2. CREATE (b:Person {name: 'Bob', age: 27}) → creates Bob node
  3. CREATE (a)-[:FOLLOWS]->(b) → creates FOLLOWS relationship from Alice to Bob
  4. RETURN a, b → returns both nodes

Key Points:

  • CREATE always creates new nodes
  • Relationship direction is Alice → Bob
  • Relationship type is FOLLOWS

Q2. Analyze the difference between CREATE and MERGE with an example.

// Query 1
CREATE (p:Person {name: 'Alice', age: 25})
RETURN p;

// Query 2
MERGE (p:Person {name: 'Alice', age: 25})
RETURN p;

Answer:

Query 1 — Run twice:

Two separate nodes created (duplicates)

:Person (Alice)  :Person (Alice)
name: "Alice"    name: "Alice"
age: 25          age: 25

Query 2 — Run twice:

Only one node created (second run matches existing)

:Person (Alice)
name: "Alice"
age: 25

Comparison:

AspectCREATEMERGE
First runCreates nodeCreates node
Second runCreates duplicateReturns existing
Result2 nodes1 node

Key Takeaway:

Use CREATE when you want to always create. Use MERGE when you want to create only if it doesn’t exist.


Q3. Analyze the following one-hop and two-hop traversals.

        Carol
          ↑ FOLLOWS
          │
David ←─ Alice ─→ Bob
  FOLLOWS         FOLLOWS

Query 1 — One-hop:

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->(b:Person)
RETURN b.name;

Query 2 — Two-hop:

MATCH (a:Person {name: 'Alice'})-[:FOLLOWS]->()-[:FOLLOWS]->(c:Person)
RETURN c.name;

Answer:

Query 1 Output:

b.name
Bob
Carol

-> Explanation: One-hop returns directly connected nodes from Alice: Bob and Carol.

Query 2 Output:

c.name
David

-> Explanation: Two-hop returns nodes two steps away: Alice → Bob → David.

Key Points:

  • One-hop: immediate neighbors
  • Two-hop: nodes two relationships away
  • Direction matters in traversal

Q4. Analyze the following Cypher query for friend recommendations.

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
WHERE NOT (p)-[:FRIENDS_WITH]-(f)
AND p <> f
RETURN DISTINCT f.name, f.location
LIMIT 10;

Answer:

Purpose: Find friends-of-friends (excluding direct friends and Alice herself).

Graph:

Alice ──FRIENDS_WITH──→ Bob ──FRIENDS_WITH──→ Carol
Alice ──FRIENDS_WITH──→ David ──FRIENDS_WITH──→ Carol

Output:

f.name    f.location
Carol     Delhi

Step-by-step:

  1. Match Alice and her direct friends (Bob, David)
  2. Traverse FRIENDS_WITH from those friends
  3. Find Carol (friend of Bob and David)
  4. Exclude direct friends (Bob, David) and Alice
  5. Return Carol as recommendation

Key Points:

  • NOT (p)-[:FRIENDS_WITH]-(f) excludes direct friends
  • p <> f excludes Alice herself
  • DISTINCT removes duplicates
  • LIMIT 10 restricts results

Q5. Analyze the following PageRank example.

A → C ← B
    ↑
    D
    ↑
    E

Scores:

NodePageRank Score
C0.42
A0.21
D0.18
B0.12
E0.07

Answer:

Analysis:

  • Node C has the highest PageRank (0.42) because it has incoming links from A, B, D, and E.
  • Node A has the second highest (0.21) because it links to C (important node).
  • Node E has the lowest (0.07) because it only links to D and has no incoming links.

Interpretation:

  • PageRank measures importance based on incoming links
  • A node is important if linked by other important nodes
  • Higher PageRank = more influence

Use Case:

  • Finding influential users in a social network
  • Ranking web pages
  • Identifying key entities

Q6. Analyze the shortest path query and predict the output.

        B
     2 ↗   ↘ 5
A → 1 → C → 2 → E
     4 ↘   ↗ 1
        D

Query:

MATCH p = shortestPath(
    (a:Person {name: 'A'})-[:FOLLOWS*]-(e:Person {name: 'E'})
)
RETURN [n in nodes(p) | n.name] AS path;

Answer:

Output:

path
["A", "C", "E"]

-> Explanation:

  • Path A → C → E has cost 1 + 2 = 3
  • Path A → B → E has cost 2 + 5 = 7
  • Path A → D → E has cost 4 + 1 = 5

Shortest path: A → C → E (cost = 3)

Key Points:

  • shortestPath() finds minimum cost path
  • [n in nodes(p) | n.name] extracts node names
  • Direction matters in traversal

Q7. Analyze the following Cypher query for popular posts.

MATCH (p:Post)<-[:LIKES]-(Person)
RETURN p.postid, p.content, count(*) AS likeCount
ORDER BY likeCount DESC
LIMIT 5;

Answer:

Purpose: Find top 5 posts by number of likes.

Output:

postidcontentlikeCount
p100“Graph DB Rocks!”150
p101“Neo4j is amazing!”120
p102“Cypher is powerful!”95
p103“NoSQL is the future!”80
p104“Graph analytics!”75

-> Explanation:

  1. Match posts and their likes
  2. Count likes for each post
  3. Sort by like count descending
  4. Return top 5

Key Points:

  • count(*) counts likes
  • ORDER BY ... DESC sorts descending
  • LIMIT 5 restricts results

Q8. Analyze the following Neo4j property graph example.

:Person (Alice)  ──FRIENDS_WITH (since: 2020)──→  :Person (Bob)
{name: "Alice",                                   {name: "Bob",
 age: 25,                                          age: 27,
 location: "Bangalore"}                            location: "Mumbai"}
      │                                                 │
      │ CREATED                                         │ LIKES
      ↓                                                 ↓
:Post (Graph DB)                                  :Post (Graph DB)
{title: "Graph DB",                               {createdAt: "2024-09-01"}
 content: "Neo4j is amazing!",
 createdAt: "2024-09-01"}

Answer:

Nodes:

  • Alice (Person) with properties: name, age, location
  • Bob (Person) with properties: name, age, location
  • Post (Graph DB) with properties: title, content, createdAt

Relationships:

  • Alice → Bob (FRIENDS_WITH) with property: since
  • Alice → Post (CREATED)
  • Bob → Post (LIKES) with property: createdAt

Analysis:

  1. Alice and Bob are friends since 2020
  2. Alice created a post about Graph DB
  3. Bob liked the post
  4. Post has title, content, and createdAt properties

Key Points:

  • Labels define node types
  • Relationships connect nodes
  • Properties store details
  • Both nodes and relationships can have properties

Q9. Design a Cypher query for a recommendation system.

Answer:

Scenario: Recommend products to a user based on what similar users purchased.

Graph:

User1 ──PURCHASED──→ Product A
User1 ──PURCHASED──→ Product B
User2 ──PURCHASED──→ Product A
User2 ──PURCHASED──→ Product B
User2 ──PURCHASED──→ Product C

Query:

MATCH (u1:User {name: 'User1'})-[:PURCHASED]->(p:Product)<-[:PURCHASED]-(u2:User)
WHERE u1 <> u2
AND NOT (u1)-[:PURCHASED]->(p)
RETURN DISTINCT p.name AS recommendation, count(*) AS score
ORDER BY score DESC
LIMIT 5;

-> Explanation:

  1. Find products User1 purchased
  2. Find other users who purchased the same products
  3. Find products those users purchased that User1 has not
  4. Rank by number of similar users
  5. Return top 5 recommendations

Output:

recommendationscore
Product C1

Key Points:

  • Collaborative filtering
  • Based on similar users
  • Excludes already purchased
  • Ranks by popularity

Q10. Design a complete graph database solution for a social network.

Answer:

Requirements:

  • Users with profiles
  • Friendships
  • Posts and comments
  • Likes and tags
  • Recommendations

1. Create Users:

CREATE (alice:Person {userid: 'u1001', name: 'Alice', age: 25, location: 'Bangalore'});
CREATE (bob:Person {userid: 'u1002', name: 'Bob', age: 27, location: 'Mumbai'});
CREATE (carol:Person {userid: 'u1003', name: 'Carol', age: 26, location: 'Delhi'});

2. Create Friendships:

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MERGE (a)-[:FRIENDS_WITH {since: date()}]->(b);

MATCH (b:Person {name: 'Bob'}), (c:Person {name: 'Carol'})
MERGE (b)-[:FRIENDS_WITH {since: date()}]->(c);

3. Create Posts:

MATCH (a:Person {name: 'Alice'})
CREATE (a)-[:CREATED]->(post:Post {postid: 'p100', content: 'Graph DB Rocks!', createdAt: date()});

4. Add Comments:

MATCH (b:Person {name: 'Bob'}), (post:Post {postid: 'p100'})
CREATE (b)-[:COMMENTED {content: 'Nice post!', createdAt: date()}]->(post);

5. Like Posts:

MATCH (b:Person {name: 'Bob'}), (post:Post {postid: 'p100'})
MERGE (b)-[:LIKES {createdAt: date()}]->(post);

6. Add Tags:

MERGE (t:Tag {name: 'Neo4j'})
MATCH (post:Post {postid: 'p100'})
MERGE (post)-[:HAS_TAG]->(t);

7. Find Friends:

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
RETURN f.name, f.location;

8. Find Popular Posts:

MATCH (p:Post)<-[:LIKES]-(Person)
RETURN p.postid, p.content, count(*) AS likeCount
ORDER BY likeCount DESC
LIMIT 5;

9. Friend Recommendations:

MATCH (p:Person {name: 'Alice'})-[:FRIENDS_WITH]-(f:Person)
WHERE NOT (p)-[:FRIENDS_WITH]-(f)
AND p <> f
RETURN DISTINCT f.name, f.location
LIMIT 10;

10. Shortest Path:

MATCH p = shortestPath(
    (a:Person {name: 'Alice'})-[:FRIENDS_WITH*]-(c:Person {name: 'Carol'})
)
RETURN [n in nodes(p) | n.name] AS path;

Solution Architecture:

┌─────────────────────────────────────────────────────┐
│  Applications     │  Cypher Query    │  Tools       │
│  (Web, Mobile)    │  Language        │  (Browser)   │
├─────────────────────────────────────────────────────┤
│           Neo4j Database Engine                     │
├─────────────────────────────────────────────────────┤
│              Graph Storage                          │
│  :Person │ :Post │ :Tag │ :Comment                  │
│  FRIENDS_WITH │ CREATED │ LIKES │ HAS_TAG          │
└─────────────────────────────────────────────────────┘

Benefits:

  1. Fast relationship traversal
  2. Flexible schema
  3. Powerful queries
  4. Real-time recommendations
  5. Scalable

SUMMARY TABLE

SectionCountTopics Covered
MCQ50Graph databases, nodes, relationships, properties, labels, Cypher, CREATE, MERGE, traversal, algorithms, Neo4j, social network
Theory20Graph database definition, relational vs graph, property graph model, Cypher, traversal, algorithms, PageRank, community detection, path finding, similarity, Neo4j architecture, nodes/relationships, social network queries, DFS/BFS, popular posts, recommendations, data model, complete workflow
Analytical10Cypher output prediction, CREATE vs MERGE, one-hop/two-hop, friend recommendations, PageRank analysis, shortest path, popular posts, property graph analysis, recommendation system design, complete social network design

On this page