-1

I'm having trouble in resolving Haystack queries using SQ, objects. If I'm performing the same query but using Django ORM and it's Q objects, everything works fine.

I can't figure out what I'm doing wrong here since Haystach documentation states that SQ objects are similar to Q ones. Any help is much appreciated. Thanks!

Here's the code I have:

class PublicationSearch(object):


    def __init__(self, search_data):
        self.__dict__.update(search_data)


    def search_all_words(self, sq):

        if self.all_words:
            words = self.all_words.split()
            title_sq = SQ()
            full_text_sq = SQ()

            for word in words:
                title_sq = title_sq | SQ(title__icontains=word)
                full_text_sq = full_text_sq | SQ(full_text__icontains=word)
            keyword_sq = title_sq | full_text_sq
            sq = sq & keyword_sq

        return sq


class AdvancedPublicationForm(AdvancedPublicationBaseForm):


    def search(self):

        cleaned_data = super(AdvancedPublicationForm, self).clean()

        # if no query word was submitted, return an empty sqs
        if not any(cleaned_data.itervalues()):
            return self.no_query_found()

        results = self.build_results(cleaned_data)

        return results


    def build_results(self, search_data):

        sq = SQ()
        results = None
        searcher = PublicationSearch(search_data)

        for key in search_data.iterkeys():
            dispatch = getattr(searcher, 'search_%s' % key)
            sq = dispatch(sq)

        if sq and len(sq):
            results = SearchQuerySet().models(Publication).add(sq)

        else:
            results = []
        return results

The query for a sample of two words is looking like this:

(AND: (OR: (AND: ), ('title__icontains', u'casamento'), ('title__icontains', u'civil'), (AND: ), ('full_text__icontains', u'casamento'), ('full_text__icontains', u'civil')))

And the error returned:

Failed to query Elasticsearch using '( OR title:(casamento) OR title:(civil) OR  OR full_text:(casamento) OR full_text:(civil))'
jabez
  • 896
  • 1
  • 9
  • 22

1 Answers1

0

I manage to find the way. Refactoring to look like below.

title_sq.add(SQ(title__icontains=word), SQ.OR)
full_text_sq.add(SQ(full_text__icontains=word), SQ.OR)
jabez
  • 896
  • 1
  • 9
  • 22