Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Henrik Fransas
Feb 25, 2015
  5874
(0 votes)

How to do custom query and click tracking with EPiServer Find

Custom query tracking

Sometimes it is necessary to do your own query and/or click tracking for EPiServer Find. One example is if you for example are doing many query’s at the same time for the search page. I have made an example of this with the Alloy project where the result looks like this (I know that this example could be solved with one query and facets but the example is simplified, in a real world each section/query would have it’s own facets).

example1

As you can see the search for “remote locations appear” does results in one hit in the section for Products but not anywhere else. I have implemented the track() in each query like this:

public IEnumerable<SearchContentModel.SearchHit> SearchForProducts(string searchText, int maxResults) { var query = _client.Search<ProductPage>().For(searchText); var searchResults = query.Take(maxResults).Track().GetContentResult(); return searchResults.Items.Select(s => new SearchContentModel.SearchHit() { Title = s.Name, Url = s.LinkURL, Excerpt = s.Name }); }

This will create a little strange behaviour in the statistics part of the Find GUI where it could be like this:

 withoutHit

As you can see, the query ends up in the statistics over queries without any hits but as we saw in the search result there were one hit.

This is not so strange because when doing this search we did actually four searches against EPiServer Find and for three of them there were no hits but for the fourth it was. This makes it hard on EPiServer Find, to be able to figure out it if should handle it like one query or many so we need to make it easier for Find to do it’s work.

First we need to remove the tracking part from the query so the same example as above looks like:

public IEnumerable<SearchContentModel.SearchHit> SearchForProducts(string searchText, int maxResults) { var query = _client.Search<ProductPage>().For(searchText); var searchResults = query.Take(maxResults).GetContentResult(); return searchResults.Items.Select(s => new SearchContentModel.SearchHit() { Title = s.Name, Url = s.LinkURL, Excerpt = s.Name }); }

After that we create a new function called TrackQuery that looks like this:

public void TrackQuery(string query, int nrOfHits, string id) { SearchClient.Instance.Statistics().TrackQuery(query, x => { x.Id = id; x.Tags = ServiceLocator.Current.GetInstance<IStatisticTagsHelper>().GetTags(false); x.Query.Hits = nrOfHits; }); }

In this function we use the function TrackQuery that exist in SearchClient.Instance.Statistics() that takes the string to query for as the first parameter and a System.Action<TrackQueryCommand> as a second parameter. To the command we pass in the id of the TrackContext, the statistic tags and the total number of hits that query resulted in.

Now we need to call this function and we do that from the SearchPageController like this:

model.TrackId = new TrackContext().Id; _ePiServerFindSearchService.TrackQuery(q, model.NumberOfHits, model.TrackId);

We create a new TrackContext and saves the Id of it in the ViewModel because we need it in the next part where we do custom click tracking. model.NumberOfHits is the total number of hits for all four queries. And now we got correct statistics, at least if you look from a visitor perspective because the visitor does not care how many queries it is against EPiServer Find, they only care about the complete result.

Custom click tracking

This part is a little more tricky but necessary in many solutions. The reason for that is that the built in click tracking in EPiServer Find only works with unified search, if you return a result with GetContentResult or with GetResult there will not be any click tracking by default. This is because EPiServer Find can’t be shore on where to hook up on the url that will be used to present the result. If you do a Unified Search and have all the right javascript loaded all your urls in the search result will look something like this:
http://www.yoursite.se/?_t_id=1B2sd2AYadasgTpgAmY7PhCfg%3d%3d&_t_q=custom&_t_tags=language%3asv&_t_ip=168.21.10.116&_t_hit.id=TypeName/_ewwe59e65-9c7c-40wsdadasd-bba0-fb6c8f8b57c5_sv&_t_hit.pos=1

The strange querystring is the Id of the TrackContext, Tags, Ip address of the client, and the result items id that contains of the type of the result and the id of the result.
To be able to get this to work on all our queries we need to do a couple of things. First we need the create a function that we can use to send our tracking request to EPiServer Find. It looks like this:

public void TrackClick(string query, string hitId, string trackId) { SearchClient.Instance.Statistics().TrackHit(query, hitId, command => { command.Hit.Id = hitId; command.Id = trackId; command.Ip = "127.0.0.1"; command.Tags = ServiceLocator.Current.GetInstance<IStatisticTagsHelper>().GetTags(false); command.Hit.Position = null; }); }

The function TrackHit exist in the same place as TrackQuery and works pretty much the same but it also takes the id of the hit as a parameter and the TrackQueryCommand has a couple of more properties that needs to be set.
Command.Hit.Id is the id of the hit
Command.Id is the id of the TrackingContext (or any other way to identify that you used when registered the TrackQuery)
Command.Ip is the client ip adress. I think this is pretty unimportant because often it is only the ip adress of the load balancer
Command.Tags is the tags
Command.Hit.Position is the position in the result the hit was on. I set it to null here because it is not so interesting right now

To be able to use this function we need to extend our searchhit object to include the hitid and hittype and we need to set it on every search. We do it like this:

