Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Track search activity

Describes the autocomplete, spelling suggestions, and related queries provided by the search statistics.

Optimizely Search & Navigation offers a web-based interface (HTTP API) for tracking search activity, which collects statistical data about search queries submitted by site visitors and the results they click on. By analyzing this data, you can gain deeper insights into the efficiency of your search functionality, identify areas for improvement, and optimize the search experience to deliver more relevant content to visitors. To learn how to leverage tracking data to enhance search relevance, see Auto Boosting.

While you can use any programming language that can make HTTP requests to interact with the search statistics API, JavaScript is commonly used for this purpose. JavaScript is often employed because it runs in web browsers, making it easy to implement these features directly in web applications.

Automatic tracking

To gather search statistics for later analysis, use the Track() method in the search query:

SearchClient.Instance.UnifiedSearchFor(q)
  .Filter(f => f.MatchType(typeof(FashionProduct)))
  .Track()
  .GetResult();

📘

Note

In support of website visitors that do not want to be tracked, the system will look at the Do Not Track (DNT) header of incoming requests, and ignore tracking for visitors for which DNT is enabled.

Example

SearchClient.Instance.UnifiedSearchFor(searchQuery).Track().GetResult()

Track() adds the required tracking information to the URLs of the search hits. The client-side scripts used for tracking require EPiServer.Framework.Web.RenderingTags in the page templates.

Example

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<%@ Import Namespace="EPiServer.Framework.Web" %>
<%@ Import Namespace="EPiServer.Framework.Web.Mvc.Html" %>
<html>
  <head runat="server">
    ...
    <%= Html.RequiredClientResources(RenderingTags.Header) %>
  </head>
  <body>
    ...
    <%= Html.RequiredClientResources(RenderingTags.Footer)%>
  </body>
</html>

When using Unified Search, Track() enables tracking of a query and its hits. When using Track() on a non-Unified Search, only query tracking is enabled. Use custom tracking (explained below) to track hits with a non-Unified Search.

This data can be used to improve the search experience in several ways, such as:

  • Autocomplete – Suggesting possible search terms as users type, to help them find what they are looking for more quickly.
  • Spelling Suggestions – Offering corrections for misspelled search terms, ensuring users get relevant results even if they make typing errors.
  • Related Queries – Recommending additional search terms that are related to the user's original query, helping them explore more content.

Autocomplete

After adding some autocomplete text in the Search & Navigation user interface under Manage > Optimization > Autocomplete, you can enable the autocomplete feature on the search textbox in the front-end. Add a jQuery script to add autocomplete, as shown below.

📘

Note

The autocomplete example is dependent upon jQuery and jQuery UI scripts used on your website. However, there are no jQuery requirements for Optimizely Search & Navigation Autocomplete. You can use any library of choice or solution to make this work on your website.

  • https://jqueryui.com/
  • https://jquery.com/

📘

Note

Security restrictions may prevent you from using JSONP with Optimizely Search & Navigation’s Autocomplete.

< script language = "javascript" >
  $(function () {
      $("#txtSeach").autocomplete({
          source: function (request, response) {
            $.ajax({
              url: "@Model.PublicProxyPath" +
                "/_autocomplete?prefix=" +
                encodeURIComponent(request.term) +
                "&size=5" +
                "&tags=" +
                encodeURIComponent("@Model.Tags"),
              success: function (data) {
                response($.map(data.hits, function (item) {
                  return {
                    label: item.query,
                    value: item.query
                  };
                }));
              }
            });
          },
          minLength: 2
        };
      }); <
    /script>

Then, add txtSearch to the search form:

<input id="txtSeach" type="text" tabindex="1" name="q"/>

📘

Note

Autocomplete only works from the beginning of a phrase. The search term must begin with the first word. You can get existing autocomplete items from the _autocomplete/list endpoint: /_autocomplete/list?q=(%40%20%7C"")YOURWORD.*

Spellcheck

Search statistics can provide spellchecks and popular queries similar to those passed to the spellchecker based on what other users searched for. A jQuery example is below.

<script type="text/javascript">
  $.get('/find_v2/_spellcheck?query=camonix?size=1', function (data)
    {
      $.each(data.hits, function(index, value)
        {
          $('#spellcheck').append("<p>"
                                  +"Spellcheck for 'camonix': <a href=/Search/?q=" 
                                  + value.suggestion 
                                  + ">" 
                                  + value.suggestion 
                                  + "</a></p>");
        })
    });
</script>
<div id="spellcheck"></div>

The spellchecker accepts these parameters:

  • query  – (required) the query to return spellchecks for.
  • size  – (optional) the number of spellchecks to return.

Related queries

Sometimes, it is valuable to discover search relationships; for example, people searching for a also search for b. Search statistics call these related queries. You can request them using the following jQuery.

<script type="text/javascript">
  $.get('/find_v2/_didyoumean?query=chamoni&size=1', function (data)
    {
      $.each(data.hits, function(index, value)
        {
          $('#didyoumean').append("<p>"
                                + "Didyoumean for 'chamonix': <a href=/Search/?q=" 
                                + value.suggestion 
                                + ">" 
                                + value.suggestion 
                                + "</a></p>");
        })
    });
</script>
<div id="didyoumean"></div>

Related queries accept these parameters:

  • query – (required) the query to return related queries.
  • size – (optional) the number of related queries to return.

Custom tracking

See also the blog post How to do custom query and click tracking with EPiServer Find.

To implement a custom tracking mechanism, use the StatisticsClient, which offers two methods: TrackQuery() and TrackHit().

Access the StatisticsClient as follows:

SearchClient.Instance.Statistics().TrackQuery(...)
SearchClient.Instance.Statistics().TrackHit(...)

Use TrackQuery() to track the user query. It returns a TrackQueryResult with the TrackId.

Use the TrackId returned from TrackQuery() to track hits through the existing JavaScript. You typically implement this with a non-Unified Search and must manually enable hit tracking. You must supply the required tracking information as query string parameters in the hit URL.

Tracking query string parameters

  • _t_id – TrackId, returned from client.Statistics().TrackQuery(...).
  • _t_q  – The search query string.
  • _t_tags – Tags for categorization of the collected data. Normally, it contains site and language tags.
  • _t_hit.id – The expected format for a hit ID. (hitId argument to StatisticsClient.TrackHit) is the type name used in the index, and separates the document's ID in the index by a slash. Example: EPiServer_Templates_Alloy_Models_Pages_ProductPage/_cb1b190b-ec66-4426-83fb24546e24136c_en

When SearchHit<T> objects (from GetResult) are available, combine the SearchHit.Type and SearchHit.Id properties for the appropriate search hit.

If you instead must construct this value based on only the object that was indexed, use this syntax:

client.Conventions.TypeNameConvention.GetTypeName(myObj.GetType()) + "/" + client.Conventions.IdConvention.GetId(myObj)

TrackHit()

TrackHit() tracks a search hit; it provides click tracking. TrackHit() takes a query and hit ID as parameters. The hit ID parameter format matches the _t_hit.id parameter above.