Jay N
Jay N

Reputation: 418

Firebase realtime query startAt and endAt not working as intended on a joint property

I have a joint property for querying multiple values at a time. It looks like this:

enter image description here

And here's my querying code:

rootRef.child("leagues")
            .orderByChild("division_size")
            .startAt("1_1")
            .endAt("1_10")
            .addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    if (snapshot.exists()) {
                        log.error("League Available")
                    } else {
                        log.error("League Not Available")
                    }
                }

                override fun onCancelled(error: DatabaseError) {
                    log.error("Failed to read value.", error.toException())
                }
            })

Notice the size in "division_size" of startAt is 1 and endAt is 10. This is giving me incorrect result, the snapshot doesn't exist when I do that but when I switch the size of endAt to 9 or any single digit then it works.

How can I make it to work on all digits, lets say from 1 to 100?

Upvotes: 0

Views: 247

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317412

The problem is because of the way strings sort in lexicographic order. Strings don't consider any sort of numeric values when sorting, even if the strings might contain a number. They just look at the UTF-8 (or ascii) values of the individual characters. Your division size strings sort like this:

  1. 1_1
  2. 1_10
  3. 1_2
  4. 1_21
  5. ...
  6. 1_9

See the pattern? The third character is being sorted by is ascii value, not by the embedded number's value.

I suggest using a different system to sort your database children that takes only numbers into account and not strings. Since I don't know the properties of your division_size strings, it's hard to recommend something. But I think you can figure out what you need to do instead (and again, it won't involve strings, just numbers, probably in different child values).

Upvotes: 2

Related Questions