在Spring Boot环境下,可以通过以下步骤来获取SearchHits中的距离:

  1. 首先,确保StoreIndex类中有一个字段用来存储距离信息。可以通过添加一个字段来实现,例如:
@Field(type = FieldType.Text, name = "name")
private String name;

@GeoPointField
private GeoPoint location;

private Double distance;
  1. 然后,在查询时使用GeoDistanceSortBuilder来排序查询结果,并将距离信息存储到StoreIndex对象的distance字段中。例如:
GeoDistanceSortBuilder sortBuilder = SortBuilders.geoDistanceSort("location", lat, lon)
        .unit(DistanceUnit.KILOMETERS)
        .order(SortOrder.ASC);

SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withFilter(QueryBuilders.matchAllQuery())
        .withSort(sortBuilder)
        .build();

SearchHits<StoreIndex> searchHits = elasticsearchRestTemplate.search(searchQuery, StoreIndex.class);
for (SearchHit<StoreIndex> searchHit : searchHits) {
    StoreIndex storeIndex = searchHit.getContent();
    storeIndex.setDistance(searchHit.getSortValues()[0]);
}

在上述代码中,lat和lon是经纬度坐标,elasticsearchRestTemplate是Elasticsearch提供的用于执行查询的工具类。

通过以上步骤,就可以将查询结果中的距离信息存储到StoreIndex对象的distance字段中了

在springboot环境下 SearchHitsStoreIndex怎么取距离

原文地址: https://www.cveoy.top/t/topic/iauc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录