其他 Elasticsearch 操作支持

本章涵盖了无法通过存储库接口直接访问的 Elasticsearch 操作的额外支持。 建议按照自定义存储库实现中的描述,将这些操作添加为自定义实现。spring-doc.cadn.net.cn

索引设置

使用 Spring Data Elasticsearch 创建 Elasticsearch 索引时,可以通过 @Setting 注解定义不同的索引设置。 以下是可用的参数:spring-doc.cadn.net.cn

同样也可以定义 索引排序(请查阅链接的 Elasticsearch 文档以了解可能的字段类型和值):spring-doc.cadn.net.cn

@Document(indexName = "entities")
@Setting(
  sortFields = { "secondField", "firstField" },                                  (1)
  sortModes = { Setting.SortMode.max, Setting.SortMode.min },                    (2)
  sortOrders = { Setting.SortOrder.desc, Setting.SortOrder.asc },
  sortMissingValues = { Setting.SortMissing._last, Setting.SortMissing._first })
class Entity {
    @Nullable
    @Id private String id;

    @Nullable
    @Field(name = "first_field", type = FieldType.Keyword)
    private String firstField;

    @Nullable @Field(name = "second_field", type = FieldType.Keyword)
    private String secondField;

    // getter and setter...
}
1 定义排序字段时,请使用 Java 属性名称(firstField),而不是可能为 Elasticsearch 定义的名称(first_field
2 sortModessortOrderssortMissingValues 是可选的,但如果设置了它们,则条目数量必须与 sortFields 元素的数量相匹配。

索引映射

当 Spring Data Elasticsearch 使用 IndexOperations.createMapping() 方法创建索引映射时,它会使用 映射注解概述 中描述的注解,尤其是 @Field 注解。 此外,还可以将 @Mapping 注解添加到类上。 此注解具有以下属性:spring-doc.cadn.net.cn

  • mappingPath JSON 格式的类路径资源;如果此资源不为空,则将其用作映射,不再执行其他映射处理。spring-doc.cadn.net.cn

  • enabled 当设置为 false 时,此标志会被写入映射中,且不再进行进一步处理。spring-doc.cadn.net.cn

  • dateDetectionnumericDetection 在未设置为 DEFAULT 时,会在映射中设置相应的属性。spring-doc.cadn.net.cn

  • dynamicDateFormats 当此字符串数组不为空时,它定义了用于自动日期检测的日期格式。spring-doc.cadn.net.cn

  • runtimeFieldsPath 一个 JSON 格式的类路径资源,包含运行时字段的定义,该资源会被写入索引映射中,例如:spring-doc.cadn.net.cn

{
  "day_of_week": {
    "type": "keyword",
    "script": {
      "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
    }
  }
}

过滤器构建器

过滤器构建器提升了查询速度。spring-doc.cadn.net.cn

private ElasticsearchOperations operations;

IndexCoordinates index = IndexCoordinates.of("sample-index");

Query query = NativeQuery.builder()
	.withQuery(q -> q
		.matchAll(ma -> ma))
	.withFilter( q -> q
		.bool(b -> b
			.must(m -> m
				.term(t -> t
					.field("id")
					.value(documentId))
			)))
	.build();

SearchHits<SampleEntity> sampleEntities = operations.search(query, SampleEntity.class, index);

使用滚动处理大型结果集

Elasticsearch 拥有一个 scroll API,用于分块获取大型结果集。 Spring Data Elasticsearch 在内部使用该功能来提供 <T> SearchHitsIterator<T> SearchOperations.searchForStream(Query query, Class<T> clazz, IndexCoordinates index) 方法的实现。spring-doc.cadn.net.cn

IndexCoordinates index = IndexCoordinates.of("sample-index");

Query searchQuery = NativeQuery.builder()
    .withQuery(q -> q
        .matchAll(ma -> ma))
    .withFields("message")
    .withPageable(PageRequest.of(0, 10))
    .build();

SearchHitsIterator<SampleEntity> stream = elasticsearchOperations.searchForStream(searchQuery, SampleEntity.class,
index);

List<SampleEntity> sampleEntities = new ArrayList<>();
while (stream.hasNext()) {
  sampleEntities.add(stream.next());
}

stream.close();

SearchOperations API 中没有方法可以访问滚动 ID,如果需要访问该 ID,可以使用 AbstractElasticsearchTemplate 的以下方法(这是不同 ElasticsearchOperations 实现的基础实现):spring-doc.cadn.net.cn

@Autowired ElasticsearchOperations operations;

AbstractElasticsearchTemplate template = (AbstractElasticsearchTemplate)operations;

IndexCoordinates index = IndexCoordinates.of("sample-index");

Query query = NativeQuery.builder()
    .withQuery(q -> q
        .matchAll(ma -> ma))
    .withFields("message")
    .withPageable(PageRequest.of(0, 10))
    .build();

SearchScrollHits<SampleEntity> scroll = template.searchScrollStart(1000, query, SampleEntity.class, index);

String scrollId = scroll.getScrollId();
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasSearchHits()) {
  sampleEntities.addAll(scroll.getSearchHits());
  scrollId = scroll.getScrollId();
  scroll = template.searchScrollContinue(scrollId, 1000, SampleEntity.class);
}
template.searchScrollClear(scrollId);

