Search code examples
pythonpython-3.xgoogle-analytics-api

How to filter report from google analytics v4 with many optional strings in python?


The dimension I use is ga:pagePathLevel2 because inside path level I have article ID that I couple with the rest of the data from the database.

Example: /lifestyle/40846-scenic-eclipse

lets say I have ids ids = [23692, 23693, 23964, 23965, 23966]

Now I would like to create a filter, that will return report only for those pages, that have this ids in their pagePathLevel2 String.

Any help?

Thank you

The rest of the object

{
        'reportRequests': [
            {
                'viewId': VIEW_ID,
                'dateRanges': [
                    {'startDate': current_dt.strftime(date_format), 'endDate': end_dt.strftime(date_format)}],
                'metrics': [{'expression': 'ga:uniquePageviews'}, {'expression': 'ga:pageviews'},
                            {'expression': 'ga:timeOnPage'}, ],
                "dimensions": [{"name": "ga:pagePathLevel2"}],
                "dimensionFilterClauses": [
                    {
                        "filters": ...
                    }
                ]

            }]
    }

Solution

  • You can use regex to match the IDs in ga:pagePathLevel2.

    So, here is how the value of filters should look like.

    [
        {
            "dimensionName": "ga:pagePathLevel2",
            "operator": "REGEXP",
            "expressions": ["23692|23693|23964|23965|23966"]
        }
    ]
    

    Hope it helps !