Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 30 ยท Projects

Project: a social network on a graph

Model users, follows and posts in Neo4j, then write the Cypher for a feed, mutual friends and follow suggestions, with JavaScript stand-ins you can run.

In this project you design the core of a small social network: people follow each other, write posts, and see a feed of what the people they follow have written. You will also add the two features that make a network feel alive: "mutual friends" and "people you may know". It brings together everything from the Cypher chapter: patterns, MERGE, aggregation, WITH and modeling.

Neo4j cannot run on this site, so the Cypher in the code blocks is read-only. To keep the project hands-on, each feature has a JavaScript stand-in that implements the same logic on in-memory objects and prints the answer the query would give for the sample data. The stand-in is a faithful model of the rules, not the real database: Neo4j adds indexes, transactions, durability and a query planner.

Step 1: the model

Start from the questions, as in Graph data modeling:

  1. Who does a user follow, and who follows them?
  2. What did the people I follow post recently?
  3. Which people do Ada and Ben both follow?
  4. Whom should I follow next?

That gives two kinds of node and three kinds of relationship.

flowchart LR
    U1(("User<br/>ada")) -- "FOLLOWS<br/>since" --> U2(("User<br/>ben"))
    U2 -- "POSTED" --> P1["Post<br/>text, at"]
    U1 -- "LIKED" --> P1

The model: users follow users, users post posts, and users like posts. Everything else is derived by queries.

The setup statements create the uniqueness constraints (which also create indexes) so that starting points are cheap and duplicates are impossible:

CYPHER
CREATE CONSTRAINT user_handle IF NOT EXISTS
FOR (u:User) REQUIRE u.handle IS UNIQUE

CREATE CONSTRAINT post_id IF NOT EXISTS
FOR (p:Post) REQUIRE p.id IS UNIQUE

A post's timestamp goes in a property, at, as a number or a datetime. You will sort by it for the feed. Posts are separate nodes, not properties of a user, because they have their own identity, can be liked, and are read independently.

Step 2: following, idempotently

A "follow" button may be pressed twice, or a request may be retried. MERGE makes it safe: it creates the relationship only if it does not exist yet (see Cypher: MERGE, SET, DELETE and constraints).

CYPHER
MATCH (me:User {handle: $me}), (other:User {handle: $other})
WHERE me <> other
MERGE (me)-[f:FOLLOWS]->(other)
  ON CREATE SET f.since = timestamp()

Note the WHERE me <> other so that nobody follows themselves, and the use of parameters. The disconnected MATCH is fine here: both patterns are anchored by a unique index, so the product is one row by one row (see Query performance: indexes, EXPLAIN and PROFILE). Unfollowing is the mirror image: MATCH (:User {handle: $me})-[f:FOLLOWS]->(:User {handle: $other}) DELETE f.

Writing a post creates the node and links it in one statement:

CYPHER
MATCH (me:User {handle: $me})
CREATE (me)-[:POSTED]->(p:Post {id: randomUUID(), text: $text, at: timestamp()})
RETURN p.id

Step 3: the feed

The feed is one hop to the people I follow, one more to their posts, newest first:

CYPHER
MATCH (me:User {handle: $me})-[:FOLLOWS]->(author:User)-[:POSTED]->(p:Post)
RETURN author.handle AS author, p.text AS text, p.at AS at
ORDER BY p.at DESC
LIMIT 20

Everything before RETURN is a traversal from a single indexed start node. The work depends on how many people I follow and how many posts they have, which is why the feed does not slow down as the whole network grows. It does slow down for someone who follows thousands of very active accounts. Large social networks therefore often precompute feeds or limit by recency (for example, only consider posts after a cutoff time in a WHERE), but the pattern above is the right starting point.

JS Stand-in: users, follows and the feed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ada follows Ben and Cy, so Dee's post does not appear in her feed, even though Ben and Cy follow Dee. The feed only shows posts by people Ada follows directly.

Step 4: mutual friends

"Which people do two users both follow?" is a pattern with two arms meeting at the same node:

CYPHER
MATCH (a:User {handle: $a})-[:FOLLOWS]->(common:User)<-[:FOLLOWS]-(b:User {handle: $b})
RETURN common.handle AS mutual
ORDER BY mutual

Two anchors, both found by index, and a traversal outwards from each. The mutual count is the size of that result: count(common).

Step 5: people you may know

Suggestions are a friend-of-friend query, as in Recommendations and fraud detection with graphs: people followed by the people I follow, whom I do not follow yet, ranked by how many of my follows lead to them.

CYPHER
MATCH (me:User {handle: $me})-[:FOLLOWS]->(via:User)-[:FOLLOWS]->(candidate:User)
WHERE candidate <> me AND NOT (me)-[:FOLLOWS]->(candidate)
RETURN candidate.handle AS suggestion,
       count(via) AS followedBy,
       collect(via.handle) AS through
ORDER BY followedBy DESC, suggestion
LIMIT 10

NOT (me)-[:FOLLOWS]->(candidate) is a pattern used as a filter: it removes people already followed. The stand-in runs both queries on the same graph as before (the program repeats the setup so that it is self-contained).

JS Stand-in: mutual follows and suggestions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ada and Fay have no follow in common (an empty list is a valid answer, just as the query would return no rows), while Ada and Ben both follow Cy. Dee is the better suggestion for Ada because two of the people Ada follows, Ben and Cy, both follow Dee, while Eli is followed only through Cy.

Step 6: next steps

You now have the shape of a real feature set. To go further:

  • Add LIKED relationships and a "most liked this week" query using count() and a time filter.
  • Add hashtags as nodes ((:Post)-[:TAGGED]->(:Tag)) and search by tag. Watch for popular tags becoming supernodes.
  • Use PageRank from Graph algorithms: PageRank, communities, shortest paths to find influential users.
  • Put the data behind a driver call with parameters and test each query with PROFILE on realistic data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use MERGE for the follow action?

    MERGE is idempotent: if the pattern already exists it is matched instead of created.
  2. 2. Why is the feed query fast even when the network has millions of users?

    The work depends on the neighbourhood of one user, not the size of the whole graph.
  3. 3. What does NOT (me)-[:FOLLOWS]->(candidate) do in the suggestions query?

    A pattern used as a predicate is true when the pattern exists; with NOT it removes candidates already followed.
  4. 4. Why are posts modeled as nodes rather than properties of the user?

    Things that other things connect to, or that are queried on their own, should be nodes.

Summary

  • The model is small: User and Post nodes with FOLLOWS, POSTED and LIKED relationships, plus unique constraints on the handle and the id.
  • MERGE keeps follow actions idempotent, and parameters keep queries reusable.
  • The feed, mutual follows and suggestions are all short traversals from indexed starting nodes.
  • Suggestions rank candidates by the number of distinct people who lead to them.
  • The JavaScript programs are stand-ins implementing the same rules on plain objects; Neo4j itself provides storage, indexes and planning.

Next: Project: an event and order store on Cassandra.