1、建立geo_point类型的mapping
第一个地理位置的数据类型,就是geo_point,geo_point,说白了,就是一个地理位置坐标点,包含了一个经度,一个维度,经纬度,就可以唯一定位一个地球上的坐标
PUT /my_index { "mappings": { "my_type": { "properties": { "location": { "type": "geo_point" } } } } }
2、写入geo_point的方法
PUT my_index/my_type/1 { "text": "Geo-point as an object", "location": { "lat": 41.12, "lon": -71.34 } }
3、根据地理位置进行查询
最最简单的,根据地理位置查询一些点,比如说,下面geo_bounding_box查询,查询某个矩形的地理位置范围内的坐标点
GET /my_index/my_type/_search { "query": { "geo_bounding_box": { "location": { "top_left": { "lat": 42, "lon": -72 }, "bottom_right": { "lat": 40, "lon": -74 } } } } } { "took": 81, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "my_index", "_type": "my_type", "_id": "1", "_score": 1, "_source": { "location": { "lat": 41.12, "lon": -71.34 } } } ] } }
需求一:统计一下,举例我当前坐标的几个范围内的酒店的数量,比如说举例我0~100m有几个酒店,100m~300m有几个酒店,300m以上有几个酒店
GET /hotel_app/hotels/_search { "size": 0, "aggs": { "agg_by_distance_range": { "geo_distance": { "field": "pin.location", "origin": { "lat": 40, "lon": -70 }, "unit": "mi", "ranges": [ { "to": 100 }, { "from": 100, "to": 300 }, { "from": 300 } ] } } } } { "took": 5, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 1, "max_score": 0, "hits": [] }, "aggregations": { "agg_by_distance_range": { "buckets": [ { "key": "*-100.0", "from": 0, "to": 100, "doc_count": 1 }, { "key": "100.0-300.0", "from": 100, "to": 300, "doc_count": 0 }, { "key": "300.0-*", "from": 300, "doc_count": 0 } ] } } }
需求二:搜索出,举例我200m,或者1公里内的酒店
GET /hotel_app/hotels/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": { "geo_distance": { "distance": "200km", "pin.location": { "lat": 40, "lon": -70 } } } } } }