Search code examples
google-analyticsgoogle-analytics-apigoogle-ads-api

Big discrepancy between Analytics API/Query Explorer and Interface


I've been trying to use the Analytics API to get site search terms into a Google Ads script. I've used this basic setup before and it worked perfectly, but the data this time doesn't match what's in the interface by a long shot. I've also tried using the query explorer but that's also giving me very different numbers to what's in the interface (by almost a factor of 10).

I've checked and double checked that the metrics and dimensions I'm using are correct, but there really aren't that many options. Does anyone know what I'm doing wrong?

Here's the code I've been using:

  // Build the query for the Analytics API
  var query = {
    "optionalArgs": { "dimensions": "ga:searchKeyword", },
    "ids": "ga:" + analyticsView,
    "metrics": "ga:searchUniques",
    "start-date": startDate,
    "end-date": "yesterday" };
  var results = Analytics.Data.Ga.get(query.ids, query['start-date'], query['end-date'], query.metrics, query.optionalArgs);

  // Format the results for Javascript
  var formattedJson = JSON.stringify(results, null, 2);
  var jsonData = JSON.parse(formattedJson);

  // Iterate through the results 
  for (var i = 0; i < jsonData.rows.length; i++) {
    var row = jsonData.rows[i];
    var searchTerm = row[0];
    var sessions = row[1];

I've tried with ga:sessions instead of searchUniques and a few other combinations of metrics and dimensions but nothing works and based on the documentation the ones I have in the code really seem to me to be the right ones!


Solution

  • In case anyone else gets stuck here, my issue was simply that I was limited to a maximum of 10,000 entities returned, and since I wasn't sorting them I was getting 10,000 random ones back and not what I expected. As soon as I sorted them descending by what I needed I got exactly what I expected!