Santa

Let’s Talk

We would love to hear from you. Want to know more about
our services or have any questions? Say Hi!

How to implement SOLR Search Code in Sitecore?

May 09, 2023
How to implement SOLR Search Code in Sitecore?
Keyur Garala
Keyur Garala
Sitecore Certified Solutions Architect
how-to-implement-solr-search-code-in-sitecore

Sitecore provides SOLR search. SOLR is designed to provide fast search results, even with large amounts of data.

Solr provides more advanced search features, such as faceted search, fuzzy search, boost and stemming. These features can help users find what they're looking for more quickly and easily.

Please find below sample code for SOLR search which will help us to provide more accurate search result data.

Before the start of this blog, you need to take keyword from web page to our controller action method for the implementation of Solr search.

Please refer below sample code for SOLR search implementation.

Initialize Queryables:

In the very first steps you need to make one function and initialize SOLR index with its queryable. Below is the code for the reference.

Generally, we are refereeing Sitecore web index for our search implementation. But if you have created any custom index then you have to refer that one for this function.

public IQueryable<SearchModel> GetQueryables() 
    { 
        var indexableItem = new SitecoreIndexableItem(“sitecore_web_index”); 
        using (var context = ContentSearchManager.GetIndex(indexableItem).CreateSearchContext()) 
        { 
            var queryable = context.GetQueryable<SearchModel>(); 
            return queryable; 
        } 
    } 

You can change index name by SitecoreIndexableItem(“your_custom_index”) syntax.

Default Predicates:

After initializing, we need some default queryables for the stating node, language and latest version, so we have to make one function for it, below is the code for the reference.

public IQueryable<SearchModel> GetPredicates(IQueryable<SearchModel> queryable) 
    { 
        var predicate = PredicateBuilder.False<SearchModel>(); 
        predicate = predicate.Or(p => p.Path.Contains(“Your sitecore path”)); //starting path of the search 
        predicate = predicate.And(p => p.Language == Sitecore.Context.Language.Name); //take language by its context and prepare appropriate query 
        predicate = predicate.And(p => p["_latestversion"].Equals("1")); //take only latest version of item 
        return queryable.Where(predicate); 
    } 
                        

It will create query for specific path, language and latest item version.

Boost in Predicates:

In the predicates, we have one feature for the boost. From this feature we can boost our result to the upper level and lower level. For example, in there are multiple fields are in my Sitecore, title, description, content, short desc, bio, contact number etc.

In this case I want to first see results from the title, then the description and then the others. So, we have one boost function to achieve this scenario. Below is the code for the reference.

public IQueryable<SearchModel> SearchwithName(IQueryable<SearchModel> queryable, string name) 
    { 
        var titlePredicates = PredicateBuilder.False<SearchModel>(); 
        titlePredicates = titlePredicates.Or(item => item.Title.Contains(name).Boost(10)); 
        titlePredicates = titlePredicates.Or(item => item.FirstName.Contains(name).Boost(9)); 
        titlePredicates = titlePredicates.Or(item => item.LastName.Contains(name).Boost(9)); 
        return queryable.Where(titlePredicates);
    } 
                        

Here, we can consider boost= 10 is taking as highest priority and 0 is taking as lowest priority.

You can also add some other fields in this custom function for the customization as per project requirement.

Facets:

Facets, also known as smart filters, are a type of search filter that customers can utilize to quickly narrow down their search results.

By FacetOn function we can check the the result from that field how many results are associated with it. Here we passed 1 because minimum one item is associated with Newstype field.

var facetsAll = queryable.FacetOn(x => x["newstypes"], 1); 

and take this facet into list by below code.

var newsFacet = facetsAll.Categories.Where(x => x.Name == "newstypes").ToList().Select(q =>
    q.Values).ToList()[0].Select(v => v.Name).ToList();

How to get result from Queryables and Predicates:

Here for giving an example, I make controller action method and take keyword from ajax to my method. Using GetResults() method it will execute the query and give the result from SOLR.

public ActionResult SearchResults(string keyword = null,int page = 0) 
    { 
        var queryable = _searchMediator.GetQueryables(); 
        //set all default predicates 
        queryable = _searchMediator.GetPredicates(queryable); 
        //search keyword 
        if (!string.IsNullOrEmpty(name)) 
         queryable = _searchMediator.SearchwithName(queryable,name.ToLower()); 
        List<Item> result = queryable.Page(page, newsCountInt).GetResults().Select(x => x.Document.GetItem()); 
        return result; 
    } 
                        

Above sample code will help you to execute the SOLR search implementation and you can implement fully functional search in your website.


YOU MAY ALSO LIKE