Learn business growth with Google Analytics 4 Forums Google Analytics 4 Can you use both 'and' and 'or' filters in a single Google Analytics API request? Reply To: Can you use both 'and' and 'or' filters in a single Google Analytics API request?

  • William

    Member
    29 March 2023 at 7:15 pm

    Sure, I’d be happy to help! You’re correct in that you can’t specify both andGroup and orGroup in the same filter, but there’s a way to work around this. You can nest one group within another.

    Here’s how you can do that:
    `json
    “dimensionFilter”: {
    “orGroup”: {
    “expressions”: [
    {
    “filter”: {
    “fieldName”: “Browser”,
    “stringFilter”: {
    “matchType”: “CONTAINS”,
    “value”: “moz”
    }
    }
    },
    {
    “andGroup”: {
    “expressions”: [
    {
    “filter”: {
    “fieldName”: “Browser”,
    “stringFilter”: {
    “matchType”: “CONTAINS”,
    “value”: “ed”
    }
    }
    },
    {
    “filter”: {
    “fieldName”: “Browser”,
    “stringFilter”: {
    “matchType”: “CONTAINS”,
    “value”: “ch”
    }
    }
    }
    ]
    }
    },
    {
    “filter”: {
    “fieldName”: “Browser”,
    “stringFilter”: {
    “matchType”: “CONTAINS”,
    “value”: “test”
    }
    }
    }
    ]
    }
    }
    `
    This would match a Browser field that either contains “moz”, contains both “ed” and “ch”, or contains “test”. Hope this helps!

    As for using “and” and “or” filters with metric filters in the same request, you can use a similar structure. However, do note that only certain metrics can be used for metric filters, and not all metrics will work. You should refer to the Google Analytics API documentation for more information.