Python elasticsearch-dsl django pagination

后端 未结 4 468
长发绾君心
长发绾君心 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:24

    Another way forward is to create a proxy between the Paginator and the Elasticsearch query. Paginator requires two things, __len__ (or count) and __getitem__ (that takes a slice). A rough version of the proxy works like this:

    class ResultsProxy(object):
        """
        A proxy object for returning Elasticsearch results that is able to be
        passed to a Paginator.
        """
    
        def __init__(self, es, index=None, body=None):
            self.es = es
            self.index = index
            self.body = body
    
        def __len__(self):
            result = self.es.count(index=self.index,
                                   body=self.body)
            return result['count']
    
        def __getitem__(self, item):
            assert isinstance(item, slice)
    
            results = self.es.search(
                index=self.index,
                body=self.body,
                from_=item.start,
                size=item.stop - item.start,
            )
    
            return results['hits']['hits']
    

    A proxy instance can be passed to Paginator and will make requests to ES as needed.

提交回复
热议问题