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 and here:

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

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials