0

I have the following JSON tree from my realtime database:

{
  "old_characters" :
  {
      "Reptile" : {
        "kick" : 20,
        "punch" : 15
      },
      "Scorpion" : {
        "kick" : 15,
        "punch" : 10
      },
      "Sub-zero" : {
        "kick" : 30,
        "punch" : 10
      }
  },
  "new_characters" : {
    //...ect
  }
}

Is it possible to set rules in my firebase console so that I can index my data based on the character with the highest value of kick?

The constraints are:
- character_name are dynamic.
- Key "kick" is static, but its value is dynamic.

Result should be:

  1. Sub-zero first (kick 30)
  2. Reptile second (kick 20)
  3. Scorpion third (kick 15)
Red M
  • 2,609
  • 3
  • 30
  • 50

1 Answers1

1

What you want seems to be a fairly simple Firebase query on the kick property:

var ref = firebase.dababase().ref('old_characters');
var query = ref.orderByChild('kick');
query.once(function(snapshot) {
  snapshot.forEach(function(characterSnapshot) {
    console.log(characterSnapshot.key);
    console.log(characterSnapshot.child('kick').val());
  });
});

You'll note that this prints the results in ascending order. You can:

  • either reverse the results client-side
  • or add an inverted property with -1 * score to each character and then order on that

To learn more about the inverting/sorting descending, have a look at some of these previous questions:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I was able to do it from the client but is it possible to do it using indexing via rules within the Firebase console so that it will automatically return the values in ascending order based on the kick – Red M Jan 30 '19 at 03:04
  • 1
    There is no way to affect the default order in which child nodes are returned. You will always need an `ref.orderByChild('kick');` in your code for that. – Frank van Puffelen Jan 30 '19 at 04:33
  • I see. I assumed that indexing will be able to change the default order base on the applied rule from the console. Is there a link for understanding the magic happening behind scenes when using rules on the firebase console? What makes implementing that rule result in a much efficient querying? Because from the client perspective, I cannot see any changes. The result is the same. – Red M Jan 30 '19 at 20:07
  • The result is the same, but without an index any filtering happens on the client. If you want to see the difference, do an unindexed filtering query in a web client and check the traffic in the web sockets tab of your browser's debugging tool. – Frank van Puffelen Jan 30 '19 at 21:45