Welcome to OStack Knowledge Sharing 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...