2

当我在 python 中查询 Google Analytics 时,我无法获取 30 天活跃用户的数据。我的代码如下。我的问题是我需要指定日期或日期作为维度。“必须将 ga:nthDay、ga:date 或 ga:day 中的至少一个指定为维度才能查询此指标。” 我只是不确定正确的语法是什么。

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
import httplib2

#create service credentials
#this is where you'll need your json key
#replace "keys/key.json" with the path to your own json key
key_file_location = 'maypath'
credentials = 
ServiceAccountCredentials.from_json_keyfile_name(key_file_location, 

['https://www.googleapis.com/auth/analytics.readonly'])


# create a service object you'll later on to create reports
http = credentials.authorize(httplib2.Http())
service = build('analytics', 'v4', http=http, 
            discoveryServiceUrl=
('https://analyticsreporting.googleapis.com/$discovery/rest'))

response = service.reports().batchGet(
body={
    'reportRequests': [
        {
            'viewId': 'ga:thisismyid',
            'dateRanges': [{'startDate': '2017-10-01', 'endDate': '2017-10-01'}],
            'metrics': [{'expression': 'ga:sessions'}, 
                        {'expression': 'ga:bounceRate'},
                        {'expression': 'ga:avgSessionDuration'},
                        {'expression': 'ga:users'},
                        {'expression': 'ga:newUsers'},
                        {'expression': 'ga:sessionsPerUser'},
                        {'expression': 'ga:30dayUsers'}],
            'dimensions': [{"name": "ga:pagePath"}, 
                           {"name": "ga:city"}],
            'orderBys': [{"fieldName": "ga:sessions", "sortOrder": "DESCENDING"}],  
            'pageSize': 10
        }]
}
).execute()

所以,在这个例子中,我要求在一个日期提供一堆指标,包括 30 天的活跃用户。照原样,我遇到了这个错误:“无法同时查询选定的维度和指标”,这可能是因为我没有将 ga:date 或 ga:day 指定为我的维度之一。我已经尝试了几种方法,但我的语法必须关闭。

那么我如何将 ga:day 指定为一个维度,以获取在我提取数据的日期结束的 30 天用户数?请注意,如果我只是在上面的代码中去掉对 ga:30dayUsers 的请求,它就可以正常工作。

4

1 回答 1

1

这是一个简单的批处理案例,我参考了GA API V4 Dimensions&Metrics

body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '2018-01-11',
                        'endDate': '2018-01-18'}],
          'metrics': [{'expression': 'ga:28dayUsers'}],
          # 'metrics': [{'expression': 'ga:sessions'}]
          'dimensions': [{'name': 'ga:date'}]
        }]
  }

于 2018-01-27T08:58:02.623 回答