Elasticsearch Java API中的多个平均聚合

时间:2019-02-07 09:29:35

标签: java elasticsearch

是否存在与此子聚合等效的Java代码。 我需要Java代码来构建子聚合对象。

{
  "query": {
    "SOME BOOL QUERIES HERE"
  },
 "aggs" : {
        "trs_timestamp" : {
            "date_histogram" : {
                "field" : "trs_timestamp",
                "interval" : "day"
            },
        "aggs" : {
                "AvgTT" : { "avg" : { "field" : "action_time" }},
                "AvgST" : { "avg" : { "field" : "st" }},
                "AvgCALC" : { "avg" : { "field" : "ncalc" }},
                "AvgRC" : { "avg" : { "field" : "rc" }},
                "AvgFR" : { "avg" : { "field" : "st" }}
            }
        }
    } 
}


2 个答案:

答案 0 :(得分:2)

您可以为此使用Elasticsearch Java API和AggregationBuilders,例如:

SearchResponse response = client.prepareSearch()
        .addAggregation(AggregationBuilders.avg("AvgTT").field("action_time"))
        .addAggregation(AggregationBuilders.avg("AvgST").field("st"))
        .addAggregation(AggregationBuilders.avg("AvgCALC").field("ncalc"))
        .addAggregation(AggregationBuilders.avg("AvgRC").field("rc"))
        .addAggregation(AggregationBuilders.avg("AvgFR").field("st"))
        .execute()
        .actionGet();

答案 1 :(得分:0)

例如:

public class MatlabLAB2 {

    public static void main(String[] args) {
        int capital = 100;
        int nDay = 7;
        int[] buyP = {5, 20, 7, 10, 4, 80, 1};
        int[] sellP = {25, 50, 100, 3, 10, 2, 95};

        findProfit(capital, nDay, buyP, sellP);
    }

    public static void findProfit(int capital, int NDay, int[] BuyingP, int[] SellingP) {


        int[] Array = new int[NDay];
        int Profit = 0;

        for (int i = 0; i <= BuyingP.length; i++) {

            for (int j = i; j <= SellingP.length; j++) {

                for (int k = 0; k <= NDay-1; k++) {
                    Array[k] = (capital / BuyingP[i]) * SellingP[j];
                }
                Profit = findMaxOfArray(Array);

            }
        }
        System.out.println(Profit);
    }

    public static int findMaxOfArray(int[] a) {
        int max = 0;
        for (int i = 0; i <= a.length-1; i++) {
            if (a[i] >= max) {
                max = a[i];
            }
        }
        return max;
    }
}


the result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at matlab.lab.pkg2.MatlabLAB2.findProfit(MatlabLAB2.java:24)
at matlab.lab.pkg2.MatlabLAB2.main(MatlabLAB2.java:11)
Java Result: 1

您会看到SearchResponse sr = node.client().prepareSearch() .setQuery( /* your query */ ) .addAggregation( /* add an aggregation */ ) .execute().actionGet(); 而不是addAggregation意味着您可以向查询添加多个聚合。 https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-aggs.html