Using multiple expressions in Google Analytics API

Viewed 267

I'm using the Google Analytics Python API and I want to look for several partial string matches in a dimension. Something like the following works fine:

"filters": [
    {
    "dimensionName": "ga:pagePath",
    "operator": "PARTIAL",
    "expressions": ["substring1"]
    },
    {
    "dimensionName": "ga:pagePath",
    "operator": "PARTIAL",
    "expressions": ["substring2"]
    }    
           ]

But I would like to combine these expressions, so it is easier to do similar to a lot of substrings. I saw that "expressions" will take regex, so I tried using the code below but it doesn't work. Can anybody help?

"filters": [
    {
    "dimensionName": "ga:pagePath",
    "operator": "PARTIAL",
    "expressions": ["substring1|substring2"]
    }    
           ]

I feel sure this is an easy question but I can't find an answer anywhere. I think I might be using the wrong method.

1 Answers

Initialize data as a list of dictionaries:

filters = [{
    "dimensionName": "ga:pagePath",
    "operator": "PARTIAL",
    "expressions": ["substring1"]
    },
    {
    "dimensionName": "ga:pagePath",
    "operator": "PARTIAL",
    "expressions": ["substring2"]
    }    
           ]

Group-by using itertools:

import itertools

records = []

for key, group in itertools.groupby(filters, lambda x: x['dimensionName']):
    groups = list(group)
    rec = {'dimensionName':key}

    # assuming there are no duplicates of the operator
    rec['operator'] = min([x['operator'] for x in groups])    

    # the `sum` expression reduces the list of lists of expressions it is slow but readable. For production, revisit
    rec['expressions'] = sum([x['expressions'] for x in groups],[])

    records.append(rec)

print(records)

# [{'dimensionName': 'ga:pagePath',
#  'operator': 'PARTIAL',
#  'expressions': ['substring1', 'substring2']}]
Related