Contact Us

Apache Solr is a search platform that helps with the search and navigation of many websites. It constitutes a range of features, including distributed indexing, automated failover and recovery, and replication with load-balancing querying.

Sitecore by utilizing the capabilities of Solr provides the best search feature that there is. There, of course, is a configuration process if you want to install and use Solr with Sitecore. In this article, you will learn about Solr along with its benefits. Lastly, there is an installation guide with a few easy steps for you to set it up.

 

What is Solr in Sitecore?

Be it performing a search within the content database to storing analytics and testing data, Sitecore uses a search engine internally for a variety of purposes. The following are the two types of search engines internally:

  • Lucene
  • Solr

 

Note: The Lucene search engine is deprecated with a later release

But in this blog, we will discuss Solr Search. Solr is based on Apache. It is an open-source enterprise-search platform. It provides fast indexing and searching capabilities, spell checking, hit-highlighting, faceting, distributed indexing and searching, multi-node scaling, and higher performance than Lucene.

Solr performs much better and scales robustly when you have many items. It indexes and searches multiple sites and returns content recommendations basis the search query's taxonomy.

 

Benefits of Solr

  • Create custom Indexes: You should create a custom index with only the required template and fields for the best search performance.
  • Use Facets: If you want to implement category filtration, you can facet instead of using regular queries to the aggregate result count based on the categories.
  • Use Custom model instead of SearchResultItem: You can map many properties you don't need during your search.

 

Installation of Solr

Before moving forward to the Solr installation, you should know which version of Sitecore to install.

You can follow the below steps to download

Download "Solr-7.5.0.zip" from this URL

https://archive.apache.org/dist/lucene/Solr/

Create folder Solr in the "C:\" location, or choose any folder in "C:\".

JRE and JDK are significant to install Solr on our machine.

 

Indexing Sitecore content

Step 1: If you can find the connection string for Solr in "connectionstrings.config" then it means it is correct.

<?xml version="1.0" encoding="utf-8"?> 
<connectionStrings configBuilders="SitecoreConnectionStringsBuilder">  
<add name="Solr.search" connectionString="https://Solrfor102:8984/Solr" />

Step 2: Create a data template.

Image 1

Step 3: Create a View Rendering to display the content that will be indexed using standard Sitecore development methods.

Image 2

Step 4: Use the template to create content items and add data.

Image 3

Step 5: If you are using any existing indexes, then rebuild by using the Sitecore Control Panel’s Index manager.

Step 6: After indexing, check if the data is present in the index by going into the Solr interface.

Image 4

After creating the index you can start code in Visual Studio.

 

Creating Search page with Codes

For coding, use MVC 4.5, API and React and follow the Sitecore headless.

->Create a model class on the Solr server to map fields.

public class SearchOutputModel: SearchResultItem

{

[IndexField("title_t")]
public string ArticleTitle { get; set; }

[IndexField("brief_t")]
public string ArticleDescription { get; set; }

[IndexField("articleurl_s")]
public string ArticleUrl { get; set; }

[IndexField("articleimage_s")]
public string ArticleImage { get; set; }

[IndexField("articlespeciality_s")]public string ArticleSpeciality { get; set; }

}

->Create controller and inherit ApiController

public class GetArticlesController : ApiController

{

}

->Add an action method with HttpPost attribute, one class parameter with json return.

[Route("altudoapi/handlesearch")]

[HttpPost]
public IHttpActionResult handlesearch(SearchParam searchData)
{

if (searchData != null)

{

if (!string.IsNullOrEmpty(searchData.SearchKeyword))

{

// {

//get database

var contextDB = Sitecore.Context.Database;

List <StandardSearchResult> searchResults = new List<StandardSearchResult>();

ISearchIndex searchIndex = ContentSearchManager.GetIndex($"sitecore_{contextDB.Name}_index");

//create search context

using (IProviderSearchContext searchContext = searchIndex.CreateSearchContext())

{

searchResults = searchContext.GetQueryable()

.Where(x => x.TemplateName == "HealthArticle")

.Where(x => x.ArticleTitle.Contains(searchData.SearchKeyword) || x.ArticleDescription.Contains(searchData.SearchKeyword))

.Select(x => new StandardSearchResult

{

Title = x.ArticleTitle,

Brief= x.ArticleDescription,

Url = x.ArticleUrl,

ImageUrl =x.ArticleImage,

ArticleSpeciality = x.ArticleSpeciality

}).ToList();

}

return Json(searchResults);

}

else {

return Json(new List());

}

  }

else

{

return Json(new List());

}

}

