如何在elasticsearch-py中按地理距离进行过滤?

时间:2016-03-31 12:50:47

标签: python-2.7 elasticsearch elasticsearch-py

使用Python 2.7和elasticsearch-py

给出以下JSON:

[
    {
        "Name":
        "Addresses": [
            "StreetAdd": "xxx",
            "GeoLocation": {
                "lat": xx,
                "long": yy
            }
        ]
    },
    {
        // And so on.
    }   
]

以下映射:

mapping = {
    "mappings": {
        "leads": {
            "properties": {
                "Addresses": {
                    "type": "nested",
                    "include_in_parent": "true",
                    "properties": {
                        "GeoLocation": "geo_point"
                    }
                }
            }
        }
    }
}

我如何获得位于纬度40,经度-70的10公里范围内的位置?我的尝试如下:

search_body = {
    "query" : { 
        "filtered": {
            "query": {
                "match_all" : { }
            },
            "filter": {
                "geo_distance": {
                    "distance": "10km",
                    "Addresses.GeoLocation": {
                        "lat": 40.0,
                        "lon": -70.0
                    }
                }
            }
        }
    },
    "size": 50
}

result = es.search(index=ES_INDEX, body=search_body, sort="Name:asc")
for hit in result["hits"]["hits"]:
    print hit["_source"]["Name"]

但是,这会引发以下错误:

...
C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\elasticsearch\connection\base.pyc in _raise_error(self, status_code, raw_data)
    103             pass
    104 
--> 105         raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
    106 
    107 

RequestError: TransportError(400, u'search_phase_execution_exception')

不熟悉ES,所以我很难设想应该用什么模式来解决这个问题。

是什么给出了?

1 个答案:

答案 0 :(得分:1)

问题在于您的映射。这是固定版本

mapping = {
    "mappings": {
        "leads": {
            "properties": {
                "Addresses": {
                    "type": "nested",
                    "include_in_parent": "true",
                    "properties": {
                        "GeoLocation": {
                            "type":"geo_point" <-- Note the type here
                        }
                    }
                }
            }
        }
    }
}