简体   繁体   English

通过spring数据从elasticsearch获得一个字段

[英]get one field from elasticsearch by spring data

I have a ES Document like this 我有这样的ES文档

class User {
    String name;
    String describe;
    List<String> items;
}

I'm using spring data to talk to ES by the Repository interface 我正在使用Spring数据通过Repository接口与ES通讯

interface UserRepository extends Repository<User, String> {
}

Now I need to build a rest interface which responses a JSON-format data like this 现在,我需要构建一个rest接口,以像这样响应JSON格式的数据

{"name": String, "firstItem": String}

Because the describe and items in User is very big, it's very expensive to retrieve all field from the ES. 由于Userdescribeitems很大,因此从ES检索所有字段非常昂贵。

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. 我知道ES具有名为“响应过滤”的功能,可以满足我的要求,但是我找不到在Spring Data中使用它的方法。

How to do this in spring data? 如何在Spring数据中执行此操作?

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) 但是,Spring Data ES尚不支持后者(尚未)

For the former, you can leverage NativeSearchQueryBuilder and specify a FetchSourceFilter that will only retrieve the fields you need. 对于前者,您可以利用NativeSearchQueryBuilder并指定一个FetchSourceFilter ,它将仅检索您需要的字段。 The latter is not supported yet in Spring Data ES. 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. 你可以做的是创造另一个名为场firstItem在你存储的第一个元素items ,这样就可以返回它的这个查询。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM