ES7学习笔记(十三)GEO位置搜索 (2)

location的类型是GeoPoint,添加数据的方法没有变化,转化成Json就可以了。再看看查询怎么用,

public void searchGeo() throws IOException { SearchRequest searchRequest = new SearchRequest("my_geo"); SearchSourceBuilder ssb = new SearchSourceBuilder(); //工体的坐标 GeoPoint geoPoint = new GeoPoint(39.93367367974064d,116.47845257733152d); //geo距离查询 name=geo字段 QueryBuilder qb = QueryBuilders.geoDistanceQuery("location") //距离 3KM .distance(3d, DistanceUnit.KILOMETERS) //坐标工体 .point(geoPoint); ssb.query(qb); searchRequest.source(ssb); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit.getSourceAsString()); } }

SearchRequest指定索引my_geo

创建工体的坐标点GeoPoint

创建geo距离查询,指定geo字段location,距离3km,坐标点工体

其他的地方没有变化

运行一下,看看结果,

{"name":"路人乙","location":{"lat":39.93360786576342,"lon":116.47853840802}}

只有在“朝阳公园”的路人乙被查询了出来,符合预期。

距离排序

有的小伙伴可能会有这样的疑问,我不想按照距离去查询,只想把查询结果按照离“我”的距离排序,该怎么做呢?再看一下,

public void searchGeoSort() throws IOException { SearchRequest searchRequest = new SearchRequest("my_geo"); SearchSourceBuilder ssb = new SearchSourceBuilder(); //工体的坐标 GeoPoint geoPoint = new GeoPoint(39.93367367974064d,116.47845257733152d); GeoDistanceSortBuilder sortBuilder = SortBuilders .geoDistanceSort("location", geoPoint) .order(SortOrder.ASC); ssb.sort(sortBuilder); searchRequest.source(ssb); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit.getSourceAsString()); } }

这次查询并没有设置查询条件,而是创建了一个geo距离排序,同样,先指定geo字段location,和当前的坐标工体,再设置排序是升序。运行一下,看看结果,

{"name":"路人乙","location":{"lat":39.93360786576342,"lon":116.47853840802}} {"name":"路人甲","location":{"lat":39.902799980059335,"lon":116.42721165631102}}

离“工体”比较近的“路人乙”排在了第一个,也是符合预期的。有问题大家评论区留言吧~

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppysw.html