def query_entity(index, entity_id=None, name=None, department=None, state=None,
max=None, order=None, fields=[], flatten=False):
"""Busca entidades políticas (localidades, departamentos, o provincias)
según parámetros de búsqueda de una consulta.
Args:
index (str): Nombre del índice sobre el cual realizar la búsqueda.
name (str): Nombre del tipo de entidad (opcional).
department (str): ID o nombre de departamento para filtrar (opcional).
state (str): ID o nombre de provincia para filtrar (opcional).
max (int): Limita la cantidad de resultados (opcional).
order (str): Campo por el cual ordenar los resultados (opcional).
fields (list): Campos a devolver en los resultados (opcional).
Returns:
list: Resultados de búsqueda de entidades.
"""
terms = []
sorts = {}
if entity_id:
condition = build_condition(ID, entity_id)
terms.append(condition)
if name:
condition = build_condition(NAME, name, fuzzy=True)
terms.append(condition)
if department:
if department.isdigit():
condition = build_condition(DEPT_ID, department)
else:
condition = build_condition(DEPT_NAME, department, fuzzy=True)
terms.append(condition)
if state:
if state.isdigit():
condition = build_condition(STATE_ID, state)
else:
if len(state.split()) == 1:
condition = build_condition(STATE_NAME, state, fuzzy=True)
else:
condition = build_condition(STATE_NAME, state,
kind='match_phrase_prefix')
terms.append(condition)
if order:
if ID in order: sorts[ID_KEYWORD] = {'order': 'asc'}
if NAME in order: sorts[NAME_KEYWORD] = {'order': 'asc'}
query = {'query': {'bool': {'must': terms}} if terms else {"match_all": {}},
'size': max or 10, 'sort': sorts, '_source': fields}
try:
result = Elasticsearch().search(index=index, body=query)
except ElasticsearchException as error:
return []
return [parse_entity(hit, flatten) for hit in result['hits']['hits']]
评论列表
文章目录