# Insights
<!-- [START badges] -->
[![Build Status](https://travis-ci.com/algolia/algolia-insights.svg?token=xSE7bJnvaeTRSGevyTux&branch=master)](https://travis-ci.com/algolia/algolia-insights) [![npm version](https://badge.fury.io/js/alg-insights.svg)](https://badge.fury.io/js/alg-insights)
<!-- [END badges] -->

Library for detecting front-end search metrics

## Concept

Algolia insights library allows developers to report click and conversion metrics related
to search queries. It does so by correlating events with queryIDs generated by the search API when a query parameter `clickAnalytics=true` is set.

Once a search has been initialized and the queryID received, the library currently supports two types of events - click and conversion.

## Getting started

### <a name="loading"></a>Loading and initializing the library

Insights library can be either loaded via jsDelivr CDN or directly bundled with your application.
We recommend loading the library by adding the snippet below to all pages where you wish to track search
search analytics.

```html
  <script>
    !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e.aa=e.aa||function(){(e.aa.queue=e.aa.queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],i.async=1,i.src="https://cdn.jsdelivr.net/npm/alg-insights@0.1.0/dist/alg-insights.js",c.parentNode.insertBefore(i,c)}(window,document,"script",0,"aa");

    // Initialize library
    aa('init', {
      apiKey: 'SEARCH_API_KEY',
      applicationID: 'APPLICATION_ID'
    })
  </script>
```

### Enabling queryID response from Algolia engine

In order for the Algolia engine to return a queryID on each search request, a special query parameter `clickAnalytics=true` should be set.

InstantSearch
```js
  const search = instantsearch({
    appId: 'APPLICATION_ID',
    apiKey: 'SEARCH_API_KEY',
    indexName: 'INDEX_NAME',
    searchParameters: {
      clickAnalytics: true
    }
  });
```

algoliasearch-helper:
```js
  const helper = algoliasearchHelper(client, 'INDEX_NAME', {
    clickAnalytics: true
  });
```

### Initializing search analytics

After loading the library you will need to call the initSearch function of the library and provide a callback function that will return the queryID sent by the Algolia engine. The queryID can be retrieved from the raw results array inside your helper.

```js
// Initialize search analytics - 
// should be called after the UI has rendered
// and you have the reference to search state and 
// inputSelector exists in the DOM
aa('initSearch', {
  getQueryID: () => search.helper.lastResults &&  search.helper.lastResults._rawResults[0].queryID
})
```

### Reporting click events

To report a click event, you have to call `aa('click',{objectID: clickedObjectID, position: positionOfElement})`. 
- The 2nd argument passed to the click event is the __objectdID__. It is the ID of the result that has been clicked. It is required.
- The 3rd argument is also required. It is the __absolute__ position of the clicked element inside the DOM.

Depending on the library and implementation details, these two can both be done straight from the hit template or in a custom event handler.

### Reporting conversion events

Upon a conversion event, the API is a bit different and you will only have to call the conversion event with `aa('conversion',{objectID: clickedObjectID})`. The 2nd parameter is the same as above, it is the ID of the clicked result. This ID will be used to derive the queryID. Internally, the library keeps a store of associated click and search events. When a conversion event happens, it tries to correlate the conversion to a click event via the queryID. If no event is found, it assumes that the conversion event did not happen as a result of search.

### Library implementation examples

All library examples are done with an assumption, that you have already completed the first step of loading the library.

- [InstantSearch.js example](https://github.com/algolia/algolia-insights/blob/master/examples/INSTANTSEARCH.md)
- [algoliasearch-helper example](https://github.com/algolia/algolia-insights/blob/master/examples/HELPER.md)

#### Running examples locally

To run all examples and play around with the code you have to run two separate commands:
- `yarn dev` - runs webpack and node dev server
- `yarn build:dev` - runs rollup in watch mode - livereload if you do changes to the insights library

<!-- - [React InstantSearch example](https://github.com/algolia/algolia-insights/blob/master/examples/REACT-INSTANTSEARCH.md)
- [Vue InstantSearch example](https://github.com/algolia/algolia-insights/blob/master/examples/VUE-INSTANTSEARCH.md) -->

<!-- If you are not using algolia as your search engine and you won't be able to provide the getQueryID function, but you can instead call the "search" function when a search query is sent with the
query that is being sent.

```js
mySearchInput.addEventListener('input', (e) => {
  // Send search event to analytics
  AlgoliaAnalytics.search({query: e.target.value, index: 'products'});
});
``` -->




