Redis-specific Query Methods

查询方法允许从方法名称自动推导出简单的查找器查询,如下图例所示:

Query methods allow automatic derivation of simple finder queries from the method name, as shown in the following example: .Sample Repository finder Method

public interface PersonRepository extends CrudRepository<Person, String> {

  List<Person> findByFirstname(String firstname);
}

请确保用于查找符方法中的属性已设置为索引。

Please make sure properties used in finder methods are set up for indexing.

Redis 存储库的查询方法仅支持分页查询实体和实体集合。

Query methods for Redis repositories support only queries for entities and collections of entities with paging.

利用派生查询方法在为运行查询建模时可能总是不够的。RedisCallback 在与索引结构甚至自定义索引的实际匹配方面提供更多的控制。要这样做,请提供一个返回单个或 Iterable 设置 id 值的 RedisCallback,如下图例所示:

Using derived query methods might not always be sufficient to model the queries to run. RedisCallback offers more control over the actual matching of index structures or even custom indexes. To do so, provide a RedisCallback that returns a single or Iterable set of id values, as shown in the following example: .Sample finder using RedisCallback

String user = //...

List<RedisSession> sessionsByUser = template.find(new RedisCallback<Set<byte[]>>() {

  public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
    return connection
      .sMembers("sessions:securityContext.authentication.principal.username:" + user);
  }}, RedisSession.class);

下表概述了 Redis 支持的关键字和包含该关键字的方法从本质上翻译成什么:

The following table provides an overview of the keywords supported for Redis and what a method containing that keyword essentially translates to:

Table 1. Supported keywords inside method names
Keyword Sample Redis snippet

And

findByLastnameAndFirstname

SINTER …:firstname:rand …:lastname:al’thor

Or

findByLastnameOrFirstname

SUNION …:firstname:rand …:lastname:al’thor

Is, Equals

findByFirstname, findByFirstnameIs, findByFirstnameEquals

SINTER …:firstname:rand

IsTrue

FindByAliveIsTrue

SINTER …:alive:1

IsFalse

findByAliveIsFalse

SINTER …:alive:0

Top,First

findFirst10ByFirstname,findTop5ByFirstname

Sorting Query Method results

Redis 仓库允许多种形式来定义排序顺序。当检索哈希或设置时,Redis 本身不支持正在进行的排序。因此,Redis 仓库查询方法构建一个 Comparator,该 Comparator 会在以 List 方式返回结果之前应用于结果。我们来看看下例:

Redis repositories allow various approaches to define sorting order. Redis itself does not support in-flight sorting when retrieving hashes or sets. Therefore, Redis repository query methods construct a Comparator that is applied to the result before returning results as List. Let’s take a look at the following example:

Example 1. Sorting Query Results
interface PersonRepository extends RedisRepository<Person, String> {

  List<Person> findByFirstnameOrderByAgeDesc(String firstname); 1

  List<Person> findByFirstname(String firstname, Sort sort);   2
}
1 Static sorting derived from method name.
2 Dynamic sorting using a method argument.