地理空间搜索是ElasticSearch中的一个重要功能,它允许用户基于地理位置进行搜索和分析。这一功能在许多场景中非常有用,例如寻找附近的餐厅、商店或服务点等。下面将详细介绍如何在ElasticSearch中使用Geo地理空间搜索功能。
在ElasticSearch中,有两种类型的Geo字段:geo_point
和 geo_shape
。
PUT my_index
{
"mappings": {
"properties": {
"location": {
"type": "geo_point"
}
}
}
}
一旦定义了geo_point
字段,就可以开始索引包含地理位置信息的文档。
POST my_index/_doc/1
{
"text": "Geo-point as an object",
"location": {
"lat": 40.12,
"lon": -71.34
}
}
POST my_index/_doc/2
{
"text": "Geo-point as a string",
"location": "40.12,-71.34"
}
POST my_index/_doc/3
{
"text": "Geo-point as an array",
"location": [-71.34, 40.12]
}
ElasticSearch提供了多种地理查询方式,包括距离范围查询、多边形查询、矩形查询等。
这是最常见的地理查询之一,用于查找特定距离内的所有点。
GET my_index/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_distance": {
"distance": "200km",
"location": {
"lat": 40,
"lon": -70
}
}
}
}
}
}
用于查找位于指定多边形区域内的所有点。
GET my_index/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_polygon": {
"location": {
"points": [
{"lat": 40, "lon": -70},
{"lat": 30, "lon": -80},
{"lat": 20, "lon": -90}
]
}
}
}
}
}
}
除了查询外,ElasticSearch还支持地理聚合操作,比如计算某个区域内点的中心位置或者分布情况。
用于计算一组地理位置点的中心点。
GET my_index/_search
{
"size": 0,
"aggs": {
"centroid": {
"geo_centroid": {
"field": "location"
}
}
}
}