Skip to content

Commit

Permalink
centralize datetime string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
fang-xing-esql committed Mar 16, 2024
1 parent fc6c2dc commit 64bc8a6
Show file tree
Hide file tree
Showing 14 changed files with 159 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,14 @@ birth_date:date |bd:date
1964-06-02T00:00:00.000Z|1964-06-02T00:00:00.000Z
;

convertFromString
convertFromString#[skip:-8.13.99, reason: default date formatter is changed in 8.14]
// tag::to_datetime-str[]
ROW string = ["1953-09-02T00:00:00.000Z", "1964-06-02T00:00:00.000Z", "1964-06-02 00:00:00"]
| EVAL datetime = TO_DATETIME(string)
// end::to_datetime-str[]
;
warning:Line 2:19: evaluation of [TO_DATETIME(string)] failed, treating result as null. Only first 20 failures recorded.
warning:Line 2:19: java.lang.IllegalArgumentException: failed to parse date field [1964-06-02 00:00:00] with format [yyyy-MM-dd'T'HH:mm:ss.SSS'Z']
warning:Line 2:19: java.lang.IllegalArgumentException: failed to parse date field [1964-06-02 00:00:00] with format [strict_date_optional_time]

// tag::to_datetime-str-result[]
string:keyword |datetime:date
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@

import java.io.IOException;

import static org.elasticsearch.xpack.ql.util.DateUtils.UTC_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeLongToString;
import static org.elasticsearch.xpack.ql.util.NumericUtils.unsignedLongAsNumber;
import static org.elasticsearch.xpack.ql.util.SpatialCoordinateTypes.CARTESIAN;
import static org.elasticsearch.xpack.ql.util.SpatialCoordinateTypes.GEO;
Expand Down Expand Up @@ -116,7 +117,7 @@ protected XContentBuilder valueToXContent(XContentBuilder builder, ToXContent.Pa
protected XContentBuilder valueToXContent(XContentBuilder builder, ToXContent.Params params, int valueIndex)
throws IOException {
long longVal = ((LongBlock) block).getLong(valueIndex);
return builder.value(UTC_DATE_TIME_FORMATTER.formatMillis(longVal));
return builder.value(convertDatetimeLongToString(longVal, ESQL_DEFAULT_DATE_TIME_FORMATTER));
}
};
case "geo_point", "geo_shape" -> new PositionToXContent(block) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@
import java.util.List;
import java.util.Map;

