Sitecore Content Search — The Basics

Rainfall Software
Rainfall Software
Published in
2 min readFeb 14, 2023

Let’s take a look at the basics of programming with Sitecore’s Content Search API.

First of all, to perform a search, you need to create a search context and a search query. The search context specifies the search index you want to search in, while the search query is used to specify the search criteria such as keywords, language, and item templates.

Photo by Marten Newhall on Unsplash

Here’s an example to give you an idea of how to do a basic search:

using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;

var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(x => x.Content.Contains("example"));

foreach (var result in query.GetResults())
{
Console.WriteLine(result.Content);
}
}

Here, we retrieve the sitecore_web_index index and create a search context. Then, we create a queryable search result set using the GetQueryable method and specify the search criteria using the Where method. Finally, we use the GetResults method to retrieve the search results and print out the Content field for each result.

Now, what if you want to customize your search results? No problem, the Content Search API has got you covered! You can sort your results, limit the number of results returned, and even categorize them based on certain fields.

Here’s an example that shows you how to do this:

using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;

var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(x => x.Content.Contains("example"))
.OrderByDescending(x => x.CreatedDate)
.Take(10);

foreach (var result in query.GetResults())
{
Console.WriteLine(result.Content);
}
}

In this example, we sort the results in descending order by the CreatedDate field and limit the number of results returned to 10 using the OrderByDescending and Take methods.

Finally, once you have retrieved your search results, you can work with them in Sitecore however you like. You can display them on your website, use them to build custom reports, or anything else you can imagine!

--

--