Retrieving specific fields using the Elasticsearch Java API

后端 未结 1 624
醉梦人生
醉梦人生 2020-12-03 05:58

I am using the Java API for Elasticsearch. Having saved entities into indexes, it is possible to retrieve them together with the complete source. However, I only want to ret

相关标签:
1条回答
  • 2020-12-03 06:14

    You can specify the fields you need using the setFetchSource(String[] includes, String[] excludes) method. Try this instead

    SearchResponse response = client.prepareSearch("my-index")
       .setTypes("my-type")
       .setSearchType(SearchType.QUERY_AND_FETCH)
       .setFetchSource(new String[]{"field1"}, null)
       .setQuery(QueryBuilders.termsQuery("field1", "1234"))
       .execute()
       .actionGet();
    
    for (SearchHit hit : response.getHits()){
       Map map = hit.getSource();
       map.toString();
    }
    

    map will only contain the fields you've specified.

    Note that .setFetchSource("field1", null) (if you need a single field) or .setFetchSource("field*", null) (if you need several wildcarded fields) would work, too.

    0 讨论(0)
提交回复
热议问题