import static org.elasticsearch.xpack.ql.util.DateUtils.UTC_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeLongToString;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeStringToLong;
import static org.elasticsearch.xpack.ql.util.NumericUtils.asLongUnsigned;
import static org.elasticsearch.xpack.ql.util.NumericUtils.unsignedLongAsNumber;
import static org.elasticsearch.xpack.ql.util.SpatialCoordinateTypes.CARTESIAN;
Expand Down Expand Up @@ -97,7 +99,7 @@ private static Object valueAt(String dataType, Block block, int offset, BytesRef
}
case "date" -> {
long longVal = ((LongBlock) block).getLong(offset);
yield UTC_DATE_TIME_FORMATTER.formatMillis(longVal);
yield convertDatetimeLongToString(longVal, ESQL_DEFAULT_DATE_TIME_FORMATTER);
}
case "boolean" -> ((BooleanBlock) block).getBoolean(offset);
case "version" -> new Version(((BytesRefBlock) block).getBytesRef(offset, scratch)).toString();
Expand Down Expand Up @@ -143,7 +145,7 @@ static Page valuesToPage(BlockFactory blockFactory, List<ColumnInfo> columns, Li
);
case "ip" -> ((BytesRefBlock.Builder) builder).appendBytesRef(parseIP(value.toString()));
case "date" -> {
long longVal = UTC_DATE_TIME_FORMATTER.parseMillis(value.toString());
long longVal = convertDatetimeStringToLong(value.toString(), ESQL_DEFAULT_DATE_TIME_FORMATTER);
((LongBlock.Builder) builder).appendLong(longVal);
}
case "boolean" -> ((BooleanBlock.Builder) builder).appendBoolean(((Boolean) value));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import org.elasticsearch.common.logging.HeaderWarning;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;
import org.elasticsearch.xpack.esql.EsqlIllegalArgumentException;
import org.elasticsearch.xpack.esql.VerificationException;
Expand Down Expand Up @@ -80,6 +79,8 @@
import static java.util.Collections.singletonList;
import static org.elasticsearch.common.logging.LoggerMessageFormat.format;
import static org.elasticsearch.xpack.esql.stats.FeatureMetric.LIMIT;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeStringToLong;
import static org.elasticsearch.xpack.ql.analyzer.AnalyzerRules.resolveFunction;
import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME;
import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD;
Expand Down Expand Up @@ -750,7 +751,7 @@ private static Expression stringToDate(Expression stringExpression) {
Long millis = null;
// TODO: better control over this string format - do we want this to be flexible or always redirect folks to use date parsing
try {
millis = str == null ? null : DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parseMillis(str);
millis = str == null ? null : convertDatetimeStringToLong(str, ESQL_DEFAULT_DATE_TIME_FORMATTER);
} catch (Exception ex) { // in case of exception, millis will be null which will trigger an error
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.elasticsearch.compute.ann.ConvertEvaluator;
import org.elasticsearch.xpack.esql.expression.function.FunctionInfo;
import org.elasticsearch.xpack.esql.expression.function.Param;
import org.elasticsearch.xpack.esql.expression.function.scalar.date.DateParse;
import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
import org.elasticsearch.xpack.ql.tree.Source;
Expand All @@ -20,6 +19,8 @@
import java.util.List;
import java.util.Map;

import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeStringToLong;
import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME;
import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE;
import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER;
Expand Down Expand Up @@ -70,6 +71,6 @@ protected NodeInfo<? extends Expression> info() {

@ConvertEvaluator(extraName = "FromString", warnExceptions = { IllegalArgumentException.class })
static long fromKeyword(BytesRef in) {
return DateParse.process(in, DateParse.DEFAULT_FORMATTER);
return convertDatetimeStringToLong(in.utf8ToString(), ESQL_DEFAULT_DATE_TIME_FORMATTER);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
import java.util.List;
import java.util.Map;

import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.EsqlConverter.STRING_TO_IP;
import static org.elasticsearch.xpack.ql.type.DataTypes.IP;
import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD;
import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT;
import static org.elasticsearch.xpack.ql.util.StringUtils.parseIP;

public class ToIP extends AbstractConvertFunction {

Expand Down Expand Up @@ -59,6 +59,6 @@ protected NodeInfo<? extends Expression> info() {

@ConvertEvaluator(extraName = "FromString", warnExceptions = { IllegalArgumentException.class })
static BytesRef fromKeyword(BytesRef asString) {
return parseIP(asString.utf8ToString());
return (BytesRef) STRING_TO_IP.convert(asString);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import java.util.List;
import java.util.Map;

import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeLongToString;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypes.CARTESIAN_POINT;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypes.CARTESIAN_SHAPE;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypes.GEO_POINT;
Expand All @@ -36,7 +38,6 @@
import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT;
import static org.elasticsearch.xpack.ql.type.DataTypes.UNSIGNED_LONG;
import static org.elasticsearch.xpack.ql.type.DataTypes.VERSION;
import static org.elasticsearch.xpack.ql.util.DateUtils.UTC_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.ql.util.NumericUtils.unsignedLongAsNumber;
import static org.elasticsearch.xpack.ql.util.SpatialCoordinateTypes.CARTESIAN;
import static org.elasticsearch.xpack.ql.util.SpatialCoordinateTypes.GEO;
Expand Down Expand Up @@ -117,7 +118,7 @@ static BytesRef fromIP(BytesRef ip) {

@ConvertEvaluator(extraName = "FromDatetime")
static BytesRef fromDatetime(long datetime) {
return new BytesRef(UTC_DATE_TIME_FORMATTER.formatMillis(datetime));
return new BytesRef(convertDatetimeLongToString(datetime, ESQL_DEFAULT_DATE_TIME_FORMATTER));
}

@ConvertEvaluator(extraName = "FromDouble")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
package org.elasticsearch.xpack.esql.expression.function.scalar.date;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.compute.ann.Evaluator;
import org.elasticsearch.compute.ann.Fixed;
import org.elasticsearch.compute.operator.EvalOperator.ExpressionEvaluator;
Expand All @@ -24,13 +23,13 @@
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.type.DataTypes;

import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;

import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.EsqlConverter.STRING_TO_CHRONO_FIELD;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.extractLongChronoField;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isDate;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact;

Expand Down Expand Up @@ -76,27 +75,21 @@ private ChronoField chronoField() {
// TODO: move the slimmed down code here to toEvaluator?
if (chronoField == null) {
Expression field = children().get(0);
if (field.foldable() && field.dataType() == DataTypes.KEYWORD) {
try {
BytesRef br = BytesRefs.toBytesRef(field.fold());
chronoField = ChronoField.valueOf(br.utf8ToString().toUpperCase(Locale.ROOT));
} catch (Exception e) {
return null;
}
if (field.foldable()) {
chronoField = (ChronoField) STRING_TO_CHRONO_FIELD.convert(field);
}
}
return chronoField;
}

@Evaluator(warnExceptions = { IllegalArgumentException.class })
static long process(long value, BytesRef chronoField, @Fixed ZoneId zone) {
ChronoField chrono = ChronoField.valueOf(chronoField.utf8ToString().toUpperCase(Locale.ROOT));
return Instant.ofEpochMilli(value).atZone(zone).getLong(chrono);
return extractLongChronoField(value, chronoField, zone);
}

@Evaluator(extraName = "Constant")
static long process(long value, @Fixed ChronoField chronoField, @Fixed ZoneId zone) {
return Instant.ofEpochMilli(value).atZone(zone).getLong(chronoField);
return extractLongChronoField(value, chronoField, zone);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
import java.util.Locale;
import java.util.function.Function;

import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeLongToString;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.FIRST;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.SECOND;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isDate;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact;
import static org.elasticsearch.xpack.ql.util.DateUtils.UTC_DATE_TIME_FORMATTER;

public class DateFormat extends EsqlConfigurationFunction implements OptionalArgument {

Expand Down Expand Up @@ -83,19 +84,24 @@ public boolean foldable() {

@Evaluator(extraName = "Constant")
static BytesRef process(long val, @Fixed DateFormatter formatter) {
return new BytesRef(formatter.formatMillis(val));
return new BytesRef(convertDatetimeLongToString(val, formatter));
}

@Evaluator
static BytesRef process(long val, BytesRef formatter, @Fixed Locale locale) {
return process(val, toFormatter(formatter, locale));
return new BytesRef(convertDatetimeLongToString(val, toFormatter(formatter, locale)));
}

@Override
public ExpressionEvaluator.Factory toEvaluator(Function<Expression, ExpressionEvaluator.Factory> toEvaluator) {
var fieldEvaluator = toEvaluator.apply(field);
if (format == null) {
return dvrCtx -> new DateFormatConstantEvaluator(source(), fieldEvaluator.get(dvrCtx), UTC_DATE_TIME_FORMATTER, dvrCtx);
return dvrCtx -> new DateFormatConstantEvaluator(
source(),
fieldEvaluator.get(dvrCtx),
ESQL_DEFAULT_DATE_TIME_FORMATTER,
dvrCtx
);
}
if (format.dataType() != DataTypes.KEYWORD) {
throw new IllegalArgumentException("unsupported data type for format [" + format.dataType() + "]");
Expand All @@ -115,7 +121,9 @@ public ExpressionEvaluator.Factory toEvaluator(Function<Expression, ExpressionEv
}

private static DateFormatter toFormatter(Object format, Locale locale) {
DateFormatter result = format == null ? UTC_DATE_TIME_FORMATTER : DateFormatter.forPattern(((BytesRef) format).utf8ToString());
DateFormatter result = format == null
? ESQL_DEFAULT_DATE_TIME_FORMATTER
: DateFormatter.forPattern(((BytesRef) format).utf8ToString());
return result.withLocale(locale);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import java.util.function.Function;

import static org.elasticsearch.common.time.DateFormatter.forPattern;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.ESQL_DEFAULT_DATE_TIME_FORMATTER;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convertDatetimeStringToLong;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.FIRST;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.SECOND;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString;
Expand All @@ -36,7 +38,6 @@

public class DateParse extends EsqlScalarFunction implements OptionalArgument {

public static final DateFormatter DEFAULT_FORMATTER = toFormatter(new BytesRef("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), UTC);
private final Expression field;
private final Expression format;

Expand Down Expand Up @@ -83,21 +84,20 @@ public boolean foldable() {

@Evaluator(extraName = "Constant", warnExceptions = { IllegalArgumentException.class })
public static long process(BytesRef val, @Fixed DateFormatter formatter) throws IllegalArgumentException {
String dateString = val.utf8ToString();
return formatter.parseMillis(dateString);
return convertDatetimeStringToLong(val.utf8ToString(), formatter);
}

@Evaluator(warnExceptions = { IllegalArgumentException.class })
static long process(BytesRef val, BytesRef formatter, @Fixed ZoneId zoneId) throws IllegalArgumentException {
return process(val, toFormatter(formatter, zoneId));
return convertDatetimeStringToLong(val.utf8ToString(), toFormatter(formatter, zoneId));
}

@Override
public ExpressionEvaluator.Factory toEvaluator(Function<Expression, ExpressionEvaluator.Factory> toEvaluator) {
ZoneId zone = UTC; // TODO session timezone?
ExpressionEvaluator.Factory fieldEvaluator = toEvaluator.apply(field);
if (format == null) {
return new DateParseConstantEvaluator.Factory(source(), fieldEvaluator, DEFAULT_FORMATTER);
return new DateParseConstantEvaluator.Factory(source(), fieldEvaluator, ESQL_DEFAULT_DATE_TIME_FORMATTER);
}
if (format.dataType() != DataTypes.KEYWORD) {
throw new IllegalArgumentException("unsupported data type for date_parse [" + format.dataType() + "]");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
package org.elasticsearch.xpack.esql.expression.function.scalar.math;

import org.elasticsearch.common.Rounding;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.compute.operator.EvalOperator.ExpressionEvaluator;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.xpack.esql.EsqlIllegalArgumentException;
import org.elasticsearch.xpack.esql.capabilities.Validatable;
import org.elasticsearch.xpack.esql.expression.function.FunctionInfo;
Expand All @@ -22,7 +20,6 @@
import org.elasticsearch.xpack.esql.expression.predicate.operator.arithmetic.Mul;
import org.elasticsearch.xpack.ql.common.Failures;
import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.expression.Foldables;
import org.elasticsearch.xpack.ql.expression.Literal;
import org.elasticsearch.xpack.ql.expression.TypeResolutions;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
Expand All @@ -35,6 +32,8 @@
import java.util.function.Function;

import static org.elasticsearch.xpack.esql.expression.Validations.isFoldable;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.EsqlConverter.STRING_DATETIME_TO_LONG;
import static org.elasticsearch.xpack.esql.type.EsqlDataTypeConverter.convert;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.FIRST;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.FOURTH;
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.SECOND;
Expand Down Expand Up @@ -110,17 +109,17 @@ public ExpressionEvaluator.Factory toEvaluator(Function<Expression, ExpressionEv
int b = ((Number) buckets.fold()).intValue();

if (field.dataType() == DataTypes.DATETIME) {
long f = foldToLong(from);
long t = foldToLong(to);
long f = (long) STRING_DATETIME_TO_LONG.convert(from);
long t = (long) STRING_DATETIME_TO_LONG.convert(to);
return DateTrunc.evaluator(
source(),
toEvaluator.apply(field),
new DateRoundingPicker(b, f, t).pickRounding().prepareForUnknown()
);
}
if (field.dataType().isNumeric()) {
double f = ((Number) from.fold()).doubleValue();
double t = ((Number) to.fold()).doubleValue();
double f = (double) convert(from.fold(), DataTypes.DOUBLE);
double t = (double) convert(to.fold(), DataTypes.DOUBLE);

// We could make this more efficient, either by generating the evaluators with byte code or hand rolling this one.
Literal rounding = new Literal(source(), pickRounding(b, f, t), DataTypes.DOUBLE);
Expand Down Expand Up @@ -211,13 +210,6 @@ public void validate(Failures failures) {
failures.add(isFoldable(buckets, operation, SECOND)).add(isFoldable(from, operation, THIRD)).add(isFoldable(to, operation, FOURTH));
}

private long foldToLong(Expression e) {
Object value = Foldables.valueOf(e);
return DataTypes.isDateTime(e.dataType())
? ((Number) value).longValue()
: DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parseMillis(BytesRefs.toString(value));
}

@Override
public DataType dataType() {
if (field.dataType().isNumeric()) {
Expand Down
Loading

0 comments on commit 64bc8a6

Please sign in to comment.