简体   繁体   中英

Google Analytics Reporting API v4 sort results

Based on the example here: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

I am trying to find search result information within a public library catalog. I can get results by filling in the proper metrics and dimensions, but I can't figure out how to integrate 'sort' into the

def get_report(analytics):
  """Queries the Analytics Reporting API V4.
  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '1daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:avgSearchResultViews'}],
          'dimensions': [{'name': 'ga:searchKeyword'}],
        }]          

      }
  ).execute()

Does anyone know how I can integrate a sort and possible a maxResults limiter in the block of code above? Google has info regarding sort here: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sort . I have tried adding the "-" to the metrics expression and even adding a whole new line for 'sort', but it hasn't been able to help me yet.

Example:

{
  "reportRequests":[
  {
    ...
    "orderBys": [
    {
      "fieldName": "ga:users",
      "sortOrder": "DESCENDING"
    },{
      "fieldName": "ga:source"
    }],
  }]
}

Source: GA API migration

Here is how. Zeloslaw's answer doesn't have "orderType" but you have to use it.

{
    "reportRequests": [
      {
        "viewId": "<your_view_id>",
        "dateRanges": [
          {
            "startDate": "30daysAgo",
            "endDate": "yesterday"
          }
        ],
        "metrics": [
            {
              "formattingType": "METRIC_TYPE_UNSPECIFIED",
              "expression": "ga:searchUniques"
            }
          ],
          "dimensions": [
            {
              "name": "ga:searchKeyword"
            }
          ],
          "orderBys": [
            {
              "orderType": "VALUE",
              "sortOrder": "DESCENDING",
              "fieldName": "ga:searchUniques"
            }
          ],
          "samplingLevel": "DEFAULT"
      }
    ]
  }

you can find other details for batchGet here https://developers.google.com/analytics/devguides/reporting/core/v4/basics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM