List Comprehensions and Pattern Comprehensions

`[x IN list WHERE pred | expr]` and `[(n)-[:R]->(m) | m.name]` — Cypher's two functional power-tools.

0/4 done

Overview

List Comprehensions and Pattern Comprehensions

[x IN list WHERE pred | expr] and [(n)-[:R]->(m) | m.name] — Cypher's two functional power-tools.

Why it matters

Pattern comprehensions let you 'project a pattern' inline, no extra MATCH needed — perfect for shaping nested JSON.

Going deeper

Cypher has two functional comprehensions:

// List comprehension: filter + transform an existing list.
[x IN range(1,10) WHERE x % 2 = 0 | x * x]   // -> [4, 16, 36, 64, 100]

// Pattern comprehension: project a pattern inline, no extra MATCH.
MATCH (p:Person {name:'Alice'})
RETURN p.name,
  [(p)-[:KNOWS]->(f) | f.name]        AS friends,
  [(p)-[:KNOWS]->(f) WHERE f.vip | f.name] AS vipFriends;

Pattern comprehensions shine when shaping nested JSON for an API: each row can carry sub-lists pulled from the graph without fanning out into duplicate rows (which is what an extra MATCH + collect would cause). They also short-circuit cleanly to an empty list when the pattern matches nothing — no OPTIONAL MATCH null-handling needed.

Analogy

Pattern comprehensions are taking a quick mental inventory without leaving the room. Instead of walking to another shelf (a second MATCH) to list 'all of Alice's friends', you glance around from where you stand and jot the names inline: [(alice)-[:KNOWS]->(f) | f.name]. One expression, no extra trip.

Pitfalls — what breaks when this is weak

  • Using MATCH + collect where a pattern comprehension fits. Causes row multiplication you then have to de-dup. Fix: project inline.
  • Heavy logic inside the comprehension. It runs per element; keep it cheap. Fix: precompute upstream with WITH.
  • Confusing the two forms. List comprehension needs an existing list; pattern comprehension needs a graph pattern.

Make it stick

Use the prompts below to anchor list comprehensions and pattern comprehensions to a real graph you own.

  • Which API response do you currently build with MATCH + collect that a pattern comprehension would simplify?
  • Where are you doing OPTIONAL MATCH null-handling that an empty-list comprehension would avoid?
  • Is any comprehension in your code doing expensive per-element work that belongs upstream?

Reading in progress · 0 of 4 activities done