Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting number of nodes

Tags:

neo4j

cypher

I am querying a Neo4j database that stores building floorpans. An example of a query is:

MATCH (s:STOREYVERTEX) <-- (room0: LIVING) 
MATCH (s) <-- (room1: DINING) 
MATCH (s) <-- (room2: KITCHEN) 
MATCH (room0) - [edge0: DOOR] -> (room2) 
MATCH (room2) - [edge1: DOOR] -> (room1) 
RETURN s

Now this returns all graphs that have a subgraph corresponding to the constraints. I would like to somehow limit the number of nodes that the result graph have, so for the given example I would like to get only the graphs that have exactly 3 nodes, all of type ROOM.

Is there a way to do this in Cypher?

Edit: Something like this does not work:

MATCH (s:STOREYVERTEX) <-- (rooms:ROOM) 
WITH s, count(distinct(rooms)) as numberOfRooms
WHERE numberOfRooms = 3
MATCH (s) <-- (room1: DINING) 
MATCH (s) <-- (room2: KITCHEN) 
MATCH (room0) - [edge0: DOOR] -> (room2) 
MATCH (room2) - [edge1: DOOR] -> (room1) 
RETURN s
like image 810
Banana Avatar asked Jul 26 '15 16:07

Banana


1 Answers

Yes, you can do that, like this:

MATCH (s:STOREYVERTEX) <-- (rooms:ROOM) 
WITH s, count(distinct(rooms)) as numberOfRooms
WHERE numberOfRooms = 3
RETURN s;

This just checks how many distinct different rooms are connected to a STOREYVERTEX, and only returns the s values where that's 3.

You didn't specify what the DOOR stuff was about in your query, but you should be able to modify this query from here to get where you want to go.

like image 121
FrobberOfBits Avatar answered Oct 21 '22 04:10

FrobberOfBits