谷歌ndb中GeoPt的奇怪查询比较

时间:2018-03-13 09:58:18

标签: google-app-engine app-engine-ndb google-app-engine-python

我尝试使用GeoProperty查询数据存储区中的实体,但奇怪的是它将比较GeoProperty的第一个参数lat。 如果比较lat,那么它将直接返回结果。唯一的例外是纬度相等,然后比较经度。 例如,GeoPt(11,10)< GeoPt(9,20)将返回False,因为前纬度不小于后者。然而,后者比前者更大。因此,当我想查询数据存储区中的实体时,这种比较会让我感到困扰。任何解决方案?

2 个答案:

答案 0 :(得分:0)

您希望在数据存储区中查询位于特定步行时间内的条目,这些条目位于用户所在位置。该步行时间可以粗略地转换为距离。这将允许您使用似乎适合您的用例的搜索API的距离特殊功能。

因此,假设每个商店条目都有一个store_location字段,其中包含一个地理位置,并且您的用户坐标为(11,10),您可以使用以下搜索查询搜索距您的用户半径100米范围内的商店:

query = "distance(store_location, geopoint(11, 10)) < 100"

答案 1 :(得分:0)

您需要查看NDB的一些替代方案以进行空间查询。关于 Spatial数据库的维基百科文章有一个Geodatabases列表,你必须在AppEngine之外实现并调用。

或者,您可以使用搜索API,the link dan-cornilescu引用:

import webapp2
from google.appengine.api import search

class MainHandler(webapp2.RequestHandler):
    def get(self):

        stores_idx = search.Index(name='stores')

        store_a = search.Document(
            doc_id='store_a',
            fields=[search.GeoField(name='LOC', value=search.GeoPoint(32, -112))]
        )

        store_b = search.Document(
            doc_id='store_b',
            fields=[search.GeoField(name='LOC', value=search.GeoPoint(32, -111))]
        )

        stores_idx.put(store_a)
        stores_idx.put(store_b)

        # Search for stores kinda close (-112 vs -112.1), and not so close

        results_100 = stores_idx.search(
            "distance(LOC, geopoint(32, -112.1)) < 100"
        )

        results_100000 = stores_idx.search(
            "distance(LOC, geopoint(32, -112.1)) < 100000"
        )

        results_1000000 = stores_idx.search(
            "distance(LOC, geopoint(32, -112.1)) < 1000000"
        )


        self.response.write(
"""
%s stores within 100 meters of (32, -112.1) <br/>
%s stores within 100,000 meters of (32, -112.1) <br/>
%s stores within 1,000,000 meters of (32, -112.1) <br/>
""" % (
    len(list(results_100)),
    len(list(results_100000)),
    len(list(results_1000000)),
)
)

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

产生:

0 stores within 100 meters of (32, -112.1)
1 stores within 100,000 meters of (32, -112.1)
2 stores within 1,000,000 meters of (32, -112.1)