1
votes

Annotation Query and return only specific nested field with spring data elasticsearch

Version

springboot:2.1.7.RELEASE

spring-data-elasticsearch: 2.1.7.RELEASE

elasticsearch: 6.5.4


document:

@Data
@Document(indexName = "test_book", type = "test_book")
public class Book {
    @Id
    private String id;

    private String name;

    private LocalDateTime time;
    /**
     *
     */
    private Publishing publishing;

    /**
     * 
     */
    private Author author;
}

Repository:

public interface BookRepository extends ElasticsearchRepository<Book,String> {

    @Query("{" +
            "\"_source\": {" +
            "   \"includes\": " +
            "       [ \"name\"]" +
            "}," +
            "\"bool\" : {" +
            "   \"must\" : [{" +
            "       \"term\" : {" +
            "           \"id.keyword\" : \"?0\"" +
            "           }" +
            "       }]" +
            "   }" +
            "}")
    Book queryBookNameById(String id);
}

I just want to get the data of the name, which can relatively save memory resources. But I got an error, can’t I use it like this? Or can only use elasticsearchTemplate?

ParsingException[no [query] registered for [_source]
]
    at org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder(AbstractQueryBuilder.java:332)
    at org.elasticsearch.index.query.WrapperQueryBuilder.doRewrite(WrapperQueryBuilder.java:165)
    at org.elasticsearch.index.query.AbstractQueryBuilder.rewrite(AbstractQueryBuilder.java:279)
    at org.elasticsearch.search.builder.SearchSourceBuilder.rewrite(SearchSourceBuilder.java:921)
    at org.elasticsearch.search.builder.SearchSourceBuilder.rewrite(SearchSourceBuilder.java:80)
    at org.elasticsearch.index.query.Rewriteable.rewriteAndFetch(Rewriteable.java:97)
    at org.elasticsearch.index.query.Rewriteable.rewriteAndFetch(Rewriteable.java:87)
    at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:215)
    at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:68)
    at org.elasticsearch.action.support.TransportAction$RequestFilterChain.proceed(TransportAction.java:167)
    at org.elasticsearch.xpack.security.action.filter.SecurityActionFilter.apply(SecurityActionFilter.java:126)
......
1

1 Answers

0
votes

This currently does not work with the @Query annotation for repositories. Spring Data Elasticsearch will wrap the value of the annotation as the query value and so includes the _source part into the query.

We would need to add additional parameters to the annotation (includes and excludes) to be able to build a correct query and make this work. I will create an Jira issue for this to keep track of this feature request.

Jira issue