Search code examples
javaelasticsearchelasticsearch-plugin

Elasticsearch Get the values of a field from all the documents


I'm trying to get the values of a field from all the documents. I tried the following without setting the id, in hopes that it would returns all the results, however, it objected and gave an error that I had to set the ID, which resulted in returning the value of just one field that has that id that I had specified:

GetResponse response = NodeClient().prepareGet().setIndex("index-name")
               .setType("user").setId("1")
               .setFields("id").execute().actionGet();
GetField field = response.getField("id");
result = field.getValues();

How can I return a list of all the values of a field from all the documents I have in an index?

Thank you.


Solution

  • Instead of getting a single document by id, you need to perform a search for all documents:

    SearchResponse response = NodeClient().prepareSearch("index-name")
        .setTypes("user")
        .setSource("id")             <---- list the fields you want to retrieve
        .setFrom(0)
        .setSize(1000)               <---- increase this is you have more documents
        .execute().actionGet();
    
    for (SearchHit hit : response.getHits()) { 
        String id = hit.getSource().get("id");
        // do something with the id value
    }