Elasticsearch 地理位置范围查询

Geo Distance Range Query

索引mapping定义:

索引中定义一个字段pin,添加一个属性location,type为geo_point

"pin" : {
"properties" : {
"location" : {
"type" : "geo_point"
}
}
}

DSL:

报文中的包含一个match all的query , filter中的distance指定了距离范围,pin.location是经纬度

{
"bool" : {
"must" : {
"match_all" : {}
}
,
"filter" : {
"geo_distance" : {
"distance" : "200km",
"pin.location" : {
"lat" : 40,
"lon" : -70
}
}
}
}
}

代码:

拼装 query 和 sort

       QueryBuilder builder = new GeoDistanceRangeQueryBuilder ("pin.location"
.point(lat,lon)
.from("0km")
.to("10000km")
.includeLower(true)
.includeUpper(false)
.optimizeBbox("memory")
.geoDistance(GeoDistance.ARC);

GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("location");
GeoDistanceSortBuilder sort = new GeoDistanceSortBuilder("location");
sort.unit(DistanceUnit.KILOMETERS);
sort.order(SortOrder.ASC);
sort.point(lat,lon);

构造dsl生产器

        SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); 
sourceBuilder.query(QueryBuilders.boolQuery())
.must(builder)
sourceBuilder.sort(sort);

调用elasticsearch

final SearchResponse response = executeGet(new ClientCallback<SearchResponse>() {
@Override
public ActionFuture<SearchResponse> execute(final Client client) {
final SearchSourceBuilder sourceBuilder = SearchParamUtils
.genSearchSourceBuilderFromSearchParam(searchParam);
String[] indexNames = new String[aliasIndexNameList.size()];
SearchRequest request = Requests.searchRequest(aliasIndexNameList.toArray(indexNames))
.types(type);
request.source(sourceBuilder.toString());
if (searchParam.getSearchType() != null) {
request.searchType(searchParam.getSearchType());
}
return client.search(request);
}
})
;

获取每条记录的距离

        SearchResult searchResult = new SearchResult();
SearchHits hits = response.getHits();
for (SearchHit hit : hits.getHits()) {
Object[] sortArray = hit.getSortValues();
if(sortArray!=null&&sortArray.length>0){
BigDecimal geoDis = new BigDecimal((Double) sortArray[sortArray.length-1]);
map.put("geoDistance", geoDis.setScale(0, BigDecimal.ROUND_HALF_DOWN));
System.out.println("距离" + hit.getSource().get("geoDistance"));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值