5

Can we access or use a new index created in solr with documents that are inserted from content hub and we need to access this index in our solution.

DO we need to create the index in Sitecore config files to access the index.

Need some insights on this approach

4 Answers 4

1

In order to connect to the index in Solr that contains documents stored from Content Hub, SolrNet.Microsoft.DependencyInjection needs to installed to connect and read the documents from the index as below.

  1. Install the SolrNet.Microsoft.DependencyInjection in your project that will be connecting to Solr and reading the documents from it.

  2. Create the model containing the properties stored in your Solr index as below.

using SolrNet.Attributes;

public class ContentHubDocument
{
   [SolrField("uniqueKey")]
   [SolrUniqueKey]
   public string UniqueKey { get; set; }

   [SolrField("title")]
   public string Title { get; set; }

   [SolrField("description")]
   public string Description { get; set; }
}
  1. Register Solr Url into Service collection as below, that contains the indexname along with the model defined above.
using Microsoft.Extensions.DependencyInjection;
using Sitecore.DependencyInjection;
using SitecoreCustomExtensions.Models;
using SolrNet;

public class RegisterDependencies : IServicesConfigurator
{
   public void Configure(IServiceCollection serviceCollection)
   {
      serviceCollection.AddSolrNet<ContentHubDocument>("{{SolrUrl}}/solr/{{SolrIndexName}}");
   }
}
  1. Register the above service collection by adding config patch as below.
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <services>
        <configurator type="SitecoreCustomExtensions.Pipelines.RegisterDependencies,SitecoreCustomExtensions" />
    </services>
  </sitecore>
</configuration>
  1. Then finally you can read the documents stored in Solr through injecting the dependency for ISolrOperations<ContentHubDocument> in your repository as below.
using SitecoreCustomExtensions.Models;
using SolrNet;

public class ContentHubRepository : IContentHubRepository
{
   private readonly ISolrOperations<ContentHubDocument> _solr;
   public ContentHubRepository(ISolrOperations<ContentHubDocument> solr)
   {
      _solr = solr;
   }
   public void GetIndexData()
   {
      string query = "*:*";
      var contentHubDocuments = _solr.Query(query);
      if (contentHubDocuments != null)
      { 
         // Iterate through solr documents.
         foreach(var contentHubDocument in contentHubDocuments)
         {

         }
      }
   }
}

Using above way, you will be able to successfully connect to Solr and read the documents stored in it.

You can find more details for initializing the SolrNet on below document.

https://github.com/SolrNet/SolrNet/blob/master/Documentation/Initialization.md

Hope that helps!!! Let me know in case you have any queries.

1

I think so Yes, you can access and use a new Solr index created with documents inserted from Content Hub in your Sitecore solution.

First check that the index is properly created in Solr and that it contains the documents you expect. You can do this using the Solr Admin UI.

In your Sitecore instance, you need to define the index in the configuration files. This is typically done in the Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config or a custom index configuration file.

After that You need to add a new <index> entry for your new Solr index.

<index name="your_custom_index" type="solr">
  <solr>
    <connectionString>http://localhost:8983/solr/your_custom_index</connectionString>
    <defaultIndexFieldName>yourFieldName</defaultIndexFieldName>
  </solr>
</index>

Use the below Sitecore Content Search API to query the new index.

using Sitecore.ContentSearch;
using Sitecore.ContentSearch.SearchTypes;

public void SearchInCustomIndex(string query)
{
    using (var context = ContentSearchManager.GetIndex("your_custom_index").CreateSearchContext())
    {
        var results = context.GetQueryable<SearchResultItem>()
            .Where(item => item.Content.Contains(query))
            .ToList();

        // Process results as needed
    }
}

Hope this helps!!!

1
  • This didnot work for me
    – MBN
    Commented Sep 19 at 15:27
1

To interact with a Solr index directly in your application without using Sitecore’s configuration, you can use SolrNet, a popular .NET library for Solr. Below is an example of how to query a Solr index using SolrNet.

  1. Install SolrNet NuGet Package
Install-Package SolrNet
  1. If you want to use dependency injection, you can also install this package.
Install-Package SolrNet.Microsoft.DependencyInjection
  1. Use this sample code to get documents.
using System;
using System.Collections.Generic;
using SolrNet;
using SolrNet.Attributes;
using Microsoft.Extensions.DependencyInjection;

namespace SolrExample
{
    // Define a class representing the Solr document fields
    public class SolrDocument
    {
        [SolrField("id")]
        public string Id { get; set; }

        [SolrField("_fullpath")]
        public string Path { get; set; }

        [SolrField("_template")]
        public string Template { get; set; }
    }

    public class ProgramData
    {
        public void Data(string ss)
        {
            // Configure the SolrNet service
            var services = new ServiceCollection();
            services.AddSolrNet<SolrDocument>("https://localhost:8983/solr/10.3.1.dev.local_master_index");
            var serviceProvider = services.BuildServiceProvider();

            // Get the Solr instance
            var solr = serviceProvider.GetRequiredService<ISolrOperations<SolrDocument>>();

            // Define a Solr query
            var query = new SolrQueryByField("_parent", "11111111111111111111111111111111");

            // Execute the query
            SolrQueryResults<SolrDocument> results = solr.Query(query);

            // Display the results
            foreach (var doc in results)
            {
                Console.WriteLine($"ID: {doc.Id}, Path: {doc.Path}, Template: {doc.Template}");
            }

            Console.WriteLine("Query finished.");
        }
    }
}

See the result you get.

enter image description here

You may also need to install the Microsoft.Extensions.DependencyInjection if you don't have in your application.

Hope this helps.

0

If you want to use Sitecore Content Search API then use other answers but if you want simple way to get simple data you can directly query Solr. Since Sitecore has connection string to Solr you can also manually construct Solr query and then map repsonse to object. Below is a simple API to get location data from custom index.

public async Task<IEnumerable<LocationSearchResultName>> GetRegionNames(double lat, double lng)
{
  var regionNames = new List<LocationSearchResultName>();
  var geoFieldName = "polygon_grpt";

  using (var client = new HttpClient())
    {
        var query = $"{YourIndexName}/select?fl=location_t%20and%20_group%20and%20_name&q={geoFieldName}%3A\"Intersects({lng}%20{lat})\"&wt=json";

        //Set basic auth authorization header if user info exists in uri
        var uri = new Uri(Sitecore.Configuration.Settings.GetConnectionString("solr.search"));
        if (!string.IsNullOrEmpty(uri.UserInfo))
        {
            var byteArray = Encoding.ASCII.GetBytes(uri.UserInfo);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(byteArray));
        }

        var response = await client.GetAsync($"{Sitecore.Configuration.Settings.GetConnectionString("solr.search")}/{query}");

        var responseContent = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
        {
            MyLogger.Log.Warn($"{responseContent}");
        }

        var docs = JObject.Parse(responseContent);

        regionNames = docs["response"]["docs"].ToObject<List<LocationSearchResultName>>();
    }

  return regionNames;
 }

More info can be found here https://kcdevblog.com/post/sitecore-geojson-solr-search/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.