Reputation: 67
I am using Spring Data Redis to save some addresses, each contains a location
property of type Point
that holds the geo-coordinates of the particular address. Also, the property is annotated with @GeoIndexed
. Like what described here: Geospatial Index.
My Address
model looks like this:
@RedisHash("addresses")
public class Address {
@Id
private String id;
@GeoIndexed
private Point location;
}
I was able to get all nearby addresses to a given point and distance with this repository query:
public interface AddressRepository extends CrudRepository<Address, String> {
List<Address> findByLocationNear(Point location, Distance distance);
}
My problem is that the returned addresses by the above query are unsorted but I need them to be sorted from the nearest to the furthest (ASC
option described here: GEORADIUS - Redis Command).
So, generally, I need a way to pass additional arguments to this query such as sorting or limiting the results (any option of GEORADIUS - Redis Command).
Can anyone help, please?
Upvotes: 2
Views: 921
Reputation: 54
You can bypass this problem by implementing your solution using the GeoOperations
class.
In this way, you can use the RedisGeoCommands.GeoRadiusCommandArgs.limit(n)
and you will be able to limit the number of results to the first n matching.
Take a look here on the official documentation of Spring Data Redis: GeoRadiusCommandArgs
You can find also some examples directly into the Spring Data Redis tests.
Update:
This is the final code I came to by implementing a new service
method instead of the 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;
}
}
Upvotes: 1