Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SCRIPTING: Move Aggregation Script Context to its own class #33820

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,6 @@ public boolean advanceExact(int doc) throws IOException {
@Override
public Object run() { return Double.valueOf(runAsDouble()); }

@Override
public long runAsLong() { return (long)runAsDouble(); }

@Override
public double runAsDouble() {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,4 @@ public double runAsDouble() {
return ((Number)run()).doubleValue();
}

@Override
public long runAsLong() {
return ((Number)run()).longValue();
}
}
165 changes: 165 additions & 0 deletions server/src/main/java/org/elasticsearch/script/AggregationScript.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
* 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.script;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.Scorable;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.lucene.ScorerAware;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.search.lookup.LeafSearchLookup;
import org.elasticsearch.search.lookup.SearchLookup;

public abstract class AggregationScript implements ScorerAware {

public static final String[] PARAMETERS = {};

public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("aggs", Factory.class);

private static final Map<String, String> DEPRECATIONS;

static {
Map<String, String> deprecations = new HashMap<>();
deprecations.put(
"doc",
"Accessing variable [doc] via [params.doc] from within an aggregation-script " +
"is deprecated in favor of directly accessing [doc]."
);
deprecations.put(
"_doc",
"Accessing variable [doc] via [params._doc] from within an aggregation-script " +
"is deprecated in favor of directly accessing [doc]."
);
DEPRECATIONS = Collections.unmodifiableMap(deprecations);
}

/**
* The generic runtime parameters for the script.
*/
private final Map<String, Object> params;

/**
* A leaf lookup for the bound segment this script will operate on.
*/
private final LeafSearchLookup leafLookup;

/**
* A scorer that will return the score for the current document when the script is run.
*/
protected Scorable scorer;

private Object value;

public AggregationScript(Map<String, Object> params, SearchLookup lookup, LeafReaderContext leafContext) {
this.params = new ParameterMap(new HashMap<>(params), DEPRECATIONS);
this.leafLookup = lookup.getLeafSearchLookup(leafContext);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't think doc or _score works in value aggregation scripts? Looking at the user of this, I don't see where setDocument is called.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know about the score (though a scorer is set for this script in e.g org.elasticsearch.search.aggregations.support.values.ScriptBytesValues#setScorer) but the document is set in many places like org.elasticsearch.search.aggregations.support.values.ScriptLongValues#advanceExact

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I see the calls to setDocument now. It still looks like the scorer is not set anywhere, but it also looks quite deceptive so I fear there is something more complex going on.

this.params.putAll(leafLookup.asMap());
}

/**
* Return the parameters for this script.
*/
public Map<String, Object> getParams() {
return params;
}

/**
* The doc lookup for the Lucene segment this script was created for.
*/
public Map<String, ScriptDocValues<?>> getDoc() {
return leafLookup.doc();
}

/**
* Set the current document to run the script on next.
*/
public void setDocument(int docid) {
leafLookup.setDocument(docid);
}

@Override
public void setScorer(Scorable scorer) {
this.scorer = scorer;
}

/** Return the score of the current document. */
public double getScore() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should have score accessible as score and _score?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's what I was going to ask you, but yea I think score can go away here right?

try {
return scorer == null ? 0.0 : scorer.score();
} catch (IOException e) {
throw new ElasticsearchException("couldn't lookup score", e);
}
}

/**
* Sets per-document aggregation {@code _value}.
* <p>
* The default implementation just calls {@code setNextVar("_value", value)} but
* some engines might want to handle this differently for better performance.
* <p>
* @param value per-document value, typically a String, Long, or Double
*/
public void setNextAggregationValue(Object value) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At minimum this should be typed (we should have separate script classes for each underlying doc values type), but I would much rather this be built into the script itself, so instead of setting the value, an iterate type call is made, similar to the doc values api.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rjernst as it turns out this isn't so trivial :(

Determining the exact type of the script upstream would require a lot of refactoring starting with org.elasticsearch.search.aggregations.support.ValuesSourceConfig (did some initial cleanups towards that in #34323).
Maybe we should do that in a next step?

this.value = value;
}

public Number get_score() {
return getScore();
}

public Object get_value() {
return value;
}

/**
* Return the result as a long. This is used by aggregation scripts over long fields.
*/
public long runAsLong() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't need these methods if we make typed versions of scripts, where execute would then return the correct type. Additionally, don't we always return double for all numeric fields (ie runAsLong isn't actually used)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's used in: org.elasticsearch.search.aggregations.support.ValuesSource.Numeric.WithScript.LongValues.
but you're right typed versions of this context should be possible, will try tomorrow :)

return ((Number) execute()).longValue();
}

public double runAsDouble() {
return ((Number) execute()).doubleValue();
}

public abstract Object execute();

/**
* A factory to construct {@link AggregationScript} instances.
*/
public interface LeafFactory {
AggregationScript newInstance(LeafReaderContext ctx) throws IOException;

/**
* Return {@code true} if the script needs {@code _score} calculated, or {@code false} otherwise.
*/
boolean needs_score();
}

/**
* A factory to construct stateful {@link AggregationScript} factories for a specific index.
*/
public interface Factory {
LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class ScriptModule {
static {
CORE_CONTEXTS = Stream.of(
SearchScript.CONTEXT,
SearchScript.AGGS_CONTEXT,
AggregationScript.CONTEXT,
ScoreScript.CONTEXT,
SearchScript.SCRIPT_SORT_CONTEXT,
TermsSetQueryScript.CONTEXT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
* <li>Construct a {@link LeafFactory} for a an index using {@link Factory#newFactory(Map, SearchLookup)}</li>
* <li>Construct a {@link SearchScript} for a Lucene segment using {@link LeafFactory#newInstance(LeafReaderContext)}</li>
* <li>Call {@link #setDocument(int)} to indicate which document in the segment the script should be run for next</li>
* <li>Call one of the {@code run} methods: {@link #run()}, {@link #runAsDouble()}, or {@link #runAsLong()}</li>
* <li>Call one of the {@code run} methods: {@link #run()} or {@link #runAsDouble()}</li>
* </ol>
*/
public abstract class SearchScript implements ScorerAware, ExecutableScript {
Expand Down Expand Up @@ -115,11 +115,6 @@ public void setNextAggregationValue(Object value) {
@Override
public void setNextVar(String field, Object value) {}

/** Return the result as a long. This is used by aggregation scripts over long fields. */
public long runAsLong() {
throw new UnsupportedOperationException("runAsLong is not implemented");
}

@Override
public Object run() {
return runAsDouble();
Expand All @@ -146,7 +141,6 @@ public interface Factory {
/** The context used to compile {@link SearchScript} factories. */
public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("search", Factory.class);
// TODO: remove these contexts when it has its own interface
public static final ScriptContext<Factory> AGGS_CONTEXT = new ScriptContext<>("aggs", Factory.class);
// Can return a double. (For ScriptSortType#NUMBER only, for ScriptSortType#STRING normal CONTEXT should be used)
public static final ScriptContext<Factory> SCRIPT_SORT_CONTEXT = new ScriptContext<>("sort", Factory.class);
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.index.fielddata.SortingBinaryDocValues;
import org.elasticsearch.index.fielddata.SortingNumericDoubleValues;
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.script.AggregationScript;
import org.elasticsearch.search.aggregations.support.ValuesSource.WithScript.BytesValues;
import org.elasticsearch.search.aggregations.support.values.ScriptBytesValues;
import org.elasticsearch.search.aggregations.support.values.ScriptDoubleValues;
Expand Down Expand Up @@ -183,9 +183,9 @@ public SortedBinaryDocValues bytesValues(LeafReaderContext context) {

public static class Script extends Bytes {

private final SearchScript.LeafFactory script;
private final AggregationScript.LeafFactory script;

public Script(SearchScript.LeafFactory script) {
public Script(AggregationScript.LeafFactory script) {
this.script = script;
}

Expand All @@ -199,8 +199,6 @@ public boolean needsScores() {
return script.needs_score();
}
}


}

public abstract static class Numeric extends ValuesSource {
Expand Down Expand Up @@ -252,9 +250,9 @@ public DocValueBits docsWithValue(LeafReaderContext context) throws IOException
public static class WithScript extends Numeric {

private final Numeric delegate;
private final SearchScript.LeafFactory script;
private final AggregationScript.LeafFactory script;

public WithScript(Numeric delegate, SearchScript.LeafFactory script) {
public WithScript(Numeric delegate, AggregationScript.LeafFactory script) {
this.delegate = delegate;
this.script = script;
}
Expand Down Expand Up @@ -287,9 +285,9 @@ public SortedNumericDoubleValues doubleValues(LeafReaderContext context) throws
static class LongValues extends AbstractSortingNumericDocValues implements ScorerAware {

private final SortedNumericDocValues longValues;
private final SearchScript script;
private final AggregationScript script;

LongValues(SortedNumericDocValues values, SearchScript script) {
LongValues(SortedNumericDocValues values, AggregationScript script) {
this.longValues = values;
this.script = script;
}
Expand Down Expand Up @@ -318,9 +316,9 @@ public boolean advanceExact(int target) throws IOException {
static class DoubleValues extends SortingNumericDoubleValues implements ScorerAware {

private final SortedNumericDoubleValues doubleValues;
private final SearchScript script;
private final AggregationScript script;

DoubleValues(SortedNumericDoubleValues values, SearchScript script) {
DoubleValues(SortedNumericDoubleValues values, AggregationScript script) {
this.doubleValues = values;
this.script = script;
}
Expand Down Expand Up @@ -377,10 +375,10 @@ public SortedNumericDoubleValues doubleValues(LeafReaderContext context) {
}

public static class Script extends Numeric {
private final SearchScript.LeafFactory script;
private final AggregationScript.LeafFactory script;
private final ValueType scriptValueType;

public Script(SearchScript.LeafFactory script, ValueType scriptValueType) {
public Script(AggregationScript.LeafFactory script, ValueType scriptValueType) {
this.script = script;
this.scriptValueType = scriptValueType;
}
Expand Down Expand Up @@ -417,9 +415,9 @@ public boolean needsScores() {
public static class WithScript extends Bytes {

private final ValuesSource delegate;
private final SearchScript.LeafFactory script;
private final AggregationScript.LeafFactory script;

public WithScript(ValuesSource delegate, SearchScript.LeafFactory script) {
public WithScript(ValuesSource delegate, AggregationScript.LeafFactory script) {
this.delegate = delegate;
this.script = script;
}
Expand All @@ -437,9 +435,9 @@ public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOExc
static class BytesValues extends SortingBinaryDocValues implements ScorerAware {

private final SortedBinaryDocValues bytesValues;
private final SearchScript script;
private final AggregationScript script;

BytesValues(SortedBinaryDocValues bytesValues, SearchScript script) {
BytesValues(SortedBinaryDocValues bytesValues, AggregationScript script) {
this.bytesValues = bytesValues;
this.script = script;
}
Expand All @@ -457,7 +455,7 @@ public boolean advanceExact(int doc) throws IOException {
for (int i = 0; i < count; ++i) {
final BytesRef value = bytesValues.nextValue();
script.setNextAggregationValue(value.utf8ToString());
Object run = script.run();
Object run = script.execute();
CollectionUtils.ensureNoSelfReferences(run, "ValuesSource.BytesValues script");
values[i].copyChars(run.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
import org.elasticsearch.index.fielddata.IndexOrdinalsFieldData;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.script.AggregationScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.AggregationExecutionException;
import org.joda.time.DateTimeZone;
Expand Down Expand Up @@ -113,11 +113,11 @@ public static <VS extends ValuesSource> ValuesSourceConfig<VS> resolve(
return config;
}

private static SearchScript.LeafFactory createScript(Script script, QueryShardContext context) {
private static AggregationScript.LeafFactory createScript(Script script, QueryShardContext context) {
if (script == null) {
return null;
} else {
SearchScript.Factory factory = context.getScriptService().compile(script, SearchScript.AGGS_CONTEXT);
AggregationScript.Factory factory = context.getScriptService().compile(script, AggregationScript.CONTEXT);
return factory.newFactory(script.getParams(), context.lookup());
}
}
Expand All @@ -135,7 +135,7 @@ private static DocValueFormat resolveFormat(@Nullable String format, @Nullable V

private final ValuesSourceType valueSourceType;
private FieldContext fieldContext;
private SearchScript.LeafFactory script;
private AggregationScript.LeafFactory script;
private ValueType scriptValueType;
private boolean unmapped = false;
private DocValueFormat format = DocValueFormat.RAW;
Expand All @@ -154,7 +154,7 @@ public FieldContext fieldContext() {
return fieldContext;
}

public SearchScript.LeafFactory script() {
public AggregationScript.LeafFactory script() {
return script;
}

Expand All @@ -171,7 +171,7 @@ public ValuesSourceConfig<VS> fieldContext(FieldContext fieldContext) {
return this;
}

public ValuesSourceConfig<VS> script(SearchScript.LeafFactory script) {
public ValuesSourceConfig<VS> script(AggregationScript.LeafFactory script) {
this.script = script;
return this;
}
Expand Down
Loading