Sunday, January 24, 2021

Connect .Net Core 5.0 MVC to Solr 8 using SolrExpress

 Download the next packages using package manager

 Install-Package SolrExpress -Version 5.5.0  
 Install-Package SolrExpress.Solr5 -Version 5.5.0  
 Install-Package SolrExpress.DI.CoreClr -Version 5.5.0 


In Startup.cs


 public void ConfigureServices(IServiceCollection services)  
     {  
 .....  
       services.AddSolrExpress<SolrModel>(builder => builder  
           .UseOptions(  
                 q => {   
                     q.HasHostAddress("http://IP:8983/solr/ZING/");  
                    }  
                 )  
           .UseSolr5());   
 .....  
     }  


Define Model

   public class SolrModel : Document  
   {  
     [SolrField("biblo_id")]  
     public int biblo_id { get; set; }  
     [SolrField("title")]  
     public string title { get; set; }  
     [SolrField("author")]  
     public string author { get; set; }  
   }  


On Controller Page


 using Microsoft.Extensions.DependencyInjection;  
 using Newtonsoft.Json;  
 using SolrExpress;  
 using SolrExpress.Configuration;  
 using SolrExpress.DI.CoreClr;  
 using SolrExpress.Options;  
 using SolrExpress.Search.Extension;  
 using SolrExpress.Search.Parameter.Extension;  
 using SolrExpress.Search.Result.Extension;  
 using SolrExpress.Solr5.Extension;  
 using SolrExpress.Solr5.Update;  
 namespace ArabAuthorsIndex.Controllers  
 {  
   public class SolrController : Controller  
   {  
     private DocumentCollection<SolrModel> _solrModel;  
     public SolrController(DocumentCollection<SolrModel> solrModel)  
     {  
       _solrModel = solrModel;  
     }  
     public string search()  
     {  
       _solrModel  
           .Select()  
           //.Fields(d => d.biblo_id, d => d.author)  
           //.FacetField(d => d.author)  
           .Filter(d => d.biblo_id, 1)  
           .Limit(10) //.Limit(itemsPerPage)  
           //.Offset(2) //.Offset(page)  
           .Execute()  
           //.Information(out var information)  
           .Document(out var documents)  
           //.Facets(out var facets)  
           ;  
       return JsonConvert.SerializeObject(documents, Formatting.Indented);  
     }  
     public string update()  
     {  
       var document1 = new SolrModel  
       {  
         author = "Mohamed",  
         title = "ymmud"  
       };  
       var document2 = new SolrModel  
       {  
         author = "Rafie",  
         title = "ymmud2"  
       };  
       _solrModel.Update().Add(document1, document2).Execute();  
       _solrModel.Update().Delete("2").Execute();  //delete document by solr id
       return search();  
     }  




No comments: