【问题标题】:Django-haystack - how to make only a subset of items be searchable?Django-haystack - 如何仅使项目的一个子集可搜索?
【发布时间】:2014-04-21 20:20:56
【问题描述】:

我有一些项目正在使用 Django-haystack(elasticsearch 后端)进行索引,以便进行搜索。这很好用,但用户可以收藏这些项目,我希望用户能够搜索他们的收藏夹,就像他们能够搜索所有项目一样。收藏夹用多对多直通关系表示,因为我需要记录用户收藏某个项目的时间。有什么方法可以让 haystack 只搜索用户的收藏夹?我不想为每个用户的收藏夹生成单独的索引,因为它们将是冗余的,因为这些项目是相同的并且已经被主索引索引。这是我的模型和搜索索引的样子供参考:

class Gallery(models.Model):   
    faves = models.ManyToManyField(
        User, through='Favorite', null=True, related_name="faves")

class Favorite(models.Model):
    user = models.ForeignKey(User)
    gallery = models.ForeignKey(Gallery)
    date = models.DateField(auto_now_add=True)

    class Meta:
        ordering = ["date"]

class GalleryIndex(indexes.SearchIndex, indexes.Indexable):

    def get_model(self):
        return Gallery

谢谢。

【问题讨论】:

  • 这真的适用于这个用例吗?从我所见,ES 将所有内容存储为平面文档,这是按关系过滤(用户收藏夹中的项目)。我不会将收藏某个项目的用户存储为数组或其他内容,并将其作为索引参数的一部分。我需要能够通过(user.faves 中的对象)之类的东西进行过滤

标签: python django elasticsearch django-haystack


【解决方案1】:

您需要查看 RelatedSearchQuerySet (http://django-haystack.readthedocs.org/en/latest/searchqueryset_api.html#relatedsearchqueryset)。不过,请务必阅读页面上有关性能影响的警告;我刚试过这个,它明显比大多数查询慢。

你会想要这样的:

from django.contrib.auth.models import User
from haystack.query import RelatedSearchQuerySet
from .models import Gallery

u = User.objects.get(...)
sqs = RelatedSearchQuerySet().load_all()
sqs = sqs.load_all_queryset(Gallery, u.faves.all())

这应该会给你一个 SearchQuerySet 只包含用户的收藏夹,你可以进一步过滤和搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    相关资源
    最近更新 更多