查询重复的关系,并删除
String url ="bolt://192.168.126.xx:7687";
String userName = "neo4j";
String passWord = "xxx";
// 使用 basic authentication方式创建连接
try {
Driver driver = GraphDatabase.driver(url, AuthTokens.basic(userName, passWord), Config.builder().withMaxConnectionLifetime(30, TimeUnit.MINUTES).withMaxConnectionPoolSize(50).withConnectionAcquisitionTimeout(2, TimeUnit.MINUTES).build());
Session session = driver.session();
//查询关系类型为1种,且关系数量>1的
String cond="match (a)-[r]->(b) with a,b,count(distinct type(r)) as tr, count(r) as c where c>1 and tr=1 return a, b, c,tr limit 10";
List rst= session.run(cond).list();
while(rst.size()>0) {
for(Record r:rst) {
NodeValue a=(NodeValue)r.get("a");
NodeValue b=(NodeValue)r.get("b");
System.out.println(r);
cond="match (a)-[r]->(b) with a,b,r,(type(r)) as ct where id(a)="+a.asNode().id()+ " and id(b)="+b.asNode().id()+" match (a)-[r]->(b) with distinct ct,count(r) as cr where cr>1 return ct,cr";
List typeCountRst= session.run(cond).list();
for(Record typeCount:typeCountRst) {
cond="match (a)-[r]->(b) with a,b,r where id(a)="+a.asNode().id()+ " and id(b)="+b.asNode().id()+" and type(r)='"+typeCount.get("ct").asString()+"' return a,b,r";
List dupRst= session.run(cond).list();
for(int i=0;dupRst.size()>1&&i
Record rel=dupRst.get(i);
List dupRst2= session.run("match (a)-[r]->(b) where id(r)="+rel.get("r").asRelationship().id()+" delete r").list();
System.out.println(dupRst2);
}
}
System.out.println(typeCountRst);
}
cond="match (a)-[r]->(b) with a,b,count(distinct type(r)) as tr, count(r) as c where c>1 and tr=1 return a, b, c,tr limit 10";
rst= session.run(cond).list();
}
System.out.println("end ...");
} catch (Exception e) {
log.error("图数据库连接异常",e);
}
评论:
提交