HomeDev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

Segments

Shows how to get, filter, create, and replace segments using the Optimizely Profile Store API version 2.

A segment is a dynamic collection of profiles matching conditions based on a filter or query, such as visitors that previously responded to a campaign.

Profile Store has three types of segments.

📘

Note

Segments created from Insight cannot be modified from the Profile Store API. You can use all types as visitor group criteria, and can export al types to generate a profile reports.

Caching

Segments of the following types are dynamic and near-real-time.

  • Segments created using selected filters in Visitor Intelligence user interface
  • Segments created using user interface or API and based on profile filter definitions
  • Segments created using API based on profile queries

The cache is built only for segments that are based on events and event filter definitions. An event-based segment is not real-time because it caches profiles and refreshes the profile list every day. Calculating it once a day, because of complex queries on historical data, solves most use cases. Currently, the cache interval cannot be set for each individual customer environment.

  • The following functions are affected by the cache.
    • Personalization using a visitor group that uses the segment criterion and references an event-based segment. Additionally, the list of segments, that current visitor matches, is cached for 5 minutes for each visitor.
    • Verifies list profile Id and returns profiles that match the event-based segment.
    • Verifies list profile email and returns profiles that match the event-based segment.
  • The following function is not affected by the cache; you get the latest profiles.
    • Execute any segment draft for previewing.
    • Export a segment for Optimizely Campaign when a message is being sent to recipients that match that segment.

Event processing and updating profiles are near-real time and mostly depend on the load in the corresponding region. Normally, new events and updated profiles should be visible in the user interface and queryable using API within seconds. High loads in the region may cause some delay.

Segment properties

The segment request contains the following property fields.

  • SegmentId – Required. The ID of the segment.

  • Name – The segment name.

  • Scope –  Required. The segment scope does not have to be a registered scope; it can be any non-empty string value.

  • SegmentManager – The segment manager.

  • ProfileQuery – The query in OData $filter format; used in a segment created by Profile API.

    OData $filter format has the following form: [Profile property] [OData logical operator] [value].

    OData logical operators include eq, ne, gt, ge, lt, le, and, or, not. An example of ProfileQuery is:

      Name eq profile1
    
    • [Profile property] is case-sensitive.

    • Using string type properties with comparable operators such as gt, ge, lt, le may yield the wrong result.

    • When filtering an array, no additional brackets are needed. For example:

        FavoredBy eq "user1", "user2" (OR logic) or FavoredBy eq "user1" AND FavoredBy eq "user2"
      
  • ProfileFilter – The object specifies a profile filter; used in a segment created by Insight API.

  • MatchingProfiles – The number of profiles matching the segment at the moment when the segment was created or updated last time. This value is also recalculated, and the current number of matching profiles is included in the result when loading specific segment by ID using Profile Store API.

📘

Note

This value is not re-evaluated, and it is not updated when listing segments.

  • AvailableForPersonalization – A boolean that indicates that this segment is available for using in visitor group.
  • Archived – The boolean that indicates a segment as archived (because a segment cannot be deleted).
  • FavoredBy – The list of users that mark this segment as their favorite segment.
  • CreatedDate – The created date.
  • ModifiedDate – The modified date.
  • Filters – The segment filter collection object contains a list of filters that contain FilterDefinition to query profiles. Filters are stored in the Items property.
    Currently only one filter is supported in the filters list. A Filter contains the following properties:
    - Type – The type of the filter; either Events or Profiles.
    - Query – The FilterDefinition name to match profiles from track event or profiles properties. You create FilterDefinition from FilterDefinition endpoint before creating the segment. See Filter Definition.
    - Parameters – The list of parameters and its value in a dictionary. Parameters are defined in FilterDefinition which lets several segments share the same query with different values in parameters. See Filter Definition. All parameters are mandatory.
    - TimeFilter – The filter added on top of the query to limit the result set to a specific time window.
    - OccurrenceFilter – The filter added on top of the query to limit the result set to user match the query X times.

Example

