Cypher Query获取节点之间的重复(相同id)关系

时间:2014-02-02 07:52:49

标签: neo4j cypher

我有城市节点通过HAS_BUS关系相互连接。 例如。

CREATE (:City{id:123,name:'Mumbai'})-[:HAS_BUS{id:22323,arr_time:234,dept_time:250}]->(:City{id:124,name:'Goa'}).

虽然我想要一个总线ID是唯一的,但我错误地将同一个id的总线不止一次,即有非独特的HAS_BUS关系。

Q1。我应该如何找出哪些ID不是唯一的 问2.如何找出哪些ID不唯一并删除它们。

我写了这个查询,但得到了未知错误

MATCH ()-[r:HAS_BUS]->() with count(r.id) as t match ()-[s:HAS_BUS]->() where s.id=t with count(s.id) as times,s.id as id where count(times)>1 return id,times

数据库仅包含80个节点和6500个关系。

我实际上缺少mySQL的GROUP BY功能

DATABASE Can be downloaded from here 6MB

2 个答案:

答案 0 :(得分:5)

我假设您希望总线ID在整个图形中是唯一的,即总线ID 22323对应于整个图形中的一个HAS_BUS关系,并且不会在不同的城市中重复。

MATCH (c:City)-[r:HAS_BUS]->() 
WITH r.id as busId, count(*) as idCount
WHERE idCount>1
RETURN busId,idCount

注意:未经测试

将为您提供不止一次重复的所有busIds。 然后,您可以确定要从中删除重复项的位置,或删除所有位置并重新创建正确的位置。

您正在寻找的小组记录在http://docs.neo4j.org/chunked/milestone/query-aggregation.html

修改以删除除一个重复的总线ID之外的所有内容:确保您拥有数据库的备份 - 这未经过测试

MATCH (c:City)-[r:HAS_BUS]->() 
WITH r.id as busId, count(*) as idCount
WHERE idCount>1 //Find all duplicate ids
MATCH (c:City)-[r2:HAS_BUS]->()
WHERE r2.id=busId
with COLLECT(r2) as ids,busId //find all relations for those duplicates
with head(ids) as firstId,ids,busId 
with filter(x in ids where x<>firstId) as idsToDelete //keep the first id and collect the rest
foreach (d in idsToDelete | DELETE d); //delete the rest

答案 1 :(得分:0)

删除所有重复项的代码,但可以使用tail而不是head-filter进行简化:

MATCH (c:City)-[r:HAS_BUS]->() 
WITH r.id as busId, count(*) as idCount
WHERE idCount>1 //Find all duplicate ids
MATCH (c:City)-[r2:HAS_BUS]->()
WHERE r2.id=busId
WITH tail(collect(r2)) as to_delete
FOREACH (d IN to_delete | DELETE d)
相关问题