3

Firestore query question. I have a "geohash" field in my document which I want to filter by. I have seen Frank's @puf video about getting circular geohashes on yt. For now I don't care about a circular query yet. I have a geohash for a user. And lots of 10 precision geohashes which I want to filter.

let userGeohash = "c2b2qd"
documentRef.whereField("geohash", isGreaterThanOrEqualTo: userGeohash)

I would expect this query to return any geohashed which a great than the userGeohash. But its won't what is being returned.

input = "c2b2qd"
expected output:
"c2b2qdh7rs"
"c2b2qdh2ht"
"c2b2qd3etr"

But I get nothing returned..My logic here must be the bottleneck.. enter image description here

EXAMPLE CODE:

docRef.whereField("geohash", isGreaterThanOrEqualTo: "c2b2qdd").getDocuments { (query, error) in
            query?.documents.forEach({ (snapshot) in
                let data = snapshot.data()
                print(data["geohash"] as! String)
            })
        }


// returns the following :
c2b2qddkc3q
c2b2qddkdcm
c2b2qddpydb
c2b2qehqtkg
c2b2qey3dje
c2b2qey4e62
c2b2qey4em1
c2b2qkp7cm0
u1hg7pzxs26


// expected output: 
c2b2qddkc3q
c2b2qddkdcm
c2b2qddpydb

I've even tried using "aaaaaaaa" as my filter which also returns all the documents.

arvidurs
  • 2,853
  • 4
  • 25
  • 36

1 Answers1

4

You seem to misunderstand Firebase queries. Your query returns an open ended range:

docRef.whereField("geohash", isGreaterThanOrEqualTo: "c2b2qdd")

Specifically, this query opens the index on geohash, which is ordered lexicographically, it find the first entry that starts with c2b2qdd (or larger), and then returns all results from that point on. So that includes results like c2b2qehqtkg, since they are greater or equal than.

If you want to emulate a start with type operation, you need to use a closed range query, which includes an end condition of the range too.

docRef.whereField("geohash", isGreaterThanOrEqualTo: "c2b2qdd")
      .whereField("geohash", isLessThan: "c2b2qde")

This returns all documents that have a geohash field that starts with c2b2qdd.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807