Google has a really great great product for web creators called Custom Search Engine that allows non-coders to pretty easily add custom search to any given web site. It requires minimal coding and has a nice UI for customizations. But what happens when it’s just not right for your customer? We ran into that recently because the google search was too aggressive in it’s handling of PDF files and would include PDFs that contained keywords in the meta-data. For example searching for “Lion” (a product name) would return spurious results including totally unrelated documents. When we pulled up those docs in a text editor we found our keyword embedded in an image (xapGImg) tag.
We offered out client the option of implementing Bing Web Search as a replacement and they authorized a few hours for a demo. We immediately made a few discoveries:
- Microsoft does not provide a feature-matching product to Google’s Custom Search Engine
- There are few, limited, and dated docs on how to implement Bing Web Search
- All the Bing “stuff” is currently migrating to Azure Cognitive Services
Because of the limited docs, I decided to make some notes here and share them with the world. I hope you find them useful.
You’ll need a few things to get going:
- Get an API key from Cognitive Services. This is a bit of a pain requiring email confirmations, revisiting the site and exposing some API keys that will last 90 days. Just keep at it and remember that you are tracking “Bing Web Search”
- Once you have your keys, you can start playing around. I’d really suggest using something like PostMan to initially hit the API. It will make your debug cycle much smoother.
- Bookmark the link to the Bing API v5 Web Search Guide because it’s hard to find.
Verify your API keys are working
Use Postman or curl, or whatever tools you like to test APIs that includes adding custom headers. It’s a simple GET to https://api.cognitive.microsoft.com/bing/v5.0/search?q=[your search terms] with the custom herader “Ocp-Apim-Subscription-Key” with the value of one of your two API keys. here is an example:
Code your solution
This is really subjective and chances are you have gotten most of the value out of this post already. I’ll provide a really simple HTML/JQuery implementation to prove it works. You might be more interested in using a package on the server side. I did not easily find one.
Two elements here: The Div where we will do some DOM injection and the item template used by jquery-templates. the interesting things to here are the names of the data attributes. title, displayUrl, name, etc.
Just a little formatting CSS I lifted from other examples and then simplified a bit.
Using your API key and a search terms you can call the API and get some results. Notice that the returned JSON is an object graph and the list of results is found in the webPages.value node. Also Notice the setHeader(xhr) function that sets the header just like in the Postman example above.