java等价的elasticsearch curl 查询?

tzcvj98z  于 2021-06-13  发布在  ElasticSearch
关注(0)|答案(1)|浏览(346)

我的项目有一个新的要求,就是将当前在postresql中的所有数据迁移到elasticsearch。成功地迁移了我所有的数据,但是我一直在写java代码来搜索ElasticSearch索引中的一些数据。
点击索引的示例结构如下图所示:

我需要找到平均值 activity.attentionLevel 从索引中。
我写了下面这样的查询来查找平均值:

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

请帮助我找到java等效代码来做同样的事情。
提前谢谢

bnlyeluc

bnlyeluc1#

使用elastic的resthighlevel api类似于:

// 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

这里有更多信息。

相关问题