Concepts / Getting insights and analytics / Segment
Oct. 11, 2019

The Algolia connector for Segment is currently in private beta. It is not yet ready for production use.
If you would like to be part of our beta test, please reach out to us.

Overview

If you already have integrated Segment on your website and are sending events to Segment, you can configure your Segment dashboard to redirect the events to Algolia.

There are two steps to integrate Segment with Algolia:

  1. Enable the “Algolia” destination on your Segment dashboard.
  2. Add extra Algolia-related data to events sent to Segment.

Supported events

Not all events from Segment are redirected to Algolia.

The following events, complying with Segment E-commerce Events Spec v2, are redirected:

Enable “Algolia” destination on your Segment dashboard

On your source, click the “Add Destination” button. 1 sources

From the destination catalog, search for and add “Algolia”. 2 destinations

Once added to your source, click the settings button (the gear icon). 3 added

Copy your Application ID and Search-Only API Key from your Algolia dashboard and paste there. 4 configuration

With Segment integrated, you probably have code that looks something like the following in order to send events to Segment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
analytics.track('Product Clicked', {
  product_id: '507f1f77bcf86cd799439011',
  sku: 'G-32',
  category: 'Games',
  name: 'Monopoly: 3rd Edition',
  brand: 'Hasbro',
  variant: '200 pieces',
  price: 18.99,
  quantity: 1,
  coupon: 'MAYDEALS',
  position: 3,
  url: 'https://www.example.com/product/path',
  image_url: 'https://www.example.com/product/path.jpg'
});

Algolia requires some additional fields that are not a part of the regular Segment E-commerce Events Spec v2. Which fields are required depends on which e-commerce event is being sent. The event reference below indicates which fields are required for each event.

Event Reference

Product List Viewed

Segment parameters used by Algolia

  • products.$.product_id : the objectID of the record. Maps to objectIDs in the Insights event payload.

Segment contextual parameters used by Algolia

  • userId: an identifier for logged-in users. Can be set through analytics.identify. Maps to userToken in the Insights event payload.

  • anonymousId: an identifier for non logged-in users. Maps to userToken in the Insights event payload when userId was not set through analytics.identify.

You can read more about Segments Identities.

Extra parameters required by Algolia

  • index: Name of the targeted index. Maps to index in the Insights event payload.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
analytics.identify('user-1'); // only if user is logged in

analytics.track('Product List Viewed', {
  products: [
    {
      product_id: '507f1f77bcf86cd799439011',
      // ...
    },
    {
      product_id: '505bd76785ebb509fc183733',
      // ...
    }
  ],
  index: "<YOUR_ALGOLIA_INDEX>",  // Algolia specific, required
  // ...
});

This code sends the following payload to the Insights REST API:

1
2
3
4
5
6
7
{
  "eventType": "view",
  "eventName": "Product List Viewed",
  "userToken": "user-1",
  "index": "<YOUR_ALGOLIA_INDEX>",
  "objectIDs": [ "507f1f77bcf86cd799439011", "505bd76785ebb509fc183733" ]
}

We want to trigger the Product List Viewed event every time a user receives a new set of results.

To achieve this, we combine a debounce function with the hits connector and send Product List Viewed every time new results are presented to the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function debounce(fn, delay) {
  let timerId;
  return function(...args) {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      fn(...args);
      timerId = null;
    }, delay);
  };
}

search.addWidget(
  instantsearch.connectors.connectHits(
    // debouncing is optional
    debounce(({ hits }) => {
      const products = hits.map(hit => ({
        product_id: hit.objectID
      }));
      products.length > 0 &&
        analytics.track("Product List Viewed", {
          products
        });
    }, 500)
  )()
);

Product List Filtered

Segment parameters used by Algolia

  • filters.$.type: the facet name in the filter applied
  • filters.$.value: the facet value in the filter applied

filters map to filters in the Insights event payload.

Segment contextual parameters used by Algolia

  • userId: an identifier for logged-in users. Can be set through analytics.identify. Maps to userToken in the Insights event payload.

  • anonymousId: an identifier for non logged-in users. Maps to userToken in the Insights event payload when userId was not set through analytics.identify.

You can read more about Segments Identities.

Extra parameters required by Algolia

  • index: Name of the targeted index. Maps to index in the Insights event payload.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
analytics.identify('user-1'); // only if user is logged in

analytics.track('Product List Filtered', {
  filters: [
    {
      type: 'department',
      value: 'beauty'
    },
    {
      type: 'price',
      value: 'under-$25'
    },
  ],
  index: '<YOUR_ALGOLIA_INDEX>', // Algolia specific, required
  // ...
});

This code sends the following payload to the Insights REST API:

1
2
3
4
5
6
7
{
  "eventType": "click",
  "eventName": "Product List Filtered",
  "userToken": "user-1",
  "index": "<YOUR_ALGOLIA_INDEX>",
  "filters": [ "department:beauty", "price:under-$25" ]
}

We want to trigger Product List Filtered every time a user has interacted with a refinement widget. For example: refinementList, rangeSlider (the full list of refinement widgets is available here).

