我正在使用Spring Data Redis保存一些地址,每个地址都包含location
类型的Point
属性,该属性保存特定地址的地理坐标。另外,该属性用@GeoIndexed
注释。就像这里描述的一样:Geospatial Index。
我的Address
模型如下所示:
@RedisHash("addresses")
public class Address {
@Id
private String id;
@GeoIndexed
private Point location;
}
通过此存储库查询,我能够将所有附近的地址获取到给定的点和距离:
public interface AddressRepository extends CrudRepository<Address, String> {
List<Address> findByLocationNear(Point location, Distance distance);
}
我的问题是上述查询返回的地址未排序,但我需要将它们从最近到最远进行排序(此处描述的
ASC
选项:GEORADIUS - Redis Command)。因此,通常,我需要一种将其他参数传递给此查询的方法,例如对结果进行排序或限制(GEORADIUS - Redis Command的任何选项)。
有人可以帮忙吗?
最佳答案
您可以通过使用GeoOperations
类实现解决方案来绕过此问题。
这样,您可以使用RedisGeoCommands.GeoRadiusCommandArgs.limit(n)
,并且可以将结果数限制为前n个匹配项。
在此处查看Spring Data Redis的官方文档:GeoRadiusCommandArgs
您还可以在Spring Data Redis测试中直接找到一些示例。
更新:
这是我通过实现新的service
方法而不是repository
所得到的最终代码:
public class AddressService {
private final StringRedisTemplate stringRedisTemplate;
public AddressService(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public List<Address> findByLocationNear(Point location, Distance distance) {
Circle within = new Circle(location, distance);
GeoRadiusCommandArgs args = GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending().limit(10);
GeoOperations<String, String> geoOperations = stringRedisTemplate.opsForGeo();
GeoResults<GeoLocation<String>> nearbyLocations = geoOperations.radius("addresses:location", within, args);
// Convert geo results into addresses
List<Address> addresses = ...;
return addresses;
}
}
关于spring - 如何使用Spring Data Redis存储库指定geo radius命令附加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61108782/