Mark Oliver's World

Posted: 12/04/2021

Adding A Site Search

As the site gets more and more posts, its important to have the capability to search on the site.

Now there are several ways to do this:

The first 2 options are great if your sites content does not change very much, as google does all the heavy lifting for you, and you can just link to them.
However if you are adding or modifying content frequently, you will probably want to have the search "live" on your site.

The custom search engine is very important if your site has a lot of dynamic content, or is not easily indexed by google. e.g. if you have a lot of dynamic products in a shop.

For this blog, I'm going to implement a custom search for 2 reasons:

  • The content is dynamic, and not always indexed
  • Its a great coding challenge!

First steps

We are only interested in searching the blog posts. If I want to add any of the static pages (like About Me), then I can hard-code some search results for them, as they rarely change.

All of the blog posts are cached within the app, so we should be able to search the contents very quickly.

The posts are kept in a list of objects, and so searching the content of the posts themselves is just a "grep" on the string. They are held in MarkDown so there is minimal formatting to get in the way.

We then need to render a list of posts, and a small snippet of the post that contains the matches found on the search results page.

I also want to have a link to jump to the posts, and highlight the search term on the result too.

Solution

So I need a Blazor page that has an input box and a button on it so you can enter the search term (for now its just a simple pattern match), and a button to say go.

I also need a Blazor component, that can render the results.

In the back end, I need a searcher that will activate the search on all the posts.
I need a search result builder that will find a result in the post and build a set of matches (search term may occur more than once).

The Search page should also be able to take a search term in the uri, so I can link to search pages.

Those are all the bits I need: A page to ask for the term, and render the results, and something that can read all the posts pulling out matches.

Simple really 😃

I all honesty, its not hard to do this, the biggest complexity is in finding all the matches and pulling out the "context" of the words around the matching search term.

You can try out this feature now, by clicking Search, or if you want to find all my posts that mention Blazor, go direct to the results here

Update 15/10/2021

I forgot to remove case sensitivity from the search, and also that the "enter" key should activate the search. These are now fixed!


Thanks for reading this post.

If you want to reach out, catch me on Twitter!

I am always open to mentoring people, so get in touch.