summaryrefslogtreecommitdiff
path: root/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/support/MultiValuesSourceParser.java
blob: c2e4b4f0c3f5544fac7689651aec33c54e1faa42 (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
/*
 * 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.support;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilder.CommonFields;
import org.elasticsearch.search.aggregations.Aggregator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class MultiValuesSourceParser<VS extends ValuesSource> implements Aggregator.Parser {

    public abstract static class AnyValuesSourceParser extends MultiValuesSourceParser<ValuesSource> {

        protected AnyValuesSourceParser(boolean formattable) {
            super(formattable, ValuesSourceType.ANY, null);
        }
    }

    public abstract static class NumericValuesSourceParser extends MultiValuesSourceParser<ValuesSource.Numeric> {

        protected NumericValuesSourceParser(boolean formattable) {
            super(formattable, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
        }
    }

    public abstract static class BytesValuesSourceParser extends MultiValuesSourceParser<ValuesSource.Bytes> {

        protected BytesValuesSourceParser(boolean formattable) {
            super(formattable, ValuesSourceType.BYTES, ValueType.STRING);
        }
    }

    public abstract static class GeoPointValuesSourceParser extends MultiValuesSourceParser<ValuesSource.GeoPoint> {

        protected GeoPointValuesSourceParser(boolean formattable) {
            super(formattable, ValuesSourceType.GEOPOINT, ValueType.GEOPOINT);
        }
    }

    private boolean formattable = false;
    private ValuesSourceType valuesSourceType = null;
    private ValueType targetValueType = null;

    private MultiValuesSourceParser(boolean formattable, ValuesSourceType valuesSourceType, ValueType targetValueType) {
        this.valuesSourceType = valuesSourceType;
        this.targetValueType = targetValueType;
        this.formattable = formattable;
    }

    @Override
    public final MultiValuesSourceAggregationBuilder<VS, ?> parse(String aggregationName, QueryParseContext context)
            throws IOException {

        XContentParser parser = context.parser();
        List<String> fields = null;
        ValueType valueType = null;
        String format = null;
        Map<String, Object> missingMap = null;
        Map<ParseField, Object> otherOptions = new HashMap<>();
        XContentParser.Token token;
        String currentFieldName = null;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.VALUE_STRING) {
                if (CommonFields.FIELDS.match(currentFieldName)) {
                    fields = Collections.singletonList(parser.text());
                } else if (formattable && CommonFields.FORMAT.match(currentFieldName)) {
                    format = parser.text();
                } else if (CommonFields.VALUE_TYPE.match(currentFieldName)) {
                    throw new ParsingException(parser.getTokenLocation(),
                        "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "]. " +
                            "Multi-field aggregations do not support scripts.");
                } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
                }
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (CommonFields.MISSING.match(currentFieldName)) {
                    missingMap = new HashMap<>();
                    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
                        parseMissingAndAdd(aggregationName, currentFieldName, parser, missingMap);
                    }
                } else if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
                    throw new ParsingException(parser.getTokenLocation(),
                        "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "]. " +
                            "Multi-field aggregations do not support scripts.");

                } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
                    throw new ParsingException(parser.getTokenLocation(),
                        "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "]. " +
                            "Multi-field aggregations do not support scripts.");
                } else if (CommonFields.FIELDS.match(currentFieldName)) {
                    fields = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token == XContentParser.Token.VALUE_STRING) {
                            fields.add(parser.text());
                        } else {
                            throw new ParsingException(parser.getTokenLocation(),
                                    "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
                        }
                    }
                } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
                }
            } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
                throw new ParsingException(parser.getTokenLocation(),
                        "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
            }
        }

        MultiValuesSourceAggregationBuilder<VS, ?> factory = createFactory(aggregationName, this.valuesSourceType, this.targetValueType,
                otherOptions);
        if (fields != null) {
            factory.fields(fields);
        }
        if (valueType != null) {
            factory.valueType(valueType);
        }
        if (format != null) {
            factory.format(format);
        }
        if (missingMap != null) {
            factory.missingMap(missingMap);
        }
        return factory;
    }

    private void parseMissingAndAdd(final String aggregationName, final String currentFieldName,
                                    XContentParser parser, final Map<String, Object> missing) throws IOException {
        XContentParser.Token token = parser.currentToken();
        if (token == null) {
            token = parser.nextToken();
        }

        if (token == XContentParser.Token.FIELD_NAME) {
            final String fieldName = parser.currentName();
            if (missing.containsKey(fieldName)) {
                throw new ParsingException(parser.getTokenLocation(),
                    "Missing field [" + fieldName + "] already defined as [" + missing.get(fieldName)
                        + "] in [" + aggregationName + "].");
            }
            parser.nextToken();
            missing.put(fieldName, parser.objectText());
        } else {
            throw new ParsingException(parser.getTokenLocation(),
                "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "]");
        }
    }

    /**
     * Creates a {@link ValuesSourceAggregationBuilder} from the information
     * gathered by the subclass. Options parsed in
     * {@link MultiValuesSourceParser} itself will be added to the factory
     * after it has been returned by this method.
     *
     * @param aggregationName
     *            the name of the aggregation
     * @param valuesSourceType
     *            the type of the {@link ValuesSource}
     * @param targetValueType
     *            the target type of the final value output by the aggregation
     * @param otherOptions
     *            a {@link Map} containing the extra options parsed by the
     *            {@link #token(String, String, XContentParser.Token, XContentParser, Map)}
     *            method
     * @return the created factory
     */
    protected abstract MultiValuesSourceAggregationBuilder<VS, ?> createFactory(String aggregationName, ValuesSourceType valuesSourceType,
        ValueType targetValueType, Map<ParseField, Object> otherOptions);

    /**
     * Allows subclasses of {@link MultiValuesSourceParser} to parse extra
     * parameters and store them in a {@link Map} which will later be passed to
     * {@link #createFactory(String, ValuesSourceType, ValueType, Map)}.
     *
     * @param aggregationName
     *            the name of the aggregation
     * @param currentFieldName
     *            the name of the current field being parsed
     * @param token
     *            the current token for the parser
     * @param parser
     *            the parser
     * @param otherOptions
     *            a {@link Map} of options to be populated by successive calls
     *            to this method which will then be passed to the
     *            {@link #createFactory(String, ValuesSourceType, ValueType, Map)}
     *            method
     * @return <code>true</code> if the current token was correctly parsed,
     *         <code>false</code> otherwise
     * @throws IOException
     *             if an error occurs whilst parsing
     */
    protected abstract boolean token(String aggregationName, String currentFieldName, XContentParser.Token token, XContentParser parser,
                                     Map<ParseField, Object> otherOptions) throws IOException;
}