Skip to content

Commit

Permalink
Fix #15 Payload and ResultSet got "get_values" method
Browse files Browse the repository at this point in the history
  • Loading branch information
rochacbruno committed Jan 13, 2016
1 parent 4cb0519 commit b595b33
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
24 changes: 23 additions & 1 deletion esengine/bases/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import time
import copy
import elasticsearch.helpers as eh
from six import text_type


class ResultSet(object):
Expand Down Expand Up @@ -93,8 +94,29 @@ def to_dict(self, *args, **kwargs):
"""
return [item.to_dict(*args, **kwargs) for item in self.values]

def get_values(self, *fields):
"""
if args is only one field .get_values('id') return a list of lists
[123, 456, 789]
If args is more than one field return a list of tuples
.get_values("id", "name")
[(123, "John"), (789, "mary"), ...]
:param fields: a list of fields
:return:
"""
if not fields:
raise AttributeError("At least one field is required")

if len(fields) > 1:
return [
tuple(getattr(value, field) for field in fields)
for value in self.values
]
else:
return [getattr(value, fields[0]) for value in self.values]

def __unicode__(self):
return unicode(self.__unicode__())
return text_type(self.__unicode__())

def __str__(self):
return "<ResultSet: {i.values}>".format(i=self)
28 changes: 28 additions & 0 deletions esengine/utils/payload/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,31 @@ def count(self, model=None, **kwargs):

def paginate(self, page=1, per_page=10):
return Pagination(iterable=self, page=page, per_page=per_page)

def get_values(self, *fields, **kwargs):
"""
if args is only one field .get_values('id') return a list of lists
[123, 456, 789]
If args is more than one field return a list of tuples
.get_values("id", "name")
[(123, "John"), (789, "mary"), ...]
:param kwargs: Document class
:param fields: a list of fields
:return:
"""

values = [
hit.get('_source')
for hit in self.search(_source=fields, **kwargs)._hits
]

if not fields:
raise AttributeError("At least one field is required")

if len(fields) > 1:
return [
tuple(value.get(field) for field in fields)
for value in values
]
else:
return [value.get(fields[0]) for value in values]

0 comments on commit b595b33

Please sign in to comment.