diff --git a/core/src/main/java/org/opensearch/sql/analysis/Analyzer.java b/core/src/main/java/org/opensearch/sql/analysis/Analyzer.java index d5e8b93b13..33b924ff53 100644 --- a/core/src/main/java/org/opensearch/sql/analysis/Analyzer.java +++ b/core/src/main/java/org/opensearch/sql/analysis/Analyzer.java @@ -32,6 +32,7 @@ import org.opensearch.sql.analysis.symbol.Namespace; import org.opensearch.sql.analysis.symbol.Symbol; import org.opensearch.sql.ast.AbstractNodeVisitor; +import org.opensearch.sql.ast.Node; import org.opensearch.sql.ast.expression.Argument; import org.opensearch.sql.ast.expression.Field; import org.opensearch.sql.ast.expression.Let; @@ -174,7 +175,7 @@ public LogicalPlan visitRelation(Relation node, AnalysisContext context) { @Override public LogicalPlan visitRelationSubquery(RelationSubquery node, AnalysisContext context) { - LogicalPlan subquery = analyze(node.getChild().get(0), context); + LogicalPlan subquery = visitFirstChild(node, context); // inherit the parent environment to keep the subquery fields in current environment TypeEnvironment curEnv = context.peek(); @@ -227,13 +228,13 @@ public LogicalPlan visitTableFunction(TableFunction node, AnalysisContext contex @Override public LogicalPlan visitLimit(Limit node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); return new LogicalLimit(child, node.getLimit(), node.getOffset()); } @Override public LogicalPlan visitFilter(Filter node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); Expression condition = expressionAnalyzer.analyze(node.getCondition(), context); ExpressionReferenceOptimizer optimizer = @@ -259,15 +260,14 @@ private void verifySupportsCondition(Expression condition) { "Falling back to legacy engine. Nested function is not supported in WHERE," + " GROUP BY, and HAVING clauses."); } - ((FunctionExpression) condition) - .getArguments().stream().forEach(e -> verifySupportsCondition(e)); + ((FunctionExpression) condition).getArguments().forEach(this::verifySupportsCondition); } } /** Build {@link LogicalRename}. */ @Override public LogicalPlan visitRename(Rename node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); ImmutableMap.Builder renameMapBuilder = new ImmutableMap.Builder<>(); for (Map renameMap : node.getRenameList()) { @@ -294,7 +294,7 @@ public LogicalPlan visitRename(Rename node, AnalysisContext context) { /** Build {@link LogicalAggregation}. */ @Override public LogicalPlan visitAggregation(Aggregation node, AnalysisContext context) { - final LogicalPlan child = node.getChild().get(0).accept(this, context); + final LogicalPlan child = visitFirstChild(node, context); ImmutableList.Builder aggregatorBuilder = new ImmutableList.Builder<>(); for (UnresolvedExpression expr : node.getAggExprList()) { NamedExpression aggExpr = namedExpressionAnalyzer.analyze(expr, context); @@ -332,7 +332,7 @@ public LogicalPlan visitAggregation(Aggregation node, AnalysisContext context) { /** Build {@link LogicalRareTopN}. */ @Override public LogicalPlan visitRareTopN(RareTopN node, AnalysisContext context) { - final LogicalPlan child = node.getChild().get(0).accept(this, context); + final LogicalPlan child = visitFirstChild(node, context); ImmutableList.Builder groupbyBuilder = new ImmutableList.Builder<>(); for (UnresolvedExpression expr : node.getGroupExprList()) { @@ -355,7 +355,7 @@ public LogicalPlan visitRareTopN(RareTopN node, AnalysisContext context) { field -> newEnv.define(new Symbol(Namespace.FIELD_NAME, field.toString()), field.type())); List options = node.getNoOfResults(); - Integer noOfResults = (Integer) options.get(0).getValue().getValue(); + Integer noOfResults = (Integer) options.getFirst().getValue().getValue(); return new LogicalRareTopN(child, node.getCommandType(), noOfResults, fields, groupBys); } @@ -373,10 +373,10 @@ public LogicalPlan visitRareTopN(RareTopN node, AnalysisContext context) { */ @Override public LogicalPlan visitProject(Project node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); if (node.hasArgument()) { - Argument argument = node.getArgExprList().get(0); + Argument argument = node.getArgExprList().getFirst(); Boolean exclude = (Boolean) argument.getValue().getValue(); if (exclude) { TypeEnvironment curEnv = context.peek(); @@ -384,7 +384,7 @@ public LogicalPlan visitProject(Project node, AnalysisContext context) { node.getProjectList().stream() .map(expr -> (ReferenceExpression) expressionAnalyzer.analyze(expr, context)) .collect(Collectors.toList()); - referenceExpressions.forEach(ref -> curEnv.remove(ref)); + referenceExpressions.forEach(curEnv::remove); return new LogicalRemove(child, ImmutableSet.copyOf(referenceExpressions)); } } @@ -427,7 +427,7 @@ public LogicalPlan visitProject(Project node, AnalysisContext context) { /** Build {@link LogicalEval}. */ @Override public LogicalPlan visitEval(Eval node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); ImmutableList.Builder> expressionsBuilder = new Builder<>(); for (Let let : node.getExpressionList()) { @@ -444,7 +444,7 @@ public LogicalPlan visitEval(Eval node, AnalysisContext context) { /** Build {@link ParseExpression} to context and skip to child nodes. */ @Override public LogicalPlan visitParse(Parse node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); Expression sourceField = expressionAnalyzer.analyze(node.getSourceField(), context); ParseMethod parseMethod = node.getParseMethod(); java.util.Map arguments = node.getArguments(); @@ -467,7 +467,7 @@ public LogicalPlan visitParse(Parse node, AnalysisContext context) { /** Build {@link LogicalSort}. */ @Override public LogicalPlan visitSort(Sort node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); ExpressionReferenceOptimizer optimizer = new ExpressionReferenceOptimizer(expressionAnalyzer.getRepository(), child); @@ -490,7 +490,7 @@ public LogicalPlan visitSort(Sort node, AnalysisContext context) { /** Build {@link LogicalDedupe}. */ @Override public LogicalPlan visitDedupe(Dedupe node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); List options = node.getOptions(); // Todo, refactor the option. Integer allowedDuplication = (Integer) options.get(0).getValue().getValue(); @@ -509,7 +509,7 @@ public LogicalPlan visitDedupe(Dedupe node, AnalysisContext context) { /** Logical head is identical to {@link LogicalLimit}. */ public LogicalPlan visitHead(Head node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); return new LogicalLimit(child, node.getSize(), node.getFrom()); } @@ -529,7 +529,7 @@ public LogicalPlan visitValues(Values node, AnalysisContext context) { /** Build {@link LogicalMLCommons} for Kmeans command. */ @Override public LogicalPlan visitKmeans(Kmeans node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); java.util.Map options = node.getArguments(); TypeEnvironment currentEnv = context.peek(); @@ -541,7 +541,7 @@ public LogicalPlan visitKmeans(Kmeans node, AnalysisContext context) { /** Build {@link LogicalAD} for AD command. */ @Override public LogicalPlan visitAD(AD node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); java.util.Map options = node.getArguments(); TypeEnvironment currentEnv = context.peek(); @@ -561,18 +561,17 @@ public LogicalPlan visitAD(AD node, AnalysisContext context) { /** Build {@link LogicalML} for ml command. */ @Override public LogicalPlan visitML(ML node, AnalysisContext context) { - LogicalPlan child = node.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(node, context); TypeEnvironment currentEnv = context.peek(); - node.getOutputSchema(currentEnv).entrySet().stream() - .forEach( - v -> currentEnv.define(new Symbol(Namespace.FIELD_NAME, v.getKey()), v.getValue())); + node.getOutputSchema(currentEnv) + .forEach((key, value) -> currentEnv.define(new Symbol(Namespace.FIELD_NAME, key), value)); return new LogicalML(child, node.getArguments()); } @Override public LogicalPlan visitPaginate(Paginate paginate, AnalysisContext context) { - LogicalPlan child = paginate.getChild().get(0).accept(this, context); + LogicalPlan child = visitFirstChild(paginate, context); return new LogicalPaginate(paginate.getPageSize(), List.of(child)); } @@ -585,7 +584,8 @@ public LogicalPlan visitFetchCursor(FetchCursor cursor, AnalysisContext context) @Override public LogicalPlan visitCloseCursor(CloseCursor closeCursor, AnalysisContext context) { - return new LogicalCloseCursor(closeCursor.getChild().get(0).accept(this, context)); + LogicalPlan child = visitFirstChild(closeCursor, context); + return new LogicalCloseCursor(child); } /** @@ -593,7 +593,7 @@ public LogicalPlan visitCloseCursor(CloseCursor closeCursor, AnalysisContext con * value. Otherwise just use DEFAULT_ASC/DESC. */ private SortOption analyzeSortOption(List fieldArgs) { - Boolean asc = (Boolean) fieldArgs.get(0).getValue().getValue(); + Boolean asc = (Boolean) fieldArgs.getFirst().getValue().getValue(); Optional nullFirst = fieldArgs.stream().filter(option -> "nullFirst".equals(option.getArgName())).findFirst(); @@ -603,4 +603,13 @@ private SortOption analyzeSortOption(List fieldArgs) { } return asc ? SortOption.DEFAULT_ASC : SortOption.DEFAULT_DESC; } + + /** + * Visit the first child of the specified node with the given analysis context. + * + * @return the resulting logical plan + */ + private LogicalPlan visitFirstChild(Node node, AnalysisContext context) { + return node.getChild().getFirst().accept(this, context); + } } diff --git a/core/src/main/java/org/opensearch/sql/analysis/WindowExpressionAnalyzer.java b/core/src/main/java/org/opensearch/sql/analysis/WindowExpressionAnalyzer.java index c4229e4664..f64b93a44a 100644 --- a/core/src/main/java/org/opensearch/sql/analysis/WindowExpressionAnalyzer.java +++ b/core/src/main/java/org/opensearch/sql/analysis/WindowExpressionAnalyzer.java @@ -55,11 +55,10 @@ public LogicalPlan analyze(UnresolvedExpression projectItem, AnalysisContext con @Override public LogicalPlan visitAlias(Alias node, AnalysisContext context) { - if (!(node.getDelegated() instanceof WindowFunction)) { + if (!(node.getDelegated() instanceof WindowFunction unresolved)) { return null; } - WindowFunction unresolved = (WindowFunction) node.getDelegated(); Expression windowFunction = expressionAnalyzer.analyze(unresolved, context); List partitionByList = analyzePartitionList(unresolved, context); List> sortList = analyzeSortList(unresolved, context); @@ -98,9 +97,9 @@ private List> analyzeSortList( * The final and default value for each is determined here during expression analysis. */ private SortOption analyzeSortOption(SortOption option) { - if (option.getNullOrder() == null) { - return (option.getSortOrder() == DESC) ? DEFAULT_DESC : DEFAULT_ASC; + if (option.nullOrder() == null) { + return (option.sortOrder() == DESC) ? DEFAULT_DESC : DEFAULT_ASC; } - return new SortOption((option.getSortOrder() == DESC) ? DESC : ASC, option.getNullOrder()); + return new SortOption((option.sortOrder() == DESC) ? DESC : ASC, option.nullOrder()); } } diff --git a/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java b/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java index 4f3056b0f7..4e0a5f9355 100644 --- a/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java +++ b/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java @@ -396,10 +396,6 @@ public static List exprList(Argument... exprList) { return Arrays.asList(exprList); } - public static List unresolvedArgList(UnresolvedArgument... exprList) { - return Arrays.asList(exprList); - } - public static List defaultFieldsArgs() { return exprList(argument("exclude", booleanLiteral(false))); } @@ -421,10 +417,6 @@ public static List defaultDedupArgs() { argument("consecutive", booleanLiteral(false))); } - public static List sortOptions() { - return exprList(argument("desc", booleanLiteral(false))); - } - public static List defaultSortFieldArgs() { return exprList(argument("asc", booleanLiteral(true)), argument("type", nullLiteral())); } @@ -445,10 +437,6 @@ public static Head head(UnresolvedPlan input, Integer size, Integer from) { return new Head(input, size, from); } - public static List defaultTopArgs() { - return exprList(argument("noOfResults", intLiteral(10))); - } - public static RareTopN rareTopN( UnresolvedPlan input, CommandType commandType, diff --git a/core/src/main/java/org/opensearch/sql/ast/tree/Sort.java b/core/src/main/java/org/opensearch/sql/ast/tree/Sort.java index 073cb7aa1b..a404137ae7 100644 --- a/core/src/main/java/org/opensearch/sql/ast/tree/Sort.java +++ b/core/src/main/java/org/opensearch/sql/ast/tree/Sort.java @@ -13,7 +13,6 @@ import com.google.common.collect.ImmutableList; import java.util.List; import lombok.AllArgsConstructor; -import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -48,17 +47,13 @@ public T accept(AbstractNodeVisitor nodeVisitor, C context) { } /** Sort Options. */ - @Data - public static class SortOption { + public record SortOption(SortOrder sortOrder, NullOrder nullOrder) { /** Default ascending sort option, null first. */ public static SortOption DEFAULT_ASC = new SortOption(ASC, NULL_FIRST); /** Default descending sort option, null last. */ public static SortOption DEFAULT_DESC = new SortOption(DESC, NULL_LAST); - - private final SortOrder sortOrder; - private final NullOrder nullOrder; } public enum SortOrder { diff --git a/core/src/main/java/org/opensearch/sql/data/model/ExprValueUtils.java b/core/src/main/java/org/opensearch/sql/data/model/ExprValueUtils.java index 20813045f2..b6483774f7 100644 --- a/core/src/main/java/org/opensearch/sql/data/model/ExprValueUtils.java +++ b/core/src/main/java/org/opensearch/sql/data/model/ExprValueUtils.java @@ -100,56 +100,35 @@ public static ExprValue nullValue() { /** Construct ExprValue from Object. */ public static ExprValue fromObjectValue(Object o) { - if (null == o) { - return LITERAL_NULL; - } - if (o instanceof Map) { - return tupleValue((Map) o); - } else if (o instanceof List) { - return collectionValue(((List) o)); - } else if (o instanceof Byte) { - return byteValue((Byte) o); - } else if (o instanceof Short) { - return shortValue((Short) o); - } else if (o instanceof Integer) { - return integerValue((Integer) o); - } else if (o instanceof Long) { - return longValue(((Long) o)); - } else if (o instanceof Boolean) { - return booleanValue((Boolean) o); - } else if (o instanceof Double) { - return doubleValue((Double) o); - } else if (o instanceof String) { - return stringValue((String) o); - } else if (o instanceof Float) { - return floatValue((Float) o); - } else if (o instanceof LocalDate) { - return dateValue((LocalDate) o); - } else if (o instanceof LocalTime) { - return timeValue((LocalTime) o); - } else if (o instanceof Instant) { - return timestampValue((Instant) o); - } else if (o instanceof TemporalAmount) { - return intervalValue((TemporalAmount) o); - } else if (o instanceof LocalDateTime) { - return timestampValue(((LocalDateTime) o).toInstant(ZoneOffset.UTC)); - } else { - throw new ExpressionEvaluationException("unsupported object " + o.getClass()); - } + return switch (o) { + case null -> LITERAL_NULL; + case Map map -> tupleValue(map); + case List list -> collectionValue(list); + case Byte b -> byteValue(b); + case Short i -> shortValue(i); + case Integer i -> integerValue(i); + case Long l -> longValue(l); + case Boolean b -> booleanValue(b); + case Double v -> doubleValue(v); + case String s -> stringValue(s); + case Float v -> floatValue(v); + case LocalDate localDate -> dateValue(localDate); + case LocalTime localTime -> timeValue(localTime); + case Instant instant -> timestampValue(instant); + case TemporalAmount temporalAmount -> intervalValue(temporalAmount); + case LocalDateTime localDateTime -> timestampValue(localDateTime.toInstant(ZoneOffset.UTC)); + default -> throw new ExpressionEvaluationException("unsupported object " + o.getClass()); + }; } /** Construct ExprValue from Object with ExprCoreType. */ public static ExprValue fromObjectValue(Object o, ExprCoreType type) { - switch (type) { - case TIMESTAMP: - return new ExprTimestampValue((String) o); - case DATE: - return new ExprDateValue((String) o); - case TIME: - return new ExprTimeValue((String) o); - default: - return fromObjectValue(o); - } + return switch (type) { + case TIMESTAMP -> new ExprTimestampValue((String) o); + case DATE -> new ExprDateValue((String) o); + case TIME -> new ExprTimeValue((String) o); + default -> fromObjectValue(o); + }; } public static Byte getByteValue(ExprValue exprValue) { diff --git a/core/src/main/java/org/opensearch/sql/data/type/ExprType.java b/core/src/main/java/org/opensearch/sql/data/type/ExprType.java index 58d6ee346b..2732854a14 100644 --- a/core/src/main/java/org/opensearch/sql/data/type/ExprType.java +++ b/core/src/main/java/org/opensearch/sql/data/type/ExprType.java @@ -7,7 +7,6 @@ import static org.opensearch.sql.data.type.ExprCoreType.UNKNOWN; -import java.util.Arrays; import java.util.List; import org.opensearch.sql.data.model.ExprValue; import org.opensearch.sql.expression.Expression; @@ -44,7 +43,7 @@ default boolean shouldCast(ExprType other) { /** Get the parent type. */ default List getParent() { - return Arrays.asList(UNKNOWN); + return List.of(UNKNOWN); } /** Get the type name. */ diff --git a/core/src/main/java/org/opensearch/sql/executor/Explain.java b/core/src/main/java/org/opensearch/sql/executor/Explain.java index fffbe6f693..56abf17f16 100644 --- a/core/src/main/java/org/opensearch/sql/executor/Explain.java +++ b/core/src/main/java/org/opensearch/sql/executor/Explain.java @@ -242,7 +242,7 @@ private Map> describeSortList( p -> p.getRight().toString(), p -> ImmutableMap.of( - "sortOrder", p.getLeft().getSortOrder().toString(), - "nullOrder", p.getLeft().getNullOrder().toString()))); + "sortOrder", p.getLeft().sortOrder().toString(), + "nullOrder", p.getLeft().nullOrder().toString()))); } } diff --git a/core/src/main/java/org/opensearch/sql/expression/aggregation/AvgAggregator.java b/core/src/main/java/org/opensearch/sql/expression/aggregation/AvgAggregator.java index c32ebb6071..532258e5e7 100644 --- a/core/src/main/java/org/opensearch/sql/expression/aggregation/AvgAggregator.java +++ b/core/src/main/java/org/opensearch/sql/expression/aggregation/AvgAggregator.java @@ -43,19 +43,15 @@ public AvgAggregator(List arguments, ExprCoreType returnType) { @Override public AvgState create() { - switch (dataType) { - case DATE: - return new DateAvgState(); - case TIMESTAMP: - return new TimestampAvgState(); - case TIME: - return new TimeAvgState(); - case DOUBLE: - return new DoubleAvgState(); - default: // unreachable code - we don't expose signatures for unsupported types - throw new IllegalArgumentException( - String.format("avg aggregation over %s type is not supported", dataType)); - } + // unreachable code - we don't expose signatures for unsupported types + return switch (dataType) { + case DATE -> new DateAvgState(); + case TIMESTAMP -> new TimestampAvgState(); + case TIME -> new TimeAvgState(); + case DOUBLE -> new DoubleAvgState(); + default -> throw new IllegalArgumentException( + String.format("avg aggregation over %s type is not supported", dataType)); + }; } @Override diff --git a/core/src/main/java/org/opensearch/sql/expression/datetime/DateTimeFunctions.java b/core/src/main/java/org/opensearch/sql/expression/datetime/DateTimeFunctions.java index 411bd27993..f23a4c9411 100644 --- a/core/src/main/java/org/opensearch/sql/expression/datetime/DateTimeFunctions.java +++ b/core/src/main/java/org/opensearch/sql/expression/datetime/DateTimeFunctions.java @@ -836,9 +836,7 @@ private DefaultFunctionResolver str_to_date() { return define( BuiltinFunctionName.STR_TO_DATE.getName(), implWithProperties( - nullMissingHandlingWithProperties( - (functionProperties, arg, format) -> - DateTimeFunctions.exprStrToDate(functionProperties, arg, format)), + nullMissingHandlingWithProperties(DateTimeFunctions::exprStrToDate), TIMESTAMP, STRING, STRING)); @@ -952,9 +950,7 @@ private DefaultFunctionResolver timestampdiff() { TIMESTAMP, TIMESTAMP), implWithProperties( - nullMissingHandlingWithProperties( - (functionProperties, part, startTime, endTime) -> - exprTimestampDiffForTimeType(functionProperties, part, startTime, endTime)), + nullMissingHandlingWithProperties(DateTimeFunctions::exprTimestampDiffForTimeType), TIMESTAMP, STRING, TIME, @@ -998,21 +994,21 @@ private FunctionResolver unix_timestamp() { private DefaultFunctionResolver utc_date() { return define( BuiltinFunctionName.UTC_DATE.getName(), - implWithProperties(functionProperties -> exprUtcDate(functionProperties), DATE)); + implWithProperties(DateTimeFunctions::exprUtcDate, DATE)); } /** UTC_TIME(). return the current UTC Time in format HH:mm:ss */ private DefaultFunctionResolver utc_time() { return define( BuiltinFunctionName.UTC_TIME.getName(), - implWithProperties(functionProperties -> exprUtcTime(functionProperties), TIME)); + implWithProperties(DateTimeFunctions::exprUtcTime, TIME)); } /** UTC_TIMESTAMP(). return the current UTC TimeStamp in format yyyy-MM-dd HH:mm:ss */ private DefaultFunctionResolver utc_timestamp() { return define( BuiltinFunctionName.UTC_TIMESTAMP.getName(), - implWithProperties(functionProperties -> exprUtcTimeStamp(functionProperties), TIMESTAMP)); + implWithProperties(DateTimeFunctions::exprUtcTimeStamp, TIMESTAMP)); } /** WEEK(DATE[,mode]). return the week number for date. */ @@ -2028,32 +2024,23 @@ private DateTimeFormatter getFormatter(int dateAsInt) { } // Check below from YYYYMMDD - MMDD which format should be used - switch (length) { + return switch (length) { // Check if dateAsInt is at least 8 digits long - case FULL_DATE_LENGTH: - return DATE_FORMATTER_LONG_YEAR; + case FULL_DATE_LENGTH -> DATE_FORMATTER_LONG_YEAR; // Check if dateAsInt is at least 6 digits long - case SHORT_DATE_LENGTH: - return DATE_FORMATTER_SHORT_YEAR; + case SHORT_DATE_LENGTH -> DATE_FORMATTER_SHORT_YEAR; // Check if dateAsInt is at least 5 digits long - case SINGLE_DIGIT_YEAR_DATE_LENGTH: - return DATE_FORMATTER_SINGLE_DIGIT_YEAR; + case SINGLE_DIGIT_YEAR_DATE_LENGTH -> DATE_FORMATTER_SINGLE_DIGIT_YEAR; // Check if dateAsInt is at least 4 digits long - case NO_YEAR_DATE_LENGTH: - return DATE_FORMATTER_NO_YEAR; + case NO_YEAR_DATE_LENGTH -> DATE_FORMATTER_NO_YEAR; // Check if dateAsInt is at least 3 digits long - case SINGLE_DIGIT_MONTH_DATE_LENGTH: - return DATE_FORMATTER_SINGLE_DIGIT_MONTH; - - default: - break; - } - - throw new DateTimeException("No Matching Format"); + case SINGLE_DIGIT_MONTH_DATE_LENGTH -> DATE_FORMATTER_SINGLE_DIGIT_MONTH; + default -> throw new DateTimeException("No Matching Format"); + }; } /** diff --git a/core/src/main/java/org/opensearch/sql/expression/function/FunctionDSL.java b/core/src/main/java/org/opensearch/sql/expression/function/FunctionDSL.java index 8ebbfd3a3c..d3245d0695 100644 --- a/core/src/main/java/org/opensearch/sql/expression/function/FunctionDSL.java +++ b/core/src/main/java/org/opensearch/sql/expression/function/FunctionDSL.java @@ -115,7 +115,7 @@ public String toString() { new FunctionExpression(functionName, arguments) { @Override public ExprValue valueOf(Environment valueEnv) { - ExprValue value = arguments.get(0).valueOf(valueEnv); + ExprValue value = arguments.getFirst().valueOf(valueEnv); return function.apply(functionProperties, value); } diff --git a/core/src/main/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctions.java b/core/src/main/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctions.java index 102834f60d..3a7badeffb 100644 --- a/core/src/main/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctions.java +++ b/core/src/main/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctions.java @@ -535,7 +535,7 @@ private static DefaultFunctionResolver round() { nullMissingHandling( v -> new ExprDoubleValue( - new BigDecimal(v.doubleValue()) + BigDecimal.valueOf(v.doubleValue()) .setScale(0, RoundingMode.HALF_UP) .doubleValue())), DOUBLE, @@ -566,7 +566,7 @@ private static DefaultFunctionResolver round() { nullMissingHandling( (x, d) -> new ExprDoubleValue( - new BigDecimal(x.floatValue()) + BigDecimal.valueOf(x.floatValue()) .setScale(d.integerValue(), RoundingMode.HALF_UP) .doubleValue())), DOUBLE, @@ -576,7 +576,7 @@ private static DefaultFunctionResolver round() { nullMissingHandling( (x, d) -> new ExprDoubleValue( - new BigDecimal(x.doubleValue()) + BigDecimal.valueOf(x.doubleValue()) .setScale(d.integerValue(), RoundingMode.HALF_UP) .doubleValue())), DOUBLE, diff --git a/core/src/main/java/org/opensearch/sql/expression/operator/convert/TypeCastOperators.java b/core/src/main/java/org/opensearch/sql/expression/operator/convert/TypeCastOperators.java index 55e223d94c..722d449a52 100644 --- a/core/src/main/java/org/opensearch/sql/expression/operator/convert/TypeCastOperators.java +++ b/core/src/main/java/org/opensearch/sql/expression/operator/convert/TypeCastOperators.java @@ -21,7 +21,6 @@ import static org.opensearch.sql.expression.function.FunctionDSL.nullMissingHandling; import static org.opensearch.sql.expression.function.FunctionDSL.nullMissingHandlingWithProperties; -import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.experimental.UtilityClass; @@ -63,9 +62,7 @@ private static DefaultFunctionResolver castToString() { return FunctionDSL.define( BuiltinFunctionName.CAST_TO_STRING.getName(), Stream.concat( - Arrays.asList( - BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BOOLEAN, TIME, DATE, TIMESTAMP) - .stream() + Stream.of(BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BOOLEAN, TIME, DATE, TIMESTAMP) .map( type -> impl( diff --git a/core/src/main/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperators.java b/core/src/main/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperators.java index 96ff7785b7..6adc4fb2a3 100644 --- a/core/src/main/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperators.java +++ b/core/src/main/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperators.java @@ -118,7 +118,7 @@ public static void register(BuiltinFunctionRepository repository) { * * */ - private static Table andTable = + private static final Table andTable = new ImmutableTable.Builder() .put(LITERAL_TRUE, LITERAL_TRUE, LITERAL_TRUE) .put(LITERAL_TRUE, LITERAL_FALSE, LITERAL_FALSE) @@ -193,7 +193,7 @@ public static void register(BuiltinFunctionRepository repository) { * * */ - private static Table orTable = + private static final Table orTable = new ImmutableTable.Builder() .put(LITERAL_TRUE, LITERAL_TRUE, LITERAL_TRUE) .put(LITERAL_TRUE, LITERAL_FALSE, LITERAL_TRUE) @@ -268,7 +268,7 @@ public static void register(BuiltinFunctionRepository repository) { * * */ - private static Table xorTable = + private static final Table xorTable = new ImmutableTable.Builder() .put(LITERAL_TRUE, LITERAL_TRUE, LITERAL_FALSE) .put(LITERAL_TRUE, LITERAL_FALSE, LITERAL_TRUE) diff --git a/core/src/main/java/org/opensearch/sql/expression/system/SystemFunctions.java b/core/src/main/java/org/opensearch/sql/expression/system/SystemFunctions.java index cf071c4f31..8352ba4220 100644 --- a/core/src/main/java/org/opensearch/sql/expression/system/SystemFunctions.java +++ b/core/src/main/java/org/opensearch/sql/expression/system/SystemFunctions.java @@ -41,7 +41,7 @@ public Pair resolve( new FunctionExpression(BuiltinFunctionName.TYPEOF.getName(), arguments) { @Override public ExprValue valueOf(Environment valueEnv) { - return new ExprStringValue(getArguments().get(0).type().legacyTypeName()); + return new ExprStringValue(getArguments().getFirst().type().legacyTypeName()); } @Override diff --git a/core/src/main/java/org/opensearch/sql/expression/text/TextFunctions.java b/core/src/main/java/org/opensearch/sql/expression/text/TextFunctions.java index 8a5302070c..92e6b53143 100644 --- a/core/src/main/java/org/opensearch/sql/expression/text/TextFunctions.java +++ b/core/src/main/java/org/opensearch/sql/expression/text/TextFunctions.java @@ -39,7 +39,7 @@ */ @UtilityClass public class TextFunctions { - private static String EMPTY_STRING = ""; + private static final String EMPTY_STRING = ""; /** * Register String Functions. @@ -182,9 +182,7 @@ private DefaultFunctionResolver concat() { @Override public ExprValue valueOf(Environment valueEnv) { List exprValues = - args.stream() - .map(arg -> arg.valueOf(valueEnv)) - .collect(Collectors.toList()); + args.stream().map(arg -> arg.valueOf(valueEnv)).toList(); if (exprValues.stream().anyMatch(ExprValue::isMissing)) { return ExprValueUtils.missingValue(); } @@ -205,7 +203,7 @@ public ExprType type() { } /** - * TODO: https://github.com/opendistro-for-elasticsearch/sql/issues/710
+ * TODO: ...
* Extend to accept variable argument amounts.
*
* Concatenates a list of Strings with a separator string. Supports following
@@ -419,7 +417,7 @@ private static ExprValue exprLeft(ExprValue expr, ExprValue length) { private static ExprValue exprAscii(ExprValue expr) { return new ExprIntegerValue( - expr.stringValue().length() == 0 ? 0 : (int) expr.stringValue().charAt(0)); + expr.stringValue().isEmpty() ? 0 : (int) expr.stringValue().charAt(0)); } private static ExprValue exprLocate(ExprValue subStr, ExprValue str) { diff --git a/core/src/main/java/org/opensearch/sql/planner/physical/ProjectOperator.java b/core/src/main/java/org/opensearch/sql/planner/physical/ProjectOperator.java index 55422dacd3..a3e44f4827 100644 --- a/core/src/main/java/org/opensearch/sql/planner/physical/ProjectOperator.java +++ b/core/src/main/java/org/opensearch/sql/planner/physical/ProjectOperator.java @@ -27,13 +27,14 @@ import org.opensearch.sql.planner.SerializablePlan; /** Project the fields specified in {@link ProjectOperator#projectList} from input. */ +@Getter @ToString @EqualsAndHashCode(callSuper = false) @AllArgsConstructor public class ProjectOperator extends PhysicalPlan implements SerializablePlan { - @Getter private PhysicalPlan input; - @Getter private List projectList; - @Getter private List namedParseExpressions; + private PhysicalPlan input; + private List projectList; + private List namedParseExpressions; @Override public R accept(PhysicalPlanNodeVisitor visitor, C context) { diff --git a/core/src/main/java/org/opensearch/sql/planner/physical/SortHelper.java b/core/src/main/java/org/opensearch/sql/planner/physical/SortHelper.java index ea117ee6df..6bf17475b4 100644 --- a/core/src/main/java/org/opensearch/sql/planner/physical/SortHelper.java +++ b/core/src/main/java/org/opensearch/sql/planner/physical/SortHelper.java @@ -42,11 +42,11 @@ private static List>> constructComparator for (Pair pair : sortList) { SortOption option = pair.getLeft(); ExprValueOrdering ordering = - ASC.equals(option.getSortOrder()) + ASC.equals(option.sortOrder()) ? ExprValueOrdering.natural() : ExprValueOrdering.natural().reverse(); ordering = - NULL_FIRST.equals(option.getNullOrder()) ? ordering.nullsFirst() : ordering.nullsLast(); + NULL_FIRST.equals(option.nullOrder()) ? ordering.nullsFirst() : ordering.nullsLast(); comparators.add(Pair.of(pair.getRight(), ordering)); } return comparators; diff --git a/core/src/test/java/org/opensearch/sql/analysis/AnalyzerTest.java b/core/src/test/java/org/opensearch/sql/analysis/AnalyzerTest.java index 2412bd9474..bf60696da8 100644 --- a/core/src/test/java/org/opensearch/sql/analysis/AnalyzerTest.java +++ b/core/src/test/java/org/opensearch/sql/analysis/AnalyzerTest.java @@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.opensearch.sql.analysis.DataSourceSchemaIdentifierNameResolver.DEFAULT_DATASOURCE_NAME; @@ -298,7 +299,7 @@ public void analyze_filter_visit_score_function() { LogicalPlan logicalPlan = analyze(unresolvedPlan); OpenSearchFunctions.OpenSearchFunction relevanceQuery = (OpenSearchFunctions.OpenSearchFunction) ((LogicalFilter) logicalPlan).getCondition(); - assertEquals(true, relevanceQuery.isScoreTracked()); + assertTrue(relevanceQuery.isScoreTracked()); } @Test @@ -323,7 +324,7 @@ public void analyze_filter_visit_without_score_function() { LogicalPlan logicalPlan = analyze(unresolvedPlan); OpenSearchFunctions.OpenSearchFunction relevanceQuery = (OpenSearchFunctions.OpenSearchFunction) ((LogicalFilter) logicalPlan).getCondition(); - assertEquals(false, relevanceQuery.isScoreTracked()); + assertFalse(relevanceQuery.isScoreTracked()); } @Test @@ -352,7 +353,7 @@ public void analyze_filter_visit_score_function_with_double_boost() { LogicalPlan logicalPlan = analyze(unresolvedPlan); OpenSearchFunctions.OpenSearchFunction relevanceQuery = (OpenSearchFunctions.OpenSearchFunction) ((LogicalFilter) logicalPlan).getCondition(); - assertEquals(true, relevanceQuery.isScoreTracked()); + assertTrue(relevanceQuery.isScoreTracked()); } @Test @@ -791,7 +792,7 @@ public void project_nested_invalid_field_throws_exception() { AstDSL.defaultFieldsArgs(), AstDSL.alias( "message", function("nested", qualifiedName("message")), null)))); - assertEquals(exception.getMessage(), "Illegal nested field name: message"); + assertEquals("Illegal nested field name: message", exception.getMessage()); } @Test @@ -806,7 +807,7 @@ public void project_nested_invalid_arg_type_throws_exception() { AstDSL.defaultFieldsArgs(), AstDSL.alias( "message", function("nested", stringLiteral("message")), null)))); - assertEquals(exception.getMessage(), "Illegal nested field name: message"); + assertEquals("Illegal nested field name: message", exception.getMessage()); } @Test @@ -821,8 +822,8 @@ public void project_nested_no_args_throws_exception() { AstDSL.defaultFieldsArgs(), AstDSL.alias("message", function("nested"), null)))); assertEquals( - exception.getMessage(), - "on nested object only allowed 2 parameters (field,path) or 1 parameter (field)"); + "on nested object only allowed 2 parameters (field,path) or 1 parameter (field)", + exception.getMessage()); } @Test @@ -844,8 +845,8 @@ public void project_nested_too_many_args_throws_exception() { stringLiteral("message")), null)))); assertEquals( - exception.getMessage(), - "on nested object only allowed 2 parameters (field,path) or 1 parameter (field)"); + "on nested object only allowed 2 parameters (field,path) or 1 parameter (field)", + exception.getMessage()); } @Test @@ -902,19 +903,18 @@ public void remove_source() { + "https://github.com/opensearch-project/sql/issues/917 is resolved") @Test public void project_source_change_type_env() { - SemanticCheckException exception = - assertThrows( - SemanticCheckException.class, - () -> - analyze( + assertThrows( + SemanticCheckException.class, + () -> + analyze( + AstDSL.projectWithArg( AstDSL.projectWithArg( - AstDSL.projectWithArg( - AstDSL.relation("schema"), - AstDSL.defaultFieldsArgs(), - AstDSL.field("integer_value"), - AstDSL.field("double_value")), + AstDSL.relation("schema"), AstDSL.defaultFieldsArgs(), - AstDSL.field("float_value")))); + AstDSL.field("integer_value"), + AstDSL.field("double_value")), + AstDSL.defaultFieldsArgs(), + AstDSL.field("float_value")))); } @Test @@ -1185,7 +1185,7 @@ public void sql_group_by_function_in_uppercase() { AstDSL.alias("AVG(integer_value)", aggregate("AVG", qualifiedName("integer_value"))))); } - /** SELECT abs(name), abs(avg(age) FROM test GROUP BY abs(name). */ + /** SELECT abs(name), abs(avg(age)) FROM test GROUP BY abs(name). */ @Test public void sql_expression_over_one_aggregation() { assertAnalyzeEqual( @@ -1425,7 +1425,7 @@ public void parse_relation_with_patterns_expression_no_args() { @Test public void kmeanns_relation() { Map argumentMap = - new HashMap() { + new HashMap<>() { { put("centroids", new Literal(3, DataType.INTEGER)); put("iterations", new Literal(2, DataType.INTEGER)); @@ -1440,7 +1440,7 @@ public void kmeanns_relation() { @Test public void ad_batchRCF_relation() { Map argumentMap = - new HashMap() { + new HashMap<>() { { put("shingle_size", new Literal(8, DataType.INTEGER)); } @@ -1453,7 +1453,7 @@ public void ad_batchRCF_relation() { @Test public void ad_fitRCF_relation() { Map argumentMap = - new HashMap() { + new HashMap<>() { { put("shingle_size", new Literal(8, DataType.INTEGER)); put("time_decay", new Literal(0.0001, DataType.DOUBLE)); @@ -1468,7 +1468,7 @@ public void ad_fitRCF_relation() { @Test public void ad_fitRCF_relation_with_time_field() { Map argumentMap = - new HashMap() { + new HashMap<>() { { put("shingle_size", new Literal(8, DataType.INTEGER)); put("time_decay", new Literal(0.0001, DataType.DOUBLE)); @@ -1683,7 +1683,7 @@ public void ml_relation_predict_kmeans() { LogicalPlan actual = analyze(AstDSL.project(new ML(AstDSL.relation("schema"), argumentMap), AstDSL.allFields())); - assertTrue(((LogicalProject) actual).getProjectList().size() >= 1); + assertFalse(((LogicalProject) actual).getProjectList().isEmpty()); assertTrue( ((LogicalProject) actual) .getProjectList() @@ -1744,14 +1744,14 @@ public void ml_relation_predict_rcf_without_time_field() { @Test public void visit_paginate() { LogicalPlan actual = analyze(new Paginate(10, AstDSL.relation("dummy"))); - assertTrue(actual instanceof LogicalPaginate); + assertInstanceOf(LogicalPaginate.class, actual); assertEquals(10, ((LogicalPaginate) actual).getPageSize()); } @Test void visit_cursor() { LogicalPlan actual = analyze((new FetchCursor("test"))); - assertTrue(actual instanceof LogicalFetchCursor); + assertInstanceOf(LogicalFetchCursor.class, actual); assertEquals( new LogicalFetchCursor( "test", dataSourceService.getDataSource("@opensearch").getStorageEngine()), @@ -1762,9 +1762,10 @@ void visit_cursor() { public void visit_close_cursor() { var analyzed = analyze(new CloseCursor().attach(new FetchCursor("pewpew"))); assertAll( - () -> assertTrue(analyzed instanceof LogicalCloseCursor), - () -> assertTrue(analyzed.getChild().get(0) instanceof LogicalFetchCursor), + () -> assertInstanceOf(LogicalCloseCursor.class, analyzed), + () -> assertInstanceOf(LogicalFetchCursor.class, analyzed.getChild().getFirst()), () -> - assertEquals("pewpew", ((LogicalFetchCursor) analyzed.getChild().get(0)).getCursor())); + assertEquals( + "pewpew", ((LogicalFetchCursor) analyzed.getChild().getFirst()).getCursor())); } } diff --git a/core/src/test/java/org/opensearch/sql/analysis/WindowExpressionAnalyzerTest.java b/core/src/test/java/org/opensearch/sql/analysis/WindowExpressionAnalyzerTest.java index acb11f0b57..2f12f642ec 100644 --- a/core/src/test/java/org/opensearch/sql/analysis/WindowExpressionAnalyzerTest.java +++ b/core/src/test/java/org/opensearch/sql/analysis/WindowExpressionAnalyzerTest.java @@ -118,10 +118,10 @@ void can_analyze_sort_options() { ImmutablePair.of(option, AstDSL.qualifiedName("integer_value"))))); LogicalPlan plan = analyzer.analyze(ast, analysisContext); - LogicalSort sort = (LogicalSort) plan.getChild().get(0); + LogicalSort sort = (LogicalSort) plan.getChild().getFirst(); assertEquals( expect, - sort.getSortList().get(0).getLeft(), + sort.getSortList().getFirst().getLeft(), "Assertion failed on input option: " + option); }); } diff --git a/core/src/test/java/org/opensearch/sql/data/model/ExprNullValueTest.java b/core/src/test/java/org/opensearch/sql/data/model/ExprNullValueTest.java index 81bcf8f7b3..47d22af174 100644 --- a/core/src/test/java/org/opensearch/sql/data/model/ExprNullValueTest.java +++ b/core/src/test/java/org/opensearch/sql/data/model/ExprNullValueTest.java @@ -6,7 +6,7 @@ package org.opensearch.sql.data.model; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -42,9 +42,9 @@ public void toStringTest() { @Test public void equal() { - assertTrue(LITERAL_NULL.equals(LITERAL_NULL)); - assertFalse(LITERAL_FALSE.equals(LITERAL_NULL)); - assertFalse(LITERAL_NULL.equals(LITERAL_FALSE)); + assertEquals(LITERAL_NULL, LITERAL_NULL); + assertNotEquals(LITERAL_FALSE, LITERAL_NULL); + assertNotEquals(LITERAL_NULL, LITERAL_FALSE); } @Test diff --git a/core/src/test/java/org/opensearch/sql/data/model/ExprStringValueTest.java b/core/src/test/java/org/opensearch/sql/data/model/ExprStringValueTest.java index 2a5e5033f7..c3af4d4050 100644 --- a/core/src/test/java/org/opensearch/sql/data/model/ExprStringValueTest.java +++ b/core/src/test/java/org/opensearch/sql/data/model/ExprStringValueTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.opensearch.sql.data.type.ExprCoreType.STRING; import org.junit.jupiter.api.Test; @@ -17,18 +16,18 @@ public class ExprStringValueTest { @Test public void equals_to_self() { ExprValue string = ExprValueUtils.stringValue("str"); - assertEquals(string.stringValue(), "str"); - assertTrue(string.equals(string)); + assertEquals("str", string.stringValue()); + assertEquals(string, string); } @Test public void equal() { - ExprValue v1 = new ExprStringValue("str"); + ExprStringValue v1 = new ExprStringValue("str"); ExprValue v2 = ExprValueUtils.stringValue("str"); - assertTrue(v1.equals(v2)); - assertTrue(v2.equals(v1)); - assertEquals(0, ((ExprStringValue) v1).compare((ExprStringValue) v2)); - assertEquals(0, ((ExprStringValue) v2).compare((ExprStringValue) v1)); + assertEquals(v1, v2); + assertEquals(v2, v1); + assertEquals(0, v1.compare(v2)); + assertEquals(0, ((ExprStringValue) v2).compare(v1)); } @Test diff --git a/core/src/test/java/org/opensearch/sql/data/model/ExprValueUtilsTest.java b/core/src/test/java/org/opensearch/sql/data/model/ExprValueUtilsTest.java index 0baf5052e4..bbbb69b9ad 100644 --- a/core/src/test/java/org/opensearch/sql/data/model/ExprValueUtilsTest.java +++ b/core/src/test/java/org/opensearch/sql/data/model/ExprValueUtilsTest.java @@ -50,18 +50,18 @@ @DisplayName("Test Expression Value Utils") public class ExprValueUtilsTest { - private static LinkedHashMap testTuple = new LinkedHashMap<>(); + private static final LinkedHashMap testTuple = new LinkedHashMap<>(); static { testTuple.put("1", new ExprIntegerValue(1)); } - private static List numberValues = + private static final List numberValues = Stream.of((byte) 1, (short) 1, 1, 1L, 1f, 1D) .map(ExprValueUtils::fromObjectValue) .collect(Collectors.toList()); - private static List nonNumberValues = + private static final List nonNumberValues = Arrays.asList( new ExprStringValue("1"), ExprBooleanValue.of(true), @@ -72,10 +72,10 @@ public class ExprValueUtilsTest { new ExprTimestampValue("2012-08-07 18:00:00"), new ExprIntervalValue(Duration.ofSeconds(100))); - private static List allValues = + private static final List allValues = Lists.newArrayList(Iterables.concat(numberValues, nonNumberValues)); - private static List> numberValueExtractor = + private static final List> numberValueExtractor = Arrays.asList( ExprValueUtils::getByteValue, ExprValueUtils::getShortValue, @@ -83,24 +83,24 @@ public class ExprValueUtilsTest { ExprValueUtils::getLongValue, ExprValueUtils::getFloatValue, ExprValueUtils::getDoubleValue); - private static List> nonNumberValueExtractor = + private static final List> nonNumberValueExtractor = Arrays.asList( ExprValueUtils::getStringValue, ExprValueUtils::getBooleanValue, ExprValueUtils::getCollectionValue, ExprValueUtils::getTupleValue); - private static List> dateAndTimeValueExtractor = + private static final List> dateAndTimeValueExtractor = Arrays.asList( ExprValue::dateValue, ExprValue::timeValue, ExprValue::timestampValue, ExprValue::intervalValue); - private static List> allValueExtractor = + private static final List> allValueExtractor = Lists.newArrayList( Iterables.concat( numberValueExtractor, nonNumberValueExtractor, dateAndTimeValueExtractor)); - private static List numberTypes = + private static final List numberTypes = Arrays.asList( ExprCoreType.BYTE, ExprCoreType.SHORT, @@ -108,10 +108,11 @@ public class ExprValueUtilsTest { ExprCoreType.LONG, ExprCoreType.FLOAT, ExprCoreType.DOUBLE); - private static List nonNumberTypes = Arrays.asList(STRING, BOOLEAN, ARRAY, STRUCT); - private static List dateAndTimeTypes = + private static final List nonNumberTypes = + Arrays.asList(STRING, BOOLEAN, ARRAY, STRUCT); + private static final List dateAndTimeTypes = Arrays.asList(DATE, TIME, TIMESTAMP, INTERVAL); - private static List allTypes = + private static final List allTypes = Lists.newArrayList(Iterables.concat(numberTypes, nonNumberTypes, dateAndTimeTypes)); private static Stream getValueTestArgumentStream() { @@ -125,7 +126,7 @@ private static Stream getValueTestArgumentStream() { 1D, "1", true, - Arrays.asList(integerValue(1)), + List.of(integerValue(1)), ImmutableMap.of("1", integerValue(1)), LocalDate.parse("2012-08-07"), LocalTime.parse("18:00:00"), @@ -149,7 +150,7 @@ private static Stream getTypeTestArgumentStream() { private static Stream invalidGetNumberValueArgumentStream() { return Lists.cartesianProduct(nonNumberValues, numberValueExtractor).stream() - .map(list -> Arguments.of(list.get(0), list.get(1))); + .map(list -> Arguments.of(list.getFirst(), list.get(1))); } @SuppressWarnings("unchecked") @@ -200,8 +201,7 @@ public void invalidGetNumberValue(ExprValue value, Function e /** Test Invalid to convert. */ @ParameterizedTest(name = "invalid convert ExprValue:{0} to ExprType:{2}") @MethodSource("invalidConvert") - public void invalidConvertExprValue( - ExprValue value, Function extractor, ExprCoreType toType) { + public void invalidConvertExprValue(ExprValue value, Function extractor) { Exception exception = assertThrows(ExpressionEvaluationException.class, () -> extractor.apply(value)); assertThat(exception.getMessage(), Matchers.containsString("invalid")); diff --git a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java index 237477050d..a1d5adf3ae 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java @@ -24,7 +24,6 @@ import static org.opensearch.sql.expression.function.BuiltinFunctionName.CAST_TO_BOOLEAN; import com.google.common.collect.ImmutableList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -73,7 +72,7 @@ void register() { @Test void compile() { when(mockExpression.type()).thenReturn(UNDEFINED); - when(functionSignature.getParamTypeList()).thenReturn(Arrays.asList(UNDEFINED)); + when(functionSignature.getParamTypeList()).thenReturn(List.of(UNDEFINED)); when(mockfunctionResolver.getFunctionName()).thenReturn(mockFunctionName); when(mockfunctionResolver.resolve(any())) .thenReturn(Pair.of(functionSignature, functionExpressionBuilder)); @@ -82,7 +81,7 @@ void compile() { BuiltinFunctionRepository repo = new BuiltinFunctionRepository(mockMap); repo.register(mockfunctionResolver); - repo.compile(functionProperties, mockFunctionName, Arrays.asList(mockExpression)); + repo.compile(functionProperties, mockFunctionName, List.of(mockExpression)); verify(functionExpressionBuilder, times(1)).apply(eq(functionProperties), any()); } @@ -90,7 +89,7 @@ void compile() { void compile_datasource_defined_function() { DefaultFunctionResolver dataSourceFunctionResolver = mock(DefaultFunctionResolver.class); when(mockExpression.type()).thenReturn(UNDEFINED); - when(functionSignature.getParamTypeList()).thenReturn(Arrays.asList(UNDEFINED)); + when(functionSignature.getParamTypeList()).thenReturn(List.of(UNDEFINED)); when(dataSourceFunctionResolver.getFunctionName()).thenReturn(mockFunctionName); when(dataSourceFunctionResolver.resolve(any())) .thenReturn(Pair.of(functionSignature, functionExpressionBuilder)); @@ -100,7 +99,7 @@ void compile_datasource_defined_function() { functionProperties, Collections.singletonList(dataSourceFunctionResolver), mockFunctionName, - Arrays.asList(mockExpression)); + List.of(mockExpression)); verify(functionExpressionBuilder, times(1)).apply(eq(functionProperties), any()); } @@ -178,7 +177,7 @@ void resolve_should_throw_exception_for_unsupported_conversion() { Collections.emptyList(), registerFunctionResolver(mockFunctionName, BYTE, STRUCT)) .apply(functionProperties, ImmutableList.of(mockExpression))); - assertEquals(error.getMessage(), "Type conversion to type STRUCT is not supported"); + assertEquals("Type conversion to type STRUCT is not supported", error.getMessage()); } @Test diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java index 44a3ccabbd..55fc09d1a7 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java @@ -126,7 +126,7 @@ void castStringToInt() { @Test void castStringToIntException() { FunctionExpression expression = DSL.castInt(DSL.literal("invalid")); - assertThrows(RuntimeException.class, () -> expression.valueOf()); + assertThrows(RuntimeException.class, expression::valueOf); } @Test @@ -180,7 +180,7 @@ void castStringToLong() { @Test void castStringToLongException() { FunctionExpression expression = DSL.castLong(DSL.literal("invalid")); - assertThrows(RuntimeException.class, () -> expression.valueOf()); + assertThrows(RuntimeException.class, expression::valueOf); } @Test @@ -212,7 +212,7 @@ void castStringToFloat() { @Test void castStringToFloatException() { FunctionExpression expression = DSL.castFloat(DSL.literal("invalid")); - assertThrows(RuntimeException.class, () -> expression.valueOf()); + assertThrows(RuntimeException.class, expression::valueOf); } @Test @@ -244,7 +244,7 @@ void castStringToDouble() { @Test void castStringToDoubleException() { FunctionExpression expression = DSL.castDouble(DSL.literal("invalid")); - assertThrows(RuntimeException.class, () -> expression.valueOf()); + assertThrows(RuntimeException.class, expression::valueOf); } @Test diff --git a/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java b/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java index 0d9fe80339..c908242a65 100644 --- a/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java +++ b/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java @@ -46,32 +46,20 @@ public static int compare(ExprValue v1, ExprValue v2) { "invalid to call compare operation on values of different types"); } - switch ((ExprCoreType) v1.type()) { - case BYTE: - return v1.byteValue().compareTo(v2.byteValue()); - case SHORT: - return v1.shortValue().compareTo(v2.shortValue()); - case INTEGER: - return getIntegerValue(v1).compareTo(getIntegerValue(v2)); - case LONG: - return getLongValue(v1).compareTo(getLongValue(v2)); - case FLOAT: - return getFloatValue(v1).compareTo(getFloatValue(v2)); - case DOUBLE: - return getDoubleValue(v1).compareTo(getDoubleValue(v2)); - case STRING: - return getStringValue(v1).compareTo(getStringValue(v2)); - case BOOLEAN: - return v1.booleanValue().compareTo(v2.booleanValue()); - case TIME: - return v1.timeValue().compareTo(v2.timeValue()); - case DATE: - return v1.dateValue().compareTo(v2.dateValue()); - case TIMESTAMP: - return v1.timestampValue().compareTo(v2.timestampValue()); - default: - throw new ExpressionEvaluationException( - String.format("%s instances are not comparable", v1.getClass().getSimpleName())); - } + return switch ((ExprCoreType) v1.type()) { + case BYTE -> v1.byteValue().compareTo(v2.byteValue()); + case SHORT -> v1.shortValue().compareTo(v2.shortValue()); + case INTEGER -> getIntegerValue(v1).compareTo(getIntegerValue(v2)); + case LONG -> getLongValue(v1).compareTo(getLongValue(v2)); + case FLOAT -> getFloatValue(v1).compareTo(getFloatValue(v2)); + case DOUBLE -> getDoubleValue(v1).compareTo(getDoubleValue(v2)); + case STRING -> getStringValue(v1).compareTo(getStringValue(v2)); + case BOOLEAN -> v1.booleanValue().compareTo(v2.booleanValue()); + case TIME -> v1.timeValue().compareTo(v2.timeValue()); + case DATE -> v1.dateValue().compareTo(v2.dateValue()); + case TIMESTAMP -> v1.timestampValue().compareTo(v2.timestampValue()); + default -> throw new ExpressionEvaluationException( + String.format("%s instances are not comparable", v1.getClass().getSimpleName())); + }; } } diff --git a/integ-test/src/test/java/org/opensearch/sql/legacy/CursorIT.java b/integ-test/src/test/java/org/opensearch/sql/legacy/CursorIT.java index 565c40b121..8120ae29c8 100644 --- a/integ-test/src/test/java/org/opensearch/sql/legacy/CursorIT.java +++ b/integ-test/src/test/java/org/opensearch/sql/legacy/CursorIT.java @@ -51,7 +51,7 @@ public void invalidNegativeFetchSize() throws IOException { StringUtils.format("SELECT firstname, state FROM %s", TestsConstants.TEST_INDEX_ACCOUNT); Response response = null; try { - String queryResult = executeFetchQuery(query, -2, JDBC); + executeFetchQuery(query, -2, JDBC); } catch (ResponseException ex) { response = ex.getResponse(); } @@ -70,7 +70,7 @@ public void invalidNonNumericFetchSize() throws IOException { StringUtils.format("SELECT firstname, state FROM %s", TestsConstants.TEST_INDEX_ACCOUNT); Response response = null; try { - String queryResult = executeFetchAsStringQuery(query, "hello world", JDBC); + executeFetchAsStringQuery(query, "hello world", JDBC); } catch (ResponseException ex) { response = ex.getResponse(); } @@ -88,7 +88,7 @@ public void testExceptionOnCursorExplain() throws IOException { Request sqlRequest = getSqlRequest(cursorRequest, true); Response response = null; try { - String queryResult = executeRequest(sqlRequest); + executeRequest(sqlRequest); } catch (ResponseException ex) { response = ex.getResponse(); } @@ -222,26 +222,25 @@ public void noCursorWhenResultsLessThanFetchSize() throws IOException { public void testCursorWithPreparedStatement() throws IOException { JSONObject response = executeJDBCRequest( - String.format( - "{" - + "\"fetch_size\": 200," - + "\"query\": \" SELECT age, state FROM %s WHERE age > ? OR state IN (?, ?)\"," - + "\"parameters\": [" - + " {" - + " \"type\": \"integer\"," - + " \"value\": 25" - + " }," - + " {" - + " \"type\": \"string\"," - + " \"value\": \"WA\"" - + " }," - + " {" - + " \"type\": \"string\"," - + " \"value\": \"UT\"" - + " }" - + "]" - + "}" - + TestsConstants.TEST_INDEX_ACCOUNT)); + "{" + + "\"fetch_size\": 200," + + "\"query\": \" SELECT age, state FROM %s WHERE age > ? OR state IN (?, ?)\"," + + "\"parameters\": [" + + " {" + + " \"type\": \"integer\"," + + " \"value\": 25" + + " }," + + " {" + + " \"type\": \"string\"," + + " \"value\": \"WA\"" + + " }," + + " {" + + " \"type\": \"string\"," + + " \"value\": \"UT\"" + + " }" + + "]" + + "}" + + TestsConstants.TEST_INDEX_ACCOUNT); assertTrue(response.has(CURSOR)); verifyIsV1Cursor(response.getString(CURSOR)); } @@ -249,18 +248,18 @@ public void testCursorWithPreparedStatement() throws IOException { @Test public void testRegressionOnDateFormatChange() throws IOException { loadIndex(Index.DATETIME); - /** - * With pagination, the field should be date formatted to MySQL format as in - * - * @see PR #367 - * TEST_INDEX_DATE_TIME has three docs with login_time as date field with following values - * 1.2015-01-01 - * 2.2015-01-01T12:10:30Z - * 3.1585882955 - * 4.2020-04-08T11:10:30+05:00 - * - */ + /* + With pagination, the field should be date formatted to MySQL format as in + + @see PR #367 + * TEST_INDEX_DATE_TIME has three docs with login_time as date field with following values + * 1.2015-01-01 + * 2.2015-01-01T12:10:30Z + * 3.1585882955 + * 4.2020-04-08T11:10:30+05:00 + * + */ List actualDateList = new ArrayList<>(); String selectQuery = StringUtils.format("SELECT login_time FROM %s LIMIT 500", TEST_INDEX_DATE_TIME); @@ -368,7 +367,7 @@ public void testCursorCloseAPI() throws IOException { // using the cursor after its cleared, will throw exception Response response = null; try { - JSONObject queryResult = executeCursorQuery(cursor); + executeCursorQuery(cursor); } catch (ResponseException ex) { response = ex.getResponse(); } @@ -388,7 +387,7 @@ public void invalidCursorIdNotDecodable() throws IOException { Response response = null; try { - JSONObject resp = executeCursorQuery(randomCursor); + executeCursorQuery(randomCursor); } catch (ResponseException ex) { response = ex.getResponse(); } @@ -443,14 +442,14 @@ public void noPaginationWithNonJDBCFormat() throws IOException { } @Test - public void testMalformedCursorGracefullyHandled() throws IOException { + public void testMalformedCursorGracefullyHandled() { ResponseException result = assertThrows( "Expected query with malformed cursor to raise error, but didn't", ResponseException.class, () -> executeCursorQuery("d:a11b4db33f")); assertTrue(result.getMessage().contains("Malformed cursor")); - assertEquals(result.getResponse().getStatusLine().getStatusCode(), 400); + assertEquals(400, result.getResponse().getStatusLine().getStatusCode()); } public void verifyWithAndWithoutPaginationResponse( @@ -509,8 +508,7 @@ public String executeFetchAsStringQuery(String query, String fetchSize, String r sqlRequest.setJsonEntity(requestBody); Response response = client().performRequest(sqlRequest); - String responseString = getResponseBody(response, true); - return responseString; + return getResponseBody(response, true); } private void verifyIsV1Cursor(String cursor) { diff --git a/legacy/src/main/java/org/opensearch/sql/legacy/cursor/DefaultCursor.java b/legacy/src/main/java/org/opensearch/sql/legacy/cursor/DefaultCursor.java index 2b0de9022c..b2651c4861 100644 --- a/legacy/src/main/java/org/opensearch/sql/legacy/cursor/DefaultCursor.java +++ b/legacy/src/main/java/org/opensearch/sql/legacy/cursor/DefaultCursor.java @@ -62,7 +62,6 @@ public class DefaultCursor implements Cursor { private static final String SCHEMA_COLUMNS = "c"; private static final String FIELD_ALIAS_MAP = "a"; private static final String PIT_ID = "p"; - private static final String SEARCH_REQUEST = "r"; private static final String SORT_FIELDS = "h"; private static final ObjectMapper objectMapper = new ObjectMapper(); @@ -175,10 +174,10 @@ private boolean isCursorIdNullOrEmpty() { } public static DefaultCursor from(String cursorId) { - /** - * It is assumed that cursorId here is the second part of the original cursor passed by the - * client after removing first part which identifies cursor type - */ + /* + It is assumed that cursorId here is the second part of the original cursor passed by the + client after removing first part which identifies cursor type + */ JSONObject json = decodeCursor(cursorId); DefaultCursor cursor = new DefaultCursor(); cursor.setFetchSize(json.getInt(FETCH_SIZE)); @@ -263,17 +262,15 @@ private static Map fieldAliasMap(JSONObject json) { } private static List getColumnsFromSchema(JSONArray schema) { - List columns = - IntStream.range(0, schema.length()) - .mapToObj( - i -> { - JSONObject jsonColumn = schema.getJSONObject(i); - return new Schema.Column( - jsonColumn.getString("name"), - jsonColumn.optString("alias", null), - Schema.Type.valueOf(jsonColumn.getString("type").toUpperCase())); - }) - .collect(Collectors.toList()); - return columns; + return IntStream.range(0, schema.length()) + .mapToObj( + i -> { + JSONObject jsonColumn = schema.getJSONObject(i); + return new Schema.Column( + jsonColumn.getString("name"), + jsonColumn.optString("alias", null), + Schema.Type.valueOf(jsonColumn.getString("type").toUpperCase())); + }) + .collect(Collectors.toList()); } } diff --git a/legacy/src/main/java/org/opensearch/sql/legacy/utils/SQLFunctions.java b/legacy/src/main/java/org/opensearch/sql/legacy/utils/SQLFunctions.java index d46a80f6d3..2fee585591 100644 --- a/legacy/src/main/java/org/opensearch/sql/legacy/utils/SQLFunctions.java +++ b/legacy/src/main/java/org/opensearch/sql/legacy/utils/SQLFunctions.java @@ -112,7 +112,7 @@ public class SQLFunctions { .flatMap(Set::stream) .collect(Collectors.toSet()); - private Map generatedIds = new HashMap<>(); + private final Map generatedIds = new HashMap<>(); /** * Generates next id for given method name. The id's are increasing for each method name, so @@ -135,7 +135,7 @@ public Tuple function( case "cast": { SQLCastExpr castExpr = - (SQLCastExpr) ((SQLIdentifierExpr) paramers.get(0).value).getParent(); + (SQLCastExpr) ((SQLIdentifierExpr) paramers.getFirst().value).getParent(); String typeName = castExpr.getDataType().getName(); functionStr = cast(typeName, paramers); break; @@ -144,7 +144,7 @@ public Tuple function( { functionStr = lower( - (SQLExpr) paramers.get(0).value, + (SQLExpr) paramers.getFirst().value, getLocaleForCaseChangingFunction(paramers), name); break; @@ -153,7 +153,7 @@ public Tuple function( { functionStr = upper( - (SQLExpr) paramers.get(0).value, + (SQLExpr) paramers.getFirst().value, getLocaleForCaseChangingFunction(paramers), name); break; @@ -181,7 +181,7 @@ public Tuple function( for (int i = 1; i < paramers.size(); i++) { result.add((SQLExpr) paramers.get(i).value); } - functionStr = concat_ws(paramers.get(0).value.toString(), result); + functionStr = concat_ws(paramers.getFirst().value.toString(), result); break; @@ -197,53 +197,55 @@ public Tuple function( break; case "year": - functionStr = dateFunctionTemplate("year", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("year", (SQLExpr) paramers.getFirst().value); break; case "month_of_year": case "month": - functionStr = dateFunctionTemplate("monthValue", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("monthValue", (SQLExpr) paramers.getFirst().value); break; case "monthname": - functionStr = dateFunctionTemplate("month", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("month", (SQLExpr) paramers.getFirst().value); break; case "week_of_year": functionStr = dateFunctionTemplate( "weekOfWeekyear", "get(WeekFields.ISO.weekOfWeekBasedYear())", - (SQLExpr) paramers.get(0).value); + (SQLExpr) paramers.getFirst().value); break; case "day_of_year": - functionStr = dateFunctionTemplate("dayOfYear", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("dayOfYear", (SQLExpr) paramers.getFirst().value); break; case "day_of_month": case "dayofmonth": - functionStr = dateFunctionTemplate("dayOfMonth", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("dayOfMonth", (SQLExpr) paramers.getFirst().value); break; case "day_of_week": functionStr = dateFunctionTemplate( - "dayOfWeek", "getDayOfWeekEnum().getValue()", (SQLExpr) paramers.get(0).value); + "dayOfWeek", "getDayOfWeekEnum().getValue()", (SQLExpr) paramers.getFirst().value); break; case "date": - functionStr = date((SQLExpr) paramers.get(0).value); + functionStr = date((SQLExpr) paramers.getFirst().value); break; case "hour_of_day": - functionStr = dateFunctionTemplate("hour", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("hour", (SQLExpr) paramers.getFirst().value); break; case "minute_of_day": functionStr = dateFunctionTemplate( - "minuteOfDay", "get(ChronoField.MINUTE_OF_DAY)", (SQLExpr) paramers.get(0).value); + "minuteOfDay", + "get(ChronoField.MINUTE_OF_DAY)", + (SQLExpr) paramers.getFirst().value); break; case "minute_of_hour": - functionStr = dateFunctionTemplate("minute", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("minute", (SQLExpr) paramers.getFirst().value); break; case "second_of_minute": - functionStr = dateFunctionTemplate("second", (SQLExpr) paramers.get(0).value); + functionStr = dateFunctionTemplate("second", (SQLExpr) paramers.getFirst().value); break; case "timestamp": - functionStr = timestamp((SQLExpr) paramers.get(0).value); + functionStr = timestamp((SQLExpr) paramers.getFirst().value); break; case "maketime": functionStr = @@ -284,14 +286,14 @@ public Tuple function( case "cosh": functionStr = mathSingleValueTemplate( - "Math." + methodName, methodName, (SQLExpr) paramers.get(0).value, name); + "Math." + methodName, methodName, (SQLExpr) paramers.getFirst().value, name); break; case "rand": if (paramers.isEmpty()) { functionStr = rand(); } else { - functionStr = rand((SQLExpr) paramers.get(0).value); + functionStr = rand((SQLExpr) paramers.getFirst().value); } break; @@ -299,7 +301,7 @@ public Tuple function( // OpenSearch does not support the function name cot functionStr = mathSingleValueTemplate( - "1 / Math.tan", methodName, (SQLExpr) paramers.get(0).value, name); + "1 / Math.tan", methodName, (SQLExpr) paramers.getFirst().value, name); break; case "sign": @@ -307,7 +309,7 @@ public Tuple function( methodName = "signum"; functionStr = mathSingleValueTemplate( - "Math." + methodName, methodName, (SQLExpr) paramers.get(0).value, name); + "Math." + methodName, methodName, (SQLExpr) paramers.getFirst().value, name); break; case "pow": @@ -340,14 +342,14 @@ public Tuple function( break; case "degrees": - functionStr = degrees((SQLExpr) paramers.get(0).value, name); + functionStr = degrees((SQLExpr) paramers.getFirst().value, name); break; case "radians": - functionStr = radians((SQLExpr) paramers.get(0).value, name); + functionStr = radians((SQLExpr) paramers.getFirst().value, name); break; case "trim": - functionStr = trim((SQLExpr) paramers.get(0).value, name); + functionStr = trim((SQLExpr) paramers.getFirst().value, name); break; case "add": @@ -369,30 +371,30 @@ public Tuple function( break; case "field": - functionStr = field(Util.expr2Object((SQLExpr) paramers.get(0).value).toString()); + functionStr = field(Util.expr2Object((SQLExpr) paramers.getFirst().value).toString()); break; case "log2": - functionStr = log(SQLUtils.toSQLExpr("2"), (SQLExpr) paramers.get(0).value, name); + functionStr = log(SQLUtils.toSQLExpr("2"), (SQLExpr) paramers.getFirst().value, name); break; case "log10": - functionStr = log10((SQLExpr) paramers.get(0).value); + functionStr = log10((SQLExpr) paramers.getFirst().value); break; case "log": if (paramers.size() > 1) { functionStr = log((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value, name); } else { - functionStr = ln((SQLExpr) paramers.get(0).value); + functionStr = ln((SQLExpr) paramers.getFirst().value); } break; case "ln": - functionStr = ln((SQLExpr) paramers.get(0).value); + functionStr = ln((SQLExpr) paramers.getFirst().value); break; case "assign": - functionStr = assign((SQLExpr) paramers.get(0).value); + functionStr = assign((SQLExpr) paramers.getFirst().value); break; case "length": - functionStr = length((SQLExpr) paramers.get(0).value); + functionStr = length((SQLExpr) paramers.getFirst().value); break; case "replace": functionStr = @@ -410,13 +412,13 @@ public Tuple function( locate(paramers.get(0).value.toString(), (SQLExpr) paramers.get(1).value, start); break; case "rtrim": - functionStr = rtrim((SQLExpr) paramers.get(0).value); + functionStr = rtrim((SQLExpr) paramers.getFirst().value); break; case "ltrim": - functionStr = ltrim((SQLExpr) paramers.get(0).value); + functionStr = ltrim((SQLExpr) paramers.getFirst().value); break; case "ascii": - functionStr = ascii((SQLExpr) paramers.get(0).value); + functionStr = ascii((SQLExpr) paramers.getFirst().value); break; case "left": functionStr = left((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value); @@ -432,7 +434,7 @@ public Tuple function( functionStr = ifnull((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value); break; case "isnull": - functionStr = isnull((SQLExpr) paramers.get(0).value); + functionStr = isnull((SQLExpr) paramers.getFirst().value); break; default: @@ -738,8 +740,7 @@ private static String convertType(SQLExpr script) { } private String getScriptText(MethodField field) { - String content = ((SQLTextLiteralExpr) field.getParams().get(1).value).getText(); - return content; + return ((SQLTextLiteralExpr) field.getParams().get(1).value).getText(); } /** @@ -1028,12 +1029,12 @@ private Tuple ifFunc(List paramers) { if (paramers.get(0).value instanceof SQLNullExpr) { return new Tuple<>(name, def(name, expr2)); } - if (paramers.get(0).value instanceof MethodField) { - String condition = getScriptText((MethodField) paramers.get(0).value); + if (paramers.getFirst().value instanceof MethodField) { + String condition = getScriptText((MethodField) paramers.getFirst().value); return new Tuple<>( name, "boolean cond = " + condition + ";" + def(name, "cond ? " + expr1 + " : " + expr2)); - } else if (paramers.get(0).value instanceof SQLBooleanExpr) { - Boolean condition = ((SQLBooleanExpr) paramers.get(0).value).getValue(); + } else if (paramers.getFirst().value instanceof SQLBooleanExpr) { + boolean condition = ((SQLBooleanExpr) paramers.getFirst().value).getValue(); if (condition) { return new Tuple<>(name, def(name, expr1)); } else { @@ -1048,8 +1049,8 @@ private Tuple ifFunc(List paramers) { *

Either a or b could be a column name, literal, or a number: - if isNumeric is true --> * number - else if this string is single quoted --> literal - else --> column name */ - String key = getPropertyOrValue(paramers.get(0).key); - String value = getPropertyOrValue(paramers.get(0).value.toString()); + String key = getPropertyOrValue(paramers.getFirst().key); + String value = getPropertyOrValue(paramers.getFirst().value.toString()); String condition = key + " == " + value; return new Tuple<>( name, "boolean cond = " + condition + ";" + def(name, "cond ? " + expr1 + " : " + expr2)); @@ -1106,23 +1107,17 @@ private Tuple isnull(SQLExpr expr) { public String getCastScriptStatement(String name, String castType, List paramers) throws SqlParseException { - String castFieldName = String.format("doc['%s'].value", paramers.get(0).toString()); - switch (StringUtils.toUpper(castType)) { - case "INT": - case "LONG": - case "FLOAT": - case "DOUBLE": - return getCastToNumericValueScript(name, castFieldName, StringUtils.toLower(castType)); - case "STRING": - return String.format("def %s = %s.toString()", name, castFieldName); - case "DATETIME": - return String.format( - "def %s = DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\").format(" - + "DateTimeFormatter.ISO_DATE_TIME.parse(%s.toString()))", - name, castFieldName); - default: - throw new SqlParseException("Unsupported cast type " + castType); - } + String castFieldName = String.format("doc['%s'].value", paramers.getFirst().toString()); + return switch (StringUtils.toUpper(castType)) { + case "INT", "LONG", "FLOAT", "DOUBLE" -> getCastToNumericValueScript( + name, castFieldName, StringUtils.toLower(castType)); + case "STRING" -> String.format("def %s = %s.toString()", name, castFieldName); + case "DATETIME" -> String.format( + "def %s = DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\").format(" + + "DateTimeFormatter.ISO_DATE_TIME.parse(%s.toString()))", + name, castFieldName); + default -> throw new SqlParseException("Unsupported cast type " + castType); + }; } private String getCastToNumericValueScript(String varName, String docValue, String targetType) { @@ -1150,23 +1145,16 @@ public static Schema.Type getScriptFunctionReturnType( } public static Schema.Type getCastFunctionReturnType(String castType) { - switch (StringUtils.toUpper(castType)) { - case "FLOAT": - return Schema.Type.FLOAT; - case "DOUBLE": - return Schema.Type.DOUBLE; - case "INT": - return Schema.Type.INTEGER; - case "STRING": - return Schema.Type.TEXT; - case "DATETIME": - return Schema.Type.DATE; - case "LONG": - return Schema.Type.LONG; - default: - throw new UnsupportedOperationException( - StringUtils.format("The following type is not supported by cast(): %s", castType)); - } + return switch (StringUtils.toUpper(castType)) { + case "FLOAT" -> Schema.Type.FLOAT; + case "DOUBLE" -> Schema.Type.DOUBLE; + case "INT" -> Schema.Type.INTEGER; + case "STRING" -> Schema.Type.TEXT; + case "DATETIME" -> Schema.Type.DATE; + case "LONG" -> Schema.Type.LONG; + default -> throw new UnsupportedOperationException( + StringUtils.format("The following type is not supported by cast(): %s", castType)); + }; } /** diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/client/OpenSearchNodeClient.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/client/OpenSearchNodeClient.java index 7a9487ef6a..49307a1121 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/client/OpenSearchNodeClient.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/client/OpenSearchNodeClient.java @@ -95,7 +95,7 @@ public Map getIndexMappings(String... indexExpression) { throw e; } catch (Exception e) { throw new IllegalStateException( - "Failed to read mapping for index pattern [" + indexExpression + "]", e); + "Failed to read mapping for index pattern [" + Arrays.toString(indexExpression) + "]", e); } } @@ -123,7 +123,7 @@ public Map getIndexMaxResultWindows(String... indexExpression) return result.build(); } catch (Exception e) { throw new IllegalStateException( - "Failed to read setting for index pattern [" + indexExpression + "]", e); + "Failed to read setting for index pattern [" + Arrays.toString(indexExpression) + "]", e); } } @@ -215,7 +215,7 @@ public void deletePit(DeletePitRequest deletePitRequest) { ActionFuture execute = this.client.execute(DeletePitAction.INSTANCE, deletePitRequest); try { - DeletePitResponse deletePitResponse = execute.get(); + execute.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Error occurred while deleting PIT.", e); } diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/data/type/OpenSearchDataType.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/data/type/OpenSearchDataType.java index c35eacfc72..69b4b53a6e 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/data/type/OpenSearchDataType.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/data/type/OpenSearchDataType.java @@ -18,6 +18,7 @@ import org.opensearch.sql.data.type.ExprType; /** The extension of ExprType in OpenSearch. */ +@Getter @EqualsAndHashCode public class OpenSearchDataType implements ExprType, Serializable { @@ -59,10 +60,10 @@ public String toString() { } } - @EqualsAndHashCode.Exclude @Getter protected MappingType mappingType; + @EqualsAndHashCode.Exclude protected MappingType mappingType; // resolved ExprCoreType - @Getter protected ExprCoreType exprCoreType; + protected ExprCoreType exprCoreType; /** * Get a simplified type {@link ExprCoreType} if possible. To avoid returning `UNKNOWN` for @@ -215,7 +216,7 @@ protected OpenSearchDataType(ExprCoreType type) { // For datatypes with properties (example: object and nested types) // a read-only collection - @Getter @EqualsAndHashCode.Exclude Map properties = ImmutableMap.of(); + @EqualsAndHashCode.Exclude Map properties = ImmutableMap.of(); @Override // Called when building TypeEnvironment and when serializing PPL response diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactory.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactory.java index 41d6667ded..fe62776400 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactory.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactory.java @@ -188,7 +188,7 @@ public ExprValue construct(String field, Object value, boolean supportArrays) { private ExprValue parse( Content content, String field, Optional fieldType, boolean supportArrays) { - if (content.isNull() || !fieldType.isPresent()) { + if (content.isNull() || fieldType.isEmpty()) { return ExprNullValue.of(); } @@ -238,15 +238,14 @@ private static ExprValue parseDateTimeString(String value, OpenSearchDateType da try { TemporalAccessor accessor = formatter.parse(value); ZonedDateTime zonedDateTime = DateFormatters.from(accessor); - switch (returnFormat) { - case TIME: - return new ExprTimeValue(zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toLocalTime()); - case DATE: - return new ExprDateValue(zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toLocalDate()); - default: - return new ExprTimestampValue( - zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toInstant()); - } + return switch (returnFormat) { + case TIME -> new ExprTimeValue( + zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toLocalTime()); + case DATE -> new ExprDateValue( + zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toLocalDate()); + default -> new ExprTimestampValue( + zonedDateTime.withZoneSameLocal(ZoneOffset.UTC).toInstant()); + }; } catch (IllegalArgumentException ignored) { // nothing to do, try another format } @@ -254,17 +253,14 @@ private static ExprValue parseDateTimeString(String value, OpenSearchDateType da // if no formatters are available, try the default formatter try { - switch (returnFormat) { - case TIME: - return new ExprTimeValue( - DateFormatters.from(STRICT_HOUR_MINUTE_SECOND_FORMATTER.parse(value)).toLocalTime()); - case DATE: - return new ExprDateValue( - DateFormatters.from(STRICT_YEAR_MONTH_DAY_FORMATTER.parse(value)).toLocalDate()); - default: - return new ExprTimestampValue( - DateFormatters.from(DATE_TIME_FORMATTER.parse(value)).toInstant()); - } + return switch (returnFormat) { + case TIME -> new ExprTimeValue( + DateFormatters.from(STRICT_HOUR_MINUTE_SECOND_FORMATTER.parse(value)).toLocalTime()); + case DATE -> new ExprDateValue( + DateFormatters.from(STRICT_YEAR_MONTH_DAY_FORMATTER.parse(value)).toLocalDate()); + default -> new ExprTimestampValue( + DateFormatters.from(DATE_TIME_FORMATTER.parse(value)).toInstant()); + }; } catch (DateTimeParseException ignored) { // ignored } @@ -278,8 +274,8 @@ private static ExprValue createOpenSearchDateType(Content value, ExprType type) ExprCoreType returnFormat = dt.getExprCoreType(); if (value.isNumber()) { // isNumber var numFormatters = dt.getNumericNamedFormatters(); - if (numFormatters.size() > 0 || !dt.hasFormats()) { - long epochMillis = 0; + if (!numFormatters.isEmpty() || !dt.hasFormats()) { + long epochMillis; if (numFormatters.contains( DateFormatter.forPattern(FormatNames.EPOCH_SECOND.getSnakeCaseName()))) { // no CamelCase for `EPOCH_*` formats @@ -288,14 +284,11 @@ private static ExprValue createOpenSearchDateType(Content value, ExprType type) epochMillis = value.longValue(); } Instant instant = Instant.ofEpochMilli(epochMillis); - switch (returnFormat) { - case TIME: - return new ExprTimeValue(LocalTime.from(instant.atZone(ZoneOffset.UTC))); - case DATE: - return new ExprDateValue(LocalDate.ofInstant(instant, ZoneOffset.UTC)); - default: - return new ExprTimestampValue(instant); - } + return switch (returnFormat) { + case TIME -> new ExprTimeValue(LocalTime.from(instant.atZone(ZoneOffset.UTC))); + case DATE -> new ExprDateValue(LocalDate.ofInstant(instant, ZoneOffset.UTC)); + default -> new ExprTimestampValue(instant); + }; } else { // custom format return parseDateTimeString(value.objectValue().toString(), dt); @@ -352,14 +345,11 @@ private ExprValue parseArray( } else if (!(type instanceof OpenSearchDataType && ((OpenSearchDataType) type).getExprType().equals(ARRAY)) && !supportArrays) { - return parseInnerArrayValue(content.array().next(), prefix, type, supportArrays); + return parseInnerArrayValue(content.array().next(), prefix, type, false); } else { content .array() - .forEachRemaining( - v -> { - result.add(parseInnerArrayValue(v, prefix, type, supportArrays)); - }); + .forEachRemaining(v -> result.add(parseInnerArrayValue(v, prefix, type, supportArrays))); } return new ExprCollectionValue(result); } @@ -373,7 +363,7 @@ private ExprValue parseArray( */ private ExprValue parseGeoPoint(Content content, boolean supportArrays) { // there is only one point in doc. - if (content.isArray() == false) { + if (!content.isArray()) { final var pair = content.geoValue(); return new OpenSearchExprGeoPointValue(pair.getLeft(), pair.getRight()); } @@ -384,7 +374,7 @@ private ExprValue parseGeoPoint(Content content, boolean supportArrays) { if (first.isNumber()) { double lon = first.doubleValue(); var second = elements.next(); - if (second.isNumber() == false) { + if (!second.isNumber()) { throw new OpenSearchParseException("lat must be a number, got " + second.objectValue()); } return new OpenSearchExprGeoPointValue(second.doubleValue(), lon); diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilder.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilder.java index a218151b2e..551f82a6e4 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilder.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilder.java @@ -166,7 +166,7 @@ public int compare(NamedExpression o1, NamedExpression o2) { /** Get the {@link SortOrder} for expression. By default, the {@link SortOrder} is ASC. */ public SortOrder sortOrder(NamedExpression expression) { - return SORT_MAP.get(sortOption(expression).getSortOrder()); + return SORT_MAP.get(sortOption(expression).sortOrder()); } /** @@ -174,7 +174,7 @@ public SortOrder sortOrder(NamedExpression expression) { * missing first / DESC missing last. */ public MissingOrder missingOrder(NamedExpression expression) { - return NULL_MAP.get(sortOption(expression).getNullOrder()); + return NULL_MAP.get(sortOption(expression).nullOrder()); } private Sort.SortOption sortOption(NamedExpression expression) { diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilder.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilder.java index fa0fe19105..c0cb9e2c1d 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilder.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilder.java @@ -109,7 +109,7 @@ public QueryBuilder visitFunction(FunctionExpression func, Object context) { NestedQuery nestedQuery = (NestedQuery) luceneQueries.get( - ((FunctionExpression) func.getArguments().get(0)).getFunctionName()); + ((FunctionExpression) func.getArguments().getFirst()).getFunctionName()); return nestedQuery.buildNested(func, query); } return buildScriptQuery(func); diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/lucene/LuceneQuery.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/lucene/LuceneQuery.java index c9ef5bcca5..3b186324df 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/lucene/LuceneQuery.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/filter/lucene/LuceneQuery.java @@ -66,7 +66,7 @@ public boolean canSupport(FunctionExpression func) { * @return return true if function has supported nested function expression. */ public boolean isNestedPredicate(FunctionExpression func) { - return isNestedFunction(func.getArguments().get(0)); + return isNestedFunction(func.getArguments().getFirst()); } /** @@ -88,10 +88,9 @@ private boolean isMultiParameterQuery(FunctionExpression func) { * Check if the second argument of the function is a literal expression wrapped by cast function. */ private boolean literalExpressionWrappedByCast(FunctionExpression func) { - if (func.getArguments().get(1) instanceof FunctionExpression) { - FunctionExpression expr = (FunctionExpression) func.getArguments().get(1); + if (func.getArguments().get(1) instanceof FunctionExpression expr) { return castMap.containsKey(expr.getFunctionName()) - && expr.getArguments().get(0) instanceof LiteralExpression; + && expr.getArguments().getFirst() instanceof LiteralExpression; } return false; } @@ -114,7 +113,7 @@ public QueryBuilder build(FunctionExpression func) { private ExprValue cast(FunctionExpression castFunction, ReferenceExpression ref) { return castMap .get(castFunction.getFunctionName()) - .apply((LiteralExpression) castFunction.getArguments().get(0), ref); + .apply((LiteralExpression) castFunction.getArguments().getFirst(), ref); } /** Type converting map. */ @@ -293,8 +292,7 @@ protected QueryBuilder doBuild(String fieldName, ExprType fieldType, ExprValue l * @return the formatted date or time value if the field type requires it, otherwise the raw value */ protected Object value(ExprValue literal, ExprType fieldType) { - if (fieldType instanceof OpenSearchDateType) { - OpenSearchDateType openSearchDateType = (OpenSearchDateType) fieldType; + if (fieldType instanceof OpenSearchDateType openSearchDateType) { if (literal.type().equals(ExprCoreType.TIMESTAMP)) { return openSearchDateType.hasNoFormatter() ? literal.timestampValue().toEpochMilli() diff --git a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/sort/SortQueryBuilder.java b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/sort/SortQueryBuilder.java index 7669b569d4..51fcc5972c 100644 --- a/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/sort/SortQueryBuilder.java +++ b/opensearch/src/main/java/org/opensearch/sql/opensearch/storage/script/sort/SortQueryBuilder.java @@ -25,14 +25,14 @@ public class SortQueryBuilder { /** The mapping between Core Engine sort order and OpenSearch sort order. */ - private Map sortOrderMap = + private final Map sortOrderMap = new ImmutableMap.Builder() .put(Sort.SortOrder.ASC, SortOrder.ASC) .put(Sort.SortOrder.DESC, SortOrder.DESC) .build(); /** The mapping between Core Engine null order and OpenSearch null order. */ - private Map missingMap = + private final Map missingMap = new ImmutableMap.Builder() .put(Sort.NullOrder.NULL_FIRST, "_first") .put(Sort.NullOrder.NULL_LAST, "_last") @@ -48,7 +48,7 @@ public class SortQueryBuilder { public SortBuilder build(Expression expression, Sort.SortOption option) { if (expression instanceof ReferenceExpression) { if (((ReferenceExpression) expression).getAttr().equalsIgnoreCase("_score")) { - return SortBuilders.scoreSort().order(sortOrderMap.get(option.getSortOrder())); + return SortBuilders.scoreSort().order(sortOrderMap.get(option.sortOrder())); } return fieldBuild((ReferenceExpression) expression, option); } else if (isNestedFunction(expression)) { @@ -61,7 +61,7 @@ public SortBuilder build(Expression expression, Sort.SortOption option) { ? (ReferenceExpression) ((FunctionExpression) expression).getArguments().get(1) : generatePath(orderByName); return SortBuilders.fieldSort(orderByName) - .order(sortOrderMap.get(option.getSortOrder())) + .order(sortOrderMap.get(option.sortOrder())) .setNestedSort(new NestedSortBuilder(path.toString())); } else { throw new IllegalStateException("unsupported expression " + expression.getClass()); @@ -74,7 +74,7 @@ public SortBuilder build(Expression expression, Sort.SortOption option) { * @param nestedFunc Nested function expression. */ private void validateNestedArgs(FunctionExpression nestedFunc) { - if (nestedFunc.getArguments().size() < 1 || nestedFunc.getArguments().size() > 2) { + if (nestedFunc.getArguments().isEmpty() || nestedFunc.getArguments().size() > 2) { throw new IllegalArgumentException( "nested function supports 2 parameters (field, path) or 1 parameter (field)"); } @@ -90,7 +90,7 @@ private void validateNestedArgs(FunctionExpression nestedFunc) { private FieldSortBuilder fieldBuild(ReferenceExpression ref, Sort.SortOption option) { return SortBuilders.fieldSort( OpenSearchTextType.convertTextToKeyword(ref.getAttr(), ref.type())) - .order(sortOrderMap.get(option.getSortOrder())) - .missing(missingMap.get(option.getNullOrder())); + .order(sortOrderMap.get(option.sortOrder())) + .missing(missingMap.get(option.nullOrder())); } } diff --git a/opensearch/src/test/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactoryTest.java b/opensearch/src/test/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactoryTest.java index d82926077e..b00b901c02 100644 --- a/opensearch/src/test/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactoryTest.java +++ b/opensearch/src/test/java/org/opensearch/sql/opensearch/data/value/OpenSearchExprValueFactoryTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.opensearch.sql.data.model.ExprValueUtils.booleanValue; @@ -268,7 +269,7 @@ public void constructTimes() { ExprValue timeStringV = constructFromObject("timeStringV", "12:10:30.000Z"); assertAll( () -> assertTrue(timeStringV.isDateTime()), - () -> assertTrue(timeStringV instanceof ExprTimeValue), + () -> assertInstanceOf(ExprTimeValue.class, timeStringV), () -> assertEquals(new ExprTimeValue("12:10:30"), timeStringV), () -> assertEquals( @@ -441,7 +442,7 @@ public void constructArray() { new ExprCollectionValue( List.of( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("info", stringValue("zz")); put("author", stringValue("au")); @@ -452,7 +453,7 @@ public void constructArray() { new ExprCollectionValue( List.of( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("info", stringValue("zz")); put("author", stringValue("au")); @@ -723,7 +724,7 @@ public void constructArrayOfEpochMillis() { public void constructStruct() { assertEquals( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); @@ -732,7 +733,7 @@ public void constructStruct() { tupleValue("{\"structV\":{\"id\":1,\"state\":\"WA\"}}").get("structV")); assertEquals( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); @@ -825,8 +826,8 @@ public void constructBinary() { } /** - * Return the all elements if is OpenSearch Array. - * https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html. + * Return the all elements if is OpenSearch Array. .... */ @Test public void constructFromOpenSearchArrayReturnAll() { @@ -837,14 +838,14 @@ public void constructFromOpenSearchArrayReturnAll() { new ExprCollectionValue( List.of( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); } }), new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(2)); put("state", stringValue("CA")); @@ -855,8 +856,8 @@ public void constructFromOpenSearchArrayReturnAll() { } /** - * Return the all elements if is OpenSearch Array. - * https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html. + * Return the all elements if is OpenSearch Array. .... */ @Test public void constructFromOpenSearchArrayReturnAllWithArraySupport() { @@ -867,14 +868,14 @@ public void constructFromOpenSearchArrayReturnAllWithArraySupport() { new ExprCollectionValue( List.of( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); } }), new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(2)); put("state", stringValue("CA")); @@ -886,8 +887,8 @@ public void constructFromOpenSearchArrayReturnAllWithArraySupport() { } /** - * Return only the first element if is OpenSearch Array. - * https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html. + * Return only the first element if is OpenSearch Array. .... */ @Test public void constructFromOpenSearchArrayReturnAllWithoutArraySupport() { @@ -896,7 +897,7 @@ public void constructFromOpenSearchArrayReturnAllWithoutArraySupport() { tupleValue("{\"intV\":[1, 2, 3]}").get("intV")); assertEquals( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); @@ -908,8 +909,8 @@ public void constructFromOpenSearchArrayReturnAllWithoutArraySupport() { } /** - * Return only the first element if is OpenSearch Array. - * https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html. + * Return only the first element if is OpenSearch Array. .... */ @Test public void constructFromOpenSearchArrayReturnAllWithoutArraySupportNoFieldTolerance() { @@ -920,14 +921,14 @@ public void constructFromOpenSearchArrayReturnAllWithoutArraySupportNoFieldToler new ExprCollectionValue( List.of( new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(1)); put("state", stringValue("WA")); } }), new ExprTupleValue( - new LinkedHashMap() { + new LinkedHashMap<>() { { put("id", integerValue(2)); put("state", stringValue("CA")); diff --git a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanOptimizationTest.java b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanOptimizationTest.java index 6749f87c5b..286de7cdfc 100644 --- a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanOptimizationTest.java +++ b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanOptimizationTest.java @@ -644,9 +644,9 @@ private Runnable withAggregationPushedDown( Collections.singletonList( new TermsValuesSourceBuilder(aggregation.groupBy) .field(aggregation.groupBy) - .order(aggregation.sortBy.getSortOrder() == ASC ? "asc" : "desc") + .order(aggregation.sortBy.sortOrder() == ASC ? "asc" : "desc") .missingOrder( - aggregation.sortBy.getNullOrder() == NULL_FIRST ? "first" : "last") + aggregation.sortBy.nullOrder() == NULL_FIRST ? "first" : "last") .missingBucket(true))) .subAggregation( AggregationBuilders.avg(aggregation.aggregateName).field(aggregation.aggregateBy)) diff --git a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilderTest.java b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilderTest.java index 1bb988dacd..43b70c5fd0 100644 --- a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilderTest.java +++ b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/aggregation/AggregationQueryBuilderTest.java @@ -97,9 +97,8 @@ void should_build_composite_aggregation_for_field_reference() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("avg(age)", new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER))), - Arrays.asList(named("name", ref("name", STRING))))); + List.of(named("avg(age)", new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER))), + List.of(named("name", ref("name", STRING))))); } @Test @@ -131,9 +130,8 @@ void should_build_composite_aggregation_for_field_reference_with_order() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("avg(age)", new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER))), - Arrays.asList(named("name", ref("name", STRING))), + List.of(named("avg(age)", new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER))), + List.of(named("name", ref("name", STRING))), sort(ref("name", STRING), Sort.SortOption.DEFAULT_DESC))); } @@ -141,9 +139,8 @@ void should_build_composite_aggregation_for_field_reference_with_order() { void should_build_type_mapping_for_field_reference() { assertThat( buildTypeMapping( - Arrays.asList( - named("avg(age)", new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER))), - Arrays.asList(named("name", ref("name", STRING)))), + List.of(named("avg(age)", new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER))), + List.of(named("name", ref("name", STRING)))), containsInAnyOrder( map("avg(age)", OpenSearchDataType.of(INTEGER)), map("name", OpenSearchDataType.of(STRING)))); @@ -153,11 +150,11 @@ void should_build_type_mapping_for_field_reference() { void should_build_type_mapping_for_timestamp_type() { assertThat( buildTypeMapping( - Arrays.asList( + List.of( named( "avg(timestamp)", - new AvgAggregator(Arrays.asList(ref("timestamp", TIMESTAMP)), TIMESTAMP))), - Arrays.asList(named("timestamp", ref("timestamp", TIMESTAMP)))), + new AvgAggregator(List.of(ref("timestamp", TIMESTAMP)), TIMESTAMP))), + List.of(named("timestamp", ref("timestamp", TIMESTAMP)))), containsInAnyOrder( map("avg(timestamp)", OpenSearchDateType.of()), map("timestamp", OpenSearchDateType.of()))); @@ -167,9 +164,8 @@ void should_build_type_mapping_for_timestamp_type() { void should_build_type_mapping_for_date_type() { assertThat( buildTypeMapping( - Arrays.asList( - named("avg(date)", new AvgAggregator(Arrays.asList(ref("date", DATE)), DATE))), - Arrays.asList(named("date", ref("date", DATE)))), + List.of(named("avg(date)", new AvgAggregator(List.of(ref("date", DATE)), DATE))), + List.of(named("date", ref("date", DATE)))), containsInAnyOrder( map("avg(date)", OpenSearchDateType.of(DATE)), map("date", OpenSearchDateType.of(DATE)))); @@ -179,9 +175,8 @@ void should_build_type_mapping_for_date_type() { void should_build_type_mapping_for_time_type() { assertThat( buildTypeMapping( - Arrays.asList( - named("avg(time)", new AvgAggregator(Arrays.asList(ref("time", TIME)), TIME))), - Arrays.asList(named("time", ref("time", TIME)))), + List.of(named("avg(time)", new AvgAggregator(List.of(ref("time", TIME)), TIME))), + List.of(named("time", ref("time", TIME)))), containsInAnyOrder( map("avg(time)", OpenSearchDateType.of(TIME)), map("time", OpenSearchDateType.of(TIME)))); @@ -216,9 +211,8 @@ void should_build_composite_aggregation_for_field_reference_of_keyword() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("avg(age)", new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER))), - Arrays.asList( + List.of(named("avg(age)", new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER))), + List.of( named( "name", ref( @@ -234,9 +228,8 @@ void should_build_composite_aggregation_for_field_reference_of_keyword() { void should_build_type_mapping_for_field_reference_of_keyword() { assertThat( buildTypeMapping( - Arrays.asList( - named("avg(age)", new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER))), - Arrays.asList(named("name", ref("name", STRING)))), + List.of(named("avg(age)", new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER))), + List.of(named("name", ref("name", STRING)))), containsInAnyOrder( map("avg(age)", OpenSearchDataType.of(INTEGER)), map("name", OpenSearchDataType.of(STRING)))); @@ -284,11 +277,12 @@ void should_build_composite_aggregation_for_expression() { + " }%n" + "}"), buildQuery( - Arrays.asList( + List.of( named( "avg(balance)", - new AvgAggregator(Arrays.asList(DSL.abs(ref("balance", INTEGER))), INTEGER))), - Arrays.asList(named("age", DSL.asin(ref("age", INTEGER)))))); + new AvgAggregator( + Collections.singletonList(DSL.abs(ref("balance", INTEGER))), INTEGER))), + List.of(named("age", DSL.asin(ref("age", INTEGER)))))); } @Test @@ -342,11 +336,12 @@ void should_build_composite_aggregation_follow_with_order_by_position() { void should_build_type_mapping_for_expression() { assertThat( buildTypeMapping( - Arrays.asList( + List.of( named( "avg(balance)", - new AvgAggregator(Arrays.asList(DSL.abs(ref("balance", INTEGER))), INTEGER))), - Arrays.asList(named("age", DSL.asin(ref("age", INTEGER))))), + new AvgAggregator( + Collections.singletonList(DSL.abs(ref("balance", INTEGER))), INTEGER))), + List.of(named("age", DSL.asin(ref("age", INTEGER))))), containsInAnyOrder( map("avg(balance)", OpenSearchDataType.of(INTEGER)), map("age", OpenSearchDataType.of(DOUBLE)))); @@ -364,10 +359,9 @@ void should_build_aggregation_without_bucket() { + " }%n" + "}"), buildQuery( - Arrays.asList( + List.of( named( - "avg(balance)", - new AvgAggregator(Arrays.asList(ref("balance", INTEGER)), INTEGER))), + "avg(balance)", new AvgAggregator(List.of(ref("balance", INTEGER)), INTEGER))), Collections.emptyList())); } @@ -398,10 +392,10 @@ void should_build_filter_aggregation() { + " }%n" + "}"), buildQuery( - Arrays.asList( + List.of( named( "avg(age) filter(where age > 34)", - new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER) + new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER) .condition(DSL.greater(ref("age", INTEGER), literal(20))))), Collections.emptyList())); } @@ -450,22 +444,21 @@ void should_build_filter_aggregation_group_by() { + " }%n" + "}"), buildQuery( - Arrays.asList( + List.of( named( "avg(age) filter(where age > 34)", - new AvgAggregator(Arrays.asList(ref("age", INTEGER)), INTEGER) + new AvgAggregator(List.of(ref("age", INTEGER)), INTEGER) .condition(DSL.greater(ref("age", INTEGER), literal(20))))), - Arrays.asList(named(ref("gender", OpenSearchDataType.of(STRING)))))); + List.of(named(ref("gender", OpenSearchDataType.of(STRING)))))); } @Test void should_build_type_mapping_without_bucket() { assertThat( buildTypeMapping( - Arrays.asList( + List.of( named( - "avg(balance)", - new AvgAggregator(Arrays.asList(ref("balance", INTEGER)), INTEGER))), + "avg(balance)", new AvgAggregator(List.of(ref("balance", INTEGER)), INTEGER))), Collections.emptyList()), containsInAnyOrder(map("avg(balance)", OpenSearchDataType.of(INTEGER)))); } @@ -500,9 +493,8 @@ void should_build_histogram() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("count(a)", new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("age", INTEGER), literal(10), ""))))); + List.of(named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER))), + List.of(named(span(ref("age", INTEGER), literal(10), ""))))); } @Test @@ -541,9 +533,9 @@ void should_build_histogram_two_metrics() { + "}"), buildQuery( Arrays.asList( - named("count(a)", new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER)), - named("avg(b)", new AvgAggregator(Arrays.asList(ref("b", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("age", INTEGER), literal(10), ""))))); + named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER)), + named("avg(b)", new AvgAggregator(List.of(ref("b", INTEGER)), INTEGER))), + List.of(named(span(ref("age", INTEGER), literal(10), ""))))); } @Test @@ -576,9 +568,8 @@ void fixed_interval_time_span() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("count(a)", new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("timestamp", TIMESTAMP), literal(1), "h"))))); + List.of(named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER))), + List.of(named(span(ref("timestamp", TIMESTAMP), literal(1), "h"))))); } @Test @@ -611,9 +602,8 @@ void calendar_interval_time_span() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("count(a)", new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("date", DATE), literal(1), "w"))))); + List.of(named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER))), + List.of(named(span(ref("date", DATE), literal(1), "w"))))); } @Test @@ -646,9 +636,8 @@ void general_span() { + " }%n" + "}"), buildQuery( - Arrays.asList( - named("count(a)", new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("age", INTEGER), literal(1), ""))))); + List.of(named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER))), + List.of(named(span(ref("age", INTEGER), literal(1), ""))))); } @Test @@ -657,11 +646,9 @@ void invalid_unit() { IllegalStateException.class, () -> buildQuery( - Arrays.asList( - named( - "count(a)", - new CountAggregator(Arrays.asList(ref("a", INTEGER)), INTEGER))), - Arrays.asList(named(span(ref("age", INTEGER), literal(1), "invalid_unit"))))); + List.of( + named("count(a)", new CountAggregator(List.of(ref("a", INTEGER)), INTEGER))), + List.of(named(span(ref("age", INTEGER), literal(1), "invalid_unit"))))); } @SneakyThrows @@ -681,7 +668,7 @@ private String buildQuery( queryBuilder .buildAggregationBuilder(namedAggregatorList, groupByList, sortList) .getLeft() - .get(0) + .getFirst() .toString()) .toPrettyString(); } @@ -692,6 +679,6 @@ private Set> buildTypeMapping( } private Map.Entry map(String name, ExprType type) { - return new AbstractMap.SimpleEntry(name, type); + return new AbstractMap.SimpleEntry<>(name, type); } } diff --git a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilderTest.java b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilderTest.java index bd2a9901ed..fd114ca225 100644 --- a/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilderTest.java +++ b/opensearch/src/test/java/org/opensearch/sql/opensearch/storage/script/filter/FilterQueryBuilderTest.java @@ -107,14 +107,15 @@ void set_up() { @Test void should_build_term_query_for_equality_expression() { assertJsonEquals( - "{\n" - + " \"term\" : {\n" - + " \"name\" : {\n" - + " \"value\" : \"John\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "name" : { + "value" : "John", + "boost" : 1.0 + } + } + }""", buildQuery(DSL.equal(ref("name", STRING), literal("John")))); } @@ -156,15 +157,16 @@ void should_build_range_query_for_comparison_expression() { @Test void should_build_wildcard_query_for_like_expression() { assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"name\" : {\n" - + " \"wildcard\" : \"*John?\",\n" - + " \"case_insensitive\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "name" : { + "wildcard" : "*John?", + "case_insensitive" : true, + "boost" : 1.0 + } + } + }""", buildQuery(DSL.like(ref("name", STRING), literal("%John_")))); } @@ -172,15 +174,16 @@ void should_build_wildcard_query_for_like_expression() { void should_build_script_query_for_unsupported_lucene_query() { mockToStringSerializer(); assertJsonEquals( - "{\n" - + " \"script\" : {\n" - + " \"script\" : {\n" - + " \"source\" : \"is not null(age)\",\n" - + " \"lang\" : \"opensearch_query_expression\"\n" - + " },\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "script" : { + "script" : { + "source" : "is not null(age)", + "lang" : "opensearch_query_expression" + }, + "boost" : 1.0 + } + }""", buildQuery(DSL.isnotnull(ref("age", INTEGER)))); } @@ -188,15 +191,16 @@ void should_build_script_query_for_unsupported_lucene_query() { void should_build_script_query_for_function_expression() { mockToStringSerializer(); assertJsonEquals( - "{\n" - + " \"script\" : {\n" - + " \"script\" : {\n" - + " \"source\" : \"=(abs(age), 30)\",\n" - + " \"lang\" : \"opensearch_query_expression\"\n" - + " },\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "script" : { + "script" : { + "source" : "=(abs(age), 30)", + "lang" : "opensearch_query_expression" + }, + "boost" : 1.0 + } + }""", buildQuery(DSL.equal(DSL.abs(ref("age", INTEGER)), literal(30)))); } @@ -204,15 +208,16 @@ void should_build_script_query_for_function_expression() { void should_build_script_query_for_comparison_between_fields() { mockToStringSerializer(); assertJsonEquals( - "{\n" - + " \"script\" : {\n" - + " \"script\" : {\n" - + " \"source\" : \"=(age1, age2)\",\n" - + " \"lang\" : \"opensearch_query_expression\"\n" - + " },\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "script" : { + "script" : { + "source" : "=(age1, age2)", + "lang" : "opensearch_query_expression" + }, + "boost" : 1.0 + } + }""", buildQuery(DSL.equal(ref("age1", INTEGER), ref("age2", INTEGER)))); } @@ -258,36 +263,38 @@ void should_build_bool_query_for_and_or_expression() { @Test void should_build_bool_query_for_not_expression() { assertJsonEquals( - "{\n" - + " \"bool\" : {\n" - + " \"must_not\" : [\n" - + " {\n" - + " \"term\" : {\n" - + " \"age\" : {\n" - + " \"value\" : 30,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + " }\n" - + " ],\n" - + " \"adjust_pure_negative\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "bool" : { + "must_not" : [ + { + "term" : { + "age" : { + "value" : 30, + "boost" : 1.0 + } + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }""", buildQuery(DSL.not(DSL.equal(ref("age", INTEGER), literal(30))))); } @Test void should_use_keyword_for_multi_field_in_equality_expression() { assertJsonEquals( - "{\n" - + " \"term\" : {\n" - + " \"name.keyword\" : {\n" - + " \"value\" : \"John\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "name.keyword" : { + "value" : "John", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.equal( ref( @@ -302,15 +309,16 @@ void should_use_keyword_for_multi_field_in_equality_expression() { @Test void should_use_keyword_for_multi_field_in_like_expression() { assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"name.keyword\" : {\n" - + " \"wildcard\" : \"John*\",\n" - + " \"case_insensitive\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "name.keyword" : { + "wildcard" : "John*", + "case_insensitive" : true, + "boost" : 1.0 + } + } + }""", buildQuery( DSL.like( ref( @@ -325,22 +333,23 @@ void should_use_keyword_for_multi_field_in_like_expression() { @Test void should_build_term_query_predicate_expression_with_nested_function() { assertJsonEquals( - "{\n" - + " \"nested\" : {\n" - + " \"query\" : {\n" - + " \"term\" : {\n" - + " \"message.info\" : {\n" - + " \"value\" : \"string_value\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + " },\n" - + " \"path\" : \"message\",\n" - + " \"ignore_unmapped\" : false,\n" - + " \"score_mode\" : \"none\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "nested" : { + "query" : { + "term" : { + "message.info" : { + "value" : "string_value", + "boost" : 1.0 + } + } + }, + "path" : "message", + "ignore_unmapped" : false, + "score_mode" : "none", + "boost" : 1.0 + } + }""", buildQuery( DSL.equal( DSL.nested(DSL.ref("message.info", STRING), DSL.ref("message", STRING)), @@ -350,25 +359,26 @@ void should_build_term_query_predicate_expression_with_nested_function() { @Test void should_build_range_query_predicate_expression_with_nested_function() { assertJsonEquals( - "{\n" - + " \"nested\" : {\n" - + " \"query\" : {\n" - + " \"range\" : {\n" - + " \"lottery.number.id\" : {\n" - + " \"from\" : 1234,\n" - + " \"to\" : null,\n" - + " \"include_lower\" : false,\n" - + " \"include_upper\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + " },\n" - + " \"path\" : \"lottery.number\",\n" - + " \"ignore_unmapped\" : false,\n" - + " \"score_mode\" : \"none\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "nested" : { + "query" : { + "range" : { + "lottery.number.id" : { + "from" : 1234, + "to" : null, + "include_lower" : false, + "include_upper" : true, + "boost" : 1.0 + } + } + }, + "path" : "lottery.number", + "ignore_unmapped" : false, + "score_mode" : "none", + "boost" : 1.0 + } + }""", buildQuery(DSL.greater(DSL.nested(DSL.ref("lottery.number.id", INTEGER)), literal(1234)))); } @@ -435,21 +445,22 @@ void nested_filter_too_many_params_throws_exception() { @Test void should_build_match_query_with_default_parameters() { assertJsonEquals( - "{\n" - + " \"match\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"operator\" : \"OR\",\n" - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"lenient\" : false,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match" : { + "message" : { + "query" : "search query", + "operator" : "OR", + "prefix_length" : 0, + "max_expansions" : 50, + "fuzzy_transpositions" : true, + "lenient" : false, + "zero_terms_query" : "NONE", + "auto_generate_synonyms_phrase_query" : true, + "boost" : 1.0 + } + } + }""", buildQuery( DSL.match( DSL.namedArgument( @@ -460,25 +471,26 @@ void should_build_match_query_with_default_parameters() { @Test void should_build_match_query_with_custom_parameters() { assertJsonEquals( - "{\n" - + " \"match\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"operator\" : \"AND\",\n" - + " \"analyzer\" : \"keyword\"," - + " \"fuzziness\" : \"AUTO\"," - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"minimum_should_match\" : \"3\"," - + " \"fuzzy_rewrite\" : \"top_terms_1\"," - + " \"fuzzy_transpositions\" : false,\n" - + " \"lenient\" : false,\n" - + " \"zero_terms_query\" : \"ALL\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"boost\" : 2.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match" : { + "message" : { + "query" : "search query", + "operator" : "AND", + "analyzer" : "keyword",\ + "fuzziness" : "AUTO",\ + "prefix_length" : 0, + "max_expansions" : 50, + "minimum_should_match" : "3",\ + "fuzzy_rewrite" : "top_terms_1",\ + "fuzzy_transpositions" : false, + "lenient" : false, + "zero_terms_query" : "ALL", + "auto_generate_synonyms_phrase_query" : true, + "boost" : 2.0 + } + } + }""", buildQuery( DSL.match( DSL.namedArgument( @@ -568,16 +580,17 @@ void match_missing_query() { @Test void should_build_match_phrase_query_with_default_parameters() { assertJsonEquals( - "{\n" - + " \"match_phrase\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"slop\" : 0,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match_phrase" : { + "message" : { + "query" : "search query", + "slop" : 0, + "zero_terms_query" : "NONE", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.match_phrase( DSL.namedArgument( @@ -588,23 +601,24 @@ void should_build_match_phrase_query_with_default_parameters() { @Test void should_build_multi_match_query_with_default_parameters_single_field() { assertJsonEquals( - "{\n" - + " \"multi_match\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [\n" - + " \"field1^1.0\"\n" - + " ],\n" - + " \"type\" : \"best_fields\",\n" - + " \"operator\" : \"OR\",\n" - + " \"slop\" : 0,\n" - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0,\n" - + " }\n" - + "}", + """ + { + "multi_match" : { + "query" : "search query", + "fields" : [ + "field1^1.0" + ], + "type" : "best_fields", + "operator" : "OR", + "slop" : 0, + "prefix_length" : 0, + "max_expansions" : 50, + "zero_terms_query" : "NONE", + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0, + } + }""", buildQuery( DSL.multi_match( DSL.namedArgument( @@ -619,23 +633,24 @@ void should_build_multi_match_query_with_default_parameters_single_field() { @Test void should_build_multi_match_query_with_default_parameters_all_fields() { assertJsonEquals( - "{\n" - + " \"multi_match\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [\n" - + " \"*^1.0\"\n" - + " ],\n" - + " \"type\" : \"best_fields\",\n" - + " \"operator\" : \"OR\",\n" - + " \"slop\" : 0,\n" - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0,\n" - + " }\n" - + "}", + """ + { + "multi_match" : { + "query" : "search query", + "fields" : [ + "*^1.0" + ], + "type" : "best_fields", + "operator" : "OR", + "slop" : 0, + "prefix_length" : 0, + "max_expansions" : 50, + "zero_terms_query" : "NONE", + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0, + } + }""", buildQuery( DSL.multi_match( DSL.namedArgument( @@ -650,21 +665,22 @@ void should_build_multi_match_query_with_default_parameters_all_fields() { @Test void should_build_multi_match_query_with_default_parameters_no_fields() { assertJsonEquals( - "{\n" - + " \"multi_match\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [],\n" - + " \"type\" : \"best_fields\",\n" - + " \"operator\" : \"OR\",\n" - + " \"slop\" : 0,\n" - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0,\n" - + " }\n" - + "}", + """ + { + "multi_match" : { + "query" : "search query", + "fields" : [], + "type" : "best_fields", + "operator" : "OR", + "slop" : 0, + "prefix_length" : 0, + "max_expansions" : 50, + "zero_terms_query" : "NONE", + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0, + } + }""", buildQuery( DSL.multi_match( DSL.namedArgument( @@ -678,21 +694,22 @@ void should_build_multi_match_query_with_default_parameters_no_fields() { @Test void should_build_multi_match_query_with_default_parameters_multiple_fields() { var expected = - "{\n" - + " \"multi_match\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [%s],\n" - + " \"type\" : \"best_fields\",\n" - + " \"operator\" : \"OR\",\n" - + " \"slop\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"prefix_length\" : 0,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0,\n" - + " }\n" - + "}"; + """ + { + "multi_match" : { + "query" : "search query", + "fields" : [%s], + "type" : "best_fields", + "operator" : "OR", + "slop" : 0, + "max_expansions" : 50, + "prefix_length" : 0, + "zero_terms_query" : "NONE", + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0, + } + }"""; var actual = buildQuery( DSL.multi_match( @@ -717,27 +734,28 @@ void should_build_multi_match_query_with_default_parameters_multiple_fields() { @Test void should_build_multi_match_query_with_custom_parameters() { var expected = - "{\n" - + " \"multi_match\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [%s],\n" - + " \"type\" : \"phrase_prefix\",\n" - + " \"operator\" : \"AND\",\n" - + " \"analyzer\" : \"keyword\",\n" - + " \"slop\" : 1,\n" - + " \"fuzziness\" : \"AUTO:2,4\",\n" - + " \"prefix_length\" : 1,\n" - + " \"max_expansions\" : 3,\n" - + " \"minimum_should_match\" : \"3\",\n" - + " \"tie_breaker\" : 1.0,\n" - + " \"lenient\" : false,\n" - + " \"cutoff_frequency\" : 4.3,\n" - + " \"zero_terms_query\" : \"ALL\",\n" - + " \"auto_generate_synonyms_phrase_query\" : false,\n" - + " \"fuzzy_transpositions\" : false,\n" - + " \"boost\" : 2.0\n" - + " }\n" - + "}"; + """ + { + "multi_match" : { + "query" : "search query", + "fields" : [%s], + "type" : "phrase_prefix", + "operator" : "AND", + "analyzer" : "keyword", + "slop" : 1, + "fuzziness" : "AUTO:2,4", + "prefix_length" : 1, + "max_expansions" : 3, + "minimum_should_match" : "3", + "tie_breaker" : 1.0, + "lenient" : false, + "cutoff_frequency" : 4.3, + "zero_terms_query" : "ALL", + "auto_generate_synonyms_phrase_query" : false, + "fuzzy_transpositions" : false, + "boost" : 2.0 + } + }"""; var actual = buildQuery( DSL.multi_match( @@ -793,17 +811,18 @@ void multi_match_invalid_parameter() { @Test void should_build_match_phrase_query_with_custom_parameters() { assertJsonEquals( - "{\n" - + " \"match_phrase\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"analyzer\" : \"keyword\"," - + " \"slop\" : 2,\n" - + " \"zero_terms_query\" : \"ALL\",\n" - + " \"boost\" : 1.2\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match_phrase" : { + "message" : { + "query" : "search query", + "analyzer" : "keyword",\ + "slop" : 2, + "zero_terms_query" : "ALL", + "boost" : 1.2 + } + } + }""", buildQuery( DSL.match_phrase( DSL.namedArgument( @@ -832,14 +851,15 @@ void wildcard_query_invalid_parameter() { void wildcard_query_convert_sql_wildcard_to_lucene() { // Test conversion of % wildcard to * assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query*\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query*", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -847,14 +867,15 @@ void wildcard_query_convert_sql_wildcard_to_lucene() { DSL.namedArgument("query", literal("search query%"))))); assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query?\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query?", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -865,14 +886,15 @@ void wildcard_query_convert_sql_wildcard_to_lucene() { @Test void wildcard_query_escape_wildcards_characters() { assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query%\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query%", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -880,14 +902,15 @@ void wildcard_query_escape_wildcards_characters() { DSL.namedArgument("query", literal("search query\\%"))))); assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query_\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query_", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -895,14 +918,15 @@ void wildcard_query_escape_wildcards_characters() { DSL.namedArgument("query", literal("search query\\_"))))); assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query\\\\*\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query\\\\*", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -910,14 +934,15 @@ void wildcard_query_escape_wildcards_characters() { DSL.namedArgument("query", literal("search query\\*"))))); assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query\\\\?\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query\\\\?", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -928,14 +953,15 @@ void wildcard_query_escape_wildcards_characters() { @Test void should_build_wildcard_query_with_default_parameters() { assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query*\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query*", + "boost" : 1.0 + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -946,16 +972,17 @@ void should_build_wildcard_query_with_default_parameters() { @Test void should_build_wildcard_query_query_with_custom_parameters() { assertJsonEquals( - "{\n" - + " \"wildcard\" : {\n" - + " \"field\" : {\n" - + " \"wildcard\" : \"search query*\",\n" - + " \"boost\" : 0.6,\n" - + " \"case_insensitive\" : true,\n" - + " \"rewrite\" : \"constant_score_boolean\"\n" - + " }\n" - + " }\n" - + "}", + """ + { + "wildcard" : { + "field" : { + "wildcard" : "search query*", + "boost" : 0.6, + "case_insensitive" : true, + "rewrite" : "constant_score_boolean" + } + } + }""", buildQuery( DSL.wildcard_query( DSL.namedArgument( @@ -990,24 +1017,25 @@ void query_invalid_fields_parameter_exception_message() { @Test void should_build_query_query_with_default_parameters() { var expected = - "{\n" - + " \"query_string\" : {\n" - + " \"query\" : \"field1:query_value\",\n" - + " \"fields\" : [],\n" - + " \"type\" : \"best_fields\",\n" - + " \"default_operator\" : \"or\",\n" - + " \"max_determinized_states\" : 10000,\n" - + " \"enable_position_increments\" : true,\n" - + " \"fuzziness\" : \"AUTO\",\n" - + " \"fuzzy_prefix_length\" : 0,\n" - + " \"fuzzy_max_expansions\" : 50,\n" - + " \"phrase_slop\" : 0,\n" - + " \"escape\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}"; + """ + { + "query_string" : { + "query" : "field1:query_value", + "fields" : [], + "type" : "best_fields", + "default_operator" : "or", + "max_determinized_states" : 10000, + "enable_position_increments" : true, + "fuzziness" : "AUTO", + "fuzzy_prefix_length" : 0, + "fuzzy_max_expansions" : 50, + "phrase_slop" : 0, + "escape" : false, + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0 + } + }"""; assertJsonEquals( expected, buildQuery(DSL.query(DSL.namedArgument("query", literal("field1:query_value"))))); @@ -1016,29 +1044,30 @@ void should_build_query_query_with_default_parameters() { @Test void should_build_query_query_with_custom_parameters() { var expected = - "{\n" - + " \"query_string\" : {\n" - + " \"query\" : \"field1:query_value\",\n" - + " \"fields\" : [],\n" - + " \"type\" : \"cross_fields\",\n" - + " \"tie_breaker\" : 1.3,\n" - + " \"default_operator\" : \"and\",\n" - + " \"analyzer\" : \"keyword\",\n" - + " \"max_determinized_states\" : 10000,\n" - + " \"enable_position_increments\" : true,\n" - + " \"fuzziness\" : \"AUTO\",\n" - + " \"fuzzy_prefix_length\" : 2,\n" - + " \"fuzzy_max_expansions\" : 10,\n" - + " \"phrase_slop\" : 0,\n" - + " \"analyze_wildcard\" : true,\n" - + " \"minimum_should_match\" : \"3\",\n" - + " \"lenient\" : false,\n" - + " \"escape\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : false,\n" - + " \"fuzzy_transpositions\" : false,\n" - + " \"boost\" : 2.0,\n" - + " }\n" - + "}"; + """ + { + "query_string" : { + "query" : "field1:query_value", + "fields" : [], + "type" : "cross_fields", + "tie_breaker" : 1.3, + "default_operator" : "and", + "analyzer" : "keyword", + "max_determinized_states" : 10000, + "enable_position_increments" : true, + "fuzziness" : "AUTO", + "fuzzy_prefix_length" : 2, + "fuzzy_max_expansions" : 10, + "phrase_slop" : 0, + "analyze_wildcard" : true, + "minimum_should_match" : "3", + "lenient" : false, + "escape" : false, + "auto_generate_synonyms_phrase_query" : false, + "fuzzy_transpositions" : false, + "boost" : 2.0, + } + }"""; var actual = buildQuery( DSL.query( @@ -1082,24 +1111,25 @@ void query_string_invalid_parameter() { @Test void should_build_query_string_query_with_default_parameters_multiple_fields() { var expected = - "{\n" - + " \"query_string\" : {\n" - + " \"query\" : \"query_value\",\n" - + " \"fields\" : [%s],\n" - + " \"type\" : \"best_fields\",\n" - + " \"default_operator\" : \"or\",\n" - + " \"max_determinized_states\" : 10000,\n" - + " \"enable_position_increments\" : true,\n" - + " \"fuzziness\" : \"AUTO\",\n" - + " \"fuzzy_prefix_length\" : 0,\n" - + " \"fuzzy_max_expansions\" : 50,\n" - + " \"phrase_slop\" : 0,\n" - + " \"escape\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}"; + """ + { + "query_string" : { + "query" : "query_value", + "fields" : [%s], + "type" : "best_fields", + "default_operator" : "or", + "max_determinized_states" : 10000, + "enable_position_increments" : true, + "fuzziness" : "AUTO", + "fuzzy_prefix_length" : 0, + "fuzzy_max_expansions" : 50, + "phrase_slop" : 0, + "escape" : false, + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0 + } + }"""; var actual = buildQuery( DSL.query_string( @@ -1124,29 +1154,30 @@ void should_build_query_string_query_with_default_parameters_multiple_fields() { @Test void should_build_query_string_query_with_custom_parameters() { var expected = - "{\n" - + " \"query_string\" : {\n" - + " \"query\" : \"query_value\",\n" - + " \"fields\" : [%s],\n" - + " \"type\" : \"cross_fields\",\n" - + " \"tie_breaker\" : 1.3,\n" - + " \"default_operator\" : \"and\",\n" - + " \"analyzer\" : \"keyword\",\n" - + " \"max_determinized_states\" : 10000,\n" - + " \"enable_position_increments\" : true,\n" - + " \"fuzziness\" : \"AUTO\",\n" - + " \"fuzzy_prefix_length\" : 2,\n" - + " \"fuzzy_max_expansions\" : 10,\n" - + " \"phrase_slop\" : 0,\n" - + " \"analyze_wildcard\" : true,\n" - + " \"minimum_should_match\" : \"3\",\n" - + " \"lenient\" : false,\n" - + " \"escape\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : false,\n" - + " \"fuzzy_transpositions\" : false,\n" - + " \"boost\" : 2.0,\n" - + " }\n" - + "}"; + """ + { + "query_string" : { + "query" : "query_value", + "fields" : [%s], + "type" : "cross_fields", + "tie_breaker" : 1.3, + "default_operator" : "and", + "analyzer" : "keyword", + "max_determinized_states" : 10000, + "enable_position_increments" : true, + "fuzziness" : "AUTO", + "fuzzy_prefix_length" : 2, + "fuzzy_max_expansions" : 10, + "phrase_slop" : 0, + "analyze_wildcard" : true, + "minimum_should_match" : "3", + "lenient" : false, + "escape" : false, + "auto_generate_synonyms_phrase_query" : false, + "fuzzy_transpositions" : false, + "boost" : 2.0, + } + }"""; var actual = buildQuery( DSL.query_string( @@ -1179,26 +1210,27 @@ void should_build_query_string_query_with_custom_parameters() { @Test void should_build_query_string_query_with_default_parameters_single_field() { assertJsonEquals( - "{\n" - + " \"query_string\" : {\n" - + " \"query\" : \"query_value\",\n" - + " \"fields\" : [\n" - + " \"field1^1.0\"\n" - + " ],\n" - + " \"type\" : best_fields,\n" - + " \"default_operator\" : or,\n" - + " \"max_determinized_states\" : 10000,\n" - + " \"enable_position_increments\" : true,\n" - + " \"fuzziness\" : \"AUTO\",\n" - + " \"fuzzy_prefix_length\" : 0,\n" - + " \"fuzzy_max_expansions\" : 50,\n" - + " \"phrase_slop\" : 0,\n" - + " \"escape\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0,\n" - + " }\n" - + "}", + """ + { + "query_string" : { + "query" : "query_value", + "fields" : [ + "field1^1.0" + ], + "type" : best_fields, + "default_operator" : or, + "max_determinized_states" : 10000, + "enable_position_increments" : true, + "fuzziness" : "AUTO", + "fuzzy_prefix_length" : 0, + "fuzzy_max_expansions" : 50, + "phrase_slop" : 0, + "escape" : false, + "auto_generate_synonyms_phrase_query" : true, + "fuzzy_transpositions" : true, + "boost" : 1.0, + } + }""", buildQuery( DSL.query_string( DSL.namedArgument( @@ -1217,22 +1249,23 @@ void should_build_query_string_query_with_default_parameters_single_field() { // 3) `minimum_should_match` printed as a string void should_build_simple_query_string_query_with_default_parameters_single_field() { assertJsonEquals( - "{\n" - + " \"simple_query_string\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [\n" - + " \"field1^1.0\"\n" - + " ],\n" - + " \"default_operator\" : \"or\",\n" - + " \"analyze_wildcard\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"flags\" : -1,\n" - + " \"fuzzy_max_expansions\" : 50,\n" - + " \"fuzzy_prefix_length\" : 0,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "simple_query_string" : { + "query" : "search query", + "fields" : [ + "field1^1.0" + ], + "default_operator" : "or", + "analyze_wildcard" : false, + "auto_generate_synonyms_phrase_query" : true, + "flags" : -1, + "fuzzy_max_expansions" : 50, + "fuzzy_prefix_length" : 0, + "fuzzy_transpositions" : true, + "boost" : 1.0 + } + }""", buildQuery( DSL.simple_query_string( DSL.namedArgument( @@ -1247,20 +1280,21 @@ void should_build_simple_query_string_query_with_default_parameters_single_field @Test void should_build_simple_query_string_query_with_default_parameters_multiple_fields() { var expected = - "{\n" - + " \"simple_query_string\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [%s],\n" - + " \"default_operator\" : \"or\",\n" - + " \"analyze_wildcard\" : false,\n" - + " \"auto_generate_synonyms_phrase_query\" : true,\n" - + " \"flags\" : -1,\n" - + " \"fuzzy_max_expansions\" : 50,\n" - + " \"fuzzy_prefix_length\" : 0,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}"; + """ + { + "simple_query_string" : { + "query" : "search query", + "fields" : [%s], + "default_operator" : "or", + "analyze_wildcard" : false, + "auto_generate_synonyms_phrase_query" : true, + "flags" : -1, + "fuzzy_max_expansions" : 50, + "fuzzy_prefix_length" : 0, + "fuzzy_transpositions" : true, + "boost" : 1.0 + } + }"""; var actual = buildQuery( DSL.simple_query_string( @@ -1285,23 +1319,24 @@ void should_build_simple_query_string_query_with_default_parameters_multiple_fie @Test void should_build_simple_query_string_query_with_custom_parameters() { var expected = - "{\n" - + " \"simple_query_string\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"fields\" : [%s],\n" - + " \"analyze_wildcard\" : true,\n" - + " \"analyzer\" : \"keyword\",\n" - + " \"auto_generate_synonyms_phrase_query\" : false,\n" - + " \"default_operator\" : \"and\",\n" - + " \"flags\" : 1,\n" - + " \"fuzzy_max_expansions\" : 10,\n" - + " \"fuzzy_prefix_length\" : 2,\n" - + " \"fuzzy_transpositions\" : false,\n" - + " \"lenient\" : false,\n" - + " \"minimum_should_match\" : \"3\",\n" - + " \"boost\" : 2.0\n" - + " }\n" - + "}"; + """ + { + "simple_query_string" : { + "query" : "search query", + "fields" : [%s], + "analyze_wildcard" : true, + "analyzer" : "keyword", + "auto_generate_synonyms_phrase_query" : false, + "default_operator" : "and", + "flags" : 1, + "fuzzy_max_expansions" : 10, + "fuzzy_prefix_length" : 2, + "fuzzy_transpositions" : false, + "lenient" : false, + "minimum_should_match" : "3", + "boost" : 2.0 + } + }"""; var actual = buildQuery( DSL.simple_query_string( @@ -1430,18 +1465,19 @@ void relevancy_func_invalid_arg_values() { @Test void should_build_match_bool_prefix_query_with_default_parameters() { assertJsonEquals( - "{\n" - + " \"match_bool_prefix\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"operator\" : \"OR\",\n" - + " \"prefix_length\" : 0,\n" - + " \"max_expansions\" : 50,\n" - + " \"fuzzy_transpositions\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match_bool_prefix" : { + "message" : { + "query" : "search query", + "operator" : "OR", + "prefix_length" : 0, + "max_expansions" : 50, + "fuzzy_transpositions" : true, + "boost" : 1.0 + } + } + }""", buildQuery( DSL.match_bool_prefix( DSL.namedArgument( @@ -1485,17 +1521,18 @@ void multi_match_missing_query_even_with_struct() { @Test void should_build_match_phrase_prefix_query_with_default_parameters() { assertJsonEquals( - "{\n" - + " \"match_phrase_prefix\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"slop\" : 0,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"max_expansions\" : 50,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match_phrase_prefix" : { + "message" : { + "query" : "search query", + "slop" : 0, + "zero_terms_query" : "NONE", + "max_expansions" : 50, + "boost" : 1.0 + } + } + }""", buildQuery( DSL.match_phrase_prefix( DSL.namedArgument( @@ -1506,18 +1543,19 @@ void should_build_match_phrase_prefix_query_with_default_parameters() { @Test void should_build_match_phrase_prefix_query_with_non_default_parameters() { assertJsonEquals( - "{\n" - + " \"match_phrase_prefix\" : {\n" - + " \"message\" : {\n" - + " \"query\" : \"search query\",\n" - + " \"slop\" : 0,\n" - + " \"zero_terms_query\" : \"NONE\",\n" - + " \"max_expansions\" : 42,\n" - + " \"boost\" : 1.2,\n" - + " \"analyzer\": english\n" - + " }\n" - + " }\n" - + "}", + """ + { + "match_phrase_prefix" : { + "message" : { + "query" : "search query", + "slop" : 0, + "zero_terms_query" : "NONE", + "max_expansions" : 42, + "boost" : 1.2, + "analyzer": english + } + } + }""", buildQuery( DSL.match_phrase_prefix( DSL.namedArgument( @@ -1531,14 +1569,15 @@ void should_build_match_phrase_prefix_query_with_non_default_parameters() { @Test void cast_to_string_in_filter() { String json = - "{\n" - + " \"term\" : {\n" - + " \"string_value\" : {\n" - + " \"value\" : \"1\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "string_value" : { + "value" : "1", + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("string_value", STRING), DSL.castString(literal(1))))); @@ -1579,14 +1618,15 @@ private Integer castToInteger(Object o) { void cast_to_byte_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"byte_value\" : {\n" - + " \"value\" : %d,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "byte_value" : { + "value" : %d, + "boost" : 1.0 + } + } + }""", castToInteger(expr.valueOf().value())), buildQuery(DSL.equal(ref("byte_value", BYTE), DSL.castByte(expr)))); } @@ -1596,14 +1636,15 @@ void cast_to_byte_in_filter(LiteralExpression expr) { void cast_to_short_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"short_value\" : {\n" - + " \"value\" : %d,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "short_value" : { + "value" : %d, + "boost" : 1.0 + } + } + }""", castToInteger(expr.valueOf().value())), buildQuery(DSL.equal(ref("short_value", SHORT), DSL.castShort(expr)))); } @@ -1613,14 +1654,15 @@ void cast_to_short_in_filter(LiteralExpression expr) { void cast_to_int_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"integer_value\" : {\n" - + " \"value\" : %d,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "integer_value" : { + "value" : %d, + "boost" : 1.0 + } + } + }""", castToInteger(expr.valueOf().value())), buildQuery(DSL.equal(ref("integer_value", INTEGER), DSL.castInt(expr)))); } @@ -1630,14 +1672,15 @@ void cast_to_int_in_filter(LiteralExpression expr) { void cast_to_long_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"long_value\" : {\n" - + " \"value\" : %d,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "long_value" : { + "value" : %d, + "boost" : 1.0 + } + } + }""", castToInteger(expr.valueOf().value())), buildQuery(DSL.equal(ref("long_value", LONG), DSL.castLong(expr)))); } @@ -1647,14 +1690,15 @@ void cast_to_long_in_filter(LiteralExpression expr) { void cast_to_float_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"float_value\" : {\n" - + " \"value\" : %f,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "float_value" : { + "value" : %f, + "boost" : 1.0 + } + } + }""", castToFloat(expr.valueOf().value())), buildQuery(DSL.equal(ref("float_value", FLOAT), DSL.castFloat(expr)))); } @@ -1669,14 +1713,15 @@ void cast_to_double_in_filter(LiteralExpression expr) { assertJsonEquals( String.format( - "{\n" - + " \"term\" : {\n" - + " \"double_value\" : {\n" - + " \"value\" : %2.20f,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "term" : { + "double_value" : { + "value" : %2.20f, + "boost" : 1.0 + } + } + }""", DSL.castDouble(expr).valueOf().doubleValue()), buildQuery(DSL.equal(ref("double_value", DOUBLE), DSL.castDouble(expr)))); } @@ -1685,14 +1730,15 @@ void cast_to_double_in_filter(LiteralExpression expr) { @MethodSource({"booleanTrueCastSource"}) void cast_to_boolean_true_in_filter(LiteralExpression expr) { String json = - "{\n" - + " \"term\" : {\n" - + " \"boolean_value\" : {\n" - + " \"value\" : true,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "boolean_value" : { + "value" : true, + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("boolean_value", BOOLEAN), DSL.castBoolean(expr)))); @@ -1702,14 +1748,15 @@ void cast_to_boolean_true_in_filter(LiteralExpression expr) { @MethodSource({"booleanFalseCastSource"}) void cast_to_boolean_false_in_filter(LiteralExpression expr) { String json = - "{\n" - + " \"term\" : {\n" - + " \"boolean_value\" : {\n" - + " \"value\" : false,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "boolean_value" : { + "value" : false, + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("boolean_value", BOOLEAN), DSL.castBoolean(expr)))); @@ -1719,14 +1766,15 @@ void cast_to_boolean_false_in_filter(LiteralExpression expr) { void cast_from_boolean() { Expression booleanExpr = literal(false); String json = - "{\n" - + " \"term\" : {\n" - + " \"my_value\" : {\n" - + " \"value\" : 0,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "my_value" : { + "value" : 0, + "boost" : 1.0 + } + } + }"""; assertJsonEquals(json, buildQuery(DSL.equal(ref("my_value", BYTE), DSL.castByte(booleanExpr)))); assertJsonEquals( json, buildQuery(DSL.equal(ref("my_value", SHORT), DSL.castShort(booleanExpr)))); @@ -1735,28 +1783,30 @@ void cast_from_boolean() { assertJsonEquals(json, buildQuery(DSL.equal(ref("my_value", LONG), DSL.castLong(booleanExpr)))); json = - "{\n" - + " \"term\" : {\n" - + " \"my_value\" : {\n" - + " \"value\" : 0.0,\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "my_value" : { + "value" : 0.0, + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("my_value", FLOAT), DSL.castFloat(booleanExpr)))); assertJsonEquals( json, buildQuery(DSL.equal(ref("my_value", DOUBLE), DSL.castDouble(booleanExpr)))); json = - "{\n" - + " \"term\" : {\n" - + " \"my_value\" : {\n" - + " \"value\" : \"false\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "my_value" : { + "value" : "false", + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("my_value", STRING), DSL.castString(booleanExpr)))); } @@ -1764,14 +1814,15 @@ void cast_from_boolean() { @Test void cast_to_date_in_filter() { String json = - "{\n" - + " \"term\" : {\n" - + " \"date_value\" : {\n" - + " \"value\" : \"2021-11-08\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "date_value" : { + "value" : "2021-11-08", + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("date_value", DATE), DSL.castDate(literal("2021-11-08"))))); @@ -1791,14 +1842,15 @@ void cast_to_date_in_filter() { @Test void cast_to_time_in_filter() { String json = - "{\n" - + " \"term\" : {\n" - + " \"time_value\" : {\n" - + " \"value\" : \"17:00:00\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "time_value" : { + "value" : "17:00:00", + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, buildQuery(DSL.equal(ref("time_value", TIME), DSL.castTime(literal("17:00:00"))))); @@ -1818,14 +1870,15 @@ void cast_to_time_in_filter() { @Test void cast_to_timestamp_in_filter() { String json = - "{\n" - + " \"term\" : {\n" - + " \"timestamp_value\" : {\n" - + " \"value\" : \"2021-11-08 17:00:00\",\n" - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}"; + """ + { + "term" : { + "timestamp_value" : { + "value" : "2021-11-08 17:00:00", + "boost" : 1.0 + } + } + }"""; assertJsonEquals( json, @@ -1844,17 +1897,18 @@ void cast_to_timestamp_in_filter() { @Test void cast_in_range_query() { assertJsonEquals( - "{\n" - + " \"range\" : {\n" - + " \"timestamp_value\" : {\n" - + " \"from\" : \"2021-11-08 17:00:00\",\n" - + " \"to\" : null," - + " \"include_lower\" : false," - + " \"include_upper\" : true," - + " \"boost\" : 1.0\n" - + " }\n" - + " }\n" - + "}", + """ + { + "range" : { + "timestamp_value" : { + "from" : "2021-11-08 17:00:00", + "to" : null,\ + "include_lower" : false,\ + "include_upper" : true,\ + "boost" : 1.0 + } + } + }""", buildQuery( DSL.greater( ref("timestamp_value", TIMESTAMP), @@ -1865,15 +1919,16 @@ void cast_in_range_query() { void non_literal_in_cast_should_build_script() { mockToStringSerializer(); assertJsonEquals( - "{\n" - + " \"script\" : {\n" - + " \"script\" : {\n" - + " \"source\" : \"=(string_value, cast_to_string(+(1, 0)))\",\n" - + " \"lang\" : \"opensearch_query_expression\"\n" - + " },\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "script" : { + "script" : { + "source" : "=(string_value, cast_to_string(+(1, 0)))", + "lang" : "opensearch_query_expression" + }, + "boost" : 1.0 + } + }""", buildQuery( DSL.equal( ref("string_value", STRING), DSL.castString(DSL.add(literal(1), literal(0)))))); @@ -1883,15 +1938,16 @@ void non_literal_in_cast_should_build_script() { void non_cast_nested_function_should_build_script() { mockToStringSerializer(); assertJsonEquals( - "{\n" - + " \"script\" : {\n" - + " \"script\" : {\n" - + " \"source\" : \"=(integer_value, abs(+(1, 0)))\",\n" - + " \"lang\" : \"opensearch_query_expression\"\n" - + " },\n" - + " \"boost\" : 1.0\n" - + " }\n" - + "}", + """ + { + "script" : { + "script" : { + "source" : "=(integer_value, abs(+(1, 0)))", + "lang" : "opensearch_query_expression" + }, + "boost" : 1.0 + } + }""", buildQuery( DSL.equal(ref("integer_value", INTEGER), DSL.abs(DSL.add(literal(1), literal(0)))))); } diff --git a/opensearch/src/test/java/org/opensearch/sql/opensearch/utils/Utils.java b/opensearch/src/test/java/org/opensearch/sql/opensearch/utils/Utils.java index 0db87f89d4..7d66f98d14 100644 --- a/opensearch/src/test/java/org/opensearch/sql/opensearch/utils/Utils.java +++ b/opensearch/src/test/java/org/opensearch/sql/opensearch/utils/Utils.java @@ -5,18 +5,15 @@ package org.opensearch.sql.opensearch.utils; -import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Set; import lombok.experimental.UtilityClass; import org.apache.commons.lang3.tuple.Pair; import org.opensearch.sql.ast.tree.Sort; import org.opensearch.sql.data.type.ExprCoreType; import org.opensearch.sql.expression.Expression; import org.opensearch.sql.expression.NamedExpression; -import org.opensearch.sql.expression.ReferenceExpression; import org.opensearch.sql.expression.aggregation.AvgAggregator; import org.opensearch.sql.expression.aggregation.NamedAggregator; @@ -24,7 +21,7 @@ public class Utils { public static AvgAggregator avg(Expression expr, ExprCoreType type) { - return new AvgAggregator(Arrays.asList(expr), type); + return new AvgAggregator(Collections.singletonList(expr), type); } public static List agg(NamedAggregator... exprs) { @@ -44,12 +41,4 @@ public static List> sort( Expression expr1, Sort.SortOption option1, Expression expr2, Sort.SortOption option2) { return Arrays.asList(Pair.of(option1, expr1), Pair.of(option2, expr2)); } - - public static Set projects(ReferenceExpression... expressions) { - return ImmutableSet.copyOf(expressions); - } - - public static Set noProjects() { - return null; - } } diff --git a/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstBuilderTest.java b/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstBuilderTest.java index ced266ed78..ad1389edf0 100644 --- a/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstBuilderTest.java +++ b/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstBuilderTest.java @@ -45,9 +45,7 @@ import com.google.common.collect.ImmutableMap; import java.util.Arrays; import org.junit.Ignore; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.opensearch.sql.ast.Node; import org.opensearch.sql.ast.expression.DataType; import org.opensearch.sql.ast.expression.Literal; @@ -61,9 +59,7 @@ public class AstBuilderTest { - @Rule public ExpectedException exceptionRule = ExpectedException.none(); - - private PPLSyntaxParser parser = new PPLSyntaxParser(); + private final PPLSyntaxParser parser = new PPLSyntaxParser(); @Test public void testSearchCommand() { diff --git a/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstExpressionBuilderTest.java b/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstExpressionBuilderTest.java index fbb25549ab..0cf0e72f50 100644 --- a/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstExpressionBuilderTest.java +++ b/ppl/src/test/java/org/opensearch/sql/ppl/parser/AstExpressionBuilderTest.java @@ -46,7 +46,6 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import java.util.stream.Collectors; import org.junit.Ignore; import org.junit.Test; import org.opensearch.sql.ast.expression.AllFields; @@ -744,7 +743,7 @@ void assertFunctionNameCouldBeId(String antlrFunctionName) { Arrays.stream(antlrFunctionName.split("\\|")) .map(String::stripLeading) .map(String::stripTrailing) - .collect(Collectors.toList()); + .toList(); assertFalse(functionList.isEmpty()); for (String functionName : functionList) { diff --git a/sql/src/main/java/org/opensearch/sql/sql/parser/AstSortBuilder.java b/sql/src/main/java/org/opensearch/sql/sql/parser/AstSortBuilder.java index 2594709f4f..c8a34a9240 100644 --- a/sql/src/main/java/org/opensearch/sql/sql/parser/AstSortBuilder.java +++ b/sql/src/main/java/org/opensearch/sql/sql/parser/AstSortBuilder.java @@ -58,8 +58,8 @@ private List createSortFields() { * if absent. */ private List createSortArguments(SortOption option) { - SortOrder sortOrder = option.getSortOrder(); - NullOrder nullOrder = option.getNullOrder(); + SortOrder sortOrder = option.sortOrder(); + NullOrder nullOrder = option.nullOrder(); ImmutableList.Builder args = ImmutableList.builder(); args.add(new Argument("asc", booleanLiteral(sortOrder != DESC))); // handle both null and ASC