Spring Boot 整合 分布式搜索引擎 Elastic Search 实现 我附近的、酒店竞排
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class MyPlaceService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public List<MyPlace> findMyPlaceByLocation(double lat, double lon, int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
// 构建查询条件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.withPageable(pageRequest)
.withQuery(coordinateQuery("location").distance(lon, lat).point(lon, lat).within(50, DistanceUnit.KILOMETERS));
// 执行查询
Page<MyPlace> pageResult = elasticsearchTemplate.queryForPage(queryBuilder.build(), MyPlace.class);
return pageResult.getContent();
}
// 假设MyPlaceRepository是继承自ElasticsearchRepository的Repository
// public interface MyPlaceRepository extends ElasticsearchRepository<MyPlace, String> {
// }
}
这个代码示例展示了如何在Spring Boot应用中使用ElasticsearchTemplate来执行基于位置的搜索查询。它使用了NativeSearchQueryBuilder
来构建查询,并通过elasticsearchTemplate.queryForPage
方法执行查询并获取分页结果。这个示例假设MyPlace
实体类已经映射到Elasticsearch中相应的索引,并且MyPlaceRepository
接口继承自ElasticsearchRepository
。
评论已关闭