Q:

Firebase orderByChild not working

I have this database:
event_users
    - eventid1:
        - userid1: "username1"
        - userid2: "username2"
    - eventid2:
        - userid2: "username2"
        - userid4: "username4"

I want to get all events id where user number 2 exists on. So, as I am concern, I can use orderByChild(userid2) to achieve this. This is my code:
rootRef.child(EVENT_USERS_KEY).orderByChild(uid).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, dataSnapshot.getValue().toString());
            final long eventCount = dataSnapshot.getChildrenCount();
            Log.d(TAG, String.valueOf(eventCount));

            ...
}

Saying 'uid' is the userid of user 2 it retrieves me all events. It is ok, as user number 2 is participant on both events. But If I change that for userid1, it still retrieves me all events, while it should get only the first one. Am I understanding correctly the orderByChild() method?

A:

To get all the event ids where user number 2 exists, i suggest you create another node named users like this:
event_users
    - eventid1:
        - userid1: "username1"
        - userid2: "username2"
    - eventid2:
        - userid2: "username2"
        - userid4: "username4"
users
   - userid1
       - events
           - eventid1: true
   - userid2
       - events
           - eventid1: true
           - eventid2: true

So, to achieve this, you need just to set a listener on \users\userId\eventId and get all event ids from a particular event. This tehnique is named denormalization. I suggest you take a look at this tutorial.
Hope it helps.

