James
James

Reputation: 125

firebase orderByChild returns weird order for only one child

I have a firebase schema containing the table 'Catalog' with a few values

Catalog Table

enter image description here

I did an orderByChild() using avgDrinkPrice as the order and the output was wrong.

Output

enter image description here

Code

myRef.orderByChild("avgDrinkPrice").addValueEventListener(new ValueEventListener() {
  @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            catalogList.clear();
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                Catalog catalog = postSnapshot.getValue(Catalog.class);
                catalogList.add(catalog);
                Log.d(TAG,"Drink price " + catalog.getAvgDrinkPrice());
                catalogSize++;
            }
            //LOOP ENDS.

I have tried sorting using other numerical values such as the latitude field, longitude and rating and their orders are correct. Only when sorting by avgDrinkPrice would the order be wrong. I don't understand why. Please help.

Upvotes: 2

Views: 1313

Answers (1)

cartant
cartant

Reputation: 58400

According to your screenshot, the avgDrinkPrice property is a string, so the results are sorted correctly. It's just that they are sorted lexographically - not numerically.

There is more information on how Firebase sorts data, when ordering by child, here:

When using orderByChild(), data that contains the specified child key will be ordered as follows:

  1. Children with a null value for the specified child key come first.
  2. Children with a value of false for the specified child key come next. If multiple children have a value of false, they are sorted lexicographically by key.
  3. Children with a value of true for the specified child key come next. If multiple children have a value of true, they are sorted lexicographically by key.
  4. Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified > child node, they are sorted by key.
  5. Strings come after numbers, and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.
  6. Objects come last, and sorted lexicographically by key in ascending order.

To have the children ordered numerically, you would have to store avgDrinkPrice as a number. And lati, longti and rating are probably better stored as numbers, too.

The orderings that use your lati, longti and rating properties might appear to be numerical, but that would be because the string values being ordered probably have the same number of digits - which is not the case with avgDrinkPrice.

Upvotes: 5

Related Questions