Răsfoiți Sursa

Minor cleanup of org.elasticsearch.aggregations package (#102622)

* Convert Collections.sort() to List.sort()
* Use Map.computeIfAbsent()
* Use primitive double over Double
* Replace some lambdas with method references.
* Replaces for loops with index variable to use foreach iteration style for loops.
Martijn van Groningen 1 an în urmă
părinte
comite
850e88c589
19 a modificat fișierele cu 47 adăugiri și 84 ștergeri
  1. 2 3
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/AdjacencyMatrixAggregationBuilder.java
  2. 3 10
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/InternalAdjacencyMatrix.java
  3. 1 5
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/ParsedAdjacencyMatrix.java
  4. 3 4
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java
  5. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregator.java
  6. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregatorFactory.java
  7. 8 24
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/InternalAutoDateHistogram.java
  8. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/ArrayValuesSource.java
  9. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/ParsedMatrixStats.java
  10. 7 9
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/RunningStats.java
  11. 3 3
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/BucketSelectorPipelineAggregator.java
  12. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/BucketSortPipelineAggregationBuilder.java
  13. 1 1
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/MovFnPipelineAggregationBuilder.java
  14. 1 6
      modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/MovFnPipelineAggregator.java
  15. 1 2
      modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/adjacency/InternalAdjacencyMatrixTests.java
  16. 1 1
      modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/timeseries/TimeSeriesAggregatorTests.java
  17. 6 6
      modules/aggregations/src/test/java/org/elasticsearch/aggregations/metric/MultiPassStats.java
  18. 1 1
      modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/BucketSortPipelineAggregationBuilderTests.java
  19. 4 4
      modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/DerivativeAggregatorTests.java

+ 2 - 3
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/AdjacencyMatrixAggregationBuilder.java

@@ -30,7 +30,6 @@ import org.elasticsearch.xcontent.XContentParser;
 
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
@@ -152,14 +151,14 @@ public class AdjacencyMatrixAggregationBuilder extends AbstractAggregationBuilde
         }
         // internally we want to have a fixed order of filters, regardless of
         // the order of the filters in the request
-        Collections.sort(this.filters, Comparator.comparing(KeyedFilter::key));
+        this.filters.sort(Comparator.comparing(KeyedFilter::key));
     }
 
     private AdjacencyMatrixAggregationBuilder setFiltersAsList(List<KeyedFilter> filters) {
         this.filters = new ArrayList<>(filters);
         // internally we want to have a fixed order of filters, regardless of
         // the order of the filters in the request
-        Collections.sort(this.filters, Comparator.comparing(KeyedFilter::key));
+        this.filters.sort(Comparator.comparing(KeyedFilter::key));
         return this;
     }
 

+ 3 - 10
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/InternalAdjacencyMatrix.java

@@ -20,7 +20,6 @@ import org.elasticsearch.xcontent.XContentBuilder;
 
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.List;
@@ -181,11 +180,7 @@ public class InternalAdjacencyMatrix extends InternalMultiBucketAggregation<Inte
         for (InternalAggregation aggregation : aggregations) {
             InternalAdjacencyMatrix filters = (InternalAdjacencyMatrix) aggregation;
             for (InternalBucket bucket : filters.buckets) {
-                List<InternalBucket> sameRangeList = bucketsMap.get(bucket.key);
-                if (sameRangeList == null) {
-                    sameRangeList = new ArrayList<>(aggregations.size());
-                    bucketsMap.put(bucket.key, sameRangeList);
-                }
+                List<InternalBucket> sameRangeList = bucketsMap.computeIfAbsent(bucket.key, k -> new ArrayList<>(aggregations.size()));
                 sameRangeList.add(bucket);
             }
         }
@@ -198,11 +193,9 @@ public class InternalAdjacencyMatrix extends InternalMultiBucketAggregation<Inte
             }
         }
         reduceContext.consumeBucketsAndMaybeBreak(reducedBuckets.size());
-        Collections.sort(reducedBuckets, Comparator.comparing(InternalBucket::getKey));
+        reducedBuckets.sort(Comparator.comparing(InternalBucket::getKey));
 
