Skip to content

Commit f58680b

Browse files
authored
EQL: Add Substring function with Python semantics (#53688)
Does not reuse substring from SQL due to the difference in semantics and the accepted arguments. Currently it is missing full integration tests as, due to the usage of scripting, requires an actual integration test against a proper cluster (and likely its own QA project).
1 parent 5732112 commit f58680b

File tree

22 files changed

+704
-69
lines changed

22 files changed

+704
-69
lines changed

x-pack/plugin/eql/build.gradle

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,6 @@ dependencies {
4646

4747
// TOML parser for EqlActionIT tests
4848
testCompile 'io.ous:jtoml:2.0.0'
49-
50-
// JSON parser for tests input data
51-
testCompile "com.fasterxml.jackson.core:jackson-core:${versions.jackson}"
52-
testCompile "com.fasterxml.jackson.core:jackson-annotations:${versions.jackson}"
53-
testCompile "com.fasterxml.jackson.core:jackson-databind:${versions.jackson}"
54-
5549
}
5650

5751

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/analysis/Analyzer.java

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
import org.elasticsearch.xpack.ql.expression.Attribute;
1111
import org.elasticsearch.xpack.ql.expression.NamedExpression;
1212
import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute;
13+
import org.elasticsearch.xpack.ql.expression.function.Function;
14+
import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition;
1315
import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry;
16+
import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction;
1417
import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan;
15-
import org.elasticsearch.xpack.ql.rule.Rule;
1618
import org.elasticsearch.xpack.ql.rule.RuleExecutor;
1719

1820
import java.util.ArrayList;
@@ -35,7 +37,8 @@ public Analyzer(FunctionRegistry functionRegistry, Verifier verifier) {
3537
@Override
3638
protected Iterable<RuleExecutor<LogicalPlan>.Batch> batches() {
3739
Batch resolution = new Batch("Resolution",
38-
new ResolveRefs());
40+
new ResolveRefs(),
41+
new ResolveFunctions());
3942

4043
return asList(resolution);
4144
}
@@ -52,7 +55,7 @@ private LogicalPlan verify(LogicalPlan plan) {
5255
return plan;
5356
}
5457

55-
private static class ResolveRefs extends AnalyzeRule<LogicalPlan> {
58+
private static class ResolveRefs extends AnalyzerRule<LogicalPlan> {
5659

5760
@Override
5861
protected LogicalPlan rule(LogicalPlan plan) {
@@ -87,20 +90,34 @@ protected LogicalPlan rule(LogicalPlan plan) {
8790
}
8891
}
8992

90-
abstract static class AnalyzeRule<SubPlan extends LogicalPlan> extends Rule<SubPlan, LogicalPlan> {
93+
private class ResolveFunctions extends AnalyzerRule<LogicalPlan> {
9194

92-
// transformUp (post-order) - that is first children and then the node
93-
// but with a twist; only if the tree is not resolved or analyzed
9495
@Override
95-
public final LogicalPlan apply(LogicalPlan plan) {
96-
return plan.transformUp(t -> t.analyzed() || skipResolved() && t.resolved() ? t : rule(t), typeToken());
97-
}
96+
protected LogicalPlan rule(LogicalPlan plan) {
97+
return plan.transformExpressionsUp(e -> {
98+
if (e instanceof UnresolvedFunction) {
99+
UnresolvedFunction uf = (UnresolvedFunction) e;
98100

99-
@Override
100-
protected abstract LogicalPlan rule(SubPlan plan);
101+
if (uf.analyzed()) {
102+
return uf;
103+
}
104+
105+
String name = uf.name();
101106

102-
protected boolean skipResolved() {
103-
return true;
107+
if (uf.childrenResolved() == false) {
108+
return uf;
109+
}
110+
111+
String functionName = functionRegistry.resolveAlias(name);
112+
if (functionRegistry.functionExists(functionName) == false) {
113+
return uf.missing(functionName, functionRegistry.listFunctions());
114+
}
115+
FunctionDefinition def = functionRegistry.resolveFunction(functionName);
116+
Function f = uf.buildResolved(null, def);
117+
return f;
118+
}
119+
return e;
120+
});
104121
}
105122
}
106123
}

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/execution/PlanExecutor.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.elasticsearch.xpack.eql.analysis.Analyzer;
1313
import org.elasticsearch.xpack.eql.analysis.PreAnalyzer;
1414
import org.elasticsearch.xpack.eql.analysis.Verifier;
15+
import org.elasticsearch.xpack.eql.expression.function.EqlFunctionRegistry;
1516
import org.elasticsearch.xpack.eql.optimizer.Optimizer;
1617
import org.elasticsearch.xpack.eql.parser.ParserParams;
1718
import org.elasticsearch.xpack.eql.planner.Planner;
@@ -44,7 +45,7 @@ public PlanExecutor(Client client, IndexResolver indexResolver, NamedWriteableRe
4445
this.writableRegistry = writeableRegistry;
4546

4647
this.indexResolver = indexResolver;
47-
this.functionRegistry = null;
48+
this.functionRegistry = new EqlFunctionRegistry();
4849

4950
this.metrics = new Metrics();
5051

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/EqlFunctionRegistry.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,30 @@
66

77
package org.elasticsearch.xpack.eql.expression.function;
88

9+
import org.elasticsearch.xpack.eql.expression.function.scalar.string.Substring;
10+
import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition;
911
import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry;
1012

13+
import java.util.Locale;
14+
1115
public class EqlFunctionRegistry extends FunctionRegistry {
1216

1317
public EqlFunctionRegistry() {
18+
super(functions());
19+
}
20+
21+
private static FunctionDefinition[][] functions() {
22+
return new FunctionDefinition[][] {
23+
// Scalar functions
24+
// String
25+
new FunctionDefinition[] {
26+
def(Substring.class, Substring::new, "substring"),
27+
},
28+
};
29+
}
30+
31+
@Override
32+
protected String normalize(String name) {
33+
return name.toLowerCase(Locale.ROOT);
1434
}
1535
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.eql.expression.function.scalar.string;
8+
9+
import org.elasticsearch.common.Strings;
10+
11+
import static org.elasticsearch.common.Strings.hasLength;
12+
13+
final class StringUtils {
14+
15+
private StringUtils() {}
16+
17+
/**
18+
* Returns a substring using the Python slice semantics, meaning
19+
* start and end can be negative
20+
*/
21+
static String substringSlice(String string, int start, int end) {
22+
if (hasLength(string) == false) {
23+
return string;
24+
}
25+
26+
int length = string.length();
27+
28+
// handle first negative values
29+
if (start < 0) {
30+
start += length;
31+
}
32+
if (start < 0) {
33+
start = 0;
34+
}
35+
if (end < 0) {
36+
end += length;
37+
}
38+
if (end < 0) {
39+
end = 0;
40+
} else if (end > length) {
41+
end = length;
42+
}
43+
44+
if (start >= end) {
45+
return org.elasticsearch.xpack.ql.util.StringUtils.EMPTY;
46+
}
47+
48+
return Strings.substring(string, start, end);
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.eql.expression.function.scalar.string;
8+
9+
import org.elasticsearch.xpack.ql.expression.Expression;
10+
import org.elasticsearch.xpack.ql.expression.Expressions;
11+
import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal;
12+
import org.elasticsearch.xpack.ql.expression.FieldAttribute;
13+
import org.elasticsearch.xpack.ql.expression.Literal;
14+
import org.elasticsearch.xpack.ql.expression.function.OptionalArgument;
15+
import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction;
16+
import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe;
17+
import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate;
18+
import org.elasticsearch.xpack.ql.tree.NodeInfo;
19+
import org.elasticsearch.xpack.ql.tree.Source;
20+
import org.elasticsearch.xpack.ql.type.DataType;
21+
import org.elasticsearch.xpack.ql.type.DataTypes;
22+
23+
import java.util.Arrays;
24+
import java.util.List;
25+
import java.util.Locale;
26+
27+
import static java.lang.String.format;
28+
import static org.elasticsearch.xpack.eql.expression.function.scalar.string.SubstringFunctionProcessor.doProcess;
29+
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger;
30+
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact;
31+
import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder;
32+
33+
/**
34+
* EQL specific substring function - similar to the one in Python.
35+
* Note this is different than the one in SQL.
36+
*/
37+
public class Substring extends ScalarFunction implements OptionalArgument {
38+
39+
private final Expression source, start, end;
40+
41+
public Substring(Source source, Expression src, Expression start, Expression end) {
42+
super(source, Arrays.asList(src, start, end != null ? end : new Literal(source, null, DataTypes.NULL)));
43+
this.source = src;
44+
this.start = start;
45+
this.end = arguments().get(2);
46+
}
47+
48+
@Override
49+
protected TypeResolution resolveType() {
50+
if (!childrenResolved()) {
51+
return new TypeResolution("Unresolved children");
52+
}
53+
54+
TypeResolution sourceResolution = isStringAndExact(source, sourceText(), ParamOrdinal.FIRST);
55+
if (sourceResolution.unresolved()) {
56+
return sourceResolution;
57+
}
58+
59+
TypeResolution startResolution = isInteger(start, sourceText(), ParamOrdinal.SECOND);
60+
if (startResolution.unresolved()) {
61+
return startResolution;
62+
}
63+
64+
return isInteger(end, sourceText(), ParamOrdinal.THIRD);
65+
}
66+
67+
@Override
68+
protected Pipe makePipe() {
69+
return new SubstringFunctionPipe(source(), this, Expressions.pipe(source), Expressions.pipe(start), Expressions.pipe(end));
70+
}
71+
72+
@Override
73+
public boolean foldable() {
74+
return source.foldable() && start.foldable() && end.foldable();
75+
}
76+
77+
@Override
78+
public Object fold() {
79+
return doProcess(source.fold(), start.fold(), end.fold());
80+
}
81+
82+
@Override
83+
protected NodeInfo<? extends Expression> info() {
84+
return NodeInfo.create(this, Substring::new, source, start, end);
85+
}
86+
87+
@Override
88+
public ScriptTemplate asScript() {
89+
ScriptTemplate sourceScript = asScript(source);
90+
ScriptTemplate startScript = asScript(start);
91+
ScriptTemplate endScript = asScript(end);
92+
93+
return asScriptFrom(sourceScript, startScript, endScript);
94+
}
95+
96+
protected ScriptTemplate asScriptFrom(ScriptTemplate sourceScript, ScriptTemplate startScript, ScriptTemplate endScript) {
97+
return new ScriptTemplate(format(Locale.ROOT, formatTemplate("{eql}.%s(%s,%s,%s)"),
98+
"substring",
99+
sourceScript.template(),
100+
startScript.template(),
101+
endScript.template()),
102+
paramsBuilder()
103+
.script(sourceScript.params())
104+
.script(startScript.params())
105+
.script(endScript.params())
106+
.build(), dataType());
107+
}
108+
109+
@Override
110+
public ScriptTemplate scriptWithField(FieldAttribute field) {
111+
return new ScriptTemplate(processScript("doc[{}].value"),
112+
paramsBuilder().variable(field.exactAttribute().name()).build(),
113+
dataType());
114+
}
115+
116+
@Override
117+
public DataType dataType() {
118+
return DataTypes.KEYWORD;
119+
}
120+
121+
@Override
122+
public Expression replaceChildren(List<Expression> newChildren) {
123+
if (newChildren.size() != 3) {
124+
throw new IllegalArgumentException("expected [3] children but received [" + newChildren.size() + "]");
125+
}
126+
127+
return new Substring(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2));
128+
}
129+
}

0 commit comments

Comments
 (0)