简体   繁体   English

如何使用 neo4j 的 Cypher 查询语言匹配具有 n 个以上关系的节点?

[英]How to match a node with over n relationships using neo4j's Cypher Query Language?

A node of a Round in a game is connected to Answer nodes.游戏中 Round 的节点连接到 Answer 节点。

(:Round)<-[:IN_ROUND]-(:Answer) (: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?预计每轮有 5 个或更少的答案与之相关,我怀疑我的数据库中存在的节点不止于此,我如何查询此信息? Return all:Round nodes that have over 5 <-[:IN_ROUND]- relationships?返回所有:具有超过 5 个 <-[:IN_ROUND]- 关系的圆形节点?

You can use the WITH clause to count the number of connected nodes and then filter on this count.您可以使用WITH 子句来计算连接节点的数量,然后根据此计数进行过滤。

If you wish to specify incoming connections to Round如果您希望将传入连接指定为 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

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}│
└─────────┘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM