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 @@ -5047,6 +5047,8 @@ public RelNode visitReplace(Replace node, CalcitePlanContext context) {

List<RexNode> projectList = new ArrayList<>();

Map<String, Integer> fieldIndex = buildFieldIndex(fieldNames);

// Project all fields, replacing specified ones in-place
for (String fieldName : fieldNames) {
if (fieldsToReplace.contains(fieldName)) {
Expand Down Expand Up @@ -5095,7 +5097,7 @@ public RelNode visitReplace(Replace node, CalcitePlanContext context) {
projectList.add(fieldRef);
} else {
// Keep original field unchanged
projectList.add(context.relBuilder.field(fieldName));
projectList.add(context.relBuilder.field(fieldIndex.get(fieldName)));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.opensearch.client.Request;
import org.opensearch.sql.common.antlr.SyntaxCheckException;
import org.opensearch.sql.legacy.TestUtils;
import org.opensearch.sql.ppl.PPLIntegTestCase;

public class CalciteReplaceCommandIT extends PPLIntegTestCase {
private static final String WIDE_INDEX = "test_replace_wide";
private static final int WIDE_ATTRIBUTES = 1_000;

public void init() throws Exception {
super.init();
Expand Down Expand Up @@ -526,6 +530,59 @@ public void testEscapeSequence_noMatchLiteral() throws IOException {
verifyDataRows(result, rows("fooXbar"));
}

/** Replace on an index with many dynamic attribute fields keeps every other column's value. */
@Test
public void testReplaceOnWideIndex() throws IOException {
createWideIndexIfAbsent();
String last = "attributes.f" + (WIDE_ATTRIBUTES - 1);
JSONObject result =
executeQuery(
String.format(
"source=%s | replace 's1' WITH 'S1' IN status | replace 'x*' WITH 'y*' IN %s |"
+ " fields code, status, attributes.f1, %s",
WIDE_INDEX, last, last));
verifySchema(
result,
schema("code", null, "bigint"),
schema("status", null, "string"),
schema("attributes.f1", null, "string"),
schema(last, null, "string"));
verifyDataRows(result, rows(201, "S1", "v1", "y" + (WIDE_ATTRIBUTES - 1)));
}

private void createWideIndexIfAbsent() throws IOException {
if (TestUtils.isIndexExist(client(), WIDE_INDEX)) {
return;
}
JSONObject attributes = new JSONObject();
for (int i = 0; i < WIDE_ATTRIBUTES; i++) {
attributes.put("f" + i, new JSONObject().put("type", "keyword"));
}
JSONObject properties =
new JSONObject()
.put("@timestamp", new JSONObject().put("type", "date"))
.put("status", new JSONObject().put("type", "keyword"))
.put("code", new JSONObject().put("type", "long"))
.put("attributes", new JSONObject().put("properties", attributes));
JSONObject fieldLimit =
new JSONObject().put("total_fields", new JSONObject().put("limit", WIDE_ATTRIBUTES + 100));
JSONObject body =
new JSONObject()
.put(
"settings",
new JSONObject().put("index", new JSONObject().put("mapping", fieldLimit)))
.put("mappings", new JSONObject().put("properties", properties));
TestUtils.createIndexByRestClient(client(), WIDE_INDEX, body.toString());

Request doc = TestUtils.seedDocRequest(WIDE_INDEX, "1");
doc.setJsonEntity(
String.format(
"{\"@timestamp\": \"2026-11-09T00:00:00Z\", \"status\": \"s1\", \"code\": 201,"
+ " \"attributes\": {\"f1\": \"v1\", \"f%d\": \"x%d\"}}",
WIDE_ATTRIBUTES - 1, WIDE_ATTRIBUTES - 1));
client().performRequest(doc);
}

/**
* Build a {@code column -> value} map from interleaved varargs ({@code key1, val1, key2, val2,
* ...}). Preserves insertion order so the expected-row mapping reads naturally at the call site.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Issue #5959: replace resolves every column of the input when it builds its projection.
# The columns it does not replace must keep their names, order, types and values.

setup:
- do:
query.settings:
body:
transient:
plugins.calcite.enabled : true
- do:
indices.create:
index: issue5959
body:
settings:
number_of_shards: 1
number_of_replicas: 0
mappings:
properties:
"@timestamp":
type: date
status:
type: keyword
code:
type: long
attributes:
properties:
f0:
type: keyword
f1:
type: keyword
f2:
type: keyword
- do:
bulk:
index: issue5959
refresh: true
body:
- '{"index": {}}'
- '{"@timestamp": "2026-11-09T00:00:00Z", "status": "s1", "code": 201, "attributes": {"f1": "v1", "f2": "x2"}}'

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

---
"Replace keeps the columns it does not replace":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=issue5959 | replace \"s1\" WITH \"S1\" IN status | head 10"
- match: { total: 1 }
- match:
schema:
- { name: attributes, type: struct }
- { name: "@timestamp", type: timestamp }
- { name: code, type: bigint }
- { name: status, type: string }
- match: { datarows: [ [ { f1: "v1", f2: "x2" }, "2026-11-09 00:00:00", 201, "S1" ] ] }

---
"Replace keeps the values of flattened sub-fields":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: "source=issue5959 | replace \"s1\" WITH \"S1\" IN status | replace \"x*\" WITH \"y*\" IN attributes.f2 | fields code, status, attributes.f1, attributes.f2"
- match: { total: 1 }
- match: { datarows: [ [ 201, "S1", "v1", "y2" ] ] }
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,77 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;

import java.util.List;
import org.apache.calcite.DataContext;
import org.apache.calcite.linq4j.Enumerable;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.plan.RelTraitDef;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.schema.ScannableTable;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.impl.AbstractTable;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.test.CalciteAssert;
import org.apache.calcite.tools.Frameworks;
import org.apache.calcite.tools.Programs;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Test;
import org.opensearch.sql.common.antlr.SyntaxCheckException;
import org.opensearch.sql.common.error.ErrorReport;

public class CalcitePPLReplaceTest extends CalcitePPLAbstractTest {

private static final int WIDE_SUBFIELDS = 100_000;

public CalcitePPLReplaceTest() {
super(CalciteAssert.SchemaSpec.SCOTT_WITH_TEMPORAL);
}

@Override
protected Frameworks.ConfigBuilder config(CalciteAssert.SchemaSpec... schemaSpecs) {
final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
final SchemaPlus schema = CalciteAssert.addSchema(rootSchema, schemaSpecs);
schema.add("WIDE", new CalcitePPLWideNestedSchemaTest.WideNestedTable(WIDE_SUBFIELDS));
schema.add("REPEATED", new RepeatedNamesTable());
return Frameworks.newConfigBuilder()
.parserConfig(SqlParser.Config.DEFAULT)
.defaultSchema(schema)
.traitDefs((List<RelTraitDef>) null)
.programs(Programs.heuristicJoinOrder(Programs.RULE_SET, true, 2));
}

/**
* Resolving every column through {@code RelBuilder.field(String)}, which searches the field names
* linearly on each call, made replace O(columns^2); this query took about 40s. The timeout
* catches a regression.
*/
@Test(timeout = 10_000)
public void testReplaceOnWideSchemaIsLinear() {
RelNode root = getRelNode("source=WIDE | replace \"a\" WITH \"b\" IN NAME");
String expectedLogical =
"LogicalProject(ID=[$0], ATTRS=[$1], LONE.X=[$3], NAME=[REPLACE($"
+ (WIDE_SUBFIELDS + 5)
+ ", 'a', 'b')])\n"
+ " LogicalTableScan(table=[[scott, WIDE]])\n";
verifyLogical(root, expectedLogical);
}

/**
* Columns left unchanged resolve the way {@code RelBuilder.field(String)} does: names match
* case-sensitively, and a repeated name resolves to its first column.
*/
@Test
public void testReplaceResolvesColumnsLikeFieldByName() {
RelNode root = getRelNode("source=REPEATED | replace \"x\" WITH \"y\" IN B");
String expectedLogical =
"LogicalProject(A=[$0], a=[$1], B=[REPLACE($2, 'x', 'y')], A0=[$0])\n"
+ " LogicalTableScan(table=[[scott, REPEATED]])\n";
verifyLogical(root, expectedLogical);
}

@Test
public void testBasicReplace() {
String ppl = "source=EMP | replace \"CLERK\" WITH \"EMPLOYEE\" IN JOB";
Expand Down Expand Up @@ -409,4 +468,23 @@ public void testWildcardAndLiteralReplace_mixedPairs() {

verifyLogical(root, expectedLogical);
}

/** Columns A, a, B, A: a repeated name and a name that differs only in case. */
private static class RepeatedNamesTable extends AbstractTable implements ScannableTable {
@Override
public RelDataType getRowType(RelDataTypeFactory factory) {
return factory
.builder()
.add("A", SqlTypeName.VARCHAR)
.add("a", SqlTypeName.VARCHAR)
.add("B", SqlTypeName.VARCHAR)
.add("A", SqlTypeName.VARCHAR)
.build();
}

@Override
public Enumerable<@Nullable Object[]> scan(DataContext root) {
return Linq4j.emptyEnumerable();
}
}
}
Loading