def get_basic_search_query( entity, term, permission_filters_by_entity=None, offset=0, limit=100, fields_to_exclude=None, fuzzy=False, ): """ Performs basic search for the given term in the given entity using the SEARCH_FIELDS. It also returns number of results in other entities. :param permission_filters_by_entity: List of pairs of entities and corresponding permission filters. Only entities in this list are included in the results, and those are entities are also filtered using the corresponding permission filters. """ limit = _clip_limit(offset, limit) search_apps = tuple(get_global_search_apps_as_mapping().values()) indices = [app.search_model.get_read_alias() for app in search_apps] fields = set(chain.from_iterable(app.search_model.SEARCH_FIELDS for app in search_apps)) # Sort the fields so that this function is deterministic # and the same query is always generated with the same inputs fields = sorted(fields) query = _build_term_query(term, fields=fields, fuzzy=fuzzy) search = Search(index=indices).query(query) permission_query = _build_global_permission_query(permission_filters_by_entity) if permission_query: search = search.filter(permission_query) search = search.post_filter( Bool( should=Term(_document_type=entity.get_app_name()), ), ).sort( '_score', 'id', ).source( excludes=fields_to_exclude, ).extra( track_total_hits=True, ) search.aggs.bucket( 'count_by_type', 'terms', field='_document_type', ) return search[offset:offset + limit]
def _get_global_search_permission_filters(request): """ Gets the permissions filters that should be applied to each search entity (to enforce permissions) in global search. Only global search entities that the user has access to are returned. """ for app in get_global_search_apps_as_mapping().values(): if not has_permissions_for_app(request.user, app): continue filter_args = app.get_permission_filters(request) yield (app.es_model.get_app_name(), filter_args)
def to_internal_value(self, data): """Translates a model name to a model.""" global_search_models = get_global_search_apps_as_mapping() if data not in global_search_models: self.fail('invalid_choice', input=data) return global_search_models[data].es_model