The reason all nodes get deleted is in this line:
applesQuery.getRef().removeValue();
The Query.getRef()
call returns the location that this query runs on. Since applesQuery
is a query on post
, applesQuery.getRef()
returns the post
node itself. So applesQuery.getRef().removeValue()
removes the entire post
node.
There is no concept of a "delete query" in Firebase, where you send DELETE FROM customer WHERE post = postid
. Firebase can only delete a node when it knows its exact path. This means that you will need to execute the query, loop through its results and delete each of those.
In code:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("customers").orderByChild("post").equalTo(postid);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
postSnapshot.getRef().removeValue()
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Update: I now noticed that the value of the post
property is the same as what you have as the key for the customer. If that is always the case you don't need a query to delete the node, and can just do:
ref.child("customers").child(postid).removeValue();