summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/movavg/MovAvgPipelineAggregationBuilder.java
blob: f5f71b3ca75f8513a61f1aed1eaf8223a3295489 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.search.aggregations.pipeline.movavg;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ParseFieldRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.PipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregatorFactory;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregatorFactory;
import org.elasticsearch.search.aggregations.pipeline.AbstractPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.MovAvgModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.MovAvgModelBuilder;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.SimpleModel;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.BUCKETS_PATH;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.FORMAT;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.GAP_POLICY;

public class MovAvgPipelineAggregationBuilder extends AbstractPipelineAggregationBuilder<MovAvgPipelineAggregationBuilder> {
    public static final String NAME = "moving_avg";

    public static final ParseField MODEL = new ParseField("model");
    private static final ParseField WINDOW = new ParseField("window");
    public static final ParseField SETTINGS = new ParseField("settings");
    private static final ParseField PREDICT = new ParseField("predict");
    private static final ParseField MINIMIZE = new ParseField("minimize");

    private String format;
    private GapPolicy gapPolicy = GapPolicy.SKIP;
    private int window = 5;
    private MovAvgModel model = new SimpleModel();
    private int predict = 0;
    private Boolean minimize;

    public MovAvgPipelineAggregationBuilder(String name, String bucketsPath) {
        super(name, NAME, new String[] { bucketsPath });
    }

    /**
     * Read from a stream.
     */
    public MovAvgPipelineAggregationBuilder(StreamInput in) throws IOException {
        super(in, NAME);
        format = in.readOptionalString();
        gapPolicy = GapPolicy.readFrom(in);
        window = in.readVInt();
        model = in.readNamedWriteable(MovAvgModel.class);
        predict = in.readVInt();
        minimize = in.readOptionalBoolean();
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeOptionalString(format);
        gapPolicy.writeTo(out);
        out.writeVInt(window);
        out.writeNamedWriteable(model);
        out.writeVInt(predict);
        out.writeOptionalBoolean(minimize);
    }

    /**
     * Sets the format to use on the output of this aggregation.
     */
    public MovAvgPipelineAggregationBuilder format(String format) {
        if (format == null) {
            throw new IllegalArgumentException("[format] must not be null: [" + name + "]");
        }
        this.format = format;
        return this;
    }

    /**
     * Gets the format to use on the output of this aggregation.
     */
    public String format() {
        return format;
    }

    /**
     * Sets the GapPolicy to use on the output of this aggregation.
     */
    public MovAvgPipelineAggregationBuilder gapPolicy(GapPolicy gapPolicy) {
        if (gapPolicy == null) {
            throw new IllegalArgumentException("[gapPolicy] must not be null: [" + name + "]");
        }
        this.gapPolicy = gapPolicy;
        return this;
    }

    /**
     * Gets the GapPolicy to use on the output of this aggregation.
     */
    public GapPolicy gapPolicy() {
        return gapPolicy;
    }

    protected DocValueFormat formatter() {
        if (format != null) {
            return new DocValueFormat.Decimal(format);
        } else {
            return DocValueFormat.RAW;
        }
    }

    /**
     * Sets the window size for the moving average. This window will "slide"
     * across the series, and the values inside that window will be used to
     * calculate the moving avg value
     *
     * @param window
     *            Size of window
     */
    public MovAvgPipelineAggregationBuilder window(int window) {
        if (window <= 0) {
            throw new IllegalArgumentException("[window] must be a positive integer: [" + name + "]");
        }
        this.window = window;
        return this;
    }

    /**
     * Gets the window size for the moving average. This window will "slide"
     * across the series, and the values inside that window will be used to
     * calculate the moving avg value
     */
    public int window() {
        return window;
    }

    /**
     * Sets a MovAvgModel for the Moving Average. The model is used to
     * define what type of moving average you want to use on the series
     *
     * @param model
     *            A MovAvgModel which has been prepopulated with settings
     */
    public MovAvgPipelineAggregationBuilder modelBuilder(MovAvgModelBuilder model) {
        if (model == null) {
            throw new IllegalArgumentException("[model] must not be null: [" + name + "]");
        }
        this.model = model.build();
        return this;
    }

