Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

package org.opensearch.sql.expression.function.CollectionUDF;

import static org.opensearch.sql.expression.function.BuiltinFunctionName.ARRAY;
import static org.opensearch.sql.expression.function.BuiltinFunctionName.ARRAY_LENGTH;
import static org.opensearch.sql.expression.function.BuiltinFunctionName.ARRAY_SLICE;
import static org.opensearch.sql.expression.function.BuiltinFunctionName.IF;
Expand All @@ -15,6 +16,7 @@
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;
import org.opensearch.sql.expression.function.PPLFuncImpTable;

/**
Expand All @@ -29,6 +31,11 @@
*
* <p>Supports negative indexing where -1 refers to the last element.
*
* <p>As in SPL, a non-array (single-value) first argument is treated as a one-element array:
* indexes {@code 0} and {@code -1} return the value, any other index returns null, and a range
* returns a one-element array when it covers the value. A null single value returns null rather
* than an array holding null, so {@code isnull(mvindex(field, 0))} keeps working.
*
* <p>Implementation notes:
*
* <ul>
Expand All @@ -49,6 +56,13 @@ public RexNode resolve(RexBuilder builder, RexNode... args) {
RexNode array = args[0];
RexNode startIdx = args[1];

if (!isArray(array)) {
if (args.length == 2) {
return resolveSingleValueElement(builder, array, startIdx);
}
array = wrapAsArray(builder, array);
}

// Use resolve to get array length instead of direct makeCall
RexNode arrayLen = PPLFuncImpTable.INSTANCE.resolve(builder, ARRAY_LENGTH, array);

Expand All @@ -62,6 +76,41 @@ public RexNode resolve(RexBuilder builder, RexNode... args) {
}
}

private static boolean isArray(RexNode node) {
return node.getType().getSqlTypeName() == SqlTypeName.ARRAY;
}

/**
* Resolves mvindex(value, index) for a single (non-array) value, which behaves as a one-element
* array: CASE WHEN index = 0 OR index = -1 THEN value ELSE NULL END. The value keeps its own
* type, and a null value returns null.
*/
private static RexNode resolveSingleValueElement(
RexBuilder builder, RexNode value, RexNode index) {
RexNode isFirst =
builder.makeCall(
SqlStdOperatorTable.EQUALS, index, builder.makeExactLiteral(BigDecimal.ZERO));
RexNode isLast =
builder.makeCall(
SqlStdOperatorTable.EQUALS, index, builder.makeExactLiteral(BigDecimal.ONE.negate()));
RexNode coversValue = builder.makeCall(SqlStdOperatorTable.OR, isFirst, isLast);
return builder.makeCall(
SqlStdOperatorTable.CASE, coversValue, value, builder.makeNullLiteral(value.getType()));
}

/**
* Wraps a single (non-array) value as a one-element array for range access. A null value stays
* null instead of becoming an array holding null.
*/
private static RexNode wrapAsArray(RexBuilder builder, RexNode value) {
RexNode wrapped = PPLFuncImpTable.INSTANCE.resolve(builder, ARRAY, value);
return builder.makeCall(
SqlStdOperatorTable.CASE,
builder.makeCall(SqlStdOperatorTable.IS_NULL, value),
builder.makeNullLiteral(wrapped.getType()),
wrapped);
}

/** Non-widening integer addition for internal, int-domain array-index math. */
private static RexNode add(RexBuilder builder, RexNode left, RexNode right) {
return builder.makeCall(SqlStdOperatorTable.PLUS, left, right);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,21 @@ private static RexNode[] coerceNumericComparisonOperands(
};
}

/**
* Casts a DATE, TIME or TIMESTAMP operand to its string form, the same as {@code cast(value as
* string)} in PPL, and returns any other operand unchanged.
*/
private static RexNode castDatetimeToString(RexBuilder builder, RexNode node) {
SqlTypeName typeName = UserDefinedFunctionUtils.convertRelDataTypeToSqlTypeName(node.getType());
if (!SqlTypeFamily.DATETIME.getTypeNames().contains(typeName)) {
return node;
}
RelDataType stringType =
TYPE_FACTORY.createTypeWithNullability(
TYPE_FACTORY.createSqlType(SqlTypeName.VARCHAR), true);
return builder.makeCast(stringType, node, true, true);
}

