我正在使用 ga4 api,以下是抛出错误的代码:
'属性错误:DOES_NOT_MATCH_REGEX' 相同的过滤器适用于 GA 分析网页,但不适用于此处。
def run_ga4_report(property_id, property_name):
# Build the dimension filter to exclude matching sessionSourceMedium values
filter_expression = FilterExpression(
filter=Filter(
field_name="sessionSourceMedium",
string_filter=Filter.StringFilter(
# match_type=Filter.StringFilter.MatchType.FULL_REGEXP,
match_type=Filter.StringFilter.MatchType.DOES_NOT_MATCH_REGEX,
value=filter_pattern
)
)
)
# Build the request
request = RunReportRequest(
property=f"properties/{property_id}",
date_ranges=[
{"start_date": DATE_RANGE_START, "end_date": DATE_RANGE_END}
],
dimensions=[{"name": dim} for dim in dimensions_input],
metrics=[{"name": metric} for metric in metrics_input],
dimension_filter=filter_expression # Apply filter on sessionSourceMedium
)
# Execute the GA4 API request
try:
response = client.run_report(request)
except Exception as e:
print(f"Error fetching data from GA4 API for property {property_name} (ID: {property_id}): {e}")
return None
期望数据,但它抛出错误。如果过滤器是
FULL_REGEXP
,它就可以正常工作
如果 FULL_REGEXP 适用于您的情况,您可以反转代码中的过滤器逻辑来模拟 DOES_NOT_MATCH_REGEX。具体来说,您可以使用 NOT 逻辑表达式排除与正则表达式匹配的值。它会起作用(我使用这种方式获得了最热门的 1000 个页面,而没有找到页面/在我的情况下为 404 页)
filter_expression = FilterExpression(
not_expression=FilterExpression(
filter=Filter(
field_name="sessionSourceMedium",
string_filter=Filter.StringFilter(
match_type=Filter.StringFilter.MatchType.FULL_REGEXP,
value=filter_pattern
)
)
)
)