Sorting on chardfields in Haystack and Elasticsearch

23 Mar · by Tim Kamanin · 1 min read

Current version on Haystack (2.10) combined with Elasticsearch produces weird results when you want to sort search results on charfield, the issue has been reported here https://github.com/toastdriven/django-haystack/issues/866 and here: https://github.com/toastdriven/django-haystack/issues/569

Long story short, to fix the problem you need to set indexed=False and stored=True on CharFields that you want to use for sorting.

You should also set indexed=False on BooleanFields (if there are any in the search index model). Here's an example how the correct module would look like:

class BlogIndex(indexes.SearchIndex, indexes.Indexable):
  title = indexes.CharField(model_attr='title')
  sorted_name = indexes.CharField(model_attr='title', indexed=False, stored=True)
  text = indexes.CharField(document=True, use_template=True)
  active = indexes.BooleanField(model_attr='active', indexed=False)
  < ... >

As you see above, we have created two fields for model_attr='title', first is regular, called title, the second one is sorted_name that is used for sorts. We also set Boolean 'active' as non-indexed, however it'll work for your search filters, it just won't get tokenized (yep, strange, but fact).

Comments

Required for comment verification