{
        "Name": "string",
        "Description": "string",
        "Scope": "string",
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "filterDefinition",
                    "Parameters": {
                        "IntParameter": int,
                        "LongParameter": long,
                        "StringParameter": "string",
                        "DateTimeParameter": "datetime",
                        "DoubleParameter": double,
                        "BoolParameter": bool,
                        "TimeSpanParameter": "timespan"
                    },
                    "TimeFilter": {
                        "TimePropertyName": "string",
                        "StartDate": "2020-10-10T00:00:00Z",
                        "EndDate": {
                            "SlidingValue": 2,
                            "SlidingUnit": "Day"
                        }
                    },
                    "OccurrenceFilter": {
                        "Occurrence": 2,
                        "OccurrenceType": "GreaterThanOrEqual"
                    }
                }
            ]
        }
    }

Add time and occurrence filters

TimeFilter

TimeFilter consists of TimePropertyName, StartDate, and EndDate.

Example: Given the filter, Customers have placed an order, TimeFilter can be used to construct the following queries:

  • Find customers who have placed an order between specific dates (by setting absolute values in StartDate and EndDate).
  • Find customers who have placed an order from a specific date up until now (by setting an absolute value in StartDate).
  • Find customers who have placed an order before a specific date (by setting an absolute value in EndDate).
  • Find customers who have placed an order in the last X days (by setting the sliding value in StartDate).

TimePropertyName – the profile property name, or empty value when using event filter definition.

  • By default, the filter is applied on LastSeen profile property when using profile filter definitions.
  • The filter is always applied on EventTime event property when using the event filter definition in the segment since EventTime is the only public DateTime event property.

StartDate/EndDate – defines a time range using specific dates or a sliding time window. These two types of filters can be combined in a single segment.

  • Specific dates – a DateTime value in the format of yyyy-MM-dd or ISO 8601 date format.
    When using yyyy-MM-dd date format, the time part becomes 00:00:00.000 UTC for StartDate and 23:59:59.999 UTC for EndDate.
  • Sliding time window in days – Given a sliding time filter where SlidingValue is 2 and SlidingUnit is Day, the query will works as follow.
    • When placed in StartTime, the filter returns all records from the start of 2 days ago until now based on the property defined in TimePropertyName. For example, let's say today is January 3rd and the current time is 3 P.M, the filter returns all records from January 1st and 2nd (regardless of time) up until 3 P.M. of January 3rd.
    • When placed in EndTime, the filter returns all records before the end of 2 days ago. For example,  all records from January 1st regardless of time, and everything before is returned if today is January 3rd and the current time is 3 P.M).
    • SlidingValue minimum value is 0
    • SlidingUnit currently supports the single option: Day

OccurrenceFilter

OccurrenceFilter can be used to construct queries like "Find customers who have placed an order at least/at most/exactly X times".

You can add the occurrence filter when using the event filter definition in the segment. The filter contains two parameters:

  • Occurrence is an integer value and defines the number of times.
  • OccurrenceType is the comparison operator to check how many times the event happened compared to the defined occurrence. Supported comparisons:
    • Equal
    • LessThanOrEqual
    • GreaterThanOrEqual

In the segment example above, events should match the specified filter definition and should happen at least 2 times.

📘

Note

Occurrence filter is not supported when using profile filter definitions in the segment.

This filter should not be applied if the event filter definition query contains operators like summarize, reduce, count, make-series, top-nested, top-hitter, that produce aggregated results.

Segment methods

Get segment

Endpoint: GET api/v2.0/segments/{id}

Returns HTTP 200 OK with the segment specified by {id}.

Example of response body:

{
        "SegmentId": "2259a8f6-22b4-4166-9334-96fcfb3d40d6",
        "Name": "Profiles ordered most products",
        "Scope": "default",
        "SegmentManager": "user1",
        "ProfileQuery": "",
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 10
                    }
                }
            ]
        },
        "ProfileFilter": null,
        "MatchingProfiles": 1053,
        "AvailableForPersonalization": true,
        "Archived": false,
        "FavoredBy": [
            "user1",
            "user2"
        ],
        "CreatedDate": "2020-03-23T10:47:21.4007647Z",
        "ModifiedDate": "2020-03-23T10:47:21.4007647Z"
    }

📘

Note

ProfileQuery and Filters is null if the segment is created via InsightUI. ProfileFilter is also null if the segment is created via ProfileAPI.

Query segments

Endpoint: GET api/v2.0/segments

