|
| 1 | +/* |
| 2 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | + * you may not use this file except in compliance with the License. |
| 4 | + * You may obtain a copy of the License at |
| 5 | + * |
| 6 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | + * |
| 8 | + * Unless required by applicable law or agreed to in writing, software |
| 9 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | + * See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | + |
| 15 | +package org.elasticsearch.examples.nativescript.script.stockaggs; |
| 16 | + |
| 17 | +import org.elasticsearch.common.Nullable; |
| 18 | +import org.elasticsearch.index.fielddata.ScriptDocValues; |
| 19 | +import org.elasticsearch.script.AbstractSearchScript; |
| 20 | +import org.elasticsearch.script.ExecutableScript; |
| 21 | +import org.elasticsearch.script.NativeScriptFactory; |
| 22 | + |
| 23 | +import java.util.ArrayList; |
| 24 | +import java.util.Map; |
| 25 | + |
| 26 | +/** |
| 27 | + * Map script from https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html |
| 28 | + * <p/> |
| 29 | + * if (doc['type'].value == \"sale\") { _agg.transactions.add(doc['amount'].value) } else {_agg.transactions.add(-1 * doc['amount'].value)} |
| 30 | + */ |
| 31 | +public class MapScriptFactory implements NativeScriptFactory { |
| 32 | + |
| 33 | + @Override |
| 34 | + public ExecutableScript newScript(final @Nullable Map<String, Object> params) { |
| 35 | + Map<String, Object> agg = (Map<String, Object>) params.get("_agg"); |
| 36 | + ArrayList<Long> transactions = (ArrayList<Long>) agg.get(InitScriptFactory.TRANSACTIONS_FIELD); |
| 37 | + return new MapScript(transactions); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public boolean needsScores() { |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + private static class MapScript extends AbstractSearchScript { |
| 46 | + |
| 47 | + private final ArrayList<Long> transactions; |
| 48 | + |
| 49 | + public MapScript(ArrayList<Long> transactions) { |
| 50 | + this.transactions = transactions; |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public Object run() { |
| 56 | + ScriptDocValues.Longs amount = (ScriptDocValues.Longs) doc().get("amount"); |
| 57 | + ScriptDocValues.Strings type = (ScriptDocValues.Strings) doc().get("type"); |
| 58 | + if ("sale".equals(type.getValue())) { |
| 59 | + transactions.add(amount.getValue()); |
| 60 | + } else { |
| 61 | + transactions.add(-amount.getValue()); |
| 62 | + } |
| 63 | + return null; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments