使用Elasticsearch过滤搜索

时间:2018-11-14 13:22:23

标签: python django elasticsearch

我的项目是一种搜索工具,可以按问题和/或响应进行搜索。我希望它也能够通过例如过滤搜索主题,客户。每个响应都使用外键映射到问题,主题和客户。

我能够按问题和答案进行搜索,但是当我添加过滤器主题(下拉列表)时,它将返回0个结果。

models.py:

class Topic(models.Model):
    Definition = models.TextField(default='Definition')
    Name = models.TextField(default='Name')
    class Meta:
        ordering = ['Name']
    def __str__(self):
        return self.Name

class Question(models.Model):
    Statement = models.TextField()
    def __str__(self):
        return self.Statement

class Response(models.Model):
    Question = models.ForeignKey(Question, on_delete=models.CASCADE)
    Topic = models.ForeignKey(Topic, default=13, on_delete=models.CASCADE)
    Response = models.TextField()
    Client = models.ForeignKey(ClientDetail, default=8, on_delete=models.CASCADE)
    Planit_location = models.ForeignKey(Planit_location, default=1, on_delete=models.CASCADE)
    Date_added = models.DateField(default=datetime.date.today)

    def __str__(self):
        return self.Response

documents.py:

class ResponseDocument20(DocType):
    Question = fields.NestedField(properties={
        'Statement': fields.TextField(),
        'pk': fields.IntegerField(),
    }, include_in_root=True)
    class Meta:
        model = Response

    fields = [
        'Response'
    ]
    related_models = [Question]

    def get_instances_from_related(self, related_instance):
        if isinstance(related_instance, Question):
            return related_instance.response_set.all()

views.py:

if q:#ES
    cleanQ = stopwords.strip_stopwords(q)
    if (queryR == "questions"):
        if (queryT != "empty"):
            responses = ResponseDocument20.search().filter(Q_ES("match", Question__Statement=cleanQ.lower())&Q_ES("match", Topic__Name=queryT)).extra(size=10000)
        else:
            responses = ResponseDocument20.search().query("match", Question__Statement=cleanQ.lower()).extra(size=10000) #ES

我假设我只需要添加Topic__Name = queryT即可按主题过滤搜索,这将为我提供与搜索输入和主题匹配的结果。

0 个答案:

没有答案