-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpagination.py
83 lines (71 loc) · 2.28 KB
/
pagination.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
"""
pagination.py
:copyright: (c) 2015 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
from nereid.contrib.pagination import BasePagination
from trytond.pool import Pool
from werkzeug.utils import cached_property
class ElasticPagination(BasePagination):
"""
Specialized paginator class for Elasticsearch result sets. It takes a
`~pyes.query.Search` object and performs the search using pagination
capabilities.
"""
def __init__(self, model, search_obj, page, per_page):
"""
:param model: Name of the tryton model on which the pagination is
happening.
:param search_obj: The `~pyes.query.Search` object
:param page: The page number
:param per_page: Items per page
"""
self.model_name = model
self.search_obj = search_obj
super(ElasticPagination, self).__init__(page, per_page)
@property
def model(self):
return Pool().get(self.model_name)
@cached_property
def result_set(self):
"""
Generates the `~pyes.es.ResultSet` object after performing the search.
"""
config = Pool().get('elasticsearch.configuration')(1)
conn = config.get_es_connection(timeout=5)
return conn.search(
self.search_obj,
start=self.offset,
size=self.per_page,
doc_types=[config.make_type_name(self.model_name)]
)
@property
def count(self):
"""
Returns the total count of matched records.
"""
return self.result_set.count()
def items(self):
"""
Returns items on the current page.
"""
return self.model.browse(
map(lambda p: p.id, self.result_set)
)
def all_items(self):
"""
Returns all items.
"""
config = Pool().get('elasticsearch.configuration')(1)
conn = config.get_es_connection(timeout=5)
return self.model.browse(
map(
lambda p: p.id, conn.search(
self.search_obj,
doc_types=[
config.make_type_name(self.model_name)
]
)
)
)