-        InternalAdjacencyMatrix reduced = new InternalAdjacencyMatrix(name, reducedBuckets, getMetadata());
-
-        return reduced;
+        return new InternalAdjacencyMatrix(name, reducedBuckets, getMetadata());
     }
 
     @Override

+ 1 - 5
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/adjacency/ParsedAdjacencyMatrix.java

@@ -48,11 +48,7 @@ public class ParsedAdjacencyMatrix extends ParsedMultiBucketAggregation<ParsedAd
         ParsedAdjacencyMatrix::new
     );
     static {
-        declareMultiBucketAggregationFields(
-            PARSER,
-            parser -> ParsedBucket.fromXContent(parser),
-            parser -> ParsedBucket.fromXContent(parser)
-        );
+        declareMultiBucketAggregationFields(PARSER, ParsedBucket::fromXContent, ParsedBucket::fromXContent);
     }
 
     public static ParsedAdjacencyMatrix fromXContent(XContentParser parser, String name) throws IOException {

+ 3 - 4
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java

@@ -173,7 +173,7 @@ public class AutoDateHistogramAggregationBuilder extends ValuesSourceAggregation
     public AutoDateHistogramAggregationBuilder setMinimumIntervalExpression(String minimumIntervalExpression) {
         if (minimumIntervalExpression != null && ALLOWED_INTERVALS.containsValue(minimumIntervalExpression) == false) {
             throw new IllegalArgumentException(
-                MINIMUM_INTERVAL_FIELD.getPreferredName() + " must be one of [" + ALLOWED_INTERVALS.values().toString() + "]"
+                MINIMUM_INTERVAL_FIELD.getPreferredName() + " must be one of [" + ALLOWED_INTERVALS.values() + "]"
             );
         }
         this.minimumIntervalExpression = minimumIntervalExpression;
@@ -210,9 +210,8 @@ public class AutoDateHistogramAggregationBuilder extends ValuesSourceAggregation
         int maxRoundingInterval = Arrays.stream(roundings, 0, roundings.length - 1)
             .map(rounding -> rounding.innerIntervals)
             .flatMapToInt(Arrays::stream)
-            .boxed()
             .reduce(Integer::max)
-            .get();
+            .getAsInt();
         Settings settings = context.getIndexSettings().getNodeSettings();
         int maxBuckets = MultiBucketConsumerService.MAX_BUCKET_SETTING.get(settings);
         int bucketCeiling = maxBuckets / maxRoundingInterval;
@@ -287,7 +286,7 @@ public class AutoDateHistogramAggregationBuilder extends ValuesSourceAggregation
             this.innerIntervals = innerIntervals;
             Objects.requireNonNull(dateTimeUnit, "dateTimeUnit cannot be null");
             if (ALLOWED_INTERVALS.containsKey(dateTimeUnit) == false) {
-                throw new IllegalArgumentException("dateTimeUnit must be one of " + ALLOWED_INTERVALS.keySet().toString());
+                throw new IllegalArgumentException("dateTimeUnit must be one of " + ALLOWED_INTERVALS.keySet());
             }
             this.dateTimeUnit = ALLOWED_INTERVALS.get(dateTimeUnit);
         }

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregator.java

@@ -479,7 +479,7 @@ abstract class AutoDateHistogramAggregator extends DeferableBucketAggregator {
 
                 /**
                  * Increase the rounding of {@code owningBucketOrd} using
-                 * estimated, bucket counts, {@link #rebucket() rebucketing} the all
+                 * estimated, bucket counts, {@link FromMany#rebucket() rebucketing} the all
                  * buckets if the estimated number of wasted buckets is too high.
                  */
                 private int increaseRoundingIfNeeded(long owningBucketOrd, int oldEstimatedBucketCount, long newKey, int oldRounding) {

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregatorFactory.java

@@ -74,7 +74,7 @@ public final class AutoDateHistogramAggregatorFactory extends ValuesSourceAggreg
 
     private final AutoDateHistogramAggregatorSupplier aggregatorSupplier;
     private final int numBuckets;
-    private RoundingInfo[] roundingInfos;
+    private final RoundingInfo[] roundingInfos;
 
     public AutoDateHistogramAggregatorFactory(
         String name,

+ 8 - 24
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/InternalAutoDateHistogram.java

@@ -422,30 +422,14 @@ public final class InternalAutoDateHistogram extends InternalMultiBucketAggregat
         return new InternalAutoDateHistogram.Bucket(buckets.get(0).key, docCount, format, aggs);
     }
 
-    private static class BucketReduceResult {
-        final List<Bucket> buckets;
-        final int roundingIdx;
-        final long innerInterval;
-        final Rounding.Prepared preparedRounding;
-        final long min;
-        final long max;
-
-        BucketReduceResult(
-            List<Bucket> buckets,
-            int roundingIdx,
-            long innerInterval,
-            Rounding.Prepared preparedRounding,
-            long min,
-            long max
-        ) {
-            this.buckets = buckets;
-            this.roundingIdx = roundingIdx;
-            this.innerInterval = innerInterval;
-            this.preparedRounding = preparedRounding;
-            this.min = min;
-            this.max = max;
-        }
-    }
+    private record BucketReduceResult(
+        List<Bucket> buckets,
+        int roundingIdx,
+        long innerInterval,
+        Rounding.Prepared preparedRounding,
+        long min,
+        long max
+    ) {}
 
     private BucketReduceResult addEmptyBuckets(BucketReduceResult current, AggregationReduceContext reduceContext) {
         List<Bucket> list = current.buckets;

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/ArrayValuesSource.java

@@ -19,7 +19,7 @@ import java.util.Map;
  * Class to encapsulate a set of ValuesSource objects labeled by field name
  */
 public abstract class ArrayValuesSource<VS extends ValuesSource> {
-    protected MultiValueMode multiValueMode;
+    protected final MultiValueMode multiValueMode;
     protected String[] names;
     protected VS[] values;
 

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/ParsedMatrixStats.java

@@ -86,7 +86,7 @@ public class ParsedMatrixStats extends ParsedAggregation {
     @Override
     protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
         builder.field(CommonFields.DOC_COUNT.getPreferredName(), getDocCount());
-        if (counts != null && counts.isEmpty() == false) {
+        if (counts.isEmpty() == false) {
             builder.startArray(InternalMatrixStats.Fields.FIELDS);
             for (String fieldName : counts.keySet()) {
                 builder.startObject();

+ 7 - 9
modules/aggregations/src/main/java/org/elasticsearch/aggregations/metric/RunningStats.java

@@ -178,10 +178,8 @@ public class RunningStats implements Writeable, Cloneable {
     private void updateCovariance(final String[] fieldNames, final Map<String, Double> deltas) {
         // deep copy of hash keys (field names)
         ArrayList<String> cFieldNames = new ArrayList<>(Arrays.asList(fieldNames));
-        String fieldName;
         double dR, newVal;
-        for (int i = 0; i < fieldNames.length; ++i) {
-            fieldName = fieldNames[i];
+        for (String fieldName : fieldNames) {
             cFieldNames.remove(fieldName);
             // update running covariances
             dR = deltas.get(fieldName);
@@ -231,12 +229,12 @@ public class RunningStats implements Writeable, Cloneable {
         } else if (this.docCount == 0) {
             for (Map.Entry<String, Double> fs : other.means.entrySet()) {
                 final String fieldName = fs.getKey();
-                this.means.put(fieldName, fs.getValue().doubleValue());
-                this.counts.put(fieldName, other.counts.get(fieldName).longValue());
-                this.fieldSum.put(fieldName, other.fieldSum.get(fieldName).doubleValue());
-                this.variances.put(fieldName, other.variances.get(fieldName).doubleValue());
-                this.skewness.put(fieldName, other.skewness.get(fieldName).doubleValue());
-                this.kurtosis.put(fieldName, other.kurtosis.get(fieldName).doubleValue());
+                this.means.put(fieldName, fs.getValue());
+                this.counts.put(fieldName, other.counts.get(fieldName));
+                this.fieldSum.put(fieldName, other.fieldSum.get(fieldName));
+                this.variances.put(fieldName, other.variances.get(fieldName));
+                this.skewness.put(fieldName, other.skewness.get(fieldName));
+                this.kurtosis.put(fieldName, other.kurtosis.get(fieldName));
                 if (other.covariances.containsKey(fieldName)) {
                     this.covariances.put(fieldName, other.covariances.get(fieldName));
                 }

+ 3 - 3
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/BucketSelectorPipelineAggregator.java

@@ -24,9 +24,9 @@ import java.util.Map;
 import static org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue;
 
 public class BucketSelectorPipelineAggregator extends PipelineAggregator {
-    private GapPolicy gapPolicy;
-    private Script script;
-    private Map<String, String> bucketsPathsMap;
+    private final GapPolicy gapPolicy;
+    private final Script script;
+    private final Map<String, String> bucketsPathsMap;
 
     BucketSelectorPipelineAggregator(
         String name,

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/BucketSortPipelineAggregationBuilder.java

@@ -84,7 +84,7 @@ public class BucketSortPipelineAggregationBuilder extends AbstractPipelineAggreg
     private GapPolicy gapPolicy = GapPolicy.SKIP;
 
     public BucketSortPipelineAggregationBuilder(String name, List<FieldSortBuilder> sorts) {
-        super(name, NAME, sorts == null ? new String[0] : sorts.stream().map(s -> s.getFieldName()).toArray(String[]::new));
+        super(name, NAME, sorts == null ? new String[0] : sorts.stream().map(FieldSortBuilder::getFieldName).toArray(String[]::new));
         this.sorts = sorts == null ? Collections.emptyList() : sorts;
     }
 

+ 1 - 1
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/MovFnPipelineAggregationBuilder.java

@@ -69,7 +69,7 @@ public class MovFnPipelineAggregationBuilder extends AbstractPipelineAggregation
             }
             throw new IllegalArgumentException("Unsupported token [" + p.currentToken() + "]");
         }, GAP_POLICY, ObjectParser.ValueType.STRING);
-    };
+    }
 
     public MovFnPipelineAggregationBuilder(String name, String bucketsPath, Script script, int window) {
         super(name, NAME, new String[] { bucketsPath });

+ 1 - 6
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/MovFnPipelineAggregator.java

@@ -50,7 +50,6 @@ public class MovFnPipelineAggregator extends PipelineAggregator {
     private final DocValueFormat formatter;
     private final BucketHelpers.GapPolicy gapPolicy;
     private final Script script;
-    private final String bucketsPath;
     private final int window;
     private final int shift;
 
@@ -65,7 +64,6 @@ public class MovFnPipelineAggregator extends PipelineAggregator {
         Map<String, Object> metadata
     ) {
         super(name, new String[] { bucketsPath }, metadata);
-        this.bucketsPath = bucketsPath;
         this.script = script;
         this.formatter = formatter;
         this.gapPolicy = gapPolicy;
@@ -136,9 +134,6 @@ public class MovFnPipelineAggregator extends PipelineAggregator {
         if (index < 0) {
             return 0;
         }
-        if (index > list.size()) {
-            return list.size();
-        }
-        return index;
+        return Math.min(index, list.size());
     }
 }

+ 1 - 2
modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/adjacency/InternalAdjacencyMatrixTests.java

@@ -67,8 +67,7 @@ public class InternalAdjacencyMatrixTests extends AggregationMultiBucketAggregat
     @Override
     protected InternalAdjacencyMatrix createTestInstance(String name, Map<String, Object> metadata, InternalAggregations aggregations) {
         final List<InternalAdjacencyMatrix.InternalBucket> buckets = new ArrayList<>();
-        for (int i = 0; i < keys.size(); ++i) {
-            String key = keys.get(i);
+        for (String key : keys) {
             int docCount = randomIntBetween(0, 1000);
             buckets.add(new InternalAdjacencyMatrix.InternalBucket(key, docCount, aggregations));
         }

+ 1 - 1
modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/timeseries/TimeSeriesAggregatorTests.java

@@ -183,7 +183,7 @@ public class TimeSeriesAggregatorTests extends AggregationTestCase {
     public void testAggregationSize() throws IOException {
         CheckedConsumer<RandomIndexWriter, IOException> buildIndex = multiTsWriter();
 
-        List<Consumer<InternalTimeSeries>> verifiers = new ArrayList<Consumer<InternalTimeSeries>>();
+        List<Consumer<InternalTimeSeries>> verifiers = new ArrayList<>();
 
         verifiers.add(ts -> assertThat(ts.getBucketByKey("{dim1=aaa, dim2=xxx}").docCount, equalTo(2L)));
         verifiers.add(ts -> assertThat(ts.getBucketByKey("{dim1=aaa, dim2=yyy}").docCount, equalTo(2L)));

+ 6 - 6
modules/aggregations/src/test/java/org/elasticsearch/aggregations/metric/MultiPassStats.java

@@ -22,12 +22,12 @@ class MultiPassStats {
     private final String fieldBKey;
 
     private long count;
-    private Map<String, Double> means = new HashMap<>();
-    private Map<String, Double> variances = new HashMap<>();
-    private Map<String, Double> skewness = new HashMap<>();
-    private Map<String, Double> kurtosis = new HashMap<>();
-    private Map<String, Map<String, Double>> covariances = new HashMap<>();
-    private Map<String, Map<String, Double>> correlations = new HashMap<>();
+    private final Map<String, Double> means = new HashMap<>();
+    private final Map<String, Double> variances = new HashMap<>();
+    private final Map<String, Double> skewness = new HashMap<>();
+    private final Map<String, Double> kurtosis = new HashMap<>();
+    private final Map<String, Map<String, Double>> covariances = new HashMap<>();
+    private final Map<String, Map<String, Double>> correlations = new HashMap<>();
 
     MultiPassStats(String fieldAName, String fieldBName) {
         this.fieldAKey = fieldAName;

+ 1 - 1
modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/BucketSortPipelineAggregationBuilderTests.java

@@ -40,7 +40,7 @@ public class BucketSortPipelineAggregationBuilderTests extends BasePipelineAggre
             sorts.add(fieldSortBuilder);
         }
         BucketSortPipelineAggregationBuilder factory = new BucketSortPipelineAggregationBuilder(randomAlphaOfLengthBetween(3, 20), sorts);
-        Integer from = randomIntBetween(0, 20);
+        int from = randomIntBetween(0, 20);
         Integer size = randomBoolean() ? randomIntBetween(1, 1000) : null;
         if (randomBoolean()) {
             factory.from(from);

+ 4 - 4
modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/DerivativeAggregatorTests.java

@@ -218,7 +218,7 @@ public class DerivativeAggregatorTests extends AggregatorTestCase {
             Object[] propertiesDocCounts = (Object[]) histogram.getProperty("_count");
             Object[] propertiesSumCounts = (Object[]) histogram.getProperty("sum.value");
 
-            Long expectedSumPreviousBucket = Long.MIN_VALUE; // start value, gets
+            long expectedSumPreviousBucket = Long.MIN_VALUE; // start value, gets
             // overwritten
             for (int i = 0; i < numValueBuckets; ++i) {
                 Histogram.Bucket bucket = buckets.get(i);
@@ -270,7 +270,7 @@ public class DerivativeAggregatorTests extends AggregatorTestCase {
             Object[] propertiesDocCounts = (Object[]) histogram.getProperty("_count");
             Object[] propertiesSumCounts = (Object[]) histogram.getProperty("stats.sum");
 
-            Long expectedSumPreviousBucket = Long.MIN_VALUE; // start value, gets
+            long expectedSumPreviousBucket = Long.MIN_VALUE; // start value, gets
             // overwritten
             for (int i = 0; i < numValueBuckets; ++i) {
                 Histogram.Bucket bucket = buckets.get(i);
@@ -670,8 +670,8 @@ public class DerivativeAggregatorTests extends AggregatorTestCase {
         }
     }
 
-    private Long getTotalDocCountAcrossBuckets(List<? extends Histogram.Bucket> buckets) {
-        Long count = 0L;
+    private long getTotalDocCountAcrossBuckets(List<? extends Histogram.Bucket> buckets) {
+        long count = 0L;
         for (Histogram.Bucket bucket : buckets) {
             count += bucket.getDocCount();
         }