Find out if the Solr search service is available
Shows how you can decide if an empty Solr search result occurs because the search service is not available.
If the Solr search service is not available when you run a query, the search provider produces a result similar to the result you get when you run a LINQ query against an empty collection. This topic shows how you can decide if an the empty result occurs because the search service is not available.
For example, the following query normally returns an array with at leat one element:
var result = context.GetQueryable<SearchResultItem>()
.Where(it => it.Content == "sitecore").ToArray();
However, if the Solr instance is not available when you run the query, the query returns an empty array. The same happens for other LINQ methods, such as .First()
:
var result = context.GetQueryable<SearchResultItem>()
.Where(it => it.Content == "sitecore").First();
Normally, this query returns a first element that matches the search query. However, if the Solr instance is not available when you run the query, the query raises the InvalidOperationException("Sequence contains no elements.")
exception. This is the standard behavior of the First()
method with an empty result.
You sometimes need to distinguish between the reasons a search query produces an empty result: is the result really empty, or it is because the search service is not available?
To find out if the Solr search service is not available:
-
Pass an instance of the
ThrowOnErrorExecutionContext
execution context to the following query:RequestResponseshellvar result = context.GetQueryable<SearchResultItem>(new ThrowOnErrorExecutionContext()) .Where(it => it.Content == "sitecore").ToArray();
When you apply the ThrowOnErrorExecutionContext
context to the query, the LINQ query returns results as in the previous examples under normal conditions. However, if the Solr instance is not available, the search provider throws a SearchServiceUnavailableException
exception that you can catch and handle:
var queryable = context.GetQueryable<SearchResultItem>(new ThrowOnErrorExecutionContext());
try
{
var result = queryable.Where(it => it.Content == "sitecore").ToArray();
}
catch (SearchServiceUnavailableException ex)
{
// Handle unavailable search service
}