Search code examples
phpfiltergoogle-analytics-apigoogle-analytics-4

GA4 API - how do I request page path that does NOT start with a string


I am working with a Wordpress site to display the most popular articles from a year ago and am working with Google Analytics 4 API

I have gotten to this point - the snippet filters the pages that start with the the word "category". How do I filter pages that do NOT start with the word "category"?

  'dimensionFilter' => new FilterExpression([
    'filter' => new Filter([
        'field_name' => 'pagePath',
        'string_filter' => new Filter\StringFilter([
            'value' => '/category',
            'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH
        ])
    ])
]) 

I have tried some REGEX, but I keep getting Fatal error: Uncaught Google\ApiCore\ApiException: { "message": "Unsupported regular expression syntax in value.


Solution

  • There is a notExpression in FilterExpression. So something like below (I don't know what language your example is in, so i'm guessing the syntax.) :

    new FilterExpression([
      'notExpression' => new FilterExpression([
        'filter' => new Filter([
          'field_name' => 'pagePath',
          'string_filter' => new Filter\StringFilter([
            'value' => '/category',
            'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH
          ])
        ])
      ])
    ])
    

    I hope this helps.

    See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression#:~:text=%7D%2C%0A%20%20%22-,notExpression,-%22%3A%20%7B