使用springboot整合es查询附近公里酒店如何写代码,由分页功能
时间: 2024-03-13 08:45:45 浏览: 52
使用 Spring Boot 整合 Elasticsearch 实现查询附近公里酒店的代码如下:
1. 定义实体类 Hotel(假设有经度和纬度属性):
```java
@Data
@Document(indexName = "hotel")
public class Hotel {
private String id;
private String name;
private Double latitude;
private Double longitude;
}
```
2. 定义 Elasticsearch 的 Repository 接口:
```java
public interface HotelRepository extends ElasticsearchRepository<Hotel, String> {
Page<Hotel> findByLocationNear(Point point, Distance distance, Pageable pageable);
}
```
3. 在 Service 层实现查询附近公里酒店的方法:
```java
@Service
public class HotelService {
@Autowired
private HotelRepository hotelRepository;
public Page<Hotel> findNearbyHotels(Double latitude, Double longitude, Double distance, Integer pageNo, Integer pageSize) {
Point point = new Point(latitude, longitude);
Distance geoDistance = new Distance(distance, Metrics.KILOMETERS);
Pageable pageable = PageRequest.of(pageNo, pageSize);
return hotelRepository.findByLocationNear(point, geoDistance, pageable);
}
}
```
4. 在 Controller 层调用 Service 层的方法,并返回查询结果:
```java
@RestController
@RequestMapping("/hotels")
public class HotelController {
@Autowired
private HotelService hotelService;
@GetMapping("/nearby")
public ResponseEntity<Page<Hotel>> findNearbyHotels(
@RequestParam("latitude") Double latitude,
@RequestParam("longitude") Double longitude,
@RequestParam("distance") Double distance,
@RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
Page<Hotel> hotels = hotelService.findNearbyHotels(latitude, longitude, distance, pageNo, pageSize);
return ResponseEntity.ok(hotels);
}
}
```
以上代码实现了查询附近公里酒店的功能,并且支持分页。其中,通过使用 Elasticsearch 自带的地理位置查询功能实现了根据经纬度查询附近的酒店。
阅读全文
相关推荐

