public IEnumerable<SearchContentModel.SearchHit> SearchForProducts(string searchText, int maxResults) { var query = _client.Search<ProductPage>().For(searchText); var searchResults = query.Take(maxResults).GetContentResult(); return searchResults.Items.Select(s => new SearchContentModel.SearchHit() { Title = s.Name, Url = s.LinkURL, Excerpt = s.Name, HitId = SearchClient.Instance.Conventions.IdConvention.GetId(s), HitType = SearchClient.Instance.Conventions.TypeNameConvention.GetTypeName(s.GetType()) }); }

Except for Unified Search where both id and type exists in the SearchHit, so that looks like this:

public IEnumerable<SearchContentModel.SearchHit> Search(string searchText, int maxResults) { var query = _client.UnifiedSearchFor(searchText) .Filter(f => !f.MatchType(typeof (ArticlePage))) .Filter(f => !f.MatchType(typeof(ProductPage))) .Filter(f => !f.MatchType(typeof(NewsPage))); var searchResults = query.Take(maxResults).GetResult(); return searchResults.Hits.Select(hit => new SearchContentModel.SearchHit() { Title = hit.Document.Title, Url = hit.Document.Url, Excerpt = hit.Document.Excerpt, HitId = hit.Id, HitType = hit.Type }); }

Now we got all the basics done, we need to make shore there will be a request on every click and for that we can use jQuery and AJAX, AngularJS, Knockout JS or anything else you like, I will do it the most simple way, with jQuery and AJAX.

First we create a WebApi controller like this:

using System; using System.Web.Mvc; using CustomClickTracking.Business; using EPiServer.ServiceLocation; namespace CustomClickTracking.Controllers.Ajax { public class ClickTrackingController : Controller { [HttpGet] public JsonResult Track(string query, string hitId, string trackId) { try { var searchService = ServiceLocator.Current.GetInstance<SearchService>(); searchService.TrackClick(query, hitId, trackId); return Json(new {msg = "Click tracked"}, JsonRequestBehavior.AllowGet); } catch (Exception e) { return Json(new {Success = false}, JsonRequestBehavior.AllowGet); } } } }

Next is the tricky part, we need to attach a click event on all links in the search result and we need to set the tracking id for the whole page, but the hitid for every hit/result. To do this we use the “new” data attribute and jQuery.

We start with adding a new div that wraps all the four list with results in it and then we give that div the id ResultListWrapper. Doing like that we can create a javascript function that attach the click event to all the a tags inside that div.

We also add a new attribute to each a tag with the hitid and that id should look like this [HitType]/[HitId] so a example of a a tag looks like this:¨

<a href="@hit.Url" data-hitid="@hit.HitType/@hit.HitId">@hit.Title</a>

If we do not have set up routing to be able to route to non-EPi pages we need to do that. The most simple way is to add a route that looks like this in global.asaxc (it might not be the best way, since it opens up for all requests)

protected override void RegisterRoutes(RouteCollection routes) { base.RegisterRoutes(routes); routes.MapRoute(name: "api", url: "api/{controller}/{action}", defaults: new { controller = "ClickTrackingController", action = "index" }); }

When all this is done we create the javascript function that will hock on the click event for anchors. It looks like this:

<script type="text/javascript"> $(function () { $("#ResultListWrapper a").click(function (e) { $.get("/api/ClickTracking/Track", { query: '@Html.Raw(Model.SearchedQuery)', hitId: $(this).data("hitid"), trackId: "@Model.TrackId" }); }); }); </script>

We place the function inside a $(function()… to be shore that it runs when the DOM is fully loaded and to hook on all anchors we write $(“#ResultListWrapper a”) and this means all a that exist anywhere below the div with id ResultListWrapper.

Inside the function we do a simple get on the WebApi controller and with it I send the query, the hitid and the trackid. Because I have this script inside my resultview I  have access to the model that has the property SearchQuery and TrackId on it (that is why we added TrackId to the model in previous step.

When all this is in place we both register queries with the right information and we get the clicks on it registered.

click_registered 

This has been tested with both EPiServer Find 8 and EPiServer Find 9 and you can find the complete source code here:

https://github.com/hesta96/EPiServer-Find-Custom-Tracking

It should work out of the box if you download the complete solution, the only thing you have to do is create your own index on http://find.episerver.com and update web.config with your information (I have deleted the index that are in the source codes history).

This is a quick example on how to do this and I hope it will help.

Feb 25, 2015

Comments

Please login to comment.
Latest blogs
Optimizely Configured Commerce and Spire CMS - Figuring out Handlers

I recently entered the world of Optimizely Configured Commerce and Spire CMS. Intriguing, interesting and challenging at the same time, especially...

Ritu Madan | Mar 12, 2025

Another console app for calling the Optimizely CMS REST API

Introducing a Spectre.Console.Cli app for exploring an Optimizely SaaS CMS instance and to source code control definitions.

Johan Kronberg | Mar 11, 2025 |

Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025