如何构建我的Elasticsearch查询

时间:2018-06-07 15:25:19

标签: elasticsearch psql

我有一个看似简单的问题,但我无法解决。如果在我的索引中我有数据:

 country | id | n1 | n2 | n3 | other
---------+----+----+----+----+-------
       1 |  1 |  0 |  2 |  0 |     1
       2 |  2 |  1 |  0 |  1 |     1
       2 |  2 |  1 |  0 |  1 |     2
       2 |  2 |  1 |  0 |  1 |     3
       2 |  3 |  1 |  1 |  1 |     1
       1 |  4 |  0 |  3 |  2 |     1
       1 |  4 |  0 |  3 |  2 |     2

如何在Elasticsearch中运行以下查询?

 select DISTINCT country, id, n1, n2, n3 from MyIndex;
 country | id | n1 | n2 | n3
---------+----+----+----+----
       2 |  3 |  1 |  1 |  1
       1 |  4 |  0 |  3 |  2
       1 |  1 |  0 |  2 |  0
       2 |  2 |  1 |  0 |  1

特别是:

select country, sum(n1), sum(n2), sum(n3) from (select DISTINCT country, id, n1, n2, n3 from MyIndex) as foo group by country;
 country | sum | sum | sum
---------+-----+-----+-----
       1 |   0 |   5 |   2
       2 |   2 |   1 |   2

1 个答案:

答案 0 :(得分:0)

您需要使用termssum聚合,如下所示:

{
  "size": 0,
  "aggs": {
    "countries": {
      "terms": {
        "field": "country"
      },
      "aggs": {
        "by_id": {
          "terms": {
            "field": "id"
          },
          "aggs": {
            "sum_n1": {
              "sum": {
                "field": "n1"
              }
            },
            "sum_n2": {
              "sum": {
                "field": "n2"
              }
            },
            "sum_n3": {
              "sum": {
                "field": "n3"
              }
            }
          }
        }
      }
    }
  }
}