I encounter strange behaviour in constructor of a python class:
class MetricQuery():
query = None
def __init__(self, query = None):
self.query = query
@classmethod
def sum(self, field, response_field = None):
self.es_query = basic_aggregation("sum", field, response_field)
return self
@classmethod
def get(self):
output = self.es_query
if self.query != None: output["query"] = self.query["query"]
return output
Here's the test method for sum:
def test_sum():
query = {"query": {"match": {"active": True}}}
assert MetricQuery(query).sum("visits").get() == {"query": {"match": {"active": True}},"aggs": {"sum_visits_field": {"sum": {"field": "visits"}}}}
Test fails, saying that right contains 1 more item, "query".
It seems constructor can't set query value properly. What am I missing?
CodePudding user response:
It looks like there is a missing quotation mark at the end of the definition of query in your test method:
Your Code query = {"query": {"match": {"active": True}}
This should be: query = {"query": {"match": {"active": True}}}
This is causing a syntax error, and as a result, the value of the query is not being set correctly.
If you fix this syntax error, your test should pass.
CodePudding user response:
As @jasonharper mentioned in the comment, I confused classmethod and a regular method. (I'm new to python)
I removed all classmethod definitions and call the class as follows (to write a one line code):
def test_avg():
assert (MetricQuery()).avg("age", "my_result_field").get() == {"aggs": {"my_result_field": {"avg": {"field": "age"}}}}
Now all works fine.
I develop an Elasticsearch aggregation library, hope it'll be useful when I can complete.