def initialize(self): self.es = AsyncElasticsearch()
class ProductHandler(RequestHandler): def initialize(self): self.es = AsyncElasticsearch() @asynchronous @gen.engine def get(self): start_time = time.time() product_limit = self.get_argument("limit", 1000, True) if product_limit.isdigit(): product_limit = int(product_limit) else: product_limit = 1000 product_offset = self.get_argument("offset", 0, True) if isinstance(product_offset, str) and product_offset.isdigit(): product_offset = int(product_offset) else: product_offset = 0 product_keywords = self.get_argument("keywords", None, True) product_price_min = self.get_argument("priceMin", None, True) if product_price_min and product_price_min.isdigit(): product_price_min = int(product_price_min) product_price_max = self.get_argument("priceMax", None, True) if product_price_max and product_price_max.isdigit(): product_price_max = int(product_price_max) search_query = { "size": product_limit, "from": product_offset, "query": { "filtered": {} }, "partial_fields": { "feed": { "exclude": "float_price" } } } filtered_query = dict() if product_keywords: match_query = {"match": {"_all": { "query": product_keywords, "operator": "or" }}} filtered_query["query"] = match_query if product_price_min or product_price_max: price_range = dict() range_query = { "range": {"float_price": {}} } if product_price_min: price_range["gte"] = product_price_min if product_price_max: price_range["lte"] = product_price_max range_query["range"]["float_price"] = price_range filtered_query["filter"] = range_query if filtered_query: search_query["query"]["filtered"] = filtered_query es_json_response = yield self.es.search(index="products", body=search_query) es_time = es_json_response["took"] products = es_json_response["hits"]["hits"] products_sanitized = [] for product in products: products_sanitized.append(product["fields"]["feed"][0]) #OrderDict the response so we can ensure meta stays on top. res = OrderedDict([ ("meta", {"total": len(products), "time": "0ms", "limit": product_limit, "offset": product_offset}), ("products", products_sanitized) ]) res_time = (time.time() - start_time) res["meta"]["time"] = str(round(res_time * 1000) + es_time) + "ms" self.finish(res)