Sorting on chardfields in Haystack and Elasticsearch

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" title=""> and here:" title=""> 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:

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

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).