es收集数据以后,需要进行统计和分析,以便得出想要的结果。

1. 允许文本数据参与统计

由于clientip是text数据类型,所以需要针对该字段开启fielddata。如果是keyword类型,则不需要此步骤。

PUT /qd_ngnix_access-2022-02/_mapping
{ 
  "properties":{ 
    "clientip":{
      "type":"text",
      "fielddata":true 
    } 
  } 
}

文本字段没有做上述设置,直接进行聚合会出现:Fielddata is disabled on text fields by default。 

2. 分组统计每个分组的数据量

效果类似于以下sql。

SELECT COUNT(*) FROM table GROUP BY clientip;

 统计不同clientip值的数据条数。

post /qd_ngnix_access-2022-02/_search
{
  "size":0,
  "aggs": {
    "distinct_aggs": {
      "terms": {
        "field": "clientip"
      }
    }
  }
}

说明:aggsterms的字段代表需要gruop by的字段 

3. 统计结果输出

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10000,
      "relation" : "gte"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "distinct_aggs" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 254127,
      "buckets" : [
        {
          "key" : "123.244.49.78",
          "doc_count" : 19997
        },
        {
          "key" : "124.95.9.210",
          "doc_count" : 8216
        },
        {
          "key" : "123.244.31.168",
          "doc_count" : 5409
        },
        {
          "key" : "59.44.249.90",
          "doc_count" : 4889
        }       
        
      ]
    }
  }
}

可以看出 123.244.49.78的数量是19997,124.95.9.210的数量是8216等。

4. 统计不同值(去除重复)的个数

效果类似与以下sql语句

SELECT COUNT(DISTINCT(clientip)) FROM table ;

统计qd_ngnix_access-2022-02索引中字段clientip不同值的个数。

post /qd_ngnix_access-2022-02/_search
{
  "size":0,
  "aggs": {
    "count": {
      "cardinality": {
        "field": "clientip"
      }
    }
  }
}

 说明:aggscardinality的字段代表需要distinct的字段

 5. 统计输出

{
  "took" : 40,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10000,
      "relation" : "gte"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "count" : {
      "value" : 3932
    }
  }
}

其中aggregations中的value值3932表示值的个数。

"aggregations" : {
    "count" : {
      "value" : 3932
    }
  }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