Limiting number of nodes
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
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.
First you could label all rooms as, well, ROOM. So when you create a new, for example, kitchen node you would label it both KITCHEN and ROOM:
CREATE (a:KITCHEN:ROOM {...})
For now you can add the labels to the existing nodes like this:
MATCH (room:Kitchen) SET room :ROOM return room
Congratz, now all your kitchen nodes are also room nodes!
This allows you to treat that node as a kitchen, when you need kitchens, or as a general room, when you need those. If you do that for relevant all nodes (Living, Dining,...) you could then do something like:
MATCH (s:STOREYVERTEX)-[r]-(room: ROOM)
WITH s, count(r) as rel_count
WHERE rel_count = 3
RETURN s
This will return the nodes 's' with 3 relationships (no matter what the rel type is) to any node with the label ROOM.
终于解决了我的问题是:
MATCH (s:STOREYVERTEX) <-- (rooms)
WITH s, count(distinct(rooms)) as numberOfRooms
WHERE numberOfRooms = 3
MATCH (s) <-- (room1: KITCHEN)
MATCH (s) <-- (room2: DINING)
RETURN s
链接地址: http://www.djcxy.com/p/87116.html
上一篇: 如何保护小部件免受伪造请求
下一篇: 限制节点数