Reputation: 611
I have the following query
var predicate = PredicateBuilder.True<SearchModel>();
predicate = predicate.And(x => (templateIDs.Contains(x.TemplateId))); // To match certain templates only
var products = searchContext.GetQueryable()
.Where(predicate)
.OrderBy(i => i.Title) //will order the items by display
.Take(pageSize); //pageSize is passed through and is an integer
.GetResults();
I never get the results ordered alphabetically.
If I do the following however, the results are ordered correctly.
var fullResults = searchResults.ToList().OrderBy(x=>x.Title).Take(pageSize); //pageSize is passed through and is an integer
Does anyone know why?
And If I do it the second way (.ToList().OrderBy().Take().), would it have any performance implications, as I believe the results will be ordered and paged after the results are fetched from Solr?
Upvotes: 0
Views: 629
Reputation: 704
Sorting in Solr can be a bit confusing. Historically, there has also been some issues around sorting in the ContentSearch provider for Solr, where orderby clauses has been inversed etc. Assuming you're on a fairly recent Sitecore version, these issues has been fixed as far as I know. In order to pinpoint where your problem is, you should look in the search.log and verify that the predicate builder/content search actually performs the query you expect.
Given that the above is ok, you're probably facing a common misunderstanding on how Solr works. I'd guess your Title
field is indexed as a "text" field, such as title_t_en
, and not a string
field. Text fields are tokenized and stemmed before being stored in Solr. Sorting will therefore be performed on the tokenized terms instead of the whole string. This means a text, such as "The quick brown fox jumps over the lazy dog", will be stemmed to something like ["quick", "brown", "fox", "jump", "over", "lazy", "dog"] and an order by statement will sort it on "brown". This may cause the sorting to look very wrong, as the result may not be sorted on the first word in the string.
One way of solving this is to save a copy of your Title field into a title_s
field. You can either do this with a copy statement in the solr schema or if you want to keep the schema untouched, you can make a computed field mapped as a string. Thereby you can perform a lingual text query on the stemmed text field and order the result on the string field.
Upvotes: 1