Core Reporting API - Segments

This document describes the syntax, and considerations for using segments in the Core Reporting API.

Introduction

When using the segmentation feature of the Core Reporting API you can you can request a segment in the Core Reporting API in two ways:

  1. Segments by Id: Query using the numeric Id of a built-in or custom segment.
  2. Dynamic Segments: Specify the segment dynamically at the time of the request.

Segments by Id

You can request a segment in the Core Reporting API by using the Id of a built-in or custom segment. All available segments for a user can be retrieved with the list method of the Segments collection in the Google Analytics Management API. For each segment, the Id is available in the id property of the Segment resource.

To learn more about using segment Ids in API requests, see the Core Reporting API Reference.

Dynamic Segments

You can also dynamically create and use a segment when making an API request. Typically when creating a dynamic segment you should consider the following:

  1. Selecting Users vs Sessions
  2. Using Conditions vs Sequences
  3. Using Metric Scopes

Each consideration for creating a dynamic segment is described below at a high level. To review the complete syntax for dynamic segments see the Dynamic Segments Syntax Reference.

Dimensions and Metrics allowed in segments.
Not all dimensions and metrics can be used in segments. To review which dimensions and metrics are allowed in segments visit the Dimensions and Metrics Explorer.

1. Selecting Users vs Sessions

Specify whether you’re trying to select users or sessions (or both).

  • Use users:: to select users.
  • Use sessions:: to select sessions.
  • If conditions for both users:: and sessions:: are specified:
    1. user conditions are applied first to output the sessions for the matching users.
    2. session conditions are only applied to sessions from #1.

For example:

  • Select users who used Chrome browser in at least one of their sessions.
    • users::condition::ga:browser==Chrome
  • Select sessions where the Chrome browser was used.
    • sessions::condition::ga:browser==Chrome
  • Select sessions from the city of London from users that had at least 1 session where the Chrome browser was used.
    • users::condition::ga:browser==Chrome;sessions::condition::ga:city==London

See the conditionScope section of the syntax reference for details on selecting users and sessions.

2. Using Conditions vs Sequences

Once you've determined whether you want to segment users or sessions, you specify one or more conditions and/or sequences.

Conditions

Conditions use the condition:: prefix. For example:

  • Select users from London that have visited using the Chrome browser.
    • users::condition::ga:city==London;ga:browser==Chrome

Sequences

Sequence conditions consist of one or more steps, where each step is defined by one or more dimension/metric conditions.

Specify sequence-based conditions using the sequence:: prefix and the followed by (;–>>) or immediately followed by (;–>) operators. For example:

  • Select users that first used a desktop followed by a mobile device. Since we are segmenting users, this searches all the sessions of a user and checks if a user used desktop in one session, followed by a mobile device in one of the subsequent sessions.
    • users::sequence::ga:deviceCategory==desktop;->>ga:deviceCategory==mobile
  • You can also use multiple conditions for each step.
    • users::sequence::ga:deviceCategory==desktop;ga:operatingSystem==Windows->>ga:deviceCategory==mobile;ga:operatingSystem==Android
  • You can also combine conditions and sequences in a segment using an AND (i.e., ‘;’) operator.
    • users::condition::ga:totalEvents>10;sequence::ga:deviceCategory==desktop->>ga:deviceCategory==mobile

See the conditionType section of the syntax reference for details on simple and sequence-based conditions. For additional examples, see the Conditions and Sequences sections of the Segments Feature Reference.

3. Using Metric Scopes

A scope for a metric defines the level at which that metric is defined — HIT, SESSION, or USER. For example, ga:pageviews and ga:transactions are HIT level metrics, since they occur in a hit, whereas ga:sessionDuration and ga:bounces are SESSION level metrics since there is a single value for these per session. Conceptually, USER is the highest level scope and HIT is the lowest level scope.

Metric values can also be reported at scopes greater than its primary scope. E.g., ga:pageviews and ga:transactions can be reported at SESSION and USER level by just adding them up for each hit that occurs in those sessions or for those users.

