Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 30 ยท Graph Algorithms and Applications

Recommendations and fraud detection with graphs

Use graph patterns for collaborative filtering, friend-of-friend suggestions and fraud rings built on shared identifiers, with Cypher and Python stand-ins.

Two of the best-known uses of graph databases look very different on the surface. A recommendation engine wants to be helpful: "people who bought this also bought that". A fraud team wants to be suspicious: "these ten accounts share a phone number and a device". Underneath they are the same activity: starting from one node, walking a few relationships and counting what you find.

This lesson shows the typical patterns in Cypher and then runs the same logic in Python on small data sets. Neo4j cannot run on this site, so the Cypher is read-only. The Python programs are honest stand-ins: they apply the same counting rules to dictionaries, so you can see the numbers a query would produce on this data. They are not how a production system is built, and the data sets are invented and tiny.

Collaborative filtering as a path pattern

Collaborative filtering recommends items that people similar to you liked. In a graph, "similar" has a very direct meaning: someone who bought some of the same products as you.

flowchart LR
    Me["User<br/>Ada"] -- BOUGHT --> P1["Product<br/>Kettle"]
    O["User<br/>Other"] -- BOUGHT --> P1
    O -- BOUGHT --> R["Product<br/>Teapot"]
    Me -. "recommend?" .-> R

Ada and Other both bought the kettle. Other also bought the teapot, which Ada has not: a candidate recommendation.

The pattern is a path of length three with a filter at the end:

CYPHER
MATCH (me:User {name: 'Ada'})-[:BOUGHT]->(:Product)<-[:BOUGHT]-(peer:User)-[:BOUGHT]->(rec:Product)
WHERE peer <> me AND NOT (me)-[:BOUGHT]->(rec)
RETURN rec.name AS recommendation,
       count(DISTINCT peer) AS peers
ORDER BY peers DESC, recommendation
LIMIT 5

The WHERE NOT (me)-[:BOUGHT]->(rec) part removes things Ada already owns. Counting distinct peers (not paths) matters: a peer who shares three products with Ada would otherwise be counted three times and dominate the ranking. This simple count already works; you can refine it by weighting each peer by how similar they are to Ada, for example with the Jaccard similarity: the number of shared products divided by the number of products either of them bought.

The stand-in below does both: a plain count of peers, and a similarity-weighted score.

Python Recommend products from co-purchases

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Teapot wins with three distinct peers (Ben, Cy and Fay), then honey with two. Eli shares nothing with Ada, so Eli's tools are never suggested: the pattern only reaches people who are connected to Ada through a shared product. This is what makes the approach cheap on a big graph. It only explores the neighbourhood around one user instead of comparing that user with everyone.

Friend-of-friend suggestions

A social network suggests "people you may know" with the same shape, using a relationship between people instead of purchases:

CYPHER
MATCH (me:Person {name: 'Ada'})-[:FRIEND]-(f:Person)-[:FRIEND]-(candidate:Person)
WHERE candidate <> me AND NOT (me)-[:FRIEND]-(candidate)
RETURN candidate.name, count(f) AS mutualFriends, collect(f.name) AS via
ORDER BY mutualFriends DESC
LIMIT 10

Here the number of mutual friends is the score. Notice that the relationship is written without an arrow, so friendship works in either direction. You will build a complete version in Project: a social network on a graph. Recommendations get better with more signals: add time (recent purchases count more), popularity (do not recommend items everyone already has), and diversity.

Big graphs have a trap here: a very popular product or a celebrity connects to a vast number of nodes, which the earlier lesson called a supernode (Graph data modeling). In recommendations, popular items add little information (everyone bought the phone case) and cost a lot to traverse, so systems often skip or sample them.

Fraud: shared identifiers form rings

Fraudsters rarely work with one identity. They create many accounts, but they get lazy about reusing a phone number, a delivery address, a payment card or a device. In a relational model, finding accounts that share something means joining a table with itself, and finding chains of sharing means more joins. In a graph, you model the shared things as nodes and the connection becomes visible as a pattern.

flowchart LR
    A1["Account<br/>a1"] --> D1["Device<br/>d7"]
    A2["Account<br/>a2"] --> D1
    A2 --> P1["Phone<br/>555-0101"]
    A3["Account<br/>a3"] --> P1
    A3 --> C1["Card<br/>c9"]
    A4["Account<br/>a4"] --> C1
    A5["Account<br/>a5"] --> D2["Device<br/>d8"]

Accounts a1 to a4 are linked in a chain through a device, a phone and a card, even though a1 and a4 share nothing directly. Account a5 is on its own.

The direct question, "which pairs of accounts share an identifier?", is one pattern:

CYPHER
MATCH (a:Account)-[:USES]->(i)<-[:USES]-(b:Account)
WHERE a.id < b.id
RETURN a.id, b.id, collect(DISTINCT labels(i)[0] + ':' + i.value) AS shared

The condition a.id < b.id keeps each pair once instead of twice. The more interesting question is the whole ring: a1 and a4 share nothing, yet they are linked through a2 and a3. Cypher can walk this with a variable-length path ((a)-[:USES*2..6]-(b)), and the Graph Data Science library has weakly connected components, which assigns every account the id of its connected group in one pass (Graph algorithms). A group of five accounts sharing two phones and three devices is a stronger signal than any single account's behaviour.

The stand-in computes those groups with a union-find structure, then scores each ring.

Python Find fraud rings from shared identifiers

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Accounts a1 to a4 end up in one ring because shared identifiers chain them together, and the ring has six chargebacks across its members, so it is flagged for review. Accounts a6 and a7 are only a pair, and a5 stands alone. This is also where you must be careful: a shared identifier is a clue, not proof. Families share addresses, offices share phone lines, and public Wi-Fi shares IP addresses. Real systems weight each identifier by how rare it is, ignore the very common ones (again, supernodes), and send rings to a human or a rule engine rather than blocking people automatically.

Why graphs fit these problems

  • The question is a pattern ("A bought X, B bought X and Y"), not a table scan.
  • The answer is local: the work depends on the neighbourhood around one user or one account, not the size of the whole database.
  • New signals are easy to add: a new identifier type is a new label and relationship type, not a schema redesign.
  • Results can explain themselves: the path that produced a recommendation or a flag is the explanation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a collaborative-filtering query count DISTINCT peer rather than paths?

    Each shared product creates a separate path. Counting distinct peers gives each person one vote.
  2. 2. What does the condition WHERE a.id < b.id do in the fraud pair query?

    Without it, the pair (a, b) and the pair (b, a) are both returned.
  3. 3. How are accounts a1 and a4 linked in the ring example although they share no identifier directly?

    Connected components follow chains of shared identifiers, so accounts are in the same ring if any path connects them.
  4. 4. Why is a shared identifier not proof of fraud?

    Families and offices legitimately share data, so graph findings should be weighted and reviewed, not automatically punished.

Summary

  • A recommendation is a short path pattern: me, a shared item, a peer, a new item, minus what I already have.
  • Count distinct peers, and consider weighting by similarity such as Jaccard.
  • Friend-of-friend suggestions use the same shape, with mutual friends as the score.
  • Fraud rings come from modelling identifiers (phone, device, card, address) as nodes and finding connected groups; very common identifiers must be weighted down or ignored.
  • Findings are clues for review, not proof.
  • The Python programs are small stand-ins that apply the same counting logic; real systems add scale, time and many more signals.

Next: Project: a social network on a graph.