To hook in the Product List Filtered event trigger to a refinement widget, we recommend using their connector form. Here is an example using the refinementList.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
search.addWidget(
  instantsearch.widgets.refinementList({
    container: "#refinement-list",
    attribute: "brand"
  })
);

document.querySelector("#refinement-list").addEventListener("change", event => {
  const elem = event.target;
  if (elem.matches("input[type=checkbox]")) {
    const payload = {
      filters: [
        {
          type: "brand",
          value: elem.value
        }
      ],
      index: "..."
    };
    analytics.track("Product List Filtered", payload);
  }
});

Product Clicked

Segment parameters used by Algolia

  • product_id : the objectID of the record. Maps to objectIDs in the Insights event payload.
  • position : the absolute position of the record. Maps to positions in the Insights event payload.

Segment contextual parameters used by Algolia

  • userId: an identifier for logged-in users. Can be set through analytics.identify. Maps to userToken in the Insights event payload.

  • anonymousId: an identifier for non logged-in users. Maps to userToken in the Insights event payload when userId was not set through analytics.identify.

You can read more about Segments Identities.

Extra parameters required by Algolia

  • queryID: Required only for Click Analytics. Algolia queryID that can be found in the search response when using clickAnalytics. Maps to queryID in the Insights event payload.
  • index: Name of the targeted index. Maps to index in the Insights event payload.
1
2
3
4
5
6
7
8
9
analytics.identify('user-1'); // only if user is logged in

analytics.track('Product Clicked', {
  product_id: '507f1f77bcf86cd799439011',
  position: 3,
  index: "<YOUR_ALGOLIA_INDEX>", 
  queryID: "<YOUR_QUERY_ID>",   
  // ...
});

This code sends the following payload to the Insights REST API:

1
2
3
4
5
6
7
8
9
{
  "eventType": "click",
  "eventName": "Product Clicked",
  "userToken": "user-1",
  "index": "<YOUR_ALGOLIA_INDEX>",
  "queryID": "<YOUR_QUERY_ID>",
  "objectIDs": [ "507f1f77bcf86cd799439011" ],
  "positions": [ 3 ]
}

objectID and queryID are both available for each hit exposed in hits and infiniteHits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
search.addWidget(
  instantsearch.widgets.hits({
    clickAnalytics: true,
    enablePersonalization: true,
  })
);
search.addWidget(
  instantsearch.widgets.hits({
    container: "#hits",
    templates: {
      item: hit => `
            <article>
              <h3>${instantsearch.highlight({ attribute: "name", hit })}</h3>
              <button class="btn-add-to-cart" data-product-clicked-payload='${JSON.stringify(
                {
                  product_id: hit.objectID,
                  position: hit.__position,

                  index: '...',
                  queryID: hit.__queryID
                }
              )}'>Add to cart</button>
            </article>
          `
    }
  })
);

document.addEventListener("click", event => {
  const elem = event.target;
  if (elem.matches(".btn-add-to-cart")) {
    const payload = JSON.parse(
      elem.getAttribute("data-product-clicked-payload")
    );
    analytics.track("Product Clicked", payload);
  }
});

Order Completed

Segment parameters used by Algolia

  • producs.$.product_id : the objectID of the record. Maps to objectIDs in the Insights event payload.

Segment contextual parameters used by Algolia

  • userId: an identifier for logged-in users. Can be set through analytics.identify. Maps to userToken in the Insights event payload.

  • anonymousId: an identifier for non logged-in users. Maps to userToken in the Insights event payload when userId was not set through analytics.identify.

You can read more about Segments Identities.

Extra parameters required by Algolia

  • queryID: Required only for Click Analytics. Algolia queryID that can be found in the search response when using clickAnalytics. Maps to queryID in the Insights event payload.
  • index: Name of the targeted index. Maps to index in the Insights event payload.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
analytics.identify('user-1'); // only if user is logged in

analytics.track('Order Completed', {
  products: [
    {
      product_id: '507f1f77bcf86cd799439011',
      // ...
    },
    {
      product_id: '505bd76785ebb509fc183733',
      // ...
    }
  ],
  index: '<YOUR_ALGOLIA_INDEX>', // Algolia specific, required
  queryID: "<YOUR_QUERY_ID>", // Algolia specific, required for Analytics, optional for Personalization
  // ...
});

This code sends the following payload to the Insights REST API:

1
2
3
4
5
6
7
{
  "eventType": "conversion",
  "eventName": "Order Completed",
  "userToken": "user-1",
  "index": "<YOUR_ALGOLIA_INDEX>",
  "objectIDs": [ "507f1f77bcf86cd799439011", "505bd76785ebb509fc183733" ]
}

Since Order Completed usually occurs outside the context of InstantSearch, you have to persist the objectID, queryID and index of the records ordered. This will allow Algolia to bind a conversion event to its specific query.

objectID and queryID are both available for each hit exposed in hits and infiniteHits. For example if you need to pass them through the URL you can do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
search.addWidgets([
  instantsearch.widgets.hits({
    // ...
    templates: {
      item(hit) {
        return `
          <a href="/product.html?objectID=${hit.objectID}&queryID=${hit.__queryID}&index=my-index">
            <h2>${hit.name}</h2>
          </a>
        `;
      },
    },
  })
]);

Did you find this page helpful?