I am using ElasticSearch in my Python application and want to be able to create a reusable dictionary object that represents the query. JSON structures are described here http://pulkitsinghal.blogspot.co.uk/2012/02/how-to-use-elasticsearch-query-dsl.html and I use PyES to query the search server. With PyES, we can pass a dict object that gets jsonified before sending it to the server. I want to create a library of general queries in which only the actual term of the request changes, so I thought that I would subclass the dict so that I could, for example, pass the request to the term through the constructor, and when the dict gets jsonified, I end up with something like of this:
{
"fields": [
"name",
"shortDescription",
"longDescription"
],
"query": {
"query_string": {
"fields": [
"name"
],
"query": query_term,
"use_dis_max": true
}
}
}
? , __dict__, ? , , dict, to_dict(), ?
:
, , , "pythonic" ! (, , )
class StandardQuery(object):
search_fields = ['meta_keywords', 'meta_description', \
'fields.title.value', 'slug']
return_fields = ['slug', 'fields.title.value']
def __init__(self, query):
self.query = query
def to_dict(self):
output = dict()
output['fields'] = self.search_fields
output['query'] = {'query_string': {'fields': self.return_fields, \
'query': self.query, 'use_dis_max': True}}
return output