    /**
     * Sets a MovAvgModel for the Moving Average. The model is used to
     * define what type of moving average you want to use on the series
     *
     * @param model
     *            A MovAvgModel which has been prepopulated with settings
     */
    public MovAvgPipelineAggregationBuilder model(MovAvgModel model) {
        if (model == null) {
            throw new IllegalArgumentException("[model] must not be null: [" + name + "]");
        }
        this.model = model;
        return this;
    }

    /**
     * Gets a MovAvgModel for the Moving Average. The model is used to
     * define what type of moving average you want to use on the series
     */
    public MovAvgModel model() {
        return model;
    }

    /**
     * Sets the number of predictions that should be returned. Each
     * prediction will be spaced at the intervals specified in the
     * histogram. E.g "predict: 2" will return two new buckets at the end of
     * the histogram with the predicted values.
     *
     * @param predict
     *            Number of predictions to make
     */
    public MovAvgPipelineAggregationBuilder predict(int predict) {
        if (predict <= 0) {
            throw new IllegalArgumentException("predict must be greater than 0. Found [" + predict + "] in [" + name + "]");
        }
        this.predict = predict;
        return this;
    }

    /**
     * Gets the number of predictions that should be returned. Each
     * prediction will be spaced at the intervals specified in the
     * histogram. E.g "predict: 2" will return two new buckets at the end of
     * the histogram with the predicted values.
     */
    public int predict() {
        return predict;
    }

    /**
     * Sets whether the model should be fit to the data using a cost
     * minimizing algorithm.
     *
     * @param minimize
     *            If the model should be fit to the underlying data
     */
    public MovAvgPipelineAggregationBuilder minimize(boolean minimize) {
        this.minimize = minimize;
        return this;
    }

    /**
     * Gets whether the model should be fit to the data using a cost
     * minimizing algorithm.
     */
    public Boolean minimize() {
        return minimize;
    }

    @Override
    protected PipelineAggregator createInternal(Map<String, Object> metaData) throws IOException {
        // If the user doesn't set a preference for cost minimization, ask
        // what the model prefers
        boolean minimize = this.minimize == null ? model.minimizeByDefault() : this.minimize;
        return new MovAvgPipelineAggregator(name, bucketsPaths, formatter(), gapPolicy, window, predict, model, minimize, metaData);
    }

    @Override
    public void doValidate(AggregatorFactory<?> parent, AggregatorFactory<?>[] aggFactories,
            List<PipelineAggregationBuilder> pipelineAggregatoractories) {
        if (minimize != null && minimize && !model.canBeMinimized()) {
            // If the user asks to minimize, but this model doesn't support
            // it, throw exception
            throw new IllegalStateException("The [" + model + "] model cannot be minimized for aggregation [" + name + "]");
        }
        if (bucketsPaths.length != 1) {
            throw new IllegalStateException(PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName()
                    + " must contain a single entry for aggregation [" + name + "]");
        }
        if (parent instanceof HistogramAggregatorFactory) {
            HistogramAggregatorFactory histoParent = (HistogramAggregatorFactory) parent;
            if (histoParent.minDocCount() != 0) {
                throw new IllegalStateException("parent histogram of moving average aggregation [" + name
                        + "] must have min_doc_count of 0");
            }
        } else if (parent instanceof DateHistogramAggregatorFactory) {
            DateHistogramAggregatorFactory histoParent = (DateHistogramAggregatorFactory) parent;
            if (histoParent.minDocCount() != 0) {
                throw new IllegalStateException("parent histogram of moving average aggregation [" + name
                        + "] must have min_doc_count of 0");
            }
        } else {
            throw new IllegalStateException("moving average aggregation [" + name
                    + "] must have a histogram or date_histogram as parent");
        }
    }

