Elasticsearch支持两种类型的地理数据:支持lat/lon对的geo_point字段和支持点、线、圆圈、多边形、多多边形等的geo_shape字段。
下面只介绍geo_point
创建名称为geo的索引
curl --location --request PUT 'localhost:9200/geo' \
--header 'Content-Type: application/json' \
--data-raw '{
"settings": {
"number_of_replicas": 3,
"number_of_shards": 5
},
"mappings": {
"properties": {
"name":{
"type": "text"
},
"location":{
"type": "geo_point"
}
}
}
}'
添加测试数据
curl --location --request PUT 'localhost:9200/geo/_doc/2' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"海淀公园",
"location":
{
"lon":116.302509,
"lat":39.991152
}
}'
curl --location --request PUT 'localhost:9200/geo/_doc/1' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"天安门",
"location":
{
"lon":116.403981,
"lat":39.914492
}
}'
curl --location --request PUT 'localhost:9200/geo/_doc/3' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"北京动物园",
"location":
{
"lon":116.343184,
"lat":39.947468
}
}'
geo_point支持三种类型的查询
查找索引内距离北京站(116.433733,39.908404)3000米内的点
涉及的参数如下
curl --location --request GET 'localhost:9200/geo/_search' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": {
"geo_distance": {
"location": {
"lon":116.433733
,"lat":39.908404
},
"distance":3000,
"distance_type":"arc"
}
}
}'
查找索引内位于中央民族大学(116.326943,39.95499)以及京站(116.433733,39.908404)矩形的点
涉及的参数如下
curl --location --request GET 'localhost:9200/geo/_search' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": {
"geo_bounding_box": {
"location": {
"top_left": {
"lon": 116.326943,
"lat": 39.95499
},
"bottom_right": {
"lon": 116.433446,
"lat": 39.908737
}
}
}
}
}'
查找索引内位于西苑桥(116.300209,40.003423),巴沟山水园(116.29561,39.976004)以及北京科技大学(116.364528,39.996348)三角形内的点
涉及的参数如下
curl --location --request GET 'localhost:9200/geo/_search' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": {
"geo_polygon": {
"location": {
"points": [
{
"lon": 116.29561,
"lat": 39.976004
},
{
"lon": 116.364528,
"lat": 39.996348
},
{
"lon": 116.300209,
"lat": 40.003423
}
]
}
}
}
}'
https://www.elastic.co/guide/en/elasticsearch/reference/7.17/geo-queries.html