django-haystack ordering - How do I handle this?
Asked Answered
F

2

10

I'm using django-haystack for a search page on my site. I'm basically done, but not quite happy with the ordering and not quite sure how haystack decides how to order everything.

I know I can over-ride the SearchQuerySet by using order_by but that over-rides it entirely. Let's say I want to force the search to order by in stock (BooleanField), so that the products that are in stock show up on top, but then do everything else as it normally would. How do I do that?

I tried doing order_by('-in_stock', 'content') figure content was what it used by default but it produces very different results from if I just leave it to do its own ordering.

Thanks for any input on this matter!

Fenderson answered 8/6, 2010 at 17:49 Comment(0)
P
21

You must have a index in your search_indexes.py with in_stock:

class YourModel(indexes.SearchIndex):
    in_stock = indexes.BooleanField(model_attr='model_in_stock')

and in your urls:

sqs = SearchQuerySet().models(YourModel).order_by('-in_stock', 'score') # score is a field of haystack

In this way, you show the results first if they are in stock and then by score!

Prieto answered 23/6, 2010 at 21:32 Comment(4)
what if my custom field happens to have the same name 'score' ?Expire
is it possible that current version of Haystack doesn't support ordering by score? I've got KeyError: No field named 'score'Impressionist
I just checked the docs and it should still work, could you show me a little more of your code with dpaste.com?Prieto
Small addendum: For me (Haystack v3.2.1, ES v7) it worked with the field named _score (with the underscore). Sorting descendingly with '-_score did exactly what I needed.Jostle
F
3

To sort on a CharField, make it storable, but not indexable.

sorted_name = indexes.CharField(indexed=False, stored=True)

If you need to have it sortable and indexable, use two different fields in the SearchIndex.

Ferullo answered 27/1, 2016 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.