Google AnalyticsGoogle Analytics

创建服务帐户Create a service account

  1. 打开“服务帐户”页面Open the Service accounts page. 如果出现提示,请选择一个项目。If prompted, select a project.
  2. 单击“创建服务帐户”。Click Create service account.
  3. 在“创建服务帐户”窗口中,键入服务帐户的名称,然后选择“提供新的私钥”。In the Create service account window, type a name for the service account, and select Furnish a new private key. 出现提示时,选择“JSON 密钥文件类型”。When prompted, select JSON key file type. 然后单击“创建”。Then click Create.

这会生成新的公钥/私钥对,并将其下载到计算机上;它是此密钥的唯一副本。Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. 由你负责安全存储它。You are responsible for storing it securely.

启用 APIEnable the API

需要为 Google Cloud 项目启用“Analytics API”。You will need to enable “Analytics API” for your Google Cloud project.

向 Google Analytics 帐户添加服务帐户Add service account to the Google Analytics account

新创建的服务帐户将包含如下所示的电子邮件地址:quickstart@PROJECT-ID.iam.gserviceaccount.comThe newly created service account will have an email address that looks similar to: quickstart@PROJECT-ID.iam.gserviceaccount.com 使用此电子邮件地址添加用户到你想要通过 API 访问的 Google Analytics 视图。Use this email address to add a user to the Google analytics view you want to access via the API. 对于 SQL Analytics,仅需要读取和分析权限。For SQL Analytics only Read & Analyze permissions are needed.

在 SQL Analytics 中创建数据源Create data source in SQL Analytics

使用在“创建服务帐户”步骤中生成的 JSON 文件创建“Google Analytics”类型的数据源。Create datasource of “Google Analytics” type with the JSON file generated in the “Create a Service Account” step.

查询Queries

Google Analytics 使用 JSON 文档样式查询。Google Analytics uses JSON document-style queries. 可使用查询资源管理器工具了解可能的字段类型和维度。You can get an idea of possible field types and dimensions using the Query Explorer tool.

查询示例Example queries

{
    "ids": "ga:97038718",
    "start_date": "30daysAgo",
    "end_date": "yesterday",
    "metrics": "ga:newUsers",
    "dimensions": "ga:country",
    "max_results": 10,
    "sort": "-ga:newUsers"
}
{
    "ids": "ga:97038718",
    "start_date": "30daysAgo",
    "end_date": "yesterday",
    "metrics": "ga:newUsers",
    "dimensions": "ga:date",
    "sort": "-ga:newUsers"
}