Elasticsearch-对条件进行计数和求和

时间:2018-08-27 03:54:00

标签: elasticsearch

我的查询是:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Header/>
    <soapenv:Body>
        <soapenv:Fault>
            <faultcode>soapenv:Server</faultcode>
            <faultstring>UserId is null.</faultstring>
        </soapenv:Fault>
    </soapenv:Body>
</soapenv:Envelope>

我正在尝试显示最近1天的平均cpu,间隔为1小时。输出看起来像这样:

es_query = {
        "query": {
            "constant_score": {
                "filter": {
                    "bool": {
                        "must": [
                            {"range": {"@timestamp": {"gte": "now-1d",}}},
                            {"query_string": {"query": "hostname: {} ".format(hostname),"analyze_wildcard": True}}
                        ],
                        "should": [
                            {"match": {"metricset.name": "cpu"}},
                        ]
                    }
                }
            }
        },
        "aggs": {
            "group_by_time_interval": {
                "date_histogram": {
                    "field": "@timestamp",
                    "interval": "1h",
                    "time_zone": "PST8PDT",
                    "min_doc_count": 1
                },
                "aggs": {
                    "cpu_used_avg_pct": {"avg": {"field": "system.cpu.total.pct"}},
                },

            }
        }
    }

我想计算cpu_used_avg_pct等于0的次数。这可以通过以下发布脚本来完成:

        "group_by_time_interval": {
            "buckets": [
                {
                    "key_as_string": "2018-08-25T19:00:00.000-07:00", 
                    "doc_count": 24, 
                    "key": 1535248800000, 
                    "cpu_used_avg_pct": {
                        "value": 0.0
                    }
                }, 
                {
                    "key_as_string": "2018-08-25T20:00:00.000-07:00", 
                    "doc_count": 24, 
                    "key": 1535252400000, 
                    "cpu_used_avg_pct": {
                        "value": 0.0699
                    }
                }, 
                {
                    "key_as_string": "2018-08-25T21:00:00.000-07:00", 
                    "doc_count": 24, 
                    "key": 1535256000000, 
                    "cpu_used_avg_pct": {
                        "value": 0.071
                    }
                }, 
....

但是,有什么方法可以避免使用其他脚本来处理它?我们可以直接向ES查询添加过滤器吗?

非常感谢。 亚历克斯

0 个答案:

没有答案