Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GA4 API Python dimension_filter / filter expression wildcard/regexp? Google Analytics Universal Analytics

Using the GA4 API in Python. I've used their sample call as below. However, in my code below I'm looking for the string 'email', specified in dimension_filter.

I'd like to use dimension filter to look for a string that CONTAINS email. Currently it's looking for an exact match. Using a wildcard in SQL, this would be LIKE '%email%'.

Can anyone help with this please?

#export GOOGLE_APPLICATION_CREDENTIALS = "my filepath"


import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'credentials.json'


from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Filter,
    FilterExpression,
    FilterExpressionList,
    Metric,
    RunReportRequest,
)

"""Runs a simple report on a Google Analytics 4 property."""
# TODO(developer): Uncomment this variable and replace with your
#  Google Analytics 4 property ID before running the sample.
property_id = "1234"
# Using a default constructor instructs the client to use the credentials
# specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
client = BetaAnalyticsDataClient()
request = RunReportRequest(
        property=f"properties/{property_id}",
         dimensions=Dimension(name = "sessionMedium")]
        ,metrics=[Metric(name="transactions")]           
        ,date_ranges=[DateRange(start_date="2023-07-03", end_date="2023-07-09")]
        ,dimension_filter=FilterExpression(
            filter=Filter(
                field_name="sessionMedium",
                string_filter=Filter.StringFilter(value ="email"),
            )
        ),
    )
response = client.run_report(request)
#print_run_report_response(response)

print("Report result:")
for row in response.rows:
      #  print(row.dimension_values[0].value, row.metric_values[1].value)
                    )

as above, I've not been able to find how to do wildcards with the GA4 API.

like image 896
187213 Avatar asked Sep 14 '25 21:09

187213


1 Answers

If you want use dimension filter to look for a string that CONTAINS email then there is option matchType in StringFilter. You can use that. There is some other matchTypes also there such as EXACT, BEGINS_WITH, ENDS_WITH, FULL_REGEXP and PARTIAL_REGEXP. Bases on your use case, use correct matchType For this code you have to use CONTAINS and edit the code like this:

dimension_filter=FilterExpression(
                filter=Filter(
                    field_name="sessionMedium",
                    string_filter=Filter.StringFilter(
                        match_type=Filter.StringFilter.MatchType.CONTAINS,
                        value="email"
                    ),
                )
        ),

For more reference: FilterExpression

like image 190
mayuran.si Avatar answered Sep 16 '25 10:09

mayuran.si