Ahmet Saz
Ahmet Saz

Reputation: 61

Firebase functions search query realtime database with nodejs

This is my database

"Users" : {
        "2rnWA7TF11gSWxec7MsCA5iRhjw1" : {
          "favoriteCount" : 1,
          "interest" : [ "dogs", "cats", "technology" ],
          "speciality" : [ "Swift" ],
        },
        "3Id9oX0ZOEM00XJlnR07gGrHs762" : {
          "favoriteCount" : 7,
          "interest" : [ "dogs", "cats", "Asp.NET MVC", "JavaScript" ],
          "speciality" : [ "Microsoft Technologys" ],

      }

I want to access user information interest=dogs in whole database how can I do?

Upvotes: 0

Views: 719

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

Your current data structure allows you to easily look up the interests for a specific user. It does not however allow easy lookup for the users for a specific interest.

To allow looking up the users for an interest, you'll want to add an inverted data structure /Interests/$interest with the user ID for each user under there:

"Interests": {
  "dogs": {
    "2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
    "3Id9oX0ZOEM00XJlnR07gGrHs762": true
  },
  "cats": {
    "2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
    "3Id9oX0ZOEM00XJlnR07gGrHs762": true
  },
  "technology": {
    "2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
  }
  ...
}

Also see:

Upvotes: 2

Alex Bean
Alex Bean

Reputation: 553

You can make queries in Firebase:

Query query = usersDB.orderByChild("interest").equalTo("WHATEVERINTEREST");

query.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
     Users user = dataSnapshot.getValue(Users.class);
     doWhatever();
   }
});

However in your case as you store the information as an Array, what you can do is retrieve all the users and in your code get the information you need.

 usersDB.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                ArrayList<Users> listOfUsers = new ArrayList<Users>();

                for (DataSnapshot dsp : dataSnapshot.getChildren()) {

                    Users user = dsp.getValue(Users.class);
                    listOfUsers.add(user);
                }

                //Check the Users that contains interest
                usersWithInterest(listOfUsers,"dogs");

            }


        });

Implement an easy method that read all the list of users and check the users with a interest in dogs:

 usersWithInterest(listOfUsers, "dogs");

Upvotes: 0

Related Questions