Solr Implementaion in Sitecore JSS with Code (Third Blog) All Solr Code And Query
Code to Build Query and get data from Solr
Services Code
So this is implemented in three steps
1. Building the Query using IQueryable
2.Geting the Solr Search Index using ContentSearchManager.GetIndex
3. Creating the Search Context using CreateSearchContext
So here is the basic code to build query and getting the search results.
(In result Solr returns the whole document which contains the internal fields also
so it is important to select the needed field from the queryable.)
Services.CS
using Foundation.Solr.Interface;
using Sitecore.ContentSearch.Linq.Utilities;
using Sitecore.ContentSearch;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
namespace Foundation.Solr.Services
{
public class SearchResultService : ISearchResultService
{
public List<SearchResults> GetSearchResultsService(string searchedText)
{
var result = new List<SearchResults>();
try
{
using (var context = ContentSearchManager.GetIndex("IndexName").CreateSearchContext())
{
var queryable = BuildQueryforSearchText(context, searchedText);
if (queryable != null)
{
queryable = queryable.Select(x => new SearchResults
{
Title = x.Title,
Heading = x.Heading
});
var results = queryable.GetResults();
if (results != null && results.Hits != null && results.Hits.Any())
{
result = results.Hits.Select(x => x.Document).ToList();
}
}
}
}
catch (Exception ex)
{
}
return result;
}
private IQueryable<SearchResults> BuildQueryforSearchText(IProviderSearchContext context, string searchText)
{
IQueryable<SearchResults> queryable = null;
try
{
var builder = PredicateBuilder.True<SearchResults>();
//Add default filters
builder = DefaultEventFilterSample(builder);
if (!string.IsNullOrEmpty(searchText))
{
builder = builder.And(item => item.Title.Contains(searchText));
}
var cultureInfo = new CultureInfo(CultureInfo.GetCultureInfo(Context.Language.Name).Name);
var cultureContext = new CultureExecutionContext(CultureInfo.GetCultureInfo(Context.Language.ToString()));
queryable = context.GetQueryable<SearchResults>(cultureContext).Where(builder)
.OrderBy(asc => asc.Title, StringComparer.Create(cultureInfo, true));
}
catch (Exception ex)
{
}
return queryable;
}
private Expression<Func<SearchResults, bool>> DefaultEventFilterSample(Expression<Func<SearchResults, bool>> builder)
{ public const string TemplateID = "Some-TemplateID-Here"
var template = TemplateID.Replace("{", string.Empty).Replace("}", string.Empty).Replace("-", "").ToLower();
builder = builder.And(item => item.Template == template);
builder = builder.And(item => item.Language == Context.Language.Name);
return builder;
}
Link For Second Part : Solr Blog Second Part
Link For First Part : Solr Blog First Part
Comments
Post a Comment