Google Analytics API:为什么 API 数据与在 Analytics Dashboard 上看到的不同?

Google Analytics API: Why is the API data different than what's being seen on the Analytics Dashboard?

我已经研究了一段时间了,据我所知,它与 samplingLevel.

有关

我从大多数其他 Whosebug 问题中收集到的问题是,除非我有高级帐户,否则数据将始终按采样返回。

值得一问的是,是否可以更改我的 Google API 查询以使数据更准确一些?

我的查询代码:

$profiles = $analytics->management_profiles
    ->listManagementProfiles('myID', '~all');

foreach ($profiles->getItems() as $profile) {
    $IDvalue = $profile->getId();
    array_push($profilesArray, $IDvalue);
}

foreach ($profilesArray as $p) {
    $results = $analytics->data_ga->get(
        'ga:' . $p,
        '7daysAgo',
        'today',
        'ga:sessions');

    $profileName = $results->getProfileInfo()->getProfileName();
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    print "Profile Name: $profileName";
    echo "<br>";
    print "Total Sessions: $sessions";
    echo "<br><br>";
}

我尝试将 get() 更改为:

    $results = $analytics->data_ga->get(
        'ga:' . $p,
        '7daysAgo',
        'today',
        'ga:sessions',
        'samplingLevel:HIGHER_PRECISION');

我也试过:

    $results = $analytics->data_ga->get(
        'ga:' . $p,
        '7daysAgo',
        'today',
        'ga:sessions',
        'ga:samplingLevel==HIGHER_PRECISION');

但是查询中断并表示缺少 ID 以及其他多个错误。我意识到我可能没有正确地进行查询,但是任何可以指出编写查询的正确方法的人都会有很大帮助。那这种方法可能吗?还是我需要高级帐户才能完成我想做的事情?

采样

当您在给定时间段内有大量会话或事件时,往往会进行抽样。 处理抽样的选项:

  • 缩短日期范围。
  • 减少维数。
  • 增加 samplingLevel.

进行猜测并通过检查字段 containsSampledData 的响应来验证您的结果是否 containSampledData。同样在您的查询中,您请求 今天的数据 ,在 UI 默认情况下,它们会向您显示昨天的数据。今天的数据还在继续,因此根据您查询 API 的时间,您会得到不同的会话数答案。

API 错误:

您的代码存在一些问题。我建议查看一些 examples in the docs and look at the reference docs 以了解 API 的结构。例如你需要将可选参数作为数组传入:

foreach ($profilesArray as $p) {
  $optParams = array(
      'dimensions' => 'ga:source,ga:keyword',
      'sort' => '-ga:sessions,ga:source',
      'filters' => 'ga:medium==organic',
      'max-results' => '25',
      'samplingLevel' => 'HIGHER_PRECISION');

  $results = $analytics->data_ga->get(
      'ga:' + $p,
      '7daysAgo',
      'today',
      'ga:sessions',
      $optParams);

  ...
  // Do something with the $results.
}

警告的话,API 受制于 Limits and Quotas,因此如果您有超过 10 个视图(配置文件),您的 API 将 return 速率限制错误因为查询太快了。实施速率限制和指数退避是一种很好的做法。

迁移到 Analytics 报告 API V4

我们都喜欢拥有闪亮的新玩具。继续考虑迁移到 Analytics Reporting API V4. You've already done the hard work of figuring out OAuth, And they made available a great Migration Guide

Whosebug 建议

Whosebug 是获得实施帮助的好地方,而且您在包含代码方面做得很好(您会惊讶于有多少人不这样做)。我还建议包括您的错误响应、堆栈跟踪以及您在网上看到的资源。