You can specify the scope for each metric condition, which will determine the level at which that condition is applied. Metric scopes are specified using perUser::, perSession::, or perHit:: prefix.

For example:

  • Select users that have spent at least $10 on a website (i.e., lifetime value of a user is at least $10).
    users::condition::perUser::ga:transactionRevenue>=10
    
  • Select users who have spent at least $10 in a session.
    users::condition::perSession::ga:transactionRevenue>=10
    

Scope Restrictions

The Core Reporting API performs validation for metric scopes in order to ensure that the given query is a valid one. The rules for scope validation are:

  1. The specified metric scope must always be equal to or lower than its parent condition scope (as indicated by users:: or sessions:: prefix).
  2. The specified metric scope must be equal to or greater than its primary scope as defined in the data model. See the Metrics: Primary Scope Reference for a complete list of metrics and their primary scopes.

For example, the following are valid metric scopes:

  • Both condition and metric scopes are equal (i.e., USER level).
    • users::condition::perUser::ga:transactionRevenue>10
  • Condition scope is greater than metric scope (i.e., USER > SESSION).
    • users::condition::perSession::ga:transactionRevenue>10
  • ga:totalEvents is a HIT level metric and hence the possible scopes for it in a condition are perHit::, perSession::, or perUser:: (since all of them are greater than or equal to HIT level scope).
    • users::condition::perHit::ga:totalEvents>5
    • users::condition::perSession::ga:totalEvents>5

For example, the following are invalid metric scopes:

  • The following segment is invalid since the parent condition scope is lower than the metric scope (i.e., SESSION < USER).
    • sessions::condition::perUser::ga:transactionRevenue>10
  • Using a HIT level scope for a SESSION level metric and HIT level < SESSION level.
    • users::condition::perHit::ga:sessionDuration>60

Default Scope

When a scope for metric condition is not explicitly specified, it defaults to the condition scope. For example, the following segment will use a USER level scope for all of its metric conditions: users::condition::ga:transactionRevenue>=10;ga:sessionDuration>60

Dynamic Segments Syntax Reference

Base Syntax

The syntax to define a segment is of the form: segment=<segmentCondition>+. In other words, a segment is composed of one or more segmentCondition statements.

A <segmentCondition> is defined as: <conditionScope><conditionType><dimensionOrMetricConditions>

where:
conditionScope specifies the top-level scope of the condition(s).
conditionType specifies the type of condition(s).
dimensionOrMetricConditions specify dimension/metric conditions or sequence steps.

conditionScope

Specifies the top-level scope of the condition(s). The possible values are:

  • users:: for selecting users.
  • sessions:: for selecting sessions.

Constraints and considerations for conditionScope:

  • If multiple 'users' and 'sessions' conditions are specified in a single segment they must be combined with an AND operator.
  • Conditions that select both users and sessions must also be combined with an AND operator. When conditions for both users and sessions are specified, all user conditions are applied first to find the matching users, followed by all the session conditions on the sessions belonging to those matching users.
  • If you’re using any user level conditions, the date range must not be greater than 90 days.
  • The condition scope also determines the default scope level for all the metric conditions below it. (See the Metrics: Primary Scope Reference for more details on scope levels).

conditionType

Specifies the type of condition(s). The possible values are:

  • condition:: for specifying simple (i.e., non-sequence based) conditions.
  • sequence:: for specifying sequence-based conditions.

Constraints and considerations for conditionType:

  • If multiple 'simple conditions' and 'sequences' are specified they must always be combined with an AND operator.
  • A maximum of 10 steps for sequence-based conditions is allowed per segment.

Simple Conditions

Simple conditions consist of one or more dimension/metric conditions that can be combined.

The valid condition operators for simple conditions are:

The syntax for simple conditions is:

condition::<dimensionOrMetricConditions>

Example simple conditions:

  • users::condition::ga:transactionRevenue>10;ga:sessionDuration>60
  • A top-level negation operator can be specified to find the complement of a given simple condition that may have multiple dimension/metric conditions within it. E.g., users::condition::!ga:transactionRevenue>10;ga:sessionDuration>60

Excluding Conditions

An exclusion condition is used to create a segment which does not meet the defined condition.

