a.l.
a.l.

Reputation: 1135

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?

Upvotes: 0

Views: 4799

Answers (1)

Val
Val

Reputation: 217474

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

Upvotes: 2

Related Questions