通过spring数据从elasticsearch获得一个字段 [英] get one field from elasticsearch by spring data
问题描述
我有这样的ES文档
class User {
String name;
String describe;
List<String> items;
}
我正在使用Spring数据通过Repository接口与ES对话
I'm using spring data to talk to ES by the Repository interface
interface UserRepository extends Repository<User, String> {
}
现在,我需要构建一个rest接口,以像这样响应JSON格式的数据
Now I need to build a rest interface which responses a JSON-format data like this
{"name": String, "firstItem": String}
由于 User
中的 description
和 items
很大,因此从ES检索所有字段的成本很高.
Because the describe
and items
in User
is very big, it's very expensive to retrieve all field from the ES.
我知道ES具有名为响应过滤"的功能,可以满足我的要求,但是我找不到在Spring Data中使用它的方法.
I know the ES have a feature named "Response Filtering" which can fit my requirement, but I don't find a way to using it in Spring Data.
如何在春季数据中做到这一点?
How to do this in spring data?
推荐答案
您需要的是响应过滤(不适用于返回重字段).但是,Spring Data ES尚不支持后者.
What you need is a mix of source filtering (for not retrieving heavy fields) and response filtering (for not returning heavy fields). However, the latter is not supported in Spring Data ES (yet)
对于前者,您可以利用 NativeSearchQueryBuilder
并指定 FetchSourceFilter
,该方法将仅检索您需要的字段.Spring Data ES尚不支持后者.您可以做的是创建另一个名为 firstItem
的字段,在其中存储 items
的第一个元素,以便您可以为该查询返回它.
For the former, you can leverage NativeSearchQueryBuilder
and specify a FetchSourceFilter
that will only retrieve the fields you need. The latter is not supported yet in Spring Data ES. What you can do is to create another field named firstItem
in which you'd store the first element of items
so that you can return it for this query.
private ElasticsearchTemplate elasticsearchTemplate;
String[] includes = new String[]{"name", "firstItem"};
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withSourceFilter(new FetchSourceBuilder(includes, null))
.build();
Page<User> userPage =
elasticsearchTemplate.queryForPage(searchQuery, User.class);
这篇关于通过spring数据从elasticsearch获得一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!