1. 程式人生 > 實用技巧 >(轉)ElasticSearch中"distinct","count"和"group by"的實現

(轉)ElasticSearch中"distinct","count"和"group by"的實現

轉自https://www.jianshu.com/p/62bed9cc8349

1 - distinct

SELECT DISTINCT(user_id) FROM table WHERE user_id_type = 3;
{
  "query": {
    "term": {
      "user_id_type": 3
    }
  },
  "collapse": {
    "field": "user_id"
  }
}

{
  ...
  "hits": {
    "hits": [
      {
        "_index": "es_qd_mkt_visitor_packet_dev_v1_20180621
", "_type": "ad_crowd", "_source": { "user_id": "wx2af8414b502d4ca2_oHtrD0Vxv-_8c678figJNHmtaVQQ", "user_id_type": 3 }, "fields": { "user_id": [ "wx2af8414b502d4ca2_oHtrD0Vxv-_8c678figJNHmtaVQQ" ] } } ] } }


總結:使用collapse欄位後,查詢結果中[hits]中會出現[fields]欄位,其中包含了去重後的user_id

2 - count + distinct
SELECT COUNT(DISTINCT(user_id)) FROM table WHERE user_id_type = 3;

{
  "query": {
    "term": {
      "user_id_type": 3
    }
  },
  "aggs": {
    "count": {
      "cardinality": {
        "field": "user_id"
      }
    }
  }
}

{
  ...
  "hits": {
  ...
  },
  "aggregations": {
    "count": {
      "value": 121
    }
  }
}

總結:aggs中cardinality的欄位代表需要distinct的欄位

3 - count + group by
SELECT COUNT(user_id) FROM table GROUP BY user_id_type;

{
  "aggs": {
    "user_type": {
      "terms": {
        "field": "user_id_type"
      }
    }
  }
}

{
  ...
  "hits": {
    ...
  },
  "aggregations": {
    "user_type": {
      ...
      "buckets": [
        {
          "key": 4,
          "doc_count": 1220
        },
        {
          "key": 3,
          "doc_count": 488
        }
      ]
    }
  }
}

總結:aggs中terms的欄位代表需要gruop by的欄位

4 - count + distinct + group by
SELECT COUNT(DISTINCT(user_id)) FROM table GROUP BY user_id_type;

{
  "aggs": {
    "user_type": {
      "terms": {
        "field": "user_id_type"
      },
      "aggs": {
        "count": {
          "cardinality": {
            "field": "user_id"
          }
        }
      }
    }
  }
}

{
  ...
  "hits": {
    ...
  },
  "aggregations": {
    "user_type": {
      ...
      "buckets": [
        {
          "key": 4,
          "doc_count": 1220, //去重前資料1220條
          "count": {
            "value": 276 //去重後資料276條
          }
        },
        {
          "key": 3,
          "doc_count": 488, //去重前資料488條
          "count": {
            "value": 121 //去重後資料121條
          }
        }
      ]
    }
  }
}


5 - count + distinct + group by + where
SELECT COUNT(DISTINCT(user_id)) FROM table WHERE user_id_type = 2 GROUP BY user_id;
總結:對於既有group by又有distinct的查詢要求,需要在aggs中巢狀子aggs

6 - 注意事項
collapse關鍵字

摺疊功能ES5.3版本之後才釋出的。
聚合&摺疊只能針對keyword型別有效;