문제

I have a requirement to traverse all the nodes and delete all the nodes (and its relationships and connected nodes) based on certain criteria. For testing purpose (to make sure I can delete the nodes while traversing), i'm trying to just delete one node in the middle of the traverse and using another traversal to delete all the nodes and relationships attached to that node. I'm able to delete all the nodes and relationships but after that i'm getting IllegalStateException (Node has been deleted) when the loop is back to the 1st traversal. Is it possible to delete the nodes/relationships while traversing? If so, what is the effective way to traverse all nodes and delete some nodes along the way. Thanks in advance!

private void traverseGivenNode(Node node, TraversalDescription friendsTraversal) {

    for ( Node currentNode : friendsTraversal.traverse(node).nodes() )
    {
        if (currentNode.getProperty("name").equals("AAA")) {
            deleteNodeAndItsConnections(currentNode);

        } 
    }       
}

private void deleteNodeAndItsConnections(Node currentNode) {

    TraversalDescription traversal = graphDb.traversalDescription()
            .breadthFirst()
            .uniqueness( Uniqueness.NODE_PATH ).evaluator(Evaluators.excludeStartPosition() ).relationships( RelTypes.KNOWS, Direction.OUTGOING );


    for ( Node node : traversal.traverse(currentNode).nodes() )
    {
        deleteNode(node);
    }

    deleteNode(currentNode);

}

private void deleteNode(Node node) {
    Iterable<Relationship> allRelationships = node.getRelationships();
    for (Relationship relationship : allRelationships) {
        relationship.delete();
    }
    node.delete();
}
도움이 되었습니까?

해결책

One way to solve this would be to not delete anything until the traversals are complete. Instead, during the traversals, just add each node and relationship to be deleted to the corresponding HashSet. Afterwards, call Relationship.delete() on everything in the relationship Set, followed by Node.delete() on everything in the Node set.

다른 팁

Create set for relationships to be added and deleted.

Set<Relationship> removableRelations = new HashSet<Relationship>();
Set<Node> removableNodes = new HashSet<Node>();

Add nodes and relationships to be deleted in removableRelations and removableNodes

then write below code for removing these:

for(Relationship removableRel:removableRelations){
            removableRel.delete();
        }
for(Node remNode:removableNodes){
            remNode.delete();
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top