跳到主要内容
版本:6.1.1

脚本化字段与运行时字段

Doubao 中英对照 Scripted and runtime fields

Spring Data Elasticsearch 支持脚本化字段和运行时字段。有关这方面的详细信息,请参阅 Elasticsearch 关于脚本编写(www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html)和运行时字段(www.elastic.co/guide/en/elasticsearch/reference/8.9/runtime.html)的文档。在 Spring Data Elasticsearch 的上下文中,您可以使用

  • 脚本化字段,用于返回在结果文档上计算得出并添加到返回文档中的字段。

  • 运行时字段,它在已存储的文档上计算,可以在查询中使用和/或在搜索结果中返回。

以下代码片段将展示您可以做什么(这些展示的是命令式代码,但响应式实现的工作方式类似)。

person 实体​

这些示例中使用的实体是一个 Person 实体。该实体有一个 birthDate 属性和一个 age 属性。出生日期是固定的,而年龄取决于发出查询的时间,需要动态计算。

import org.jspecify.annotations.Nullable;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.ScriptedField;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import static org.springframework.data.elasticsearch.annotations.FieldType.*;

import java.lang.Integer;

@Document(indexName = "persons")
public record Person(
@Id
@Nullable
String id,
@Field(type = Text)
String lastName,
@Field(type = Text)
String firstName,
@Field(type = Keyword)
String gender,
@Field(type = Date, format = DateFormat.basic_date)
LocalDate birthDate,
@Nullable
@ScriptedField Integer age 1
) {
public Person(String id,String lastName, String firstName, String gender, String birthDate) {
this(id, 2
lastName,
firstName,
LocalDate.parse(birthDate, DateTimeFormatter.ISO_LOCAL_DATE),
gender,
null);
}
}
  • age 属性将在搜索结果中被计算并填充。

  • 一个用于设置测试数据的便捷构造函数。

请注意,age 属性标注了 @ScriptedField。这会抑制在索引映射中写入相应条目,并将该属性标记为接收搜索响应中计算字段的目标。

仓库接口​

本例中使用的仓库:

public interface PersonRepository extends ElasticsearchRepository<Person, String> {

SearchHits<Person> findAllBy(ScriptedField scriptedField);

SearchHits<Person> findByGenderAndAgeLessThanEqual(String gender, Integer age, RuntimeField runtimeField);
}

服务类​

该服务类注入了一个仓库和一个 ElasticsearchOperations 实例,以展示填充和使用 age 属性的几种方式。我们将代码拆分为不同片段,并在其中插入解释:

import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.RuntimeField;
import org.springframework.data.elasticsearch.core.query.ScriptData;
import org.springframework.data.elasticsearch.core.query.ScriptType;
import org.springframework.data.elasticsearch.core.query.ScriptedField;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {
private final ElasticsearchOperations operations;
private final PersonRepository repository;

public PersonService(ElasticsearchOperations operations, SaRPersonRepository repository) {
this.operations = operations;
this.repository = repository;
}

public void save() { 1
List<Person> persons = List.of(
new Person("1", "Smith", "Mary", "f", "1987-05-03"),
new Person("2", "Smith", "Joshua", "m", "1982-11-17"),
new Person("3", "Smith", "Joanna", "f", "2018-03-27"),
new Person("4", "Smith", "Alex", "m", "2020-08-01"),
new Person("5", "McNeill", "Fiona", "f", "1989-04-07"),
new Person("6", "McNeill", "Michael", "m", "1984-10-20"),
new Person("7", "McNeill", "Geraldine", "f", "2020-03-02"),
new Person("8", "McNeill", "Patrick", "m", "2022-07-04"));

repository.saveAll(persons);
}
  • 一个用于在 Elasticsearch 中存储一些数据的工具方法。

脚本化字段​

下一段展示了如何使用脚本化字段计算并返回人员的年龄。脚本化字段只能向返回的数据中添加内容,年龄不能在查询中使用(这一点请参阅运行时字段)。

public SearchHits<Person> findAllWithAge() {

var scriptedField = ScriptedField.of("age", 1
ScriptData.of(b -> b
.withType(ScriptType.INLINE)
.withScript("""
Instant currentDate = Instant.ofEpochMilli(new Date().getTime());
Instant startDate = doc['birth-date'].value.toInstant();
return (ChronoUnit.DAYS.between(startDate, currentDate) / 365);
""")));

// version 1: use a direct query
var query = new StringQuery("""
{ "match_all": {} }
""");
query.addScriptedField(scriptedField); 2
query.addSourceFilter(FetchSourceFilter.of(b -> b.withIncludes("*"))); 3

var result1 = operations.search(query, Person.class); 4

// version 2: use the repository
var result2 = repository.findAllBy(scriptedField); 5

return result1;
}
  • 定义计算人员年龄的 ScriptedField。

  • 使用 Query 时,将脚本化字段添加到查询中。

  • 向 Query 添加脚本化字段时,需要额外的源过滤器,以便同时从文档源中检索 普通 字段。

  • 获取数据,此时 Person 实体的 age 属性已设置相应值。

  • 使用仓库时,只需将脚本化字段作为方法参数添加即可。

运行时字段​

使用运行时字段时,计算值可以在查询本身中使用。以下代码用它来根据给定性别和人员的最大年龄运行查询:

public SearchHits<Person> findWithGenderAndMaxAge(String gender, Integer maxAge) {

var runtimeField = new RuntimeField("age", "long", """ 1
Instant currentDate = Instant.ofEpochMilli(new Date().getTime());
Instant startDate = doc['birthDate'].value.toInstant();
emit (ChronoUnit.DAYS.between(startDate, currentDate) / 365);
""");

// variant 1 : use a direct query
var query = CriteriaQuery.builder(Criteria
.where("gender").is(gender)
.and("age").lessThanEqual(maxAge))
.withRuntimeFields(List.of(runtimeField)) 2
.withFields("age") 3
.withSourceFilter(FetchSourceFilter.of(b -> b.withIncludes("*"))) 4
.build();

var result1 = operations.search(query, Person.class); 5

// variant 2: use the repository // <6>
var result2 = repository.findByGenderAndAgeLessThanEqual(gender, maxAge, runtimeField);

return result1;
}
}
  • 定义计算人员年龄的运行时字段。// 有关内置属性,请参阅 asciidoctor.org/docs/user-manual/#builtin-attributes。

  • 使用 Query 时,添加运行时字段。

  • 向 Query 添加脚本化字段时,需要额外的字段参数才能返回计算值。

  • 向 Query 添加脚本化字段时,需要额外的源过滤器,以便同时从文档源中检索 普通 字段。

  • 获取按查询过滤的数据,返回的实体已设置 age 属性。

  • 使用仓库时,只需将运行时字段作为方法参数添加即可。

除了在查询上定义运行时字段外,还可以在索引中定义它们,方法是将 @Mapping 注解的 runtimeFieldsPath 属性设置为指向一个包含运行时字段定义的 JSON 文件。