Suppose I have a Person model looking like this:
class Person(models.Model):
title = models.CharField(max_length=300, blank=True, null=True)
first_name = models.CharField(max_length=300, blank=True, null=True)
last_name = models.CharField(max_length=300, blank=False, null=False)
And a Haystack search index like this:
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
first_name = indexes.CharField(model_attr='first_name')
last_name = indexes.CharField(model_attr='last_name')
Say the template includes all three fields(firstname, lastname and title). If users should be able to choose in which fields to search for, do I need to build seperate indices for all possible permutations? Or can I narrow down the search to one or two of the three fields?
If so how?
I know that I am able to filter SearchQuerySets using .filter().
SearchQuerySet().filter(first_name='foo')
But this filters the set for exact values. Even __icontains
is limited to one field filtering.
You can use AutoQuery
instead of the standard filter
:
from haystack.inputs import AutoQuery
SearchQuerySet().filter(first_name=AutoQuery('foo'))
https://django-haystack.readthedocs.io/en/v2.4.1/inputtypes.html#autoquery
EDITED In order to run OR query with "haystack" use SQ objects:
from haystack.backends import SQ
from haystack.inputs import AutoQuery
SearchQuerySet().filter(
SQ(first_name=AutoQuery('foo')) | SQ(last_name=AutoQuery('foo'))
)
https://django-haystack.readthedocs.io/en/v2.4.1/searchquery_api.html#sq-objects