How to query Firebase for keys that match a string prefix

后端 未结 2 1496
梦谈多话
梦谈多话 2021-02-04 15:20

Since firebase not support any spatial indexing then I use geohash which someone advice here. Geohash is using characters to find the nearby.

So let say I have w2

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 16:00

    In addition to Andrew's answer above, what you want to do to get the desired effect with geohashes (i.e. be able to do prefix queries that let you specify accuracy in the 'query', specifically, for example every 3 characters in the geohash gets you ~ +-80km) is to store the data in a more granular and discretized manner.

    So, rather than how you're storing it now, you'll want to save the data by chopping the geohash string key into fragments (I've done it at the 3 character boundary, but you should choose an appropriate tokenization strategy that gives you the desired accuracy) and use each fragment as a child name, as such:

    root
      - geohash
          - w22
            - qt4
              - vhy
                - e1c
                  - w22qt4vhye1c3
                    - id
              - vhz
                - erc
                  - w22qt4vhzerct
                    - id
          - z99
              - qt4
                - vdf
                  - z99qt4vdf4vc
                    - id
    

    Then, as in your question, when you need to get all geohashes that start with w22qt4 you would do a query against:

    firebaseRef.child('/geohash/w22/qt4/')
    

    Which would then give you the vhy and vhz children which then have all the actual geohashes that you were interested in.

提交回复
热议问题