在Python中使用GA4 API。我使用了他们的示例调用,如下所示。但是,在下面的代码中,我正在查找
dimension_filter
中指定的字符串“email”。
我想使用维度过滤器来查找包含电子邮件的字符串。目前它正在寻找精确匹配。在 SQL 中使用通配符,就像
'%email%'
。
有人可以帮忙吗?
#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)
)
如上所述,我还没有找到如何使用 GA4 API 进行通配符。
如果您想使用维度过滤器来查找包含电子邮件的字符串,则 StringFilter 中有 matchType 选项。你可以用它。还有一些其他的 matchType,例如 EXACT、BEGINS_WITH、ENDS_WITH、FULL_REGEXP 和 PARTIAL_REGEXP。根据您的用例,使用正确的 matchType 对于此代码,您必须使用 CONTAINS 并像这样编辑代码:
dimension_filter=FilterExpression(
filter=Filter(
field_name="sessionMedium",
string_filter=Filter.StringFilter(
match_type=Filter.StringFilter.MatchType.CONTAINS,
value="email"
),
)
),
更多参考:https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression