Using Azure Cognitive Services - Bing AutoSuggest API And SPO

Microsoft recently launched multiple Azure Cognitive Service APIs. This new set of APIs is built on top of Azure’s API Management building block and points to well known APIs (Machine Learning, Bing…) that Microsoft was offering for a while but in different flavors. Thanks to Azure Cognitive Services, we now have a single way of consuming these APIs which makes our life better!
 
The Bing AutoSuggest API can be very handy to improve any search experience. In SharePoint Online, one can use Query Suggestions but they are defined at tenant level and they need to be imported upfront. This is not that user-friendly. So, what if you could simply have a Bing/Google-like experience that is suggesting queries as you type? That’s what we’ll do very easily in this post.
 
For this example, I have not been using the SharePoint Framework (SPFx) but simply jQuery UI’s autocomplete control in combination with Azure Cognitive Services. So, here are the steps to build such a control.
  • Go here and look for Cognitive Services.

  • Create a new Cognitive Services Account in order to end up with something like this,

The important part is highlighted in red. I’ve chosen the Standard pricing tier (there's no free one) and I’ve specified the Bing Autosuggest API.
  • Once done, grab one of the keys that were generated for you as you’ll need it later on.


    Now, the Azure part is done.
  • Now, in a SharePoint search center, delete the existing search box.

Add a Snippet Editor to the Search Center and add the below code.
  1. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  2.     <link rel="stylesheet" href="/_layouts/15/1033/styles/Themable/searchv15.css?rev=gHovyF1PT%2BErZeM0JGVoew%3D%3DTAG325">  
  3. <script src="//code.jquery.com/jquery-1.12.4.js"></script>  
  4. <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  5. <div class="ms-srch-sbLarge ms-srch-sb-border">  
  6.     <input placeholder="Type something..." id="keywords">  
  7.     <a title="Search" id="SearchLink" class="ms-srch-sb-searchLink" href="javascript: {}">  
  8.         <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACiUlEQVRYR+2Wv4sTURDHZ94GQxqJByb5A+QqOQ/RTkE8RLTQRiKHp4gWabLvJV7wGtHIiYWFm/cSkkotPD200srzwMYflT9QrlFbq8Rf0S7J7o48MCAr2bdB4ikk3TI/3mdmvswEYZ1/uM7vwxjg/+lAvV7f1Ov1TiPiYQDYCgAbAeA7Ea0h4n3P864Vi8X2sJqK1AGl1EkAuAIAK4h4CxFfpFKpdqvVSnqetxMAjiHifiKaF0LcHAbCCFCpVBYB4IhlWVnbttcGJVdKbSOiuwCwLIQoR4UIBdCV+76/4Lru7lKp9MmUVCm1mYieMsYWbdteMvlr+0AAPXPXdd8h4kxY5cFHHMeZtixr1fO8ySiaGAggpSwh4hTn/ESUSn71UUotEdErIcRVU+xAAKXUE0S8ZNv2Q1OSoL1arR4gogXO+R5TbBjAV8bYlnw+/9mUJGhvNBqpTqfztlAoTJhiwwC8TCazIZvNeqYkQXu5XI4lk8luoVBgpth/twNSyscAcFkIsWKqImiXUh5ExLN/qoF5IpoWQhwfFqBSqdy2LOu5bduOKXbgCBzHSVqW9R4A9nHO35gS9e21Wm2767oPEonEZC6X+2aKC92EUkpd/TlE3MU5/2hKptXf6/WeAcB5zvmyyT90E/aDpZR6r8/6vn+0WCy+HpRUV+77/h0A+MA53xvl8UgA2qlarc4Rkd5qq/oaxmKxl81m80s6nZ7odrs7iGgOAGYA4BFjbJaILkY9SMZr2K9Ea4IxdgoRD/m+PwUA+lvPWOvjXjwev6FnrjuGiBeiQkQGiNpS7TcMxEgAhoEYGUBUiJECBCD037XfzvPIAX5CnEHENuf8elBLfwUgTMBjgHEHfgB2xxwweE1PpAAAAABJRU5ErkJggg==">  
  9.     </a></div>  
  10. <script type="text/javascript">  
  11. $(function () {  
  12.     function DoSearch() {  
  13.         var url = window.location.toString();  
  14.         var k = $('#keywords').val();  
  15.         if (k == '')  
  16.             k = '*';  
  17.         if (url.indexOf('/default.aspx') != -1) {  
  18.             url = url.replace("/default.aspx""/results.aspx");  
  19.    
  20.         }  
  21.         url = url + '#k=' + encodeURIComponent(k);  
  22.         window.location = url;  
  23.     }  
  24.     $("#SearchLink").click(DoSearch);  
  25.     var KeywordIndex = window.location.toString().lastIndexOf('#k=');  
  26.     if(KeywordIndex!=-1)  
  27.     {  
  28.         var LastK = decodeURIComponent(  
  29.             window.location.toString().substring(KeywordIndex).replace('#k='''));  
  30.         var LanguagePosition=LastK.indexOf('#l=');  
  31.         if(LanguagePosition != -1)  
  32.         {  
  33.         $("#keywords").val(LastK.substring(0,LanguagePosition));  
  34.         }  
  35.         else  
  36.         {  
  37.         $("#keywords").val(LastK);  
  38.         }  
  39.     }  
  40.     $("#keywords").keydown(function(event){  
  41.         if(event.keyCode == 13) {  
  42.             if($("#keywords").val().length!=0) {  
  43.                 DoSearch();  
  44.             }  
  45.             event.preventDefault();  
  46.             return false;  
  47.         }  
  48.     });  
  49.     $('#keywords').css('width''450px');  
  50.     $( "#keywords" ).autocomplete({  
  51.         delay: 0,  
  52.         minLength:3,  
  53.         source:function(request,response){  
  54.             var k = request.term.replace('+',' ').replace('-',' ').replace('"','');  
  55.             $.ajax({  
  56.                 url: "https://api.cognitive.microsoft.com/bing/v5.0/suggestions?q=" + k + "&mkt=en-us",  
  57.                 headers: { 'Ocp-Apim-Subscription-Key''<yourkey>' }  
  58.             }).done(function (data) {  
  59.             if (data != null && data.suggestionGroups.length > 0)  
  60.             {  
  61.                 var availablekeywords = [];  
  62.                 for (var i = 0; i < data.suggestionGroups[0].searchSuggestions.length; i++)  
  63.                 {  
  64.                     availablekeywords.push(data.suggestionGroups[0].searchSuggestions[i].displayText);  
  65.                 }  
  66.                 response(availablekeywords);  
  67.             }});  
  68.         }});  
  69. });  
  • The important part here is the communication with the Bing AutoSuggest API which is handled by the AJAX call. You’ll simply have to update the key value that is associated with the Ocp-Apim-Subscription-Key HTTP header.

  • After configuring the above steps in both Azure portal & SharePoint Online, you have the search box with auto-suggestion enabled on your SharePoint Online page.