->Create sitecore view with react to call API and display on view with service hosting.

import React from 'react';

import { Text } from '@sitecore-jss/sitecore-jss-react';

import ReactDOM from 'react-dom';

import '../AppSearch/style.css';

import 'bootstrap/dist/css/bootstrap.min.css';

 

class AppSearch extends React.Component {

constructor(props) {

super(props);

this.state = {

error: null,

isLoaded: false,

searchKeyword: '',

searchResults: [],

};

 

this.handleChange = this.handleChange.bind(this);

this.handleSubmit = this.handleSubmit.bind(this);

}

 

handleChange(event) {

debugger;

this.setState({

searchKeyword: event.target.value,

});

}

 

handleSubmit(event) {

debugger;

// alert('search begings ' + this.state.searchKeyword);

let searchData = {

SearchKeyword: this.state.searchKeyword,

};

 

const requestOption = {

method: 'Post',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify(searchData),

};

 

fetch('/altudoapi/handlesearch', requestOption)

.then((response) => response.json())

.then(

(result) => {

this.setState({

error: null,

isLoaded: true,

searchResults: result,

});

console.log(this.state.searchResults.length);

},

(error) => {

this.setState({

error,

isLoaded: true,

});

}

   );

}

 

render() {

if (this.state.error) {

return (

<div>

          <input type="text" onChange={this.handleChange} id="searchKeyword" />

          <input type="submit" onClick={this.handleSubmit} value="submit" />

          <div>Error Occurred</div>

        </div>

      );

    } else if (!this.state.isLoaded) {

      return (

        <div>

          <input type="text" onChange={this.handleChange} id="searchKeyword" />

 

 

<input type="submit" onClick={this.handleSubmit} value="submit" />

          <div>Loading....</div>

        </div>

      );

    } else if (this.state.searchResults.length === 0) {

      return (

        <div>

          <input type="text" onChange={this.handleChange} id="searchKeyword" />

          <input type="submit" onClick={this.handleSubmit} value="submit" />

          <div className="alert alert-info" role="alert">

            Item not found....

          </div>

        </div>

      );

    } else {

      return (

        <div>

          <input type="text" onChange={this.handleChange} id="searchKeyword" />

          <input type="submit" onClick={this.handleSubmit} value="submit" />

          <div className="badge badge-secondary">

            Total Record Found : {this.state.searchResults.length}

          </div>

          <div>

            {this.state.searchResults.map((items) => (

              <div className="mainDiv" key={items.Name}>

                <h2>{items.Title}</h2>

                <h3>Speciality: {items.ArticleSpeciality}</h3>

                <br />

                <div>

                  <img src={items.ImageUrl} alt={items.Title} height="100" width="100"></img>

                  {items.Brief}

                </div>

                <div>

                  <a

                    target="_blank"

                    rel="noopener noreferrer"

                    href={items.Url}

                    className="ViewMore btn btn-success float-right"

                  >

                    View more

                  </a>

                </div>

              </div>

            ))}

          </div>

        </div>

      );

    }

  }

}

export default AppSearch;

->Build and publish all solutions and build react and see the result.

 

Conclusion

Apache Solr is an open-source search platform deployed to enhance Sitecore's searching and navigating capabilities. Sitecore uses Solr for indexing and quick-hunting of advanced-level queries, personalized searching, and customized visitor engagement on the platform. Feel free to get in touch with us for any Sitecore-related concerns you might be facing.