我正在尝试优化此密码查询。 我正在使用neo4j-jdbc
对于给定的源节点和目标节点列表,我想删除它们之间的关系(" follow)。
现在我只找到了在每笔交易上执行它们的方法:
例如:
源节点:34和targetNodes:777
执行:
MATCH (p1:users)-[r:follow]->(p2:users)
WHERE p1.userId='34' and p2.userId='777' and
delete r
java neo4j-jdbc代码:
public void deleteNodes(String sourceUserId, Set<String> userIdsList) {
try {
conn = neo4jDataSource.openConnection();
conn.setAutoCommit(false);
newUserDistanceList.forEach(user -> {
try {
this.deleteRelationship(sourceUserId, user.getUserId());
} catch (SQLException e) {
throw new RuntimeException("Error deleting relationship for sourceNode=" + sourceUserId + ", targetNode=" + user.getUserId(), e);
}
});
conn.commit();
} catch (Exception e) {
throw new RuntimeException("Error deleting relationship for sourceNode=" + sourceUserId, e);
} finally {
neo4jDataSource.closeConnection(conn);
}
}
public void createNodeAndSetRelationship(String sourceUserId, String targetUserId) throws SQLException {
String deleteUserStmnt =
"MATCH (p1:users)-[r:follow]->(p2:users) "+
"WHERE p1.userId=~{1} and p2.userId=~{2} and "+
"delete r";
try (final PreparedStatement ps1 = conn.prepareStatement(deleteUserStmnt)) {
ps1.setString(1, sourceUserId);
ps1.setString(2, targetUserId);
ps1.executeQuery();
}
}
您如何将其优化为一个查询以包含所有内容?它甚至可能吗?
* P.S如果您觉得有用,请添加有关此代码的任何其他说明。
对评论的回应:
我以这种方式添加了节点:
MERGE (p1:C10{userId:'1'})
MERGE (p2:C10{userId:'2'})
MERGE (p3:C10{userId:'3'})
MERGE (p1)-[r1:follow]->(p2)
MERGE (p1)-[t1:follow]->(p3)
执行删除查询时,没有删除任何内容:
MATCH (user1:C10 {userId: 1})-[r:follow]->(users:C10) WHERE
users.userId in [3, 2] DELETE r
有什么想法吗?
谢谢你, 射线。
答案 0 :(得分:1)
让我们创建一些数据来测试我们的查询是否有效。
CREATE (user1:User {id: "1"})
CREATE (user2:User {id: "2"})
CREATE (user3:User {id: "3"})
CREATE (user1)-[:FOLLOW]->(user2)
CREATE (user1)-[:FOLLOW]->(user3)
让我们编写查询以从user1和user2以及user3之间删除:FOLLOW
关系:
MATCH (user1:User {id: "1"})-[r:FOLLOW]->(users:User)
WHERE users.id in ["2", "3"]
DELETE r
祝你好运:)
注意:这也适用于字符串。
注2:您应检查userId
节点上的:user
媒体资源是否存在index(或事件constraint。
有效的neo4j-jdbc
的代码示例:
Class.forName("org.neo4j.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
String removeRelationships = "MATCH (user1:User {id: {1}})-[r:FOLLOW]->(users:User) " +
"WHERE users.id in {2} " +
"DELETE r";
try (final PreparedStatement stmt = connection.prepareStatement(removeRelationships)) {
stmt.setObject(1, "1");
stmt.setObject(2, new ArrayList<Integer>() {{
add("2");
add("3");
}});
stmt.executeQuery();
}