Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google analytics api v4 multiple metrics query

Ive been trying to get the metrics for all urls that contain a specific id in them. From this question: Adding ga:pagePath dimension to get page views for a particular URL using Google Analytics Reporting API v4 I saw the query approach and tried it instead of the object oriented version. In the query approach, the code works fantastic with the exception of it will only return the last metric sent (in this example it only returns unique page views since it is listed last for metrics). I need the values for all three returned without having to hit the api three separate times. Here is my code:

$query = [
        "viewId" => $profileId,
        "dateRanges" => [
            "startDate" => "2018-01-25",
            "endDate" => "2018-01-25"
        ],
        "metrics" => [
            "expression" => "ga:pageviews",
            "expression" => "ga:avgTimeOnPage",
            "expression" => "ga:uniquePageviews"
        ],
        "dimensions" => [
            "name" => "ga:pagepath"
        ],
        "dimensionFilterClauses" => [
            'filters' => [
                "dimension_name" => "ga:pagepath",
                "operator" => "PARTIAL", 
                "expressions" => $theId
            ]
        ]
    ];

    // build the request and response
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests(array($query));
    $report = $analytics->reports->batchGet($body);

Any thoughts on how I would do this correctly?

like image 893
Janelle Thorn Contreras Avatar asked May 16 '26 08:05

Janelle Thorn Contreras


1 Answers

For those who want to keep building queries with an array, this should work:

$request = [
    "viewId" => "123456789",
    "dateRanges" => [
        "startDate" => "2018-01-01",
        "endDate" => "today"
    ],
    "metrics" => [
        "expression" => "ga:pageviews"
    ],
    "dimensions" => [
        ["name" => "ga:browser"],
        ["name" => "ga:sessionDurationBucket"]
    ],
    "dimensionFilterClauses" => [
        'filters' => [
            "dimension_name" => "ga:pagepath",
            "operator" => "EXACT",
            "expressions" => $url
        ]
    ]
];
like image 189
Will Avatar answered May 17 '26 21:05

Will