Friday, January 30, 2015

How to use SOLR.NET to add/search documents from SOLR

In this article we will look into how to use SOLR to add and query data using  SOLR.NET

Install Apache Tomcat and  SOLR

1. Install Java version 6 or above

2.Download Apache Tomcat -Core: 32-bit/64-bit Windows Service Installer (pgp, md5)
After you install apache tomcat you can check if service is running by checking the location -http://localhost:8080/

Details on how to install and run SOLR is clearly stated in the below awesome articles

Use SOLR.NET to connect to SOLR

So now that we have Apache and SOLR running let’s look at how to use this in ASP.NET(C#)

1.Download SOLR.NET -

2.Compile the project and get the dlls from SOLRNET project (there will be SolrNet.dll, Microsoft.Practices.ServiceLocation.dll, HttpWebAdapters.dll and the pdb and xml files)

3.Create an empty ASP.NET project

4.Create a new folder in this project and copy the dlls from SOLRNET project (step 2) to that folder.

5.Add references to the 3 dlls

6.Add Global.asax and initialize SOLR.NET connection in application start
  protected void Application_Start(object sender, EventArgs e)

7.Create a class which has the same fields as the schema in SOLR. For testing purpose I added only 2 fields from schema
public class SolrSearchResult
            public string id { get; set; }

            public string title { get; set; }

8.Now we are ready to add documents to SOLR! Given below is the function to add documents to SOLR
public void AddData()
            ISolrOperations<SolrSearchResult> solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrSearchResult>>();
            SolrSearchResult test = new SolrSearchResult() { id = "changeme2", title = "changeme2" };

9.To search data use the below function

public void SearchData()
            ISolrOperations<SolrSearchResult> solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrSearchResult>>();
            SolrQueryResults<SolrSearchResult> results = solr.Query(new SolrQuery("id:\"changeme2\""));
            foreach (SolrSearchResult result in results)


Roy Steeves said...

SOLRPOST generates namespace not found error. I am obviously missing a Using setting. What is it?

psdk said...

it's simply a namespace of your project.
everything else works well at my side