/** Whether {@code node} is, or transitively contains, a {@link RexSubQuery}. */
private static boolean containsSubQuery(RexNode node) {
if (node instanceof RexSubQuery) {
Expand Down Expand Up @@ -1339,42 +1354,61 @@ void populate() {
// Register SPLIT with custom logic for empty delimiter
// Case 1: Delimiter is not empty string, use SPLIT
// Case 2: Delimiter is empty string, use REGEXP_EXTRACT_ALL with '.' pattern
// A DATE, TIME or TIMESTAMP input is implicitly cast to its string form first, the same as
// split(cast(value as string), delimiter), to match SPL where every value is splittable.
FunctionImp2 splitImpl =
(builder, str, delimiter) -> {
RexNode source = castDatetimeToString(builder, str);
// Create condition: delimiter = ''
RexNode emptyString = builder.makeLiteral("");
RexNode isEmptyDelimiter =
builder.makeCall(SqlStdOperatorTable.EQUALS, delimiter, emptyString);

// For empty delimiter: split into characters using REGEXP_EXTRACT_ALL with '.'
// pattern This matches each individual character
RexNode dotPattern = builder.makeLiteral(".");
RexNode splitChars =
builder.makeCall(SqlLibraryOperators.REGEXP_EXTRACT_ALL, source, dotPattern);

// For non-empty delimiter: use standard SPLIT
RexNode normalSplit = builder.makeCall(SqlLibraryOperators.SPLIT, source, delimiter);

// Use CASE to choose between the two approaches
// CASE WHEN isEmptyDelimiter THEN splitChars ELSE normalSplit END
return builder.makeCall(
SqlStdOperatorTable.CASE, isEmptyDelimiter, splitChars, normalSplit);
};
register(
SPLIT,
(FunctionImp2)
(builder, str, delimiter) -> {
// Create condition: delimiter = ''
RexNode emptyString = builder.makeLiteral("");
RexNode isEmptyDelimiter =
builder.makeCall(SqlStdOperatorTable.EQUALS, delimiter, emptyString);

// For empty delimiter: split into characters using REGEXP_EXTRACT_ALL with '.'
// pattern This matches each individual character
RexNode dotPattern = builder.makeLiteral(".");
RexNode splitChars =
builder.makeCall(SqlLibraryOperators.REGEXP_EXTRACT_ALL, str, dotPattern);

// For non-empty delimiter: use standard SPLIT
RexNode normalSplit = builder.makeCall(SqlLibraryOperators.SPLIT, str, delimiter);

// Use CASE to choose between the two approaches
// CASE WHEN isEmptyDelimiter THEN splitChars ELSE normalSplit END
return builder.makeCall(
SqlStdOperatorTable.CASE, isEmptyDelimiter, splitChars, normalSplit);
},
splitImpl,
PPLTypeChecker.family(SqlTypeFamily.CHARACTER, SqlTypeFamily.CHARACTER));
register(
SPLIT, splitImpl, PPLTypeChecker.family(SqlTypeFamily.DATETIME, SqlTypeFamily.CHARACTER));

// Register MVINDEX to use Calcite's ITEM/ARRAY_SLICE with index normalization
// Register MVINDEX to use Calcite's ITEM/ARRAY_SLICE with index normalization. A non-array
// first argument is treated as a one-element array, as SPL treats a single-value field as a
// one-element multivalue field (see MVIndexFunctionImp).
MVIndexFunctionImp mvIndexImpl = new MVIndexFunctionImp();
register(
MVINDEX,
new MVIndexFunctionImp(),
mvIndexImpl,
PPLTypeChecker.wrapComposite(
(CompositeOperandTypeChecker)
OperandTypes.family(SqlTypeFamily.ARRAY, SqlTypeFamily.INTEGER)
.or(
OperandTypes.family(
SqlTypeFamily.ARRAY, SqlTypeFamily.INTEGER, SqlTypeFamily.INTEGER)),
false));
register(
MVINDEX,
mvIndexImpl,
PPLTypeChecker.wrapComposite(
(CompositeOperandTypeChecker)
OperandTypes.family(SqlTypeFamily.ANY, SqlTypeFamily.INTEGER)
.or(
OperandTypes.family(
SqlTypeFamily.ANY, SqlTypeFamily.INTEGER, SqlTypeFamily.INTEGER)),
false));

registerOperator(ARRAY, PPLBuiltinOperators.ARRAY);
registerOperator(MVAPPEND, PPLBuiltinOperators.MVAPPEND);
Expand Down
4 changes: 2 additions & 2 deletions docs/user/ppl/functions/collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ Splits the string values on the delimiter and returns the string values as a mul

**Parameters**:

- `str` (Required): The string to split.
- `str` (Required): The string to split. A `DATE`, `TIME`, or `TIMESTAMP` value is split on its string form, the same as `split(cast(value as string), delimiter)`.
- `delimiter` (Required): The string to use as a delimiter for splitting.

**Return type**: `ARRAY`
Expand Down Expand Up @@ -847,7 +847,7 @@ Returns a subset of the multivalue array using the start and optional end index

**Parameters**:

- `array` (Required): The array from which to extract elements.
- `array` (Required): The array from which to extract elements. A single (non-array) value is treated as a one-element array: indexes `0` and `-1` return the value, any other index returns `null`, and a `null` value returns `null`.
- `start` (Required): The starting index (`0`-based).
- `end` (Optional): The ending index (`0`-based, inclusive).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,53 @@ public void testSplitWithMultiCharDelimiter() throws IOException {
verifyDataRows(actual, rows(List.of("1a2b3c4", "567890")));
}

@Test
public void testMvindexSingleValueField() throws IOException {
// #5948: a single-value field is treated as a one-element array, as in SPL
JSONObject actual =
executeQuery(
String.format(
"source=%s | where account_number = 1 | eval first = mvindex(firstname, 0), last ="
+ " mvindex(firstname, -1), other = mvindex(firstname, 1), age0 = mvindex(age,"
+ " 0), birth0 = mvindex(birthdate, 0), range = mvindex(firstname, 0, 0) |"
+ " fields first, last, other, age0, birth0, range",
TEST_INDEX_BANK));

verifySchema(
actual,
schema("first", "string"),
schema("last", "string"),
schema("other", "string"),
schema("age0", "int"),
schema("birth0", "timestamp"),
schema("range", "array"));
verifyDataRows(
actual,
rows(
"Amber JOHnny",
"Amber JOHnny",
null,
32,
"2017-10-23 00:00:00",
List.of("Amber JOHnny")));
}

@Test
public void testSplitDateField() throws IOException {
// #5948: a date value is split on its string form, as split(cast(birthdate as string), '-')
JSONObject actual =
executeQuery(
String.format(
"source=%s | where account_number = 1 | eval result = split(birthdate, '-'),"
+ " expected = split(cast(birthdate as string), '-') | fields result,"
+ " expected",
TEST_INDEX_BANK));

verifySchema(actual, schema("result", "array"), schema("expected", "array"));
verifyDataRows(
actual, rows(List.of("2017", "10", "23 00:00:00"), List.of("2017", "10", "23 00:00:00")));
}

@Test
public void testSplitWithEmptyDelimiter() throws IOException {
JSONObject actual =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Issue #5948: mvindex treats a single-value field as a one-element array, and split accepts a
# date/time value through an implicit cast to string, as in SPL.
setup:
- do:
query.settings:
body:
transient:
plugins.calcite.enabled : true
- do:
indices.create:
index: mvdemo_5948
body:
mappings:
properties:
s:
type: keyword
n:
type: integer
ts:
type: date
- do:
bulk:
index: mvdemo_5948
refresh: true
body:
- '{"index": {"_id": "1"}}'
- '{"s": "abc", "n": 7, "ts": "2026-01-02T03:04:05Z"}'
- '{"index": {"_id": "2"}}'
- '{"n": 8}'

---
teardown:
- do:
query.settings:
body:
transient:
plugins.calcite.enabled : null
- do:
indices.delete:
index: mvdemo_5948
ignore_unavailable: true

---
"mvindex on a single-value string field":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=mvdemo_5948 | where n = 7 | eval first = mvindex(s, 0), last = mvindex(s, -1), other = mvindex(s, 1) | fields first, last, other"
- match: { total: 1 }
- match: { datarows: [ [ "abc", "abc", null ] ] }

---
"mvindex on a single-value number field":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=mvdemo_5948 | where n = 7 | eval r = mvindex(n, 0) | fields r"
- match: { total: 1 }
- match: { datarows: [ [ 7 ] ] }

---
"mvindex on a missing single value returns null":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=mvdemo_5948 | where n = 8 | eval r = mvindex(s, 0), missing = isnull(mvindex(s, 0)) | fields r, missing"
- match: { total: 1 }
- match: { datarows: [ [ null, true ] ] }

---
"split on a date field":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=mvdemo_5948 | where n = 7 | eval p = split(ts, '-'), c = split(cast(ts as string), '-') | fields p, c"
- match: { total: 1 }
- match: { datarows: [ [ [ "2026", "01", "02 03:04:05" ], [ "2026", "01", "02 03:04:05" ] ] ] }
Loading
Loading