Find out if the Solr search service is 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.
Solr search is only for internal use in XM Cloud's UI, and should not be modified. For creating search features, use search tools such as Sitecore Search. For more information on integrating Sitecore Search in your XM Cloud environment, see Integrating Sitecore Search.
For example, the following query normally returns an array with at least 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
ThrowOnErrorExecutionContextexecution context to the following query:RequestResponsevar 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
}