如何使用 Spring Data Redis Repositories 指定 geo radius 命令的附加参数?

How to specify geo radius command additional arguments with Spring Data Redis Repositories?

我正在使用 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 class.

实现您的解决方案来绕过这个问题

这样,您可以使用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;
    }
}