Similar to TrackEvent and Profile, Segment can also get segments based on OData query. The result window size is limited and must fit the top 10000 records, so the sum of $skip and $top values must be less than 10000.

📘

Note

MatchingProfiles value is not re-evaluated, and it is not updated when listing segments.

Create segment

Endpoint: POST api/v2.0/segments

Example of request body:

{
        "Name": "Profiles ordered most products", // Required
        "Description": "Match top 10 profiles who ordered most products",
        "Scope": "default", // Required. Scope acts as a filter, 
                            // which means if a scope does not exist,
                            // the result is empty instead of giving an error
        "SegmentManager": "user1",
        "AvailableForPersonalization": true,
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 10
                    }
                }
            ]
        }
    }

Example of response body:

{
        "SegmentId": "2259a8f6-22b4-4166-9334-96fcfb3d40d6",
        "Name": "Profiles ordered most products",
        "Description": "Match top 10 profiles who ordered most products",
        "Scope": "default",
        "SegmentManager": "user1",
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 10
                    }
                }
            ]
        }
        "MatchingProfiles": 10,
        "AvailableForPersonalization": true,
        "Archived": false,
        "CreatedDate": "2020-03-23T21:47:21.4007647Z",
        "ModifiedDate": "2020-03-23T21:47:21.4007647Z"
    }

📘

Note

MatchingProfiles value is not re-evaluated, and it is not updated when listing segments. Set Filters.Items[0].Query to the FilterDefinition name. FilterDefinition executes KQL/OData query to match profiles from track events or profiles. Create the filter definition from the FilterDefinition endpoint before using it in event segment.

Replace segment

Endpoint: PUT api/v2.0/segments/{id}

  • If segment ID does not exist, the API creates a new segment;  otherwise, it is replaced.
  • If the segment is created by InsightUI, you cannot update that segment with the profile API.

Example of request body:

{
        "Name": "Top 20 profiles ordered most products", // Required
        "Description": "Match top 20 profiles who ordered most products",
        "Scope": "default", // Required. Scope acts as a filter, 
                            // which means if a scope does not exist,
                            // the result is empty instead of giving an error
        "SegmentManager": "user1",
        "AvailableForPersonalization": true,
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 20
                    }
                }
            ]
        }
    }

Example of response body:

{
        "SegmentId": "2259a8f6-22b4-4166-9334-96fcfb3d40d6",
        "Name": "Top 20 profiles ordered most products",
        "Description": "Match top 20 profiles who ordered most products",
        "Scope": "default",
        "SegmentManager": "user1",
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 20
                    }
                }
            ]
        }
        "MatchingProfiles": 20,
        "AvailableForPersonalization": true,
        "Archived": false,
        "CreatedDate": "2020-03-23T21:47:21.4007647Z",
        "ModifiedDate": "2020-03-23T21:47:21.4007647Z"
    }

Preview segment

Endpoint: POST api/v2.0/segments/preview

The result window size Take is limited and must fit 1000 records.

Example of request body:

{
        "Scope": "default", // Required. Scope acts as a filter, 
                            // which means if a scope does not exist,
                            // the result is empty instead of giving an error
        "Filters": {
            "Items": [
                {
                    "Type": "Events",
                    "Query": "fd_topOrders",
                    "Parameters": {
                        "takeTop": 20
                    }
                }
            ]
        },
        "Take": 100,
        "Skip": 0,
        "SortOption": [
            {
                "SortField": "UpdateTime",
                "SortOrder": "asc"
            }
        ]
    }

Example of response body:

{
        "items": [
            {
                "ProfileId": "4a188e8c-8b73-418b-ac37-bcd26cc64a44",
                "Name": "admin",
                "ProfileManager": null,
                "FirstSeen": "2001-01-01T00:00:00Z",
                "LastSeen": "2001-01-01T11:12:13Z",
                "Visits": 1,
                "UpdateTime": "2001-01-01T11:12:13Z",
                "Info": {
                    "Email": "[email protected]"
                },
                "ContactInformation": [
                    "Mailable",
                    "Known"
                ],
                "DeviceIds": [
                    "0187bca0-4bf3-4ce2-b35f-d843488eb8e0"
                ],
                "Scope": "default",
                "VisitorGroups": [],
                "Payload": null
            }
        ],
        "total": 20,
        "count": 1
    }

Related blog posts