使用elasticsearch获取最近的位置

Get nearest location with elasticsearch

我正在构建一个应用程序,它需要 elasticsearch 根据纬度和经度查找最近的位置。目前,我可以根据 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;
}

这几乎是完美的,但我想要弹性到 return 最近的位置,而不是在给定的距离内搜索,而不管距离有多远。这可能吗?如果是,我该怎么做?

显然可以只删除距离部分。

@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;
}

您可以按距离排序,而不是过滤。

按照这些思路应该可行:

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;
}