ES的地图检索方式
ES支持的地图检索方式有以下几种;
geo_distance
geo_bounding_box
geo_polygon
1、geo_distance:直线距离检索,如给定点A,要求返回地图上距离点A三千米的商家(点外卖场景)
2、查找索引内距离北京站(116.433733,39.908404)3000米内的点
geo_distance涉及的参数如下
location:确定一个点;
distance:确定一个半径,单位米
distance_type:确定一个图形的类型;一般是圆形,arc
POST /map/_search
{
"query": {
"geo_distance":
{
"location":
{
"lon":116.433733
,"lat":39.908404
},
"distance":3000,
"distance_type":"arc"
}
}
}
创建geo_point类型字段映射:
PUT test
{
"mappings": {
"user": {
"properties": {
"location": {
"type": "geo_point"
}
}
}
}
}
加入依赖:
使用spring-data-elasticsearch依赖
<!-- ElasticSearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3、创建Doc文档对象:
package cn.nagisa.geo.doc;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
/**
* @author nagisa
*/
@Data
@Document(indexName = "test",type = "user")
public class UserDoc {
private Long id;
private String username;
@GeoPointField
private GeoPoint location;
}
这里的Doc相当于entity,注意加上@GeoPointField,表示localcation是Es当中geo_point类型的字段
/**
* @param lat 区域中心的纬度
* @param lng 区域中心经度
* @param distance 区域半径
* @return 符合条件的数据
*/
@Override
public JsonResult fixedArea(Double lat, Double lng, Integer distance) {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
// 以某点为中心,搜索指定范围
GeoDistanceQueryBuilder distanceQueryBuilder = new GeoDistanceQueryBuilder("location");
distanceQueryBuilder
.point(lat, lng)
.distance(distance, DistanceUnit.KILOMETERS);
boolQueryBuilder.filter(distanceQueryBuilder);
//查询封装
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
NativeSearchQuery build = nativeSearchQueryBuilder
.withQuery(boolQueryBuilder)
.build();
return JsonResult.me().setResult(userRepository.search(build));
}
错误排查:
Error: all shards failed
可能原因:经纬度调换,传反了
ES--经纬度查询_es 经纬度查询_宝哥大数据的博客-CSDN博客
SpringBoot+ElasticSearch根据经纬度,简单搜索指定距离范围内的数据_springboot经纬度在5公里内_Nagisa-的博客-CSDN博客