无法从指标查询语言MQL-GCP收集数据

问题描述

我想使用下面的库执行MQL(度量查询语言)。

    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-monitoring</artifactId>
        <version>v3-rev540-1.25.0</version>
    </dependency>

这是我的代码段。它将创建监控客户端,并尝试从GCP监控中收集数据。

public void queryTimeSeriesData() throws IOException {
        // create monitoring 
        Monitoring m = createAuthorizedMonitoringClient();
        QueryTimeSeriesRequest req  = new QueryTimeSeriesRequest();
        String query = "fetch consumed_api\n" + 
                "| metric 'serviceruntime.googleapis.com/api/request_count'\n" + 
                "| align rate(2m)\n" + 
                "| every 2m\n" + 
                "| group_by [metric.response_code],\n" + 
                "    [value_request_count_max: max(value.request_count)]";
        
        req.setQuery(query);
        HashMap<String,Object> queryTransformationSpec = new HashMap<String,Object>();
        HashMap<String,Object> timingState =  new HashMap<String,Object> absoluteWindow = new HashMap<String,Object>();
        absoluteWindow.put("startTime","2020-09-03T12:40:00.000Z");
        absoluteWindow.put("endTime","2020-09-03T13:41:00.000Z");
        timingState.put("absoluteWindow",absoluteWindow);
        timingState.put("graPHPeriod","60s");
        timingState.put("queryPeriod","60s");
        queryTransformationSpec.put("timingState",timingState);
        
        
        req.set("queryTransformationSpec",queryTransformationSpec);
        req.set("reportPeriodicStats",false);
        req.set("reportQueryPlan",false);
        
        QueryTimeSeriesResponse res = m.projects().timeSeries().query("projects/MY_PROJECT_NAME",req).execute();
        System.out.println(res);
    }

上面的代码可以正常工作,但是没有返回给定startTime和endTime的数据, 它总是返回可用的最新数据点。我的代码有问题吗?

解决方法

找到在给定时间范围内执行MQL查询的方法, 新的工作代码如下:

public void queryTimeSeriesData() throws IOException {
        // create monitoring 
        Monitoring m = createAuthorizedMonitoringClient();
        QueryTimeSeriesRequest req  = new QueryTimeSeriesRequest();
        String query = "fetch consumed_api\n" + 
                "| metric 'serviceruntime.googleapis.com/api/request_count'\n" + 
                "| align rate(5m)\n" + 
                "| every 5m\n" + 
                "| group_by [metric.response_code],\n" + 
                "    [value_request_count_max: max(value.request_count)]" + 
                "| within   d'2020/09/03-12:40:00',d'2020/09/03-12:50:00'\n";
        
        req.setQuery(query);
        QueryTimeSeriesResponse res = m.projects().timeSeries().query("projects/MY_PROJECT_NAME",req).execute();
        System.out.println(res);
    }

使用within运算符将查询的开始时间和结束时间包含在查询本身中。按照针对MQL查询的Google文档:

内部-指定查询输出的时间范围。