Django Haystack:模板和模型索引的职责

use*_*688 7 django django-templates django-haystack

我已经浏览了文档,我甚至创建了一些搜索后端,但我仍然对这些事情在haystack中做了什么感到困惑.搜索结束时搜索你在类中继承的字段indices.SearchIndex,indexes.Indexable,或者是后端搜索模板中的文本?有人能解释一下吗?

在django haystack中,您将创建一个类来定义应该查询的字段(以及我理解它的方式),如下所示:

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())
Run Code Online (Sandbox Code Playgroud)

您还将创建一个可以执行某项操作的模板txt - 我不确定是什么.我知道在搜索算法期间搜索后端将覆盖此模板.

{{ 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 %}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,模板有一些我的索引类没有的字段,但搜索后端会搜索这些字段.那么为什么甚至在索引中都有字段呢?索引类的卷和索引模板是什么?有人可以向我解释一下.

Aam*_*nan 7

这ProductIndex是班级的主要内容.Haystack将使用此配置Product根据您选择的索引字段以及以何种方式索引模型.你可以在这里阅读更多相关信息.

您创建的模板将由此字段使用text = indexes.CharField(document=True, use_template=True).在此模板中,我们包含模型或相关模型中的所有重要数据,为什么?因为如果您不想只在一个字段中查找,这用于对所有数据执行搜索查询.

# 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)
Run Code Online (Sandbox Code Playgroud)