Search code examples
javaelasticsearchelasticsearch-java-api

Get Required Field From Elasticsearch


I have the below fields in my elasticsearch

"_source": {
"@timestamp": 
"cpu_stat_s": {
"temp_in_celsius":
"model_name":,
"cpu_MHz_String": ,
"cache_size_string": 
},

"memory_stat_s": {
"total_memory": ,
"swap_total": ,
"swap_free": ,
"used": ,
"free": ,
"swap_used": 
},
"process_stat_s": [
{
"process_name": ,
"mem_in_use":,
"process_pid": 
}
]

I just want to get suppose cpu_stat_s and memory_stat_s field from the elasticsearch using java api ,I searched through the Query Filters and also did

String source="{\"query\":\"ether_stat_s\"}";

SearchResponse response = client.prepareSearch("cn_*")
                       .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                        .setFrom(0).setSize(10).setExplain(true)
    .setPostFilter(FilterBuilders.rangeFilter("@timestamp").from(TIMESTAMP_FROM).to(TIMESTAMP_TO)).**setSource(source).**execute().actionGet();

But I received all fields instead of the required fields .

I can do this by getting all fields and then use a for loop and from response get the source but it would have increase the CPU time incase of billions of records .I am new to elastic search and hence it would be of great help if someone could assist me


Solution

  • After Finally more research I found the answer

    SearchResponse response = client.prepareSearch("cn_*")
                           .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                            .setFrom(0).setSize(10).setExplain(true)
                            .setPostFilter(FilterBuilders.rangeFilter("@timestamp").from(TIMESTAMP_FROM).to(TIMESTAMP_TO))
                            .setFetchSource(new String[]{"ether_stat_s"}, null)
                            .execute()
                           .actionGet();