Home > Software design >  How to match a node with over n relationships using neo4j's Cypher Query Language?
How to match a node with over n relationships using neo4j's Cypher Query Language?

Time:05-05

A node of a Round in a game is connected to Answer nodes.

(:Round)<-[:IN_ROUND]-(:Answer)

It is expected every Round to have 5 or fewer Answers related to it, I suspect there exists nodes in my database that have more than that, how can I query this information? Return all :Round nodes that have over 5 <-[:IN_ROUND]- relationships?

CodePudding user response:

You can use something like:

MATCH (n:Round)<-[:IN_ROUND]-(:Answer)
WHERE size((n)<-[:IN_ROUND]-(:Answer)) > 5
RETURN distinct(n)

You can see it works on this sample data:

MERGE (a:Round{key: 1})
MERGE (b:Round{key: 2})
MERGE (c:Answer{key: 3})
MERGE (d:Answer{key: 4})
MERGE (e:Answer{key: 5})
MERGE (f:Answer{key: 6})
MERGE (g:Answer{key: 7})
MERGE (h:Answer{key: 8})
MERGE (i:Answer{key: 9})

MERGE (c)-[:IN_ROUND{key:1}]-(a)
MERGE (d)-[:IN_ROUND{key:1}]-(a)
MERGE (e)-[:IN_ROUND{key:1}]-(a)
MERGE (f)-[:IN_ROUND{key:1}]-(a)
MERGE (g)-[:IN_ROUND{key:1}]-(a)
MERGE (h)-[:IN_ROUND{key:1}]-(a)
MERGE (i)-[:IN_ROUND{key:1}]-(b)
MERGE (c)-[:IN_ROUND{key:1}]-(b)
MERGE (e)-[:IN_ROUND{key:1}]-(b)
MERGE (f)-[:IN_ROUND{key:1}]-(b)
MERGE (g)-[:IN_ROUND{key:1}]-(b)

Returning:

╒═════════╕
│"n"      │
╞═════════╡
│{"key":1}│
└─────────┘

CodePudding user response:

You can use the WITH to count the number of connected nodes and then filter on this count.

If you wish to specify incoming connections to Round

MATCH (rnd:Round)<-[:IN_ROUND]-(a)
WITH rnd, count(a) as incomingNodes
WHERE incomingNodes>5
RETRUN rnd

If you want to count both incoming and outgoing connections:

MATCH (rnd:Round)-[:IN_ROUND]-(a)
WITH rnd, count(a) as connectedNodes
WHERE connectedNodes>5
RETRUN rnd
  • Related