Search code examples
javaelasticsearchcurlkibana

Java equivalent of elasticsearch CURL query?


My project had a new reqiurement of migrating all datas which are currently in postresql to elasticsearch. Successfully migrated all my datas, but I am stuck with writing java code to search for some datas in elastic search index.

Sample structure of a hit in index is attached in the below image: enter image description here

I need to find average of activity.attentionLevel from the index.

I wrote something like below query to find average:

GET proktor-activities/_search
{
"aggs" : {
    "avg_attention" : { 
        "avg" : { 
            "script" : "Float.parseFloat(doc['activity.attentionLevel.keyword'].value)" }
         }
    }
}

please help me to find java equivalent code for doing the same.

thanks in advance


Solution

  • Using Elastic's RestHighLevel API would be something like this:

        // Create the client
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
    
        // Specify the aggregation request
        SearchRequest searchRequest = new SearchRequest("proktor-activities");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.aggregation(AggregationBuilders
            .avg("avg_attention")
            .field("activity.attentionLevel"));
    
        searchRequest.source(searchSourceBuilder);
    
        // Execute the aggreagation with Elasticsearch
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
    
        // Read the aggregation result
        Aggregations aggregations = response.getAggregations();
        Avg averageAttention = aggregations.get("avg_attention");
        double result = averageAttention.getValue();
    
        client.close(); // get done with the client
    

    More information here.