Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

get one field from elasticsearch by spring data

I have a ES Document like this

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

I'm using spring data to talk to ES by the Repository interface

interface UserRepository extends Repository<User, String> {
}

Now I need to build a rest interface which responses a JSON-format data like this

{"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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...