Home > database >  Firebase Database Rest Api : How to OrderBy with Unknown nodes
Firebase Database Rest Api : How to OrderBy with Unknown nodes

Time:11-25

I'm using Firebase Database Rest Api and I have an application to display news, and I want a way to order these news By Descending using a (Views) count for each post, At the same time, I am fetching 10 elements LimitToFirst(10) from the firebase database into Listview and get another 10 elements when scrolling... So I am looking for a way to order all the news by (server-side) by highest views and then fetch 10 elements without fetching all the data then order it by the client, Because it will take a lot of time if there is a lot of data in addition to that I will only fetch 10 elements and show them to the listview and The problem is that my data doesn't have a fixed path in firebase to index them in rules. To clarify, I use c# and There are three options for ordering:

OrderBy(PropertyName)

OrderByValue()

OrderByKey()

My data structure is like this: Main/News/Categories/Education/PostId/

My json :

{
  "Main" : {
    "News" : {
      "Categories" : {
        "Education" : {
          "-Mn7-ZxkUPO01ifhtpEn" : {
            "Text" : "some text",
            "Title" : "some title",
            "Views" : 5
          },
          "-Mn7-ZxkUPO01difhtpEn" : {
            "Text" : "some text",
            "Title" : "some title",
            "Views" : 15
          },
          "-Mn7-ZxkUPO0d1ifhtpEn" : {
            "Text" : "some text",
            "Title" : "some title",
            "Views" : 44
          },
          "-Mn7-ZxkUPO0s1ifhtpEn" : {
            "Text" : "some text",
            "Title" : "some title",
            "Views" : 20
          },
          "-Mn7-ZxkUPO011ifhtpEn" : {
            "Text" : "some text",
            "Title" : "some title",
            "Views" : 504
          }
        }
      }
    }
  }
}

my c# code:

public class NewsClass
{
    public string Title { set; get; }
    public string Text { set; get; }
    public int Views { set; get; }
}
   var AllData = await firebaseclient
   .Child("Main/News/Categories/Education/")
   .OrderByKey()
   .LimitToFirst(10)
   .OnceAsync<NewsClass>();

Is there a way to solve this process Best regards :)

CodePudding user response:

To be able to query/order by a child property through the REST API, you need to [define an index(https://firebase.google.com/docs/database/security/indexing-data) on that property in the rules of your database.

{
  "rules": {
    ...
    "Main": {
      "News": {
        "Categories": {
          "Education": {
            ".indexOn": "views"
          }
        }
      }
    }
  }
}

If any of these node names in here are variable in your rules, you can also use a wildcard capture variable there.

  • Related