Browse Source

Rewrite filter queries in FiltersAggregationBuilder (#22076)

Queries must be rewritten before the query phase executes otherwise non-executable queries like `wrapper` query or `terms`  will fail or queries that require resources like script service can't access these service unless rewritten.

Relates to #21303
Artur Nowosielski 8 years ago
parent
commit
726f5dccc0

+ 6 - 1
core/src/main/java/org/elasticsearch/search/aggregations/bucket/filters/FiltersAggregationBuilder.java

@@ -173,7 +173,12 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
     @Override
     protected AggregatorFactory<?> doBuild(AggregationContext context, AggregatorFactory<?> parent, Builder subFactoriesBuilder)
             throws IOException {
-        return new FiltersAggregatorFactory(name, type, filters, keyed, otherBucket, otherBucketKey, context, parent,
+        List<KeyedFilter> rewrittenFilters = new ArrayList<>();
+        for(KeyedFilter kf : filters) {
+            rewrittenFilters.add(new KeyedFilter(kf.key(), QueryBuilder.rewriteQuery(kf.filter(), 
+                    context.searchContext().getQueryShardContext())));
+        }
+        return new FiltersAggregatorFactory(name, type, rewrittenFilters, keyed, otherBucket, otherBucketKey, context, parent,
                 subFactoriesBuilder, metaData);
     }
 

+ 52 - 0
rest-api-spec/src/main/resources/rest-api-spec/test/search.aggregation/60_filters.yaml

@@ -0,0 +1,52 @@
+setup:
+  - do:
+      indices.create:
+          index: test
+          body:
+            settings:
+              number_of_shards: 1
+              number_of_replicas: 0
+            mappings:
+              post:
+                properties:
+                  title:
+                    type: text
+
+  - do:
+        index:
+          index: test
+          type: test
+          id: 1
+          body: { "title" : "foo bar baz" }
+
+  - do:
+      index:
+        index: test
+        type: test
+        id: 2
+        body: { "title" : "foo foo foo" }
+
+  - do:
+      index:
+        index: test
+        type: test
+        id: 3
+        body: { "title" : "bar baz bax" }
+
+  - do:
+      indices.refresh: {}
+
+---
+"Filters aggs with wrapper query":
+  - skip:
+    version: " - 5.1.1"
+    reason:  Using filters aggs that needs rewriting, this was fixed in 5.1.2
+
+  - do:
+      search:
+        body: {"size": 0, "aggs": {"titles": {"filters": {"filters" : {"titleterms" : {"wrapper" : {"query": "eyJ0ZXJtcyIgOiB7ICJ0aXRsZSI6IFsiZm9vIl0gfX0="}}}}}}}
+
+  # validate result
+  - match: { hits.total: 3 }
+  - length: { aggregations.titles.buckets: 1 }
+  - match: { aggregations.titles.buckets.titleterms.doc_count: 2 }