我正在构建一个需要弹性搜索的应用程序,以根据纬度和经度查找最近的位置。目前,我可以根据GeoPoint和最大距离(公里)来做到这一点。
@Override
public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
LOGGER.info("<findCitiesNearby>");
FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon()).distance(distance, DistanceUnit.KILOMETERS);
SearchQuery q = new NativeSearchQueryBuilder()
.withFilter(filterBuilderGeo);
List<CityDefinition> fields = esOps.queryForList(q, CityDefinition.class);
return fields;
}
这几乎是完美的,但不是在给定距离内搜索,我希望弹性返回最近的位置,无论距离如何。这可能吗?如果是,我该怎么做?
答案 0 :(得分:1)
您可以按距离排序,而不是过滤。
这些方面应该有效:
public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
GeoDistanceSortBuilder geoDistanceSort = SortBuilders.geoDistanceSort("geo").point(geo.lat(), geo.lon())
.unit(DistanceUnit.KILOMETERS).sortMode("ASC")
.geoDistance(GeoDistance.PLANE);
final int limit = 1; // if you want only the single nearest result.
SearchQuery q = new NativeSearchQueryBuilder()
.withSort(geoDistanceSort)
.withPageable(new PageRequest(0, limit))
.build();
List<CityDefinition> fields = esOps.queryForList(q, CityDefinition.class);
return fields;
}
答案 1 :(得分:0)
显然可以删除距离部分。
@Override
public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
LOGGER.info("<findCitiesNearby>");
//FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon()).distance(distance, DistanceUnit.KILOMETERS);
FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon());
SearchQuery q = new NativeSearchQueryBuilder()
.withFilter(filterBuilderGeo);
List<?> fields = esOps.queryForList(q, CityDefinition.class);
return (List<CityDefinition>) fields;
}