弹性搜索结果按用户过滤

时间:2017-03-02 01:02:06

标签: django elasticsearch elasticsearch-dsl elasticsearch-dsl-py

我使用elasticsearch_dsl效果很好。

但是,我希望结果根据发送的用户令牌进行过滤。

我尝试过使用rest_frameworks'过滤器,但没有成功。

实现这一目标的正确方法是什么?

访问结果的URL

http://localhost:9200/_search

Models.py

class Task(models.Model):
    title = models.CharField("Title", max_length=10000, blank=True)
    owner = models.ForeignKey('auth.User', blank=True, null=True)

Search.py​​

from rest_framework import filters
connections.create_connection()

class TaskIndex(DocType):
    title = String()
    class Meta:
        index = 'task-index'

    def filter_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)


def bulk_indexing():
    TaskIndex.init()
    es = Elasticsearch()
    bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator()))


def _search(title):
    s = Search().filter('term', title=title.text)
    response = s.execute()
    return response

1 个答案:

答案 0 :(得分:-1)

只需修改_search功能,即可按用户进行过滤。我不知道你在ES中存储用户的格式,但它应该是这样的:

from elasticsearch_dsl.query import Q

def _search(title, user):
    s = Search().query('bool', must=[ 
        Q('term', title=title.text),
        Q('match', owner=user.pk),
    ])
    return s.execute()