首页 > 解决方案 > Java等效于elasticsearch CURL查询?

问题描述

我的项目有一个新的要求,将当前在 postresql 中的所有数据迁移到 elasticsearch。成功迁移了我的所有数据,但我坚持编写 java 代码来搜索弹性搜索索引中的一些数据。

下图中附加了索引命中的示例结构: 在此处输入图像描述

我需要activity.attentionLevel从索引中找到平均值。

我写了类似下面的查询来查找平均值:

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

请帮助我找到执行相同操作的 java 等效代码。

提前致谢

标签: javaelasticsearchcurlkibana

解决方案


使用 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

更多信息在这里


推荐阅读