排序规则

自 3.4 版本以来,MongoDB 支持对集合和索引创建以及各种查询操作使用排序规则。排序规则基于 ICU 排序规则定义字符串比较规则。排序规则文档包含封装在 Collation 中的各种属性,如下列表所示:

Collation collation = Collation.of("fr")         (1)

  .strength(ComparisonLevel.secondary()          (2)
    .includeCase())

  .numericOrderingEnabled()                      (3)

  .alternate(Alternate.shifted().punct())        (4)

  .forwardDiacriticSort()                        (5)

  .normalizationEnabled();                       (6)
1 Collation 需要一个区域设置才能创建。这可以是区域设置的字符串表示形式、Locale(考虑语言、国家和变体)或 CollationLocale。区域设置对于创建是强制性的。
2 排序规则强度定义了表示字符之间差异的比较级别。您可以根据所选强度配置各种选项(区分大小写、大小写排序等)。
3 指定是按数字还是按字符串比较数字字符串。
4 指定排序规则是否应将空格和标点符号视为比较目的的基本字符。
5 指定是否字符串中的变音符号从字符串的末尾开始排序,例如某些法语词典排序。
6 指定是否检查文本是否需要规范化以及是否执行规范化。

排序规则可用于创建集合和索引。如果创建指定了排序规则的集合,则除非指定不同的排序规则,否则该排序规则将应用于索引创建和查询。排序规则对整个操作有效,不能按字段指定。

与其他元数据一样,排序规则可以通过 @Document 注解的 collation 属性从域类型派生,并将在运行查询、创建集合或索引时直接应用。

当 MongoDB 在第一次交互时自动创建集合时,将不使用带注解的排序规则。这将需要额外的存储交互,从而延迟整个过程。对于这些情况,请使用 MongoOperations.createCollection
Collation french = Collation.of("fr");
Collation german = Collation.of("de");

template.createCollection(Person.class, CollectionOptions.just(collation));

template.indexOps(Person.class).ensureIndex(new Index("name", Direction.ASC).collation(german));
如果未指定排序规则 (Collation.simple()),MongoDB 将使用简单的二进制比较。

在集合操作中使用排序规则只需在查询或操作选项中指定 Collation 实例,如下面两个示例所示:

示例 1. 将排序规则与 find 结合使用
Collation collation = Collation.of("de");

Query query = new Query(Criteria.where("firstName").is("Amél")).collation(collation);

List<Person> results = template.find(query, Person.class);
示例 2. 将排序规则与 aggregate 结合使用
Collation collation = Collation.of("de");

AggregationOptions options = AggregationOptions.builder().collation(collation).build();

Aggregation aggregation = newAggregation(
  project("tags"),
  unwind("tags"),
  group("tags")
    .count().as("count")
).withOptions(options);

AggregationResults<TagCount> results = template.aggregate(aggregation, "tags", TagCount.class);
仅当操作使用的排序规则与索引排序规则匹配时才使用索引。

MongoDB Repositories 通过 @Query 注解的 collation 属性支持 Collations

© . This site is unofficial and not affiliated with VMware.