目前,我正在尝试使用 Google Analytics API 并没有成功,因为总是出现错误 - “选定的维度和指标不能一起查询。”
作为一个假设应该很容易修复和检查指标和维度,但即使我使用 DEVELOPMENT TOOL它仍然显示此错误。
python 代码:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import json
SCOPES = ['https://www.googleapis.com/auth/analytics']
KEY_FILE_LOCATION = 'key.json'
VIEW_ID = 'REPORT_ID'
def initialize_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges':
[
{'startDate': '7daysAgo', 'endDate': 'today'}
],
'metrics': [
{'expression': 'ga:transactions'},
],
'dimensions':
[
{'name': 'ga:productName'}
]
}]
}
).execute()
def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
with open('analytics_data.json', "w+") as op:
op.write(json.dumps(response))
if __name__ == '__main__':
main()
例如,如果使用基于指标/维度的 Google Python Example Code
'metrics': [
{'expression': 'sessions'},
],
'dimensions':
[
{'name': 'ga:country'}
]
它返回适当的结果,但如果我需要
ga:transactions
和 ga:productName
它返回上面的错误。想法:
可以假设即使使用正确的 View_ID(报告 ID)它仍然无法连接到适当的报告?
有人可以帮忙吗?
最佳答案
我认为您收到的错误消息是正确的。您只是试图获得不允许的指标和维度组合。您可以在 Google Analytics Query Explorer 中尝试,你会得到同样的结果。
使用带有工作 View ID 的查询设置:
如果您想查看至少包含您的产品的交易数量,我建议使用 Unique Purchase 作为指标(ga:uniquePurchases)。虽然我的测试 View 没有电子商务数据,但您可以看到,查询已成功运行:
您可以使用 Query Explorer setting link 在您自己的 View 中检查此查询。 .
关于python - 使用 GOOGLE Analytics API - 指标/维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609607/