Search code examples
djangoelasticsearchdjango-haystack

Combine results of two Haystack query sets


I have two query sets that I get by doing following:

q = Q(is_visible='true')
q |= Q(user='some_user')
q &= Q(text=request.GET.get('query', ''))

sqs1 = SearchQuerySet().filter(q)

sqs2 = SearchQuerySet().models(model.Some).filter(text=request.GET.get('query', ''))

If I just combine these two query sets together, I don't get what I want. Since the elements will have scores evaluated for their particular query. What I want is to somehow combine these two queries before passing them to SearchQuerySet, so that the search backend would calculate the scores for this whole set.

I thought of somehow putting the second query into the Q chain of first query, but I couldn't figure out how can one search just based on the model.


Solution

  • So I've solved this problem by using the following query:

    request_text = request.GET.get('query', '')
    user = request.user
    sqs = SearchQuerySet().filter(text=request_text).exclude(~Q(user='some_user') | Q(is_visible='false')
    

    As it seems, it's possible to rephrase the problem using filter and exclude.