The syntax uses the NOT Operator (the ! character) to negate a condition and exclude the sessions matching that condition.

Exclude sessions where the exit page exactly matches the root page path:
sessions::condition::!ga:exitPagePath==/

Multiple Conditions

You can either group all the user-level conditions under a single users:: prefix or you can use a separate users:: prefix for each condition. The same is true for session level conditions as well.

For example, the following segments are equivalent. In both cases condition1 and condition2 are ANDed to select users:
users::<condition1>;<condition2>
users::<condition1>users::<condition2>

Sequence Conditions

Sequence conditions consist of one or more steps, where each step is defined by one or more dimension/metric conditions. Multiple steps can be combined with special sequence operators.

The valid sequence operators for sequence conditions are:

  • –>> operator indicates that the previous step precedes the next step.
  • –> operator indicates that the previous step immediately precedes the next step.

The syntax for sequence conditions is:

sequence:: NOT? FIRST_HIT_MATCHES_FIRST_STEP? (AND (PRECEDES|IMMEDIATELY_PRECEDES) <step>)*

where:

NOT is represented by: !
FIRST_HIT_MATCHES_FIRST_STEP is represented by: ^
PRECEDES is represented by: ;–>>
IMMEDIATELY_PRECEDES is represented by: ;–>
step is represented by: <dimensionOrMetricConditions>

Example sequence conditions:

  • users::sequence::ga:deviceCategory==desktop;->ga:deviceCategory==tablet
  • A top-level negation operator can also be specified to find the complement of a given sequence that may have multiple steps and/or dimension/metric conditions within it. E.g., users::sequence::!ga:deviceCategory==desktop;->ga:deviceCategory==tablet
  • The ^ operator can be used to specify that the first step matches the first hit of the first session in the given date range. E.g., users::sequence::^ga:deviceCategory==desktop;->ga:deviceCategory==tablet

Date of Session Conditions

Segments support a type of analysis that makes use of the dateOfSession syntax; In combination with the between <> operator, you can restrict a segment to a group of users who have initiated a session within a certain date range. The maximum date range for dateOfSession is 31 days. Please see the date of session example below for details on its use.

Dimension and Metric Conditions

Combining Conditions

You can combine one or more dimension conditions with AND (i.e., ';') and OR (i.e., ',') operators with OR operator having a higher precedence.

The syntax is the same as what's used for combining filters. See Combining Filters in the Core Reporting API Reference for details.

Operators

The table below describes all of the available operators that can be used in segments and whether they are supported for dimensions and/or metrics.

Operator Description Supported in Dimension Conditions? Supported in Metric Conditions?
== Equal to or exact match. Yes
E.g.: ga:city==London
Yes
E.g.: ga:adCost==10
!= Not equal to or is not an exact match. Yes
E.g.: ga:city!=London
Yes
E.g.: ga:adCost!=10
< Less than. Yes (for numeric values only).
E.g.: ga:hour<12
Yes
E.g.: ga:adCost<10
<= Less than or equal to. Yes (for numeric values only).
E.g.: ga:hour<=12
Yes
E.g.: ga:adCost<=10
> Greater than. Yes (for numeric values only).
E.g.: ga:hour>12
Yes
E.g.: ga:adCost>10
>= Greater than or equal to. Yes (for numeric values only).
E.g.: ga:hour>=12
Yes
E.g.: ga:adCost>=10
<> Between (value is between the given range).1 Yes (for numeric values only).
E.g.: ga:hour<>1_12
Yes
E.g.: ga:adCost<>10_20
[] In list (value is one of the listed values).2 Yes
E.g.: ga:browser[]Chrome|Firefox|Opera
No
=@ Contains substring. Yes
E.g.: ga:keyword=@shoes
No
!@ Does not contain substring. Yes
E.g.: ga:keyword!@shoes
No
=~ Contains a match for regular expression. Yes
E.g.: ga:keyword=~shoes
No
!~ Does not contain a match for regular expression. Yes
E.g.: ga:keyword!~shoes
No

