Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

Firebase, query specific keys from a large set of data


Any help is much appreciated. Thank you so much for your time.

Let us say, there is a large set of articles under Articles node.

"Articles" : {
"article1Key" : {
  "articleAuthor" : "Author",
  "articleFavByNo" : 21,
  "articleKey" : "Key",
  "articleName" : "Name",
  "articlePostedOn" : "21/07/11",
  "articleTopic" : "Topic"
},
"article2Key" : {
  "articleAuthor" : "Author",
  "articleFavByNo" : 21,
  "articleKey" : "Key",
  "articleName" : "Name",
  "articlePostedOn" : "21/07/11",
  "articleTopic" : "Topic"
},
...
"article10Key" : {
  "articleAuthor" : "Author",
  "articleFavByNo" : 21,
  "articleKey" : "Key",
  "articleName" : "Name",
  "articlePostedOn" : "21/07/11",
  "articleTopic" : "Topic"
}

The articles are posted by some authors. Registered user can browse through the articles, and like them. The liked articles keys are stored in Users profile under favArticles node. Since, the article contains huge amount of data under it, only the key and name of the article is stored under User profile.

"Users" : {
"ZtlIQ2d1qJT1XpmHuGxwFSwaiEy2" : {
  "emailId" : "vs@gmail.com",
  "favArticles" : {
    "article1Key" : {
      "name" : "article1"
    },
    "article7Key" : {
      "name" : "article7"
    },
    "article4Key" : {
      "name" : "article4"
    }
  },
  "firstName" : "Vimala",
  "image" : "default",
  "lastName" : "Sridhar"
}
}

Let us say that the user has liked some 50 articles out of 1000. Now if I want to display the User favorite articles in a RecyclerView, how should I write my query to pick the specific articles from the article list?


Solution

  • Since you already keep a list of the favorites for each user, you'd just:

    1. load that list of favorites
    2. iterate over it
    3. load the references article for each

    If you're worried about the performance of this loop-and-load: Firebase loads all the articles in step 3 over the same connection, so the requests are pipelined. For reasonable numbers of articles, this is actually quite fast. See my answer here for more details: Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly