Python elasticsearch-dsl django pagination

后端 未结 4 469
长发绾君心
长发绾君心 2021-01-02 04:35

How can i use django pagination on elasticsearch dsl. My code:

query = MultiMatch(query=q, fields=[\'title\', \'body\'], fuzziness=\'AUTO\')

s = Search(usin         


        
4条回答
  •  灰色年华
    2021-01-02 05:28

    Following the advice from Danielle Madeley, I also created a proxy to search results which works well with the latest version of django-elasticsearch-dsl==0.4.4.

    from django.utils.functional import LazyObject
    
    class SearchResults(LazyObject):
        def __init__(self, search_object):
            self._wrapped = search_object
    
        def __len__(self):
            return self._wrapped.count()
    
        def __getitem__(self, index):
            search_results = self._wrapped[index]
            if isinstance(index, slice):
                search_results = list(search_results)
            return search_results
    

    Then you can use it in your search view like this:

    paginate_by = 20
    search = MyModelDocument.search()
    # ... do some filtering ...
    search_results = SearchResults(search)
    
    paginator = Paginator(search_results, paginate_by)
    page_number = request.GET.get("page")
    try:
        page = paginator.page(page_number)
    except PageNotAnInteger:
        # If page parameter is not an integer, show first page.
        page = paginator.page(1)
    except EmptyPage:
        # If page parameter is out of range, show last existing page.
        page = paginator.page(paginator.num_pages)
    

    Django's LazyObject proxies all attributes and methods from the object assigned to the _wrapped attribute. I am overriding a couple of methods that are required by Django's paginator, but don't work out of the box with the Search() instances.

提交回复
热议问题