要在存储库方法中使用 Scroll API,返回类型必须在 Elasticsearch Repository 中定义为 Stream。 该方法的实现将随后使用来自 ElasticsearchTemplate 的 scroll 方法。spring-doc.cadn.net.cn

interface SampleEntityRepository extends Repository<SampleEntity, String> {

    Stream<SampleEntity> findBy();

}

排序选项

除了分页和排序中描述的默认排序选项外,Spring Data Elasticsearch 还提供了派生自org.springframework.data.domain.Sort.Orderorg.springframework.data.elasticsearch.core.query.Order类。 它提供了在指定结果排序时可以发送给 Elasticsearch 的其他参数(参见www.elastic.co/guide/en/elasticsearch/reference/7.15/sort-search-results.html)。spring-doc.cadn.net.cn

还有一个 org.springframework.data.elasticsearch.core.query.GeoDistanceOrder 类,可用于按地理距离对搜索操作的结果进行排序。spring-doc.cadn.net.cn

如果要检索的类拥有一个名为 locationGeoPoint 属性,则以下 Sort 将根据与给定点的距离对结果进行排序:spring-doc.cadn.net.cn

Sort.by(new GeoDistanceOrder("location", new GeoPoint(48.137154, 11.5761247)))

运行时字段

从 7.12 版本开始,Elasticsearch 添加了运行时字段功能(www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime.html)。 Spring Data Elasticsearch 通过两种方式支持此功能:spring-doc.cadn.net.cn

索引映射中的运行时字段定义

定义运行时字段的第一种方法是将定义添加到索引映射中(请参阅 www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime-mapping-fields.html)。 要在 Spring Data Elasticsearch 中使用此方法,用户必须提供一个包含相应定义的 JSON 文件,例如:spring-doc.cadn.net.cn

示例 1. runtime-fields.json
{
  "day_of_week": {
    "type": "keyword",
    "script": {
      "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
    }
  }
}

此 JSON 文件的路径(必须位于类路径上)随后需在实体的 @Mapping 注解中进行设置:spring-doc.cadn.net.cn

@Document(indexName = "runtime-fields")
@Mapping(runtimeFieldsPath = "/runtime-fields.json")
public class RuntimeFieldEntity {
	// properties, getter, setter,...
}

在查询上设置的运行时字段定义

定义运行时字段的第二种方法是将定义添加到搜索查询中(请参阅 www.elastic.co/guide/en/elasticsearch/reference/7.12/runtime-search-request.html)。 以下代码示例展示了如何使用 Spring Data Elasticsearch 实现此操作:spring-doc.cadn.net.cn

使用的实体是一个具有 price 属性的简单对象:spring-doc.cadn.net.cn

@Document(indexName = "some_index_name")
public class SomethingToBuy {

	private @Id @Nullable String id;
	@Nullable @Field(type = FieldType.Text) private String description;
	@Nullable @Field(type = FieldType.Double) private Double price;

	// getter and setter
}

以下查询使用了一个运行时字段,该字段通过将价格增加 19% 来计算 priceWithTax 值,并在搜索查询中使用此值来查找所有 priceWithTax 大于或等于给定值的实体:spring-doc.cadn.net.cn

RuntimeField runtimeField = new RuntimeField("priceWithTax", "double", "emit(doc['price'].value * 1.19)");
Query query = new CriteriaQuery(new Criteria("priceWithTax").greaterThanEqual(16.5));
query.addRuntimeField(runtimeField);

SearchHits<SomethingToBuy> searchHits = operations.search(query, SomethingToBuy.class);

这适用于 Query 接口的每个实现。spring-doc.cadn.net.cn

时间点 (PIT) API

ElasticsearchOperations 支持 Elasticsearch 的时间点 API(参见 www.elastic.co/guide/en/elasticsearch/reference/8.3/point-in-time-api.html)。 以下代码片段展示了如何在虚构的 Person 类中使用此功能:spring-doc.cadn.net.cn

ElasticsearchOperations operations; // autowired
Duration tenSeconds = Duration.ofSeconds(10);

String pit = operations.openPointInTime(IndexCoordinates.of("person"), tenSeconds); (1)

// create query for the pit
Query query1 = new CriteriaQueryBuilder(Criteria.where("lastName").is("Smith"))
    .withPointInTime(new Query.PointInTime(pit, tenSeconds))                        (2)
    .build();
SearchHits<Person> searchHits1 = operations.search(query1, Person.class);
// do something with the data

// create 2nd query for the pit, use the id returned in the previous result
Query query2 = new CriteriaQueryBuilder(Criteria.where("lastName").is("Miller"))
    .withPointInTime(
        new Query.PointInTime(searchHits1.getPointInTimeId(), tenSeconds))          (3)
    .build();
