Ravers
Ravers

Reputation: 1040

Firebase DatabaseReference filter by specified values

Lets suppose I have this firebase JSON structure:

example

And I need to get all the questions which have the atribute "from" equal to "this".

I know that I can use Volley to make a StringRequest and GET all values from my questions.json. Then, in the client side I could iterate over the response and remove the ones which don't have the correct atribute, but this would only work if I have a few questions. If I have millions of questions I would need to iterate over those millions of questions.

Is there any way I could put a filter on my request to get only the question with an attribute of my choice? (Ex: search questions.json where from == this)

Upvotes: 8

Views: 13842

Answers (2)

Dishonered
Dishonered

Reputation: 8841

You can use equalTo

Query query = reference.child("questions").orderByChild("from").equalTo("this");

Upvotes: 5

Ashish P
Ashish P

Reputation: 3056

Try this if may be useful in your scenario

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

    Query query = reference.child("questions").orderByChild("from").equalTo("this");
    query.addListenerForSingleValueEvent(new ValueEventListener() { 
        @Override 
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                for (DataSnapshot issue : dataSnapshot.getChildren()) {
                // do with your result
                } 
            } 
        } 

        @Override 
        public void onCancelled(DatabaseError databaseError) {

        } 
    }); 

Upvotes: 27

Related Questions