1Between Operator <>
Allows you to query for values within a certain range. Its range values are inclusive and it can be used for both metrics and dimensions that have numeric values (e.g., ga:hour). The min and max values in the range must be separated with an underscore.

Syntax:
{dimensionOrMetricName}<>{minValue}_{maxValue}

Example:
Select sessions that occurred between the hours 12 through 23.
sessions::condition::ga:hour<>12_23

2In List Operator []
Allows you to query for values from a given list. It can only be used with dimensions. The list of values must be separated using a "|" character. If there's a "|" in the value, it must be escaped.

Syntax:
{dimensionName}[]{value1}|{value2}|...

Constraints:
A maximum of 10 values per in-list dimension condition is allowed (E.g. ga:city[]city1|city2|...|city10).

Example:
Select sessions that were from browsers Chrome, Firefox, or Opera.
sessions::condition::ga:browser[]Chrome|Firefox|Opera

Escaping Special Characters

Special characters ',' and ';' must be escaped if they occur within the value expressions. E.g., ga:keyword==nike\,shoes

For additional details on dimension and metric conditions, refer to the Core Reporting API Reference.

Constraints

The constraints related to dimension and metric conditions are:

  • A maximum of 10 dimension or metric conditions per segment.
  • The maximum expression length for dimension conditions is 1024 characters.

Migrating Legacy Dynamic Segments

Legacy dynamic segments that use the dynamic:: prefix are equivalent to session level segments with dimension and metric conditions in the current syntax. If you use legacy dynamic segments you should migrate to the new syntax by replacing the dynamic:: prefix with the sessions::condition:: prefix. For example, the two segments below are equivalent:

dynamic::ga:browser==Chrome
is equal to:
sessions::condition::ga:browser==Chrome

Segments Examples

1. Demographic: Males Languages is EN-US, interested in Games, and are from Americas.

User-based segments are applied first. So, the user-based condition returns Users that are males and are interested in games. Sessions belonging to these users are then subject to sessions-based conditions to get sessions that were from Americas and the language was EN-US.

users::condition::ga:userGender==Male;users::condition::ga:interestAffinityCategory==Games ; sessions::condition::ga:region==Americas;sessions::condition::ga:language==en-u

2. Behavior: Users who have had > 100 sessions, haven't visited in last 7 days, have made > 2 transactions per session and have spent > 100 seconds on the site per session.

users::condition::ga:sessions>100;ga:daysSinceLastSession>=7; perSession::ga:transactions>2;perSession::ga:sessionDuration>100

3. Sessions: Select sessions that have browser as Chrome, country as US, and exceptions per hit > 1 AND select users whose exits per session < 2.

sessions::condition::ga:browser==Chrome;ga:country==US;perHit::ga:exceptions>1; users::condition::perSession::ga:exits<2

4. Session with a Sequence: Select sessions with Step: Chrome and total events per hit > 5 AND select users with Step: On Desktop Followed by Step: On mobile.

sessions::sequence::ga:browser==Chrome;condition::perHit::ga:totalEvents>5;users::sequence::ga:deviceCategory==desktop->>ga:deviceCategory=mobile

5. Date of Session: Select users who have had their first session between May 20, 2014 and May 30, 2014 and have spent > 600 seconds on the site.

users::sequence::^ga:sessionCount==1;dateOfSession<>2014-05-20_2014-05-30;->>ga:sessionDurationBucket>600

Metrics: Primary Scope Reference