SearchHits<Person> searchHits2 = operations.search(query2, Person.class);
// do something with the data

operations.closePointInTime(searchHits2.getPointInTimeId());                        (4)
1 为索引(可以是多个名称)创建一个时间点,并设置保活时长,然后检索其 ID
2 将该 ID 传入查询,以便与下一个保持活跃的值一起搜索
3 对于下一个查询,请使用上一次搜索返回的 ID
4 完成后,使用最后返回的 id 关闭时间点。

搜索模板支持

支持使用搜索模板 API。 要使用此功能,首先需要创建一个存储脚本。 ElasticsearchOperations 接口扩展了 ScriptOperations,后者提供了必要的函数。 此处使用的示例假设我们有一个名为 firstName 属性的 Person 实体。 搜索模板脚本可以按如下方式保存:spring-doc.cadn.net.cn

import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.script.Script;

operations.putScript(                            (1)
  Script.builder()
    .withId("person-firstname")                  (2)
    .withLanguage("mustache")                    (3)
    .withSource("""                              (4)
      {
        "query": {
          "bool": {
            "must": [
              {
                "match": {
                  "firstName": "{{firstName}}"   (5)
                }
              }
            ]
          }
        },
        "from": "{{from}}",                      (6)
        "size": "{{size}}"                       (7)
      }
      """)
    .build()
);
1 使用 putScript() 方法来存储搜索模板脚本。
2 脚本的名称 / ID
3 搜索模板中使用的脚本必须采用 mustache 语言。
4 脚本来源
5 脚本中的搜索参数
6 分页请求偏移量
7 分页请求大小

要在搜索查询中使用搜索模板,Spring Data Elasticsearch 提供了 SearchTemplateQuery,它是 org.springframework.data.elasticsearch.core.query.Query 接口的一个实现。spring-doc.cadn.net.cn

尽管 SearchTemplateQueryQuery 接口的一个实现,但并非基类提供的所有功能都可用于 SearchTemplateQuery,例如设置 PageableSort。这些功能的值必须添加到存储的脚本中,如下面关于分页参数的示例所示。如果将这些值设置在 Query 对象上,它们将被忽略。

在以下代码中,我们将添加一个使用搜索模板查询的调用到自定义仓库实现(参见 自定义仓库实现),以此作为如何将其集成到仓库调用中的示例。spring-doc.cadn.net.cn

我们首先定义自定义仓库片段接口:spring-doc.cadn.net.cn

interface PersonCustomRepository {
	SearchPage<Person> findByFirstNameWithSearchTemplate(String firstName, Pageable pageable);
}

此仓库片段的具体实现如下:spring-doc.cadn.net.cn

public class PersonCustomRepositoryImpl implements PersonCustomRepository {

  private final ElasticsearchOperations operations;

  public PersonCustomRepositoryImpl(ElasticsearchOperations operations) {
    this.operations = operations;
  }

  @Override
  public SearchPage<Person> findByFirstNameWithSearchTemplate(String firstName, Pageable pageable) {

    var query = SearchTemplateQuery.builder()                               (1)
      .withId("person-firstname")                                           (2)
      .withParams(
        Map.of(                                                             (3)
          "firstName", firstName,
          "from", pageable.getOffset(),
          "size", pageable.getPageSize()
          )
      )
      .build();

    SearchHits<Person> searchHits = operations.search(query, Person.class); (4)

    return SearchHitSupport.searchPageFor(searchHits, pageable);
  }
}
1 创建一个 SearchTemplateQuery
2 提供搜索模板的 ID
3 参数通过 Map<String,Object> 传递
4 以与其他查询类型相同的方式执行搜索。

嵌套排序

以下示例取自 org.springframework.data.elasticsearch.core.query.sort.NestedSortIntegrationTests 类,展示了如何定义嵌套排序。spring-doc.cadn.net.cn

var filter = StringQuery.builder("""
	{ "term": {"movies.actors.sex": "m"} }
	""").build();
var order = new org.springframework.data.elasticsearch.core.query.Order(Sort.Direction.DESC,
	"movies.actors.yearOfBirth")
	.withNested(
		Nested.builder("movies")
			.withNested(
				Nested.builder("movies.actors")
					.withFilter(filter)
					.build())
			.build());

var query = Query.findAll().addSort(Sort.by(order));

关于过滤查询:此处不能使用 CriteriaQuery,因为该查询会被转换为 Elasticsearch 嵌套查询,而嵌套查询在过滤上下文中无法工作。因此,此处只能使用 StringQueryNativeQuery。当使用其中任一选项时(如上述的术语查询),必须使用 Elasticsearch 的字段名称;因此,若通过 @Field(name="…​") 定义重新定义了这些字段,请务必注意。spring-doc.cadn.net.cn

对于排序路径和嵌套路径的定义,应使用 Java 实体属性名称。spring-doc.cadn.net.cn