Elasticsearch Operations
Spring Data Elasticsearch 使用多个接口来定义可以针对 Elasticsearch 索引调用的操作 (有关响应式接口的说明,请参阅 Reactive Elasticsearch Operations)。
Spring Data Elasticsearch uses several interfaces to define the operations that can be called against an Elasticsearch index (for a description of the reactive interfaces see Reactive Elasticsearch Operations).
-
IndexOperations
defines actions on index level like creating or deleting an index. -
DocumentOperations
defines actions to store, update and retrieve entities based on their id. -
SearchOperations
define the actions to search for multiple entities using queries -
ElasticsearchOperations
combines theDocumentOperations
andSearchOperations
interfaces.
这些接口与 Elasticsearch API的结构相对应。
These interfaces correspond to the structuring of the Elasticsearch API.
这些接口的默认实现提供了:
The default implementations of the interfaces offer:
-
index management functionality.
-
Read/Write mapping support for domain types.
-
A rich query and criteria api.
-
Resource management and Exception translation.
Index management and automatic creation of indices and mappings.
Index management and automatic creation of indices and mappings.
The
None of these operations are done automatically by the implementations of 支持使用 Spring Data Elasticsearch 存储库时自动创建索引和编写映射,请参见 Automatic creation of indices with the corresponding mapping There is support for automatic creation of indices and writing the mappings when using Spring Data Elasticsearch repositories, see Automatic creation of indices with the corresponding mapping |
Usage examples
该示例展示了如何在 Spring REST 控制器中使用注入的 ElasticsearchOperations`实例。该示例假设 `Person`是使用 `@Document
、`@Id`等进行注释的类(请参见 Mapping Annotation Overview)。
The example shows how to use an injected ElasticsearchOperations
instance in a Spring REST controller.
The example assumes that Person
is a class that is annotated with @Document
, @Id
etc (see Mapping Annotation Overview).
@RestController
@RequestMapping("/")
public class TestController {
private ElasticsearchOperations elasticsearchOperations;
public TestController(ElasticsearchOperations elasticsearchOperations) { 1
this.elasticsearchOperations = elasticsearchOperations;
}
@PostMapping("/person")
public String save(@RequestBody Person person) { 2
Person savedEntity = elasticsearchOperations.save(person);
return savedEntity.getId();
}
@GetMapping("/person/{id}")
public Person findById(@PathVariable("id") Long id) { 3
Person person = elasticsearchOperations.get(id.toString(), Person.class);
return person;
}
}
1 | Let Spring inject the provided ElasticsearchOperations bean in the constructor. |
2 | Store some entity in the Elasticsearch cluster.
The id is read from the returned entity, as it might have been null in the person object and been created by Elasticsearch. |
3 | Retrieve the entity with a get by id. |
要了解 ElasticsearchOperations
的全部可能性,请参阅 API 文档。
To see the full possibilities of ElasticsearchOperations
please refer to the API documentation.
Search Result Types
当使用 DocumentOperations
接口的方法检索文档时,将仅返回发现的实体。使用 SearchOperations
接口的方法搜索时,每个实体都有更多信息,例如发现的实体的 得分 或 排序值。
When a document is retrieved with the methods of the DocumentOperations
interface, just the found entity will be returned.
When searching with the methods of the SearchOperations
interface, additional information is available for each entity, for example the score or the sortValues of the found entity.
为了返回此信息,每个实体被封装在一个 SearchHit
对象中,该对象包含此实体特定的其他信息。这些 SearchHit
对象本身在 SearchHits
对象中返回,该对象还包含关于整个搜索的信息,比如 maxScore 或请求的聚合。以下类和接口现在可用:
In order to return this information, each entity is wrapped in a SearchHit
object that contains this entity-specific additional information.
These SearchHit
objects themselves are returned within a SearchHits
object which additionally contains informations about the whole search like the maxScore or requested aggregations.
The following classes and interfaces are now available:
包含以下信息:
Contains the following information:
-
Id
-
Score
-
Sort Values
-
Highlight fields
-
Inner hits (this is an embedded
SearchHits
object containing eventually returned inner hits) -
The retrieved entity of type <T>
包含以下信息:
Contains the following information:
-
Number of total hits
-
Total hits relation
-
Maximum score
-
A list of
SearchHit<T>
objects -
Returned aggregations
-
Returned suggest results
定义一个包含 SearchHits<T>
元素的 Spring Data Page
,可用于在存储库方法中对分页进行访问。
Defines a Spring Data Page
that contains a SearchHits<T>
element and can be used for paging access using repository methods.
由 ElasticsearchRestTemplate
中低级滚动 API 函数返回,它使用 Elasticsearch 滚动 ID 丰富 SearchHits<T>
。
Returned by the low level scroll API functions in ElasticsearchRestTemplate
, it enriches a SearchHits<T>
with the Elasticsearch scroll id.
SearchOperations
接口的流功能返回的迭代器。
An Iterator returned by the streaming functions of the SearchOperations
interface.
ReactiveSearchOperations
具有返回 Mono<ReactiveSearchHits<T>>
的方法,其中包含与 SearchHits<T>
对象相同的信息,但会提供包含的 SearchHit<T>
对象,作为 Flux<SearchHit<T>>
而不是列表。
ReactiveSearchOperations
has methods returning a Mono<ReactiveSearchHits<T>>
, this contains the same information as a SearchHits<T>
object, but will provide the contained SearchHit<T>
objects as a Flux<SearchHit<T>>
and not as a list.
Queries
SearchOperations
和 ReactiveSearchOperations
接口中定义的几乎所有方法都会采用一个 Query
参数,该参数定义用于执行搜索的查询。Query
是一个接口,Spring Data Elasticsearch 提供三种实现:CriteriaQuery
、StringQuery
和 NativeQuery
。
Almost all of the methods defined in the SearchOperations
and ReactiveSearchOperations
interface take a Query
parameter that defines the query to execute for searching. Query
is an interface and Spring Data Elasticsearch provides three implementations: CriteriaQuery
, StringQuery
and NativeQuery
.
CriteriaQuery
基于 CriteriaQuery
的查询允许创建查询以搜索数据而不了解 Elasticsearch 查询的语法或基础知识。它们允许用户通过简单地链接和组合指定被搜索文档必须满足的条件的 Criteria
对象来构建查询。
CriteriaQuery
based queries allow the creation of queries to search for data without knowing the syntax or basics of Elasticsearch queries.
They allow the user to build queries by simply chaining and combining Criteria
objects that specify the criteria the searched documents must fulfill.
在讨论组合标准时的 AND 或 OR 时,请记住,在 Elasticsearch 中 AND 转换为 must 条件,而 OR 转换为 should。 |
when talking about AND or OR when combining criteria keep in mind, that in Elasticsearch AND are converted to a must condition and OR to a should |
Criteria
及其用法可以通过示例得到最好的解释(让我们假设我们有一个具有 price
属性的 Book
实体):
Criteria
and their usage are best explained by example (let’s assume we have a Book
entity with a price
property):
Criteria criteria = new Criteria("price").is(42.0);
Query query = new CriteriaQuery(criteria);
同一字段的条件可以链接,它们将与逻辑 AND 结合:
Conditions for the same field can be chained, they will be combined with a logical AND:
Criteria criteria = new Criteria("price").greaterThan(42.0).lessThan(34.0);
Query query = new CriteriaQuery(criteria);
在链接 Criteria
时,默认情况下使用 AND 逻辑:
When chaining Criteria
, by default a AND logic is used:
Criteria criteria = new Criteria("lastname").is("Miller") 1
.and("firstname").is("James") 2
Query query = new CriteriaQuery(criteria);
1 | the first Criteria |
2 | the and() creates a new Criteria and chaines it to the first one. |
如果你想要创建嵌套查询,你需要为此使用子查询。让我们假设我们要找到姓氏为 Miller,名要么为 Jack 或 John 的所有人员:
If you want to create nested queries, you need to use subqueries for this. Let’s assume we want to find all persons with a last name of Miller and a first name of either Jack or John:
Criteria miller = new Criteria("lastName").is("Miller") 1
.subCriteria( 2
new Criteria().or("firstName").is("John") 3
.or("firstName").is("Jack") 4
);
Query query = new CriteriaQuery(criteria);
1 | create a first Criteria for the last name |
2 | this is combined with AND to a subCriteria |
3 | This sub Criteria is an OR combination for the first name John |
4 | and the first name Jack |
请参阅 Criteria
类的 API 文档以全面了解不同的可用操作。
Please refer to the API documentation of the Criteria
class for a complete overview of the different available operations.
StringQuery
此类将 Elasticsearch 查询作为 JSON 字符串。以下代码显示了一个搜索名字为“Jack”的人员的查询:
This class takes an Elasticsearch query as JSON String. The following code shows a query that searches for persons having the first name "Jack":
Query query = new StringQuery("{ \"match\": { \"firstname\": { \"query\": \"Jack\" } } } ");
SearchHits<Person> searchHits = operations.search(query, Person.class);
如果你已经拥有要使用的 Elasticsearch 查询,则可以使用 StringQuery
。
Using StringQuery
may be appropriate if you already have an Elasticsearch query to use.
NativeQuery
对于复杂查询或无法通过使用 Criteria
API 表达的查询(比如在构建查询和使用聚合的时候),NativeQuery
是要使用的类。它允许使用 Elasticsearch 库中的所有不同的 co.elastic.clients.elasticsearch._types.query_dsl.Query
实现,因此被称为“本机”。
NativeQuery
is the class to use when you have a complex query, or a query that cannot be expressed by using the Criteria
API, for example when building queries and using aggregates.
It allows to use all the different co.elastic.clients.elasticsearch._types.query_dsl.Query
implementations from the Elasticsearch library therefore named "native".
以下代码显示了如何搜索具有给定 firstName
的人员,并让找到的文档具有一个术语聚合,该术语聚合会统计这些人员的 lastName
出现的次数:
The following code shows how to search for persons with a given firstName
and for the found documents have a terms aggregation that counts the number of occurrences of the lastName
for these persons:
Query query = NativeQuery.builder()
.withAggregation("lastNames", Aggregation.of(a -> a
.terms(ta -> ta.field("lastName").size(10))))
.withQuery(q -> q
.match(m -> m
.field("firstName")
.query(firstName)
)
)
.withPageable(pageable)
.build();
SearchHits<Person> searchHits = operations.search(query, Person.class);
SearchTemplateQuery
这是一个 `Query`接口的特殊实现,与存储的搜索模板结合使用。有关详细信息,请参见 Search Template support。
This is a special implementation of the Query
interface to be used in combination with a stored search template.
See Search Template support for further information.