Metric Primary Scope
ga:adClicksHIT
ga:adCostHIT
ga:adsenseAdsClicksHIT
ga:adsenseAdsViewedHIT
ga:adsenseAdUnitsViewedHIT
ga:adsenseCTRHIT
ga:adsenseECPMHIT
ga:adsensePageImpressionsHIT
ga:adsenseRevenueHIT
ga:avgDomainLookupTimeHIT
ga:avgDomContentLoadedTimeHIT
ga:avgDomInteractiveTimeHIT
ga:avgEventValueHIT
ga:avgPageDownloadTimeHIT
ga:avgPageLoadTimeHIT
ga:avgRedirectionTimeHIT
ga:avgScreenviewDurationHIT
ga:avgSearchDepthHIT
ga:avgSearchDurationHIT
ga:avgSearchResultViewsHIT
ga:avgServerConnectionTimeHIT
ga:avgServerResponseTimeHIT
ga:avgUserTimingValueHIT
ga:costPerConversionHIT
ga:costPerGoalConversionHIT
ga:costPerTransactionHIT
ga:CPCHIT
ga:CPMHIT
ga:CTRHIT
ga:domainLookupTimeHIT
ga:domContentLoadedTimeHIT
ga:domInteractiveTimeHIT
ga:domLatencyMetricsSampleHIT
ga:eventValueHIT
ga:exceptionsHIT
ga:exceptionsPerScreenviewHIT
ga:fatalExceptionsHIT
ga:fatalExceptionsPerScreenviewHIT
ga:goalAbandonRateAllHIT
ga:goalAbandonsAllHIT
ga:goalCompletionsAllHIT
ga:goalStartsAllHIT
ga:goalValueAllHIT
ga:goalValueAllPerSearchHIT
ga:goalXXAbandonRateHIT
ga:goalXXAbandonsHIT
ga:goalXXCompletionsHIT
ga:goalXXStartsHIT
ga:goalXXValueHIT
ga:impressionsHIT
ga:itemQuantityHIT
ga:itemRevenueHIT
ga:itemsPerPurchaseHIT
ga:localItemRevenueHIT
ga:localTransactionRevenueHIT
ga:localTransactionShippingHIT
ga:localTransactionTaxHIT
ga:marginHIT
ga:metricXXHIT
ga:pageDownloadTimeHIT
ga:pageLoadSampleHIT
ga:pageLoadTimeHIT
ga:pageValueHIT
ga:pageviewsHIT
ga:percentSearchRefinementsHIT
ga:redirectionTimeHIT
ga:revenuePerItemHIT
ga:revenuePerTransactionHIT
ga:ROIHIT
ga:RPCHIT
ga:screenviewsHIT
ga:searchDepthHIT
ga:searchDurationHIT
ga:searchGoalConversionRateAllHIT
ga:searchGoalXXConversionRateHIT
ga:searchRefinementsHIT
ga:searchResultViewsHIT
ga:searchUniquesHIT
ga:serverConnectionTimeHIT
ga:serverResponseTimeHIT
ga:socialActivitiesHIT
ga:socialInteractionsHIT
ga:socialInteractionsPerSessionHIT
ga:speedMetricsSampleHIT
ga:timeOnScreenHIT
ga:totalEventsHIT
ga:totalValueHIT
ga:transactionRevenueHIT
ga:transactionsHIT
ga:transactionShippingHIT
ga:transactionTaxHIT
ga:uniqueAppviewsHIT
ga:uniqueEventsHIT
ga:uniquePageviewsHIT
ga:uniquePurchasesHIT
ga:uniqueScreenviewsHIT
ga:uniqueSocialInteractionsHIT
ga:userTimingSampleHIT
ga:userTimingValueHIT
ga:adsenseExitsSESSION
ga:avgTimeOnPageSESSION
ga:avgSessionDurationSESSION
ga:bouncesSESSION
ga:entranceBounceRateSESSION
ga:entranceRateSESSION
ga:entrancesSESSION
ga:eventsPerSessionWithEventSESSION
ga:exitRateSESSION
ga:exitsSESSION
ga:goalConversionRateAllSESSION
ga:goalValuePerSessionSESSION
ga:goalXXConversionRateSESSION
ga:organicSearchesSESSION
ga:pageviewsPerSessionSESSION
ga:percentSessionsWithSearchSESSION
ga:screenviewsPerSessionSESSION
ga:searchExitRateSESSION
ga:searchExitsSESSION
ga:searchSessionsSESSION
ga:sessionDurationSESSION
ga:transactionRevenuePerSessionSESSION
ga:transactionsPerSessionSESSION
ga:bounceRateSESSION
ga:sessionsSESSION
ga:sessionsWithEventSESSION
ga:newSessionsUSER
ga:percentNewSessionsUSER
ga:usersUSER