Search code examples
javagoogle-analyticsgoogle-analytics-apigoogle-api-java-client

Pagination on Google Analytics using Java


I'm implementing a data extraction from Google Analytics using Java and I'm following this example: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-java

I managed to extract the data I need but I can't figure out how to set the start-index using its client. Below you can see the changed I made to the default implementation. I can set the page size but I can't find out how to set the start-index.

public GetReportsResponse getReport(String dateStart, String dateEnd) throws IOException {

        String[] metricsArr = {"ga:users", "ga:newUsers", "ga:sessions", "ga:totalEvents"};
        String[]  dimensionsArr = {"ga:eventLabel","ga:eventCategory","ga:eventAction", "ga:country", "ga:countryIsoCode", "ga:dateHourMinute"};

        // Create the DateRange object.
        DateRange dateRange = new DateRange();
        dateRange.setStartDate(dateStart);
        dateRange.setEndDate(dateEnd);

        // Create the Metrics object.
        ArrayList<Metric> metrics = new ArrayList<Metric>();
        for(String item : metricsArr){
            Metric m = new Metric().setExpression(item).setAlias(item.replace("ga:", ""));
            metrics.add(m);
        }

        ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
        for(String item : dimensionsArr){
            Dimension d = new Dimension().setName(item);
            dimensions.add(d);
        }

        // Create the ReportRequest object.
        ReportRequest request = new ReportRequest()
                .setViewId(this.VIEW_ID)
                .setDateRanges(Arrays.asList(dateRange))
                .setMetrics(metrics)
                .setDimensions(dimensions)
                .setFiltersExpression("ga:eventCategory=@NOTICE,ga:eventCategory==Document,ga:eventCategory==Document reader")
                .setPageSize(10000);

        ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
        requests.add(request);

        // Create the GetReportsRequest object.
        GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);

        // Call the batchGet method.
        GetReportsResponse response = service.reports().batchGet(getReport).execute();

        // Return the response.
        return response;
    }

How can I achieve that so I can navigate through all pages and extract all items?


Solution

  • The Reporting API V4 uses page tokens. The reply from the reporting API will return the next page's token, see nextPageToken. Using that you can make the exact same call but updating the pageToken in the request with the nextpagetoken from the previous reply. Note that the first call you make the reporting API will not have a page token attached to the request and the last page will not have the nextpagetoken set.

    I hope that helps.