Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Write to SOLR from .NET Core

$
0
0

.NET Core supports the SOLR index through the SolrNet.Core NuGet packages.

Here is how you update the index.

STEP 1: THE NUGET PACKAGES

You need the following NuGet packages:

STEP 2: CREATE A MODEL CLASS CONTAINING THE PROPERTIES OF YOUR SOLR INDEX

Use the SolrNet.Attributes to specify the properties of the document to index:

using System;
using SolrNet.Attributes;

namespace MyCode
{
  public class MySolrDocument
  {
    [SolrField("_uniqueid")]
    [SolrUniqueKey]
    public int RowID { get; set; }

    [SolrField("name")]
    public string Name { get; set; }

    [SolrField("age")]
    public int Age { get; set; }
  }
}

STEP 3: INJECT SOLR INTO YOUR SERVICECOLLECTION

Your code needs to know the Solr URL and which model to return when the Solr instance is queried. This is an example on how to inject Solr, your method might differ slightly:

private IServiceProvider InitializeServiceCollection()
{
    ...
    ...
    .AddSolrNet<MySolrDocument>("https://myurl:8983/solr/myindex")
    .AddSingleton<MySolrRepository>()
    .BuildServiceProvider();
    return services;
}

STEP 4: IMPLEMENT A REPOSITORY THAT CAN UPDATE THE INDEX

This is a simple repository that can update the SOLR index:

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

namespace MyCode
{
  public class MySolrRepository
  {
    private readonly ISolrOperations<MySolrDocument> _solr;

    public MappedValueRepository(ISolrOperations<MySolrDocument> solr)
    {
      _solr = solr;
    }

    public async Task Update(int id, string name, int age)
    {
        MySolrDocument solrDoc = new MySolrDocument()
        {
            RowId = id,
            Name = name,
            Age = age
        };
        await _solr.AddAsync(solrDoc);
        await _solr.CommitAsync();
    }

  }
}

Explanation:

SOLR does not have separate create and update statements. If a document with the same unique key exists, the document is updated. If not, it is created.

SOLR updates are protected using transactions. You need to call CommitAsync() before your changes are committed. SOLR also provides a RollbackAsync() method in case you need to roll back.

To delete documents, simply call DeleteAsync() with a model class containing the unique key specified in the model class.

That’s it. You are now a SOLR expert.

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles