Sitecore - Extending Coveo results with CoveoProcessParsedRestResponseArgs

There are some cases where we need to modify, on the fly, the results that Coveo gives us for certain queries. In order to achieve this, we will tap into the coveoProcessParsedRestResponse pipeline.

First, we need to modify the Coveo.SearchProvider.Rest.Custom.cfg and add our new processor: 

 <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">  
  <sitecore>  
   <pipelines>  
    <coveoProcessParsedRestResponse>  
     <processor type="XXX.XXX.XXX.RecommendationsProcessor, XXX.XXX.XXX" />  
    </coveoProcessParsedRestResponse>  
   </pipelines>  
  </sitecore>  
 </configuration>  

Let's now create the processor we specified on the patch above, this processor will be in charge of modifying the results, it should look something like this:

   public class RecommendationsProcessor : IProcessor<CoveoProcessParsedRestResponseArgs>  
   {  
     public void Process(CoveoProcessParsedRestResponseArgs args)  
     {  
       SearchResponse response = args.ResponseContent;  
       
       var sitecoreHelper = new SitecoreHelper();  
       var fieldTranslator = sitecoreHelper.GetFieldNameTranslator(sitecoreHelper.GetFirstIndexForDatabase("web"));  
       string idFieldName = fieldTranslator.TranslateToCoveoFormat("id");  
       foreach (var result in response.Results)  
       {  
         string itemId = (string)result.Raw.GetValueOrDefault(idFieldName);  
         //We can now use the itemid to calculate or retrieve whichever item data that is not present in Coveo  
         
         result["NEWPROPERTYNAME"] = WHATEVER VALUE;  
         
       }  
     }  
   }  

In the snippet above I am using an extension method to retrieve the value for certain key in a dictionary, you might find it useful as well:

 public static class DictionaryHelper  
   {  
     public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)  
     {  
       TValue value;  
       dictionary.TryGetValue(key, out value);  
       return value;  
     }  
   }  


Comments