Question

I've gone over the docs, and I've even created a few search back ends, but I"m still really confused on what these things do in haystack. Is the search back end searching the fields you put in your class that inherits indexes.SearchIndex, indexes.Indexable, or is the back end searching the text inside your template? Can someone explain this to me?

In django haystack you will create a class that defines what fields should be queried (well that's how I understand it) like so:

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='title', boost=1.75)
    description = indexes.CharField(model_attr='description')
    short_description = indexes.CharField(model_attr='short_description')

    def get_model(self):
        return Product

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.filter(active=True,
                                           published_at__lte=datetime.now())

You'll also create a template txt that will do something - I"m not sure what. I know that the search backend will go over this template during the searching algorithm.

{{ object.name }}
{{ object.description }}
{{ object.short_description }}
{% for related in object.related %}
    {{ related.name }}
    {{ related.description }}
{% endfor %}

{% for category in object.categories.all %}
    {% if category.active %}
        {{ category.name }}
    {% endif %}
{% endfor %}

As you can see the template has some fields that my index class doesn't have, however, these will be searched by the search backend. So why even have fields in the index? What are the rolls of the index class, and the index template? Can someone please explain this to me.

Was it helpful?

Solution

The ProductIndex class is the main thing here. Haystack will use this configuration to index your Product model according to the fields you have chosen to be indexed and in what way. You can read more about it here.

The template which you have created will be used by this field text = indexes.CharField(document=True, use_template=True). In this template we include every important data from model or related models, why? because this is used to perform search query on all data if you don't want to lookup in just one field.

# filtering on single field
qs = SearchQuerySet().models(Product).filter(name=query)

# filtering on multiple fields
qs = SearchQuerySet().models(Product).filter(name=query).filter(description=query)

# filtering on all data where ever there is a match
qs = SearchQuerySet().models(Product).filter(text=query)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top