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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With