3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.es.searchrequest;
22 import com.google.common.collect.ImmutableSet;
23 import java.util.LinkedHashMap;
24 import java.util.List;
26 import java.util.Objects;
27 import java.util.Optional;
29 import java.util.function.BiPredicate;
30 import java.util.stream.Collectors;
31 import java.util.stream.Stream;
32 import javax.annotation.Nullable;
33 import javax.annotation.concurrent.Immutable;
34 import org.elasticsearch.index.query.BoolQueryBuilder;
35 import org.elasticsearch.index.query.QueryBuilder;
36 import org.sonar.core.util.stream.MoreCollectors;
37 import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope;
39 import static com.google.common.base.Preconditions.checkArgument;
40 import static com.google.common.base.Preconditions.checkState;
41 import static java.util.Objects.requireNonNull;
42 import static java.util.Optional.empty;
43 import static java.util.Optional.of;
44 import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
47 * Computes filters of a given ES search request given all the filters to apply and the top-aggregations to include in
50 * <li>the ones for the query (see {@link #computeQueryFilter(AllFiltersImpl, Map) computeQueryFilter})</li>
51 * <li>the ones to apply as post filters (see {@link #computePostFilters(AllFiltersImpl, Set) computePostFilters})</li>
52 * <li>the ones for each top-aggregation (see {@link #getTopAggregationFilter(TopAggregationDefinition) getTopAggregationFilter})</li>
55 * To be able to provide accurate filters, all {@link TopAggregationDefinition} instances for which
56 * {@link #getTopAggregationFilter(TopAggregationDefinition)} may be called, must all be declared in the constructor.
58 public class RequestFiltersComputer {
60 private final Set<TopAggregationDefinition<?>> topAggregations;
61 private final Map<FilterNameAndScope, QueryBuilder> postFilters;
62 private final Map<FilterNameAndScope, QueryBuilder> queryFilters;
64 public RequestFiltersComputer(AllFilters allFilters, Set<TopAggregationDefinition<?>> topAggregations) {
65 this.topAggregations = ImmutableSet.copyOf(topAggregations);
66 this.postFilters = computePostFilters((AllFiltersImpl) allFilters, topAggregations);
67 this.queryFilters = computeQueryFilter((AllFiltersImpl) allFilters, postFilters);
70 public static AllFilters newAllFilters() {
71 return new AllFiltersImpl();
75 * Any filter of the query which can not be applied to all top-aggregations must be applied as a PostFilter.
77 * A filter with a given {@link FilterScope} can not be applied to the query when at least one sticky top-aggregation
78 * is enabled which has the same {@link FilterScope}.
80 private static Map<FilterNameAndScope, QueryBuilder> computePostFilters(AllFiltersImpl allFilters,
81 Set<TopAggregationDefinition<?>> topAggregations) {
82 Set<FilterScope> enabledStickyTopAggregationtedFieldNames = topAggregations.stream()
83 .filter(TopAggregationDefinition::isSticky)
84 .map(TopAggregationDefinition::getFilterScope)
85 .collect(MoreCollectors.toSet(topAggregations.size()));
87 // use LinkedHashMap over MoreCollectors.uniqueIndex to preserve order and write UTs more easily
88 Map<FilterNameAndScope, QueryBuilder> res = new LinkedHashMap<>();
89 allFilters.internalStream()
90 .filter(e -> enabledStickyTopAggregationtedFieldNames.contains(e.getKey().getFilterScope()))
91 .forEach(e -> checkState(res.put(e.getKey(), e.getValue()) == null, "Duplicate: %s", e.getKey()));
96 * Filters which can be applied directly to the query are only the filters which can also be applied to all
99 * Aggregations are scoped by the filter of the query. If any top-aggregation need to not be applied a filter
100 * (typical case is a filter on the field aggregated to implement sticky facet behavior), this filter can
101 * not be applied to the query and therefor must be applied as PostFilter.
103 private static Map<FilterNameAndScope, QueryBuilder> computeQueryFilter(AllFiltersImpl allFilters,
104 Map<FilterNameAndScope, QueryBuilder> postFilters) {
105 Set<FilterNameAndScope> postFilterKeys = postFilters.keySet();
107 // use LinkedHashMap over MoreCollectors.uniqueIndex to preserve order and write UTs more easily
108 Map<FilterNameAndScope, QueryBuilder> res = new LinkedHashMap<>();
109 allFilters.internalStream()
110 .filter(e -> !postFilterKeys.contains(e.getKey()))
111 .forEach(e -> checkState(res.put(e.getKey(), e.getValue()) == null, "Duplicate: %s", e.getKey()));
116 * The {@link BoolQueryBuilder} to apply directly to the query in the ES request.
118 * There could be no filter to apply to the query in the (unexpected but supported) case where all filters
119 * need to be applied as PostFilter because none of them can be applied to all top-aggregations.
121 public Optional<BoolQueryBuilder> getQueryFilters() {
122 return toBoolQuery(this.queryFilters, (e, v) -> true);
126 * The {@link BoolQueryBuilder} to add to the ES request as PostFilter
127 * (see {@link org.elasticsearch.action.search.SearchRequestBuilder#setPostFilter(QueryBuilder)}).
129 * There may be no PostFilter to apply at all. Typical case is when all filters apply to both the query and
130 * all aggregations. (corner case: when there is no filter at all...)
132 public Optional<BoolQueryBuilder> getPostFilters() {
133 return toBoolQuery(postFilters, (e, v) -> true);
137 * The {@link BoolQueryBuilder} to apply to the top aggregation for the specified {@link SimpleFieldTopAggregationDefinition}.
139 * The filter of the aggregations for a top-aggregation will either be:
141 * <li>the same as PostFilter, if the top-aggregation is non-sticky or none have the same FilterScope as
142 * {@code topAggregation}</li>
143 * <li>or the same as PostFilter minus any filter which applies to the same {@link FilterScope} of
144 * {@code topAggregation}for the (<strong>if it's sticky</strong>)</li>
147 * @throws IllegalArgumentException if specified {@link TopAggregationDefinition} has not been specified in the constructor
149 public Optional<BoolQueryBuilder> getTopAggregationFilter(TopAggregationDefinition<?> topAggregation) {
150 checkArgument(topAggregations.contains(topAggregation), "topAggregation must have been declared in constructor");
153 (e, v) -> !topAggregation.isSticky() || !topAggregation.getFilterScope().intersect(e.getFilterScope()));
156 private static Optional<BoolQueryBuilder> toBoolQuery(Map<FilterNameAndScope, QueryBuilder> queryFilters,
157 BiPredicate<FilterNameAndScope, QueryBuilder> predicate) {
158 if (queryFilters.isEmpty()) {
162 List<QueryBuilder> selectQueryBuilders = queryFilters.entrySet().stream()
163 .filter(e -> predicate.test(e.getKey(), e.getValue()))
164 .map(Map.Entry::getValue)
165 .collect(Collectors.toList());
166 if (selectQueryBuilders.isEmpty()) {
170 BoolQueryBuilder res = boolQuery();
171 selectQueryBuilders.forEach(res::must);
176 * A mean to put together all filters which apply to a given Search request.
178 public interface AllFilters {
181 * @throws IllegalArgumentException if a filter with the specified name has already been added
183 AllFilters addFilter(String name, FilterScope filterScope, @Nullable QueryBuilder filter);
185 Stream<QueryBuilder> stream();
188 private static class AllFiltersImpl implements AllFilters {
190 * Usage of LinkedHashMap only benefits unit tests by providing predictability of the order of the filters.
191 * ES doesn't care of the order.
193 private final Map<FilterNameAndScope, QueryBuilder> filters = new LinkedHashMap<>();
196 public AllFilters addFilter(String name, FilterScope filterScope, @Nullable QueryBuilder filter) {
197 requireNonNull(name, "name can't be null");
198 requireNonNull(filterScope, "filterScope can't be null");
200 if (filter == null) {
205 filters.put(new FilterNameAndScope(name, filterScope), filter) == null,
206 "A filter with name %s has already been added", name);
211 public Stream<QueryBuilder> stream() {
212 return filters.values().stream();
215 private Stream<Map.Entry<FilterNameAndScope, QueryBuilder>> internalStream() {
216 return filters.entrySet().stream();
221 * Serves as a key in internal map of filters, it behaves the same as if the filterName was directly used as a key in
222 * this map but also holds the name of the field each filter applies to.
224 * This saves from using two internal maps.
227 private static final class FilterNameAndScope {
228 private final String filterName;
229 private final FilterScope filterScope;
231 private FilterNameAndScope(String filterName, FilterScope filterScope) {
232 this.filterName = filterName;
233 this.filterScope = filterScope;
236 public FilterScope getFilterScope() {
241 public boolean equals(Object o) {
245 if (o == null || getClass() != o.getClass()) {
248 FilterNameAndScope that = (FilterNameAndScope) o;
249 return filterName.equals(that.filterName);
253 public int hashCode() {
254 return Objects.hash(filterName);