0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.