删除某些查询的前k个节点以外的所有节点

时间:2017-07-28 10:30:22

标签: neo4j cypher

我尝试在neo4j中复制以下SQL查询的行为

DELETE FROM history
WHERE history.name = $modelName AND id NOT IN (
   SELECT history.id
   FROM history
   JOIN model ON model.id = history.model_id
   ORDER BY created DESC
   LIMIT 10
)

我尝试了很多不同的查询,但基本上我总是在努力寻找TOP-k元素。这是我最接近解决方案。

MATCH (h:HISTORY)-[:HISTORY]-(m:MODEL)
WHERE h.name = $modelName
WITH h
MATCH (t:HISTORY)-[:HISTORY]-(m:MODEL)
WITH t ORDER BY t.created DESC LIMIT 10
WHERE NOT h IN t 
DELETE h

使用该查询,我会收到行expected List<T> but was Node的错误WITH t ORDER BY t.created DESC LIMIT 10 我尝试将其更改为COLLECT(t) AS t,但错误为expected Any, Map, Node or Relationship but was List<Node>

所以我几乎陷入困境。知道如何在Cypher中编写此查询吗?

1 个答案:

答案 0 :(得分:3)

遵循这种方法,您应该颠倒顺序,匹配前k个节点,收集它们,并执行匹配节点不在集合中的匹配。

MATCH (t:HISTORY)-[:HISTORY]-(:MODEL)
WITH t ORDER BY t.created DESC LIMIT 10
WITH collect(t) as saved

MATCH (h:HISTORY)-[:HISTORY]-(:MODEL)
WHERE h.name = $modelName
AND NOT h in saved
DETACH DELETE h