How to Programmatically Add Synonyms to Coveo

  • Twitter
  • LinkedIn

How to Programmatically Add Synonyms to Coveo

Quick and Dirty Coveo API

Recently a client using Sitecore came to me with an interesting request. They have a process that inserts documents into Sitecore at regular intervals with defined metadata. The client would like to be able to add synonyms for that metadata into their Coveo query pipeline. The catch is, they want all of this to happen automatically, but it looks like Coveo doesn't provide any documentation on how to do this programmatically. After a little work, I realized that I could just inspect the traffic using developer tools in the browser and reverse engineer those calls.

Adding a synonym:

// Add a list of synonyms for the provided term 
public bool AddSynonyms(string term, List synonyms, string description) 
{ 
    // Synonyms need to be wrapped in quotes 
    var synonymString = 
       string.Join(',', synonyms.Select(x => $"'{x}'").ToList()); 

    // This notation works for one way synonyms. 
    // For Synonym, Replace, and Match terms exactlycheck the documentation 
    var synonym = new Synonym 
    { 
       description = description, 
       feature = "thesaurus", 
       parent = null, 
       definition = $"expand \"{term}\" to {synonymString}", 
       position = 0 
    }; 

    Client.DefaultRequestHeaders.Authorization = 
       new AuthenticationHeaderValue("Bearer", _accessToken); 
    var stringContent = 
       new StringContent(JsonConvert.SerializeObject(synonym), 
    Encoding.UTF8, "application/json"); 
    var requestUrl = 
       $"{_baseUrl}/{_pipelineId}/statements?organizationId={_organizationId}"; 

    using var response = Client.PostAsync(requestUrl, stringContent); 
    using var content = response.Result; 
    return content.IsSuccessStatusCode; 
} 

Get a synonym by Id:

public Synonym GetSynonym(Guid id) 
{ 
    Client.DefaultRequestHeaders.Authorization = 
       new AuthenticationHeaderValue("Bearer", _accessToken); 
    var requestUrl = 
    $"{_baseUrl}/{_pipelineId}/statements/{id.ToString()}?organizationId={_organizationId}"; 

    using var response = Client.GetAsync(requestUrl).Result; 
    using var content = response.Content; 

    if (response.IsSuccessStatusCode) 
    { 
       var synonym = JsonConvert.DeserializeObject( 
              content.ReadAsStringAsync().Result); 
       synonym.Term = synonym.definition.Split(" to ")[0] 
              .Replace("expand ", "").Replace("\"", ""); 
       synonym.Synonyms = synonym.definition.Split(" to ")[1] 
              .Split(",").ToList(); 

       return synonym; 
    } 

    return null; 
} 

For the full code example, check out my Gist here:

https://gist.github.com/peterpociask/a79de0887acfecc94a3a95733ecf735a

Related Blogs

Latest Blogs