Solr Search in .NET Core

By FoxLearn 1/10/2025 8:00:15 AM   56
.NET Core offers robust support for interacting with the Solr search engine.

Although the Solr query language can be a bit tricky at times, integrating Solr with your .NET Core application is fairly straightforward.

Install Required NuGet Packages

To get started, you need to add the following NuGet packages to your project:

  • SolrNet.Core
  • SolrNet.Microsoft.DependencyInjection

You can install these using the NuGet Package Manager in Visual Studio or by running the following commands in your terminal:

dotnet add package SolrNet.Core
dotnet add package SolrNet.Microsoft.DependencyInjection

Define a Model Class to Map Solr Fields

You don't have to return all fields from the Solr index. Instead, create a model class that maps only the fields you need from Solr. Each Solr field will correspond to a property in your model.

Here’s an example of how to map fields from the Solr index to a C# model class:

using SolrNet.Attributes;

namespace MyApp
{
    public class MySolrModel
    {
        [SolrField("_fullpath")]
        public string FullPath { get; set; }

        [SolrField("advertcategorytitle_s")]
        public string CategoryTitle { get; set; }

        [SolrField("advertcategorydeprecated_b")]
        public bool Deprecated { get; set; }
    }
}

Configure SolrNet in the Dependency Injection Container

In this step, you'll need to tell your application where the Solr server is located and which model class to return. Here's how to configure SolrNet and register the necessary services using Dependency Injection (DI):

using SolrNet;
using Microsoft.Extensions.DependencyInjection;

private IServiceProvider InitializeServiceCollection()
{
    var services = new ServiceCollection()
        .AddLogging(configure => configure.AddConsole())
        .AddSolrNet<MySolrModel>("https://[solr-instance]:8983/solr/[index-name]")
        .BuildServiceProvider();

    return services;
}

Create a Repository to Perform Solr Searches

Now that Solr is set up, you can create a repository to interact with it. The repository will contain methods to perform searches against the Solr index. Here’s a simple example of a Solr search repository:

using SolrNet;
using SolrNet.Commands.Parameters;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace MyApp
{
    public class MySolrRepository
    {
        private readonly ISolrReadOnlyOperations<MySolrModel> _solr;

        public MySolrRepository(ISolrReadOnlyOperations<MySolrModel> solr)
        {
            _solr = solr;
        }

        public async Task<IEnumerable<MySolrModel>> Search(string searchString)
        {
            var results = await _solr.QueryAsync(searchString);
            return results;
        }
    }
}

The Search method performs a simple search using the query string you provide. By default, it searches in all fields marked as searchable in the Solr index.

Performing Advanced Searches

For more complex searches, you can modify the QueryAsync method to build a more detailed query. Below is an example of a search that uses multiple criteria, returns a single result, and searches specific fields:

public async Task<MySolrModel> Search(string searchString)
{
    var solrResult = (await _solr.QueryAsync(new SolrMultipleCriteriaQuery(new ISolrQuery[]
    {
        new SolrQueryByField("_template", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"),
        new SolrQueryByField("_language", "da"),
        new SolrQueryByField("_latestversion", "true"),
        new SolrQueryByField("advertcategorydeprecated_b", "false"),
        new SolrQueryByField("_title", searchString)
    }, SolrMultipleCriteriaQuery.Operator.AND), new QueryOptions { Rows = 1 }))
    .FirstOrDefault();

    return solrResult;
}

In this example, the query is more refined, using several conditions to narrow down the search. The query returns only one result (because Rows = 1 is specified), which could be useful if you are looking for a single match based on the query criteria.

Integrating Solr search functionality in a .NET Core application is not difficult once you get the hang of it. By following the steps outlined in this tutorial, you can easily configure SolrNet, create a model to map Solr fields, and set up a search repository to perform basic or advanced searches in your Solr index.