|
| 1 | +import json |
| 2 | +import logging |
| 3 | + |
| 4 | +from elasticsearch import Elasticsearch |
| 5 | + |
| 6 | +from cumulus_lambda_functions.lib.aws.es_abstract import ESAbstract, DEFAULT_TYPE |
| 7 | + |
| 8 | +LOGGER = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +class ESMiddleware(ESAbstract): |
| 12 | + |
| 13 | + def __init__(self, index, base_url, port=443) -> None: |
| 14 | + if any([k is None for k in [index, base_url]]): |
| 15 | + raise ValueError(f'index or base_url is None') |
| 16 | + self.__index = index |
| 17 | + base_url = base_url.replace('https://', '') # hide https |
| 18 | + self._engine = Elasticsearch(hosts=[{'host': base_url, 'port': port}]) |
| 19 | + |
| 20 | + def __validate_index(self, index): |
| 21 | + if index is not None: |
| 22 | + return index |
| 23 | + if self.__index is not None: |
| 24 | + return self.__index |
| 25 | + raise ValueError('index value is NULL') |
| 26 | + |
| 27 | + def __get_doc_dict(self, docs=None, doc_ids=None, doc_dict=None): |
| 28 | + if doc_dict is None and (docs is None and doc_ids is None): |
| 29 | + raise ValueError('must provide either doc dictionary or doc list & id list') |
| 30 | + if doc_dict is None: # it comes as a list |
| 31 | + if len(docs) != len(doc_ids): |
| 32 | + raise ValueError('length of doc and id is different') |
| 33 | + doc_dict = {k: v for k, v in zip(doc_ids, docs)} |
| 34 | + pass |
| 35 | + return doc_dict |
| 36 | + |
| 37 | + def __check_errors_for_bulk(self, index_result): |
| 38 | + if 'errors' not in index_result or index_result['errors'] is False: |
| 39 | + return |
| 40 | + err_list = [[{'id': v['_id'], 'error': v['error']} for _, v in each.items() if 'error' in v] for each in |
| 41 | + index_result['items']] |
| 42 | + if len(err_list) < 1: |
| 43 | + return |
| 44 | + LOGGER.exception('failed to add some items. details: {}'.format(err_list)) |
| 45 | + return err_list |
| 46 | + |
| 47 | + def create_index(self, index_name, index_body): |
| 48 | + result = self._engine.indices.create(index=index_name, body=index_body, include_type_name=False) |
| 49 | + if 'acknowledged' not in result: |
| 50 | + return result |
| 51 | + return result['acknowledged'] |
| 52 | + |
| 53 | + def has_index(self, index_name): |
| 54 | + result = self._engine.indices.exists(index=index_name) |
| 55 | + return result |
| 56 | + |
| 57 | + def create_alias(self, index_name, alias_name): |
| 58 | + result = self._engine.indices.put_alias(index_name, alias_name) |
| 59 | + if 'acknowledged' not in result: |
| 60 | + return result |
| 61 | + return result['acknowledged'] |
| 62 | + |
| 63 | + def delete_index(self, index_name): |
| 64 | + result = self._engine.indices.delete(index_name) |
| 65 | + if 'acknowledged' not in result: |
| 66 | + return result |
| 67 | + return result['acknowledged'] |
| 68 | + |
| 69 | + def index_many(self, docs=None, doc_ids=None, doc_dict=None, index=None): |
| 70 | + doc_dict = self.__get_doc_dict(docs, doc_ids, doc_dict) |
| 71 | + body = [] |
| 72 | + for k, v in doc_dict.items(): |
| 73 | + body.append({'index': {'_index': index, '_id': k, 'retry_on_conflict': 3}}) |
| 74 | + body.append(v) |
| 75 | + pass |
| 76 | + index = self.__validate_index(index) |
| 77 | + try: |
| 78 | + index_result = self._engine.bulk(index=index, |
| 79 | + body=body, doc_type=DEFAULT_TYPE) |
| 80 | + LOGGER.info('indexed. result: {}'.format(index_result)) |
| 81 | + return self.__check_errors_for_bulk(index_result) |
| 82 | + except: |
| 83 | + LOGGER.exception('cannot add indices with ids: {} for index: {}'.format(list(doc_dict.keys()), index)) |
| 84 | + return doc_dict |
| 85 | + return |
| 86 | + |
| 87 | + def index_one(self, doc, doc_id, index=None): |
| 88 | + index = self.__validate_index(index) |
| 89 | + try: |
| 90 | + index_result = self._engine.index(index=index, |
| 91 | + body=doc, doc_type=DEFAULT_TYPE, id=doc_id) |
| 92 | + LOGGER.info('indexed. result: {}'.format(index_result)) |
| 93 | + pass |
| 94 | + except: |
| 95 | + LOGGER.exception('cannot add a new index with id: {} for index: {}'.format(doc_id, index)) |
| 96 | + return None |
| 97 | + return self |
| 98 | + |
| 99 | + def update_many(self, docs=None, doc_ids=None, doc_dict=None, index=None): |
| 100 | + doc_dict = self.__get_doc_dict(docs, doc_ids, doc_dict) |
| 101 | + body = [] |
| 102 | + for k, v in doc_dict.items(): |
| 103 | + body.append({'update': {'_index': index, '_id': k, 'retry_on_conflict': 3}}) |
| 104 | + body.append({'doc': v, 'doc_as_upsert': True}) |
| 105 | + pass |
| 106 | + index = self.__validate_index(index) |
| 107 | + try: |
| 108 | + index_result = self._engine.bulk(index=index, |
| 109 | + body=body, doc_type=DEFAULT_TYPE) |
| 110 | + LOGGER.info('indexed. result: {}'.format(index_result)) |
| 111 | + return self.__check_errors_for_bulk(index_result) |
| 112 | + except: |
| 113 | + LOGGER.exception('cannot update indices with ids: {} for index: {}'.format(list(doc_dict.keys()), |
| 114 | + index)) |
| 115 | + return doc_dict |
| 116 | + return |
| 117 | + |
| 118 | + def update_one(self, doc, doc_id, index=None): |
| 119 | + update_body = { |
| 120 | + 'doc': doc, |
| 121 | + 'doc_as_upsert': True |
| 122 | + } |
| 123 | + index = self.__validate_index(index) |
| 124 | + try: |
| 125 | + update_result = self._engine.update(index=index, |
| 126 | + id=doc_id, body=update_body, doc_type=DEFAULT_TYPE) |
| 127 | + LOGGER.info('updated. result: {}'.format(update_result)) |
| 128 | + pass |
| 129 | + except: |
| 130 | + LOGGER.exception('cannot update id: {} for index: {}'.format(doc_id, index)) |
| 131 | + return None |
| 132 | + return self |
| 133 | + |
| 134 | + @staticmethod |
| 135 | + def get_result_size(result): |
| 136 | + if isinstance(result['hits']['total'], dict): # fix for different datatype in elastic-search result |
| 137 | + return result['hits']['total']['value'] |
| 138 | + else: |
| 139 | + return result['hits']['total'] |
| 140 | + |
| 141 | + def query_with_scroll(self, dsl, querying_index=None): |
| 142 | + scroll_timeout = '30s' |
| 143 | + index = self.__validate_index(querying_index) |
| 144 | + dsl['size'] = 10000 # replacing with the maximum size to minimize number of scrolls |
| 145 | + params = { |
| 146 | + 'index': index, |
| 147 | + 'size': 10000, |
| 148 | + 'scroll': scroll_timeout, |
| 149 | + 'body': dsl, |
| 150 | + } |
| 151 | + first_batch = self._engine.search(**params) |
| 152 | + total_size = self.get_result_size(first_batch) |
| 153 | + current_size = len(first_batch['hits']['hits']) |
| 154 | + scroll_id = first_batch['_scroll_id'] |
| 155 | + while current_size < total_size: # need to scroll |
| 156 | + scrolled_result = self._engine.scroll(scroll_id=scroll_id, scroll=scroll_timeout) |
| 157 | + scroll_id = scrolled_result['_scroll_id'] |
| 158 | + scrolled_result_size = len(scrolled_result['hits']['hits']) |
| 159 | + if scrolled_result_size == 0: |
| 160 | + break |
| 161 | + else: |
| 162 | + current_size += scrolled_result_size |
| 163 | + first_batch['hits']['hits'].extend(scrolled_result['hits']['hits']) |
| 164 | + return first_batch |
| 165 | + |
| 166 | + def query(self, dsl, querying_index=None): |
| 167 | + index = self.__validate_index(querying_index) |
| 168 | + return self._engine.search(body=dsl, index=index) |
| 169 | + |
| 170 | + def __is_querying_next_page(self, targeted_size: int, current_size: int, total_size: int): |
| 171 | + if targeted_size < 0: |
| 172 | + return current_size > 0 |
| 173 | + return current_size > 0 and total_size < targeted_size |
| 174 | + |
| 175 | + def query_pages(self, dsl, querying_index=None): |
| 176 | + if 'sort' not in dsl: |
| 177 | + raise ValueError('missing `sort` in DSL. Make sure sorting is unique') |
| 178 | + index = self.__validate_index(querying_index) |
| 179 | + targeted_size = dsl['sort'] if 'size' in dsl else -1 |
| 180 | + dsl['size'] = 10000 # replacing with the maximum size to minimize number of scrolls |
| 181 | + params = { |
| 182 | + 'index': index, |
| 183 | + 'size': 10000, |
| 184 | + 'body': dsl, |
| 185 | + } |
| 186 | + LOGGER.debug(f'dsl: {dsl}') |
| 187 | + result_list = [] |
| 188 | + total_size = 0 |
| 189 | + result_batch = self._engine.search(**params) |
| 190 | + result_list.extend(result_batch['hits']['hits']) |
| 191 | + current_size = len(result_batch['hits']['hits']) |
| 192 | + total_size += current_size |
| 193 | + while self.__is_querying_next_page(targeted_size, current_size, total_size): |
| 194 | + params['body']['search_after'] = result_batch['hits']['hits'][-1]['sort'] |
| 195 | + result_batch = self._engine.search(**params) |
| 196 | + result_list.extend(result_batch['hits']['hits']) |
| 197 | + current_size = len(result_batch['hits']['hits']) |
| 198 | + total_size += current_size |
| 199 | + return { |
| 200 | + 'hits': { |
| 201 | + 'hits': result_list, |
| 202 | + 'total': total_size, |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + def query_by_id(self, doc_id): |
| 207 | + index = self.__validate_index(None) |
| 208 | + dsl = { |
| 209 | + 'query': { |
| 210 | + 'term': {'_id': doc_id} |
| 211 | + } |
| 212 | + } |
| 213 | + result = self._engine.search(index=index, body=dsl) |
| 214 | + if self.get_result_size(result) < 1: |
| 215 | + return None |
| 216 | + return result['hits']['hits'][0] |
0 commit comments