    @Override
    protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
        if (format != null) {
            builder.field(FORMAT.getPreferredName(), format);
        }
        builder.field(GAP_POLICY.getPreferredName(), gapPolicy.getName());
        model.toXContent(builder, params);
        builder.field(WINDOW.getPreferredName(), window);
        if (predict > 0) {
            builder.field(PREDICT.getPreferredName(), predict);
        }
        if (minimize != null) {
            builder.field(MINIMIZE.getPreferredName(), minimize);
        }
        return builder;
    }

    public static MovAvgPipelineAggregationBuilder parse(
            ParseFieldRegistry<MovAvgModel.AbstractModelParser> movingAverageMdelParserRegistry,
            String pipelineAggregatorName, XContentParser parser) throws IOException {
        XContentParser.Token token;
        String currentFieldName = null;
        String[] bucketsPaths = null;
        String format = null;

        GapPolicy gapPolicy = null;
        Integer window = null;
        Map<String, Object> settings = null;
        String model = null;
        Integer predict = null;
        Boolean minimize = null;

        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                if (WINDOW.match(currentFieldName)) {
                    window = parser.intValue();
                    if (window <= 0) {
                        throw new ParsingException(parser.getTokenLocation(), "[" + currentFieldName + "] value must be a positive, "
                                + "non-zero integer.  Value supplied was [" + predict + "] in [" + pipelineAggregatorName + "].");
                    }
                } else if (PREDICT.match(currentFieldName)) {
                    predict = parser.intValue();
                    if (predict <= 0) {
                        throw new ParsingException(parser.getTokenLocation(), "[" + currentFieldName + "] value must be a positive integer."
                                + "  Value supplied was [" + predict + "] in [" + pipelineAggregatorName + "].");
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.VALUE_STRING) {
                if (FORMAT.match(currentFieldName)) {
                    format = parser.text();
                } else if (BUCKETS_PATH.match(currentFieldName)) {
                    bucketsPaths = new String[] { parser.text() };
                } else if (GAP_POLICY.match(currentFieldName)) {
                    gapPolicy = GapPolicy.parse(parser.text(), parser.getTokenLocation());
                } else if (MODEL.match(currentFieldName)) {
                    model = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                if (BUCKETS_PATH.match(currentFieldName)) {
                    List<String> paths = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        String path = parser.text();
                        paths.add(path);
                    }
                    bucketsPaths = paths.toArray(new String[paths.size()]);
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (SETTINGS.match(currentFieldName)) {
                    settings = parser.map();
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
                if (MINIMIZE.match(currentFieldName)) {
                    minimize = parser.booleanValue();
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "].");
                }
            } else {
                throw new ParsingException(parser.getTokenLocation(),
                        "Unexpected token " + token + " in [" + pipelineAggregatorName + "].");
            }
        }

        if (bucketsPaths == null) {
            throw new ParsingException(parser.getTokenLocation(), "Missing required field [" + BUCKETS_PATH.getPreferredName()
                    + "] for movingAvg aggregation [" + pipelineAggregatorName + "]");
        }

        MovAvgPipelineAggregationBuilder factory =
                new MovAvgPipelineAggregationBuilder(pipelineAggregatorName, bucketsPaths[0]);
        if (format != null) {
            factory.format(format);
        }
        if (gapPolicy != null) {
            factory.gapPolicy(gapPolicy);
        }
        if (window != null) {
            factory.window(window);
        }
        if (predict != null) {
            factory.predict(predict);
        }
        if (model != null) {
            MovAvgModel.AbstractModelParser modelParser = movingAverageMdelParserRegistry.lookup(model, parser.getTokenLocation());
            MovAvgModel movAvgModel;
            try {
                movAvgModel = modelParser.parse(settings, pipelineAggregatorName, factory.window());
            } catch (ParseException exception) {
                throw new ParsingException(parser.getTokenLocation(), "Could not parse settings for model [" + model + "].", exception);
            }
            factory.model(movAvgModel);
        }
        if (minimize != null) {
            factory.minimize(minimize);
        }
        return factory;
    }

    @Override
    protected int doHashCode() {
        return Objects.hash(format, gapPolicy, window, model, predict, minimize);
    }

    @Override
    protected boolean doEquals(Object obj) {
        MovAvgPipelineAggregationBuilder other = (MovAvgPipelineAggregationBuilder) obj;
        return Objects.equals(format, other.format)
                && Objects.equals(gapPolicy, other.gapPolicy)
                && Objects.equals(window, other.window)
                && Objects.equals(model, other.model)
                && Objects.equals(predict, other.predict)
                && Objects.equals(minimize, other.minimize);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }
}