Search code examples
javaelasticsearch

Retrieve selected fields from a search


I would like to retrieve only a few fields from a search in Elasticsearch run via Java client. In version 7 of the API, I used the following code:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.fetchSource( new String [] {"A", "B"}, null );

How can I do this using the API of version 8?


Solution

  • for Elasticsearch version 8, there is no fetchSource, so you can try this:

    SearchRequest searchRequest = new SearchRequest.Builder()
        .index("index_name")
        .query(query)
        .source(SourceConfig.of(s -> s.filter(f -> f.includes(List.of("field_A", "field_B")))))
        .build();
    

    SourceConfig gives access to include and exclude fields.

    I guess this is the only way, if you find another way please update us and post it in your question.