diff --git a/rest-api-spec/src/main/resources/rest-api-spec/test/search.aggregation/40_range.yml b/rest-api-spec/src/main/resources/rest-api-spec/test/search.aggregation/40_range.yml index 80aad96ce1f6b..e97a40733a757 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/test/search.aggregation/40_range.yml +++ b/rest-api-spec/src/main/resources/rest-api-spec/test/search.aggregation/40_range.yml @@ -673,3 +673,49 @@ setup: - match: { aggregations.my_range.buckets.3.from: 1.5 } - is_false: aggregations.my_range.buckets.3.to - match: { aggregations.my_range.buckets.3.doc_count: 2 } + +--- +"Range query and aggregation test": + - do: + bulk: + refresh: true + index: range-agg-w-query + body: + - '{"index": {}}' + - '{"routing": "route1", "v": -10}' + - '{"index": {}}' + - '{"routing": "route1", "v": -5}' + - '{"index": {}}' + - '{"routing": "route1", "v": 10}' + - '{"index": {}}' + - '{"routing": "route2", "v": 15}' + - '{"index": {}}' + - '{"routing": "route2", "v": 20}' + + - do: + search: + index: range-agg-w-query + body: + query: + bool: + must: + match_all: {} + filter: + - terms: + routing: + - "route1" + aggregations: + aggregationName: + range: + field: v + keyed: true + ranges: + - to: 0 + key: "0" + - from: 0 + key: "1" + _source: false + + - match: { hits.total.value: 3 } + - match: { aggregations.aggregationName.buckets.0.doc_count: 2 } + - match: { aggregations.aggregationName.buckets.1.doc_count: 1 } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/filterrewrite/FilterRewriteOptimizationContext.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/filterrewrite/FilterRewriteOptimizationContext.java index 87faafe4526de..f62b0af652052 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/filterrewrite/FilterRewriteOptimizationContext.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/filterrewrite/FilterRewriteOptimizationContext.java @@ -99,12 +99,10 @@ void setRanges(Ranges ranges) { public boolean tryOptimize(final LeafReaderContext leafCtx, final BiConsumer incrementDocCount, boolean segmentMatchAll) throws IOException { segments.incrementAndGet(); - if (!canOptimize) { - return false; - } + if (!canOptimize) return false; + if (!segmentMatchAll) return false; if (leafCtx.reader().hasDeletions()) return false; - PointValues values = leafCtx.reader().getPointValues(aggregatorBridge.fieldType.name()); if (values == null) return false; // only proceed if every document corresponds to exactly one point @@ -120,7 +118,7 @@ public boolean tryOptimize(final LeafReaderContext leafCtx, final BiConsumer