0

请注意我使用 elasticsearch 作为我的后端。

使用 django 设置,与我的模型 ObjectA 关联的 Taggit 标记似乎没有出现在我的索引中

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

当我使用列出索引文档时

http://localhost:9200/_search

并查看我在数据库中插入的 ObjectA 实例的索引记录,“标签”元素显示为

"tags": []

只有在我跑步之后

manage.py rebuild_index [or update_index]

标签是否出现,即

"tags": ["tag-a", "tag-b"]

有趣的是'title'、'description' 会自动显示而不运行rebuild_index/update_index。

objecta_text.txt

{{ object.title }}
{{ object.description }}
{% for tag in object.tags.all %} {{ tag.name }} {% endfor %}

search_indexes.py

class ObjectAIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')
    description = indexes.CharField(model_attr='description', null=True)
    tags = indexes.MultiValueField()

    def get_model(self):
        return ObjectA

    def prepare_tags(self, obj):
     return [tag.name for tag in obj.tags.all()] 

关于如何在不调用rebuild_index 的情况下让标签显示在索引文档中的任何建议?

4

1 回答 1

1

Not sure if you already figured this out, but the reason your index doesn't contain the tags after save is that they are not yet stored when the signal processor handles the index update. One hacky way to solve this is to extend haystack.signals.RealtimeSignalProcessor to trigger on updates of related models. Here is an example that would update the index for any tagged model.

signals.py

from haystack.signals import RealtimeSignalProcessor


class RelatedRealtimeSignalProcessor(RealtimeSignalProcessor):
    """
    Extension to haystack's RealtimeSignalProcessor not only causing the
    search_index to update on saved model, but also for related effected models
    """

    def handle_save(self, sender, instance, **kwargs):
        super(RelatedRealtimeSignalProcessor, self).handle_save(
            sender,
            instance,
            **kwargs
        )
        self.handle_related(sender, instance)

    def handle_delete(self, sender, instance, **kwargs):
        super(RelatedRealtimeSignalProcessor, self).handle_delete(
            sender,
            instance,
            **kwargs
        )
        self.handle_related(sender, instance)

    def handle_related(self, sender, instance):
        for related in self.get_related_models(sender, instance):
            super(RelatedRealtimeSignalProcessor, self).handle_save(
                related['sender'],
                related['instance']
            )

    def get_related_models(self, sender, instance):
        from taggit.models import TaggedItem

        related = []
        if sender == TaggedItem:
            related.append({
                'sender': instance.content_object.__class__,
                'instance': instance.content_object
            })
        return related

PS. Don't forget to update your HAYSTACK_SIGNAL_PROCESSOR = '<app>.signals.RealtimeSignalProcessor'

于 2014-05-06T17:07:08.967 回答