如何通过PHP为Google Analytics Data API(GA4)配置多个过滤条件
GA4多路径前缀过滤配置方法
核心实现逻辑:单个BEGINS_WITH类型的字符串过滤器仅支持传入单个匹配值,要实现多个前缀的或逻辑匹配,需要通过orGroup分组,把每个前缀对应的过滤规则放到分组的表达式数组中即可。
修改后的完整代码如下:
$response = $client->runReport([ 'property' => 'properties/' . $property_id, 'dateRanges' => [ new DateRange([ 'start_date' => '2022-01-01', 'end_date' => 'today', ]), ], 'dimensions' => [ new Dimension(['name' => 'pageTitle',]), new Dimension(['name' => 'fullPageUrl',]), ], 'metrics' => [ new Metric(['name' => 'screenPageViews',]), new Metric(['name' => 'activeUsers',]), new Metric(['name' => 'newUsers',]), new Metric(['name' => 'userEngagementDuration',]), ], 'dimensionFilter' => new FilterExpression([ 'or_group' => new FilterExpressionList([ 'expressions' => [ new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pagePath', 'string_filter' => new Filter\StringFilter([ 'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH, 'value' => '/133', ]) ]), ]), new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pagePath', 'string_filter' => new Filter\StringFilter([ 'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH, 'value' => '/88', ]) ]), ]), new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pagePath', 'string_filter' => new Filter\StringFilter([ 'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH, 'value' => '/678', ]) ]), ]), new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pagePath', 'string_filter' => new Filter\StringFilter([ 'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH, 'value' => '/67', ]) ]), ]), ] ]), ]), ]);
注意事项
- 此处使用
or_group是因为需求为「满足任意一个前缀规则即命中」,如果需要多条件同时满足,替换为and_group即可 - 由于
/67是/678的前缀,/678开头的路径会同时命中两条过滤规则,GA4 API会自动对结果去重,不会产生重复统计问题,无需额外处理 - 后续需要新增匹配前缀时,直接在
expressions数组中追加对应规则的FilterExpression对象即可
内容的提问来源于stack exchange,提问作者luciano
相关产品推荐
相关产品推荐

