Python中GA4 API维度过滤器如何实现包含匹配(类似LIKE %email%)
GA4 API实现包含匹配(类似SQL LIKE '%email%')
要实现类似SQL中LIKE '%email%'的包含匹配,你需要在GA4 API的Filter.StringFilter中指定match_type参数为MATCH_TYPE_CONTAINS,这个枚举值专门用来匹配包含目标字符串的维度值。
修改后的完整代码
#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", match_type=Filter.StringFilter.MatchType.MATCH_TYPE_CONTAINS # 添加包含匹配规则 ), ) ), ) response = client.run_report(request) print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) # 修正索引与语法错误
关键说明
MATCH_TYPE_CONTAINS:匹配所有包含指定字符串的维度值,对应SQL的LIKE '%value%'- 其他可选匹配类型:
MATCH_TYPE_EXACT:默认精确匹配,对应=MATCH_TYPE_BEGINS_WITH:匹配以指定字符串开头的值,对应LIKE 'value%'MATCH_TYPE_ENDS_WITH:匹配以指定字符串结尾的值,对应LIKE '%value'
内容的提问来源于stack exchange,提问作者187213
相关产品推荐
相关产品推荐

