Last week, we decided we needed to get search working in the backend for one of our products. We had a rather small database that needed to be searchable, so my initial thought was to simply do this with a simple database query over the tables involved.
Then I remembered that Azure had recently released their hosted search solution into preview a few weeks back. So I decided to give it a try.
After a few setbacks with creating a search service in the Azure Portal (something the PM for the product resolved for me after a question on Stack Overflow), I spent 3 hours going from nothing to a deployed solution.
At the moment, Azure Search has a REST-based API. There are no mentions of a .NET SDK on the website, but a third-party implementation is available:
This is a
great package that clearly mirrors the REST API, so I had no trouble going on. First you’ll need to get your API key, and store it in your configuration somewhere (I put it under
Then you need to decide which fields to put in your index. The index defines the model of your search, and typically you would create a separate index for each type of query you want to run. I wanted to search our question database, so creating the index was easy-peasy:
There is only one thing that stuck out here, namely that the
key fields in the search index
has to be strings. I only figured that out because
RedDog.Search only takes a string when you are creating an
IndexOperation (in the next snippet).
The cool part about the code above is the
Analyzer() call. The analyzer tells Azure Search how it should interpret the text it indexes. In my case, the text is in Norwegian, and the analyzer affects e.g. how stemming of words in queries work. E.g. if you in search for “numbers” with the default analyzer, it will also find results for “number” and “numbering”. You need to explicitly set the language, as the rules for which endings can be removed from words is different from language to language. After you’ve set the analyzer, no extra work is required to make searches like this work.
IsFacetable() call on the tags lets you pivot your results on tags. This is a cool feature that I didn’t have a need for at the moment, but I decided to create the index properly in case I changed my mind later.
This piece of code is only run when my web service starts up. When I want to index a question:
Now, searching this index is quite easy. I am only interested in the keys for my questions, I can efficiently look them up locally and convert them to DTOs when I know the relevant question IDs:
In total, implementing this solution — including a front-end AngularJS search — took me a grand total of 3 hours. Not bad for a service that is free for small solutions and is still in preview. Try it out today.