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 @@ -13,6 +13,7 @@
import static org.opensearch.sql.ast.tree.Sort.SortOption.DEFAULT_DESC;
import static org.opensearch.sql.ast.tree.Sort.SortOrder.ASC;
import static org.opensearch.sql.ast.tree.Sort.SortOrder.DESC;
import static org.opensearch.sql.calcite.utils.PlanUtils.ROW_NUMBER_COLUMN_FOR_DEDUP;
import static org.opensearch.sql.calcite.utils.PlanUtils.ROW_NUMBER_COLUMN_NAME;
import static org.opensearch.sql.calcite.utils.PlanUtils.ROW_NUMBER_COLUMN_NAME_MAIN;
import static org.opensearch.sql.calcite.utils.PlanUtils.ROW_NUMBER_COLUMN_NAME_SUBSEARCH;
Expand Down Expand Up @@ -843,13 +844,14 @@ public RelNode visitDedupe(Dedupe node, CalcitePlanContext context) {
if (keepEmpty) {
/*
* | dedup 2 a, b keepempty=false
* DropColumns('_row_number_)
* +- Filter ('_row_number_ <= n OR isnull('a) OR isnull('b))
* +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
* DropColumns('_row_number_dedup_)
* +- Filter ('_row_number_dedup_ <= n OR isnull('a) OR isnull('b))
* +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_dedup_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
* +- ...
*/
// Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST,
// specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC
// specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_dedup_], ['a, 'b], ['a
// ASC
// NULLS FIRST, 'b ASC NULLS FIRST]
RexNode rowNumber =
context
Expand All @@ -859,23 +861,23 @@ public RelNode visitDedupe(Dedupe node, CalcitePlanContext context) {
.partitionBy(dedupeFields)
.orderBy(dedupeFields)
.rowsTo(RexWindowBounds.CURRENT_ROW)
.as("_row_number_");
.as(ROW_NUMBER_COLUMN_FOR_DEDUP);
context.relBuilder.projectPlus(rowNumber);
RexNode _row_number_ = context.relBuilder.field("_row_number_");
// Filter (isnull('a) OR isnull('b) OR '_row_number_ <= n)
RexNode _row_number_dedup_ = context.relBuilder.field(ROW_NUMBER_COLUMN_FOR_DEDUP);
// Filter (isnull('a) OR isnull('b) OR '_row_number_dedup_ <= n)
context.relBuilder.filter(
context.relBuilder.or(
context.relBuilder.or(dedupeFields.stream().map(context.relBuilder::isNull).toList()),
context.relBuilder.lessThanOrEqual(
_row_number_, context.relBuilder.literal(allowedDuplication))));
_row_number_dedup_, context.relBuilder.literal(allowedDuplication))));
// DropColumns('_row_number_)
context.relBuilder.projectExcept(_row_number_);
context.relBuilder.projectExcept(_row_number_dedup_);
} else {
/*
* | dedup 2 a, b keepempty=false
* DropColumns('_row_number_)
* +- Filter ('_row_number_ <= n)
* +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
* DropColumns('_row_number_dedup_)
* +- Filter ('_row_number_dedup_ <= n)
* +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_dedup_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
* +- Filter (isnotnull('a) AND isnotnull('b))
* +- ...
*/
Expand All @@ -884,7 +886,8 @@ public RelNode visitDedupe(Dedupe node, CalcitePlanContext context) {
context.relBuilder.and(
dedupeFields.stream().map(context.relBuilder::isNotNull).toList()));
// Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST,
// specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC
// specifiedwindowoundedpreceding$(), currentrow$())) AS _row_number_dedup_], ['a, 'b], ['a
// ASC
// NULLS FIRST, 'b ASC NULLS FIRST]
RexNode rowNumber =
context
Expand All @@ -894,15 +897,15 @@ public RelNode visitDedupe(Dedupe node, CalcitePlanContext context) {
.partitionBy(dedupeFields)
.orderBy(dedupeFields)
.rowsTo(RexWindowBounds.CURRENT_ROW)
.as("_row_number_");
.as(ROW_NUMBER_COLUMN_FOR_DEDUP);
context.relBuilder.projectPlus(rowNumber);
RexNode _row_number_ = context.relBuilder.field("_row_number_");
// Filter ('_row_number_ <= n)
RexNode _row_number_dedup_ = context.relBuilder.field(ROW_NUMBER_COLUMN_FOR_DEDUP);
// Filter ('_row_number_dedup_ <= n)
context.relBuilder.filter(
context.relBuilder.lessThanOrEqual(
_row_number_, context.relBuilder.literal(allowedDuplication)));
// DropColumns('_row_number_)
context.relBuilder.projectExcept(_row_number_);
_row_number_dedup_, context.relBuilder.literal(allowedDuplication)));
// DropColumns('_row_number_dedup_)
context.relBuilder.projectExcept(_row_number_dedup_);
}
return context.relBuilder.peek();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,15 @@
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelShuttle;
import org.apache.calcite.rel.core.TableScan;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexOver;
import org.apache.calcite.rex.RexVisitorImpl;
import org.apache.calcite.rex.RexWindow;
import org.apache.calcite.rex.RexWindowBound;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.tools.RelBuilder;
Expand All @@ -43,6 +47,9 @@

public interface PlanUtils {

/** this is only for dedup command, do not reuse it in other command */
String ROW_NUMBER_COLUMN_FOR_DEDUP = "_row_number_dedup_";

String ROW_NUMBER_COLUMN_NAME = "_row_number_";
String ROW_NUMBER_COLUMN_NAME_MAIN = "_row_number_main_";
String ROW_NUMBER_COLUMN_NAME_SUBSEARCH = "_row_number_subsearch_";
Expand Down Expand Up @@ -347,4 +354,41 @@ static RexNode derefMapCall(RexNode rexNode) {
}
return rexNode;
}

/** Check if contains RexOver */
static boolean containsRowNumberDedup(LogicalProject project) {
return project.getProjects().stream()
.anyMatch(p -> p instanceof RexOver && p.getKind() == SqlKind.ROW_NUMBER);
}

/** Get all RexWindow list from LogicalProject */
static List<RexWindow> getRexWindowFromProject(LogicalProject project) {
final List<RexWindow> res = new ArrayList<>();
final RexVisitorImpl<Void> visitor =
new RexVisitorImpl<>(true) {
@Override
public Void visitOver(RexOver over) {
res.add(over.getWindow());
return null;
}
};
visitor.visitEach(project.getProjects());
return res;
}

static List<Integer> getSelectColumns(List<RexNode> rexNodes) {
final List<Integer> selectedColumns = new ArrayList<>();
final RexVisitorImpl<Void> visitor =
new RexVisitorImpl<Void>(true) {
@Override
public Void visitInputRef(RexInputRef inputRef) {
if (!selectedColumns.contains(inputRef.getIndex())) {
selectedColumns.add(inputRef.getIndex());
}
return null;
}
};
visitor.visitEach(rexNodes);
return selectedColumns;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Sort;
import org.apache.calcite.rel.logical.LogicalSort;
import org.apache.calcite.rel.metadata.DefaultRelMetadataProvider;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.tools.FrameworkConfig;
Expand Down Expand Up @@ -298,7 +297,7 @@ private FrameworkConfig buildFrameworkConfig() {
.parserConfig(SqlParser.Config.DEFAULT) // TODO check
.defaultSchema(opensearchSchema)
.traitDefs((List<RelTraitDef>) null)
.programs(Programs.calc(DefaultRelMetadataProvider.INSTANCE))
.programs(Programs.standard())
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use Programs.standard() in building context because the actual execution uses it.

.typeSystem(OpenSearchTypeSystem.INSTANCE);
return configBuilder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public void testQ1() throws IOException {
schema("count_order", "bigint"));
verifyDataRows(
actual,
rows(
closeTo(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix flaky

"A",
"F",
37474,
Expand All @@ -65,7 +65,7 @@ public void testQ1() throws IOException {
isPushdownEnabled() ? 25419.231826792962 : 25419.231826792948,
isPushdownEnabled() ? 0.0508660351826793 : 0.050866035182679493,
1478),
rows(
closeTo(
"N",
"F",
1041,
Expand All @@ -76,7 +76,7 @@ public void testQ1() throws IOException {
27402.659736842103,
isPushdownEnabled() ? 0.04289473684210526 : 0.042894736842105284,
38),
rows(
closeTo(
"N",
"O",
75168,
Expand All @@ -87,7 +87,7 @@ public void testQ1() throws IOException {
isPushdownEnabled() ? 25632.42277116627 : 25632.422771166166,
isPushdownEnabled() ? 0.049697381842910573 : 0.04969738184291069,
2941),
rows(
closeTo(
"R",
"F",
36511,
Expand Down
30 changes: 30 additions & 0 deletions integ-test/src/test/java/org/opensearch/sql/ppl/ExplainIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,36 @@ public void testStatsByTimeSpan() throws IOException {
String.format("source=%s | stats count() by span(birthdate,1M)", TEST_INDEX_BANK)));
}

@Test
public void testDedupPushdown() throws IOException {
String expected = loadExpectedPlan("explain_dedup_push.json");
assertJsonEqualsIgnoreId(
expected,
explainQueryToString(
"source=opensearch-sql_test_index_account | fields account_number, gender, age"
+ " | dedup 1 gender"));
}

@Test
public void testDedupKeepEmptyTruePushdown() throws IOException {
String expected = loadExpectedPlan("explain_dedup_keepempty_true_push.json");
assertJsonEqualsIgnoreId(
expected,
explainQueryToString(
"source=opensearch-sql_test_index_account | fields account_number, gender, age"
+ " | dedup gender KEEPEMPTY=true"));
}

@Test
public void testDedupKeepEmptyFalsePushdown() throws IOException {
String expected = loadExpectedPlan("explain_dedup_keepempty_false_push.json");
assertJsonEqualsIgnoreId(
expected,
explainQueryToString(
"source=opensearch-sql_test_index_account | fields account_number, gender, age"
+ " | dedup gender KEEPEMPTY=false"));
}

@Test
public void testSingleFieldRelevanceQueryFunctionExplain() throws IOException {
// This test is only applicable if pushdown is enabled
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,16 +292,21 @@ protected boolean matchesSafely(JSONArray array) {
};
}

public static TypeSafeMatcher<JSONArray> closeTo(Number... values) {
public static TypeSafeMatcher<JSONArray> closeTo(Object... values) {
final double error = 1e-10;
return new TypeSafeMatcher<JSONArray>() {
@Override
protected boolean matchesSafely(JSONArray item) {
List<Number> expectedValues = new ArrayList<>(Arrays.asList(values));
List<Number> actualValues = new ArrayList<>();
item.iterator().forEachRemaining(v -> actualValues.add((Number) v));
List<Object> expectedValues = new ArrayList<>(Arrays.asList(values));
List<Object> actualValues = new ArrayList<>();
item.iterator().forEachRemaining(v -> actualValues.add((Object) v));
return actualValues.stream()
.allMatch(v -> valuesAreClose(v, expectedValues.get(actualValues.indexOf(v))));
.allMatch(
v ->
v instanceof Number
? valuesAreClose(
(Number) v, (Number) expectedValues.get(actualValues.indexOf(v)))
: v.equals(expectedValues.get(actualValues.indexOf(v))));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"calcite": {
"logical": "LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalProject(account_number=[$0], gender=[$1], age=[$2])\n LogicalFilter(condition=[<=($3, 1)])\n LogicalProject(account_number=[$0], gender=[$1], age=[$2], _row_number_dedup_=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $1)])\n LogicalFilter(condition=[IS NOT NULL($1)])\n LogicalProject(account_number=[$0], gender=[$4], age=[$8])\n CalciteLogicalIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]])\n",
"physical": "CalciteEnumerableIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]], PushDownContext=[[PROJECT->[account_number, gender, age], FILTER->IS NOT NULL($1), COLLAPSE->gender, LIMIT->10000], OpenSearchRequestBuilder(sourceBuilder={\"from\":0,\"size\":10000,\"timeout\":\"1m\",\"query\":{\"exists\":{\"field\":\"gender\",\"boost\":1.0}},\"_source\":{\"includes\":[\"account_number\",\"gender\",\"age\"],\"excludes\":[]},\"sort\":[{\"_doc\":{\"order\":\"asc\"}}],\"collapse\":{\"field\":\"gender.keyword\"}}, requestedTotalSize=10000, pageSize=null, startFrom=0)])\n"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"calcite": {
"logical": "LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalProject(account_number=[$0], gender=[$1], age=[$2])\n LogicalFilter(condition=[OR(IS NULL($1), <=($3, 1))])\n LogicalProject(account_number=[$0], gender=[$4], age=[$8], _row_number_dedup_=[ROW_NUMBER() OVER (PARTITION BY $4 ORDER BY $4)])\n CalciteLogicalIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]])\n",
"physical": "EnumerableLimit(fetch=[10000])\n EnumerableCalc(expr#0..3=[{inputs}], expr#4=[IS NULL($t1)], expr#5=[1], expr#6=[<=($t3, $t5)], expr#7=[OR($t4, $t6)], proj#0..2=[{exprs}], $condition=[$t7])\n EnumerableWindow(window#0=[window(partition {1} order by [1] rows between UNBOUNDED PRECEDING and CURRENT ROW aggs [ROW_NUMBER()])])\n CalciteEnumerableIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]], PushDownContext=[[PROJECT->[account_number, gender, age]], OpenSearchRequestBuilder(sourceBuilder={\"from\":0,\"timeout\":\"1m\",\"_source\":{\"includes\":[\"account_number\",\"gender\",\"age\"],\"excludes\":[]}}, requestedTotalSize=2147483647, pageSize=null, startFrom=0)])\n"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"calcite": {
"logical": "LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalProject(account_number=[$0], gender=[$1], age=[$2])\n LogicalFilter(condition=[<=($3, 1)])\n LogicalProject(account_number=[$0], gender=[$1], age=[$2], _row_number_dedup_=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $1)])\n LogicalFilter(condition=[IS NOT NULL($1)])\n LogicalProject(account_number=[$0], gender=[$4], age=[$8])\n CalciteLogicalIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]])\n",
"physical": "CalciteEnumerableIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]], PushDownContext=[[PROJECT->[account_number, gender, age], FILTER->IS NOT NULL($1), COLLAPSE->gender, LIMIT->10000], OpenSearchRequestBuilder(sourceBuilder={\"from\":0,\"size\":10000,\"timeout\":\"1m\",\"query\":{\"exists\":{\"field\":\"gender\",\"boost\":1.0}},\"_source\":{\"includes\":[\"account_number\",\"gender\",\"age\"],\"excludes\":[]},\"sort\":[{\"_doc\":{\"order\":\"asc\"}}],\"collapse\":{\"field\":\"gender.keyword\"}}, requestedTotalSize=10000, pageSize=null, startFrom=0)])\n"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"calcite": {
"logical": "LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalProject(age2=[$2])\n LogicalFilter(condition=[<=($3, 1)])\n LogicalProject(avg_age=[$0], state=[$1], age2=[$2], _row_number_=[ROW_NUMBER() OVER (PARTITION BY $2 ORDER BY $2)])\n LogicalFilter(condition=[IS NOT NULL($2)])\n LogicalProject(avg_age=[$0], state=[$1], age2=[+($0, 2)])\n LogicalSort(sort0=[$1], dir0=[ASC-nulls-first])\n LogicalProject(avg_age=[$2], state=[$0], city=[$1])\n LogicalAggregate(group=[{0, 1}], avg_age=[AVG($2)])\n LogicalProject(state=[$7], city=[$5], age=[$8])\n LogicalFilter(condition=[>($8, 30)])\n CalciteLogicalIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]])\n",
"logical": "LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalProject(age2=[$2])\n LogicalFilter(condition=[<=($3, 1)])\n LogicalProject(avg_age=[$0], state=[$1], age2=[$2], _row_number_dedup_=[ROW_NUMBER() OVER (PARTITION BY $2 ORDER BY $2)])\n LogicalFilter(condition=[IS NOT NULL($2)])\n LogicalProject(avg_age=[$0], state=[$1], age2=[+($0, 2)])\n LogicalSort(sort0=[$1], dir0=[ASC-nulls-first])\n LogicalProject(avg_age=[$2], state=[$0], city=[$1])\n LogicalAggregate(group=[{0, 1}], avg_age=[AVG($2)])\n LogicalProject(state=[$7], city=[$5], age=[$8])\n LogicalFilter(condition=[>($8, 30)])\n CalciteLogicalIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]])\n",
"physical": "EnumerableLimit(fetch=[10000])\n EnumerableCalc(expr#0..2=[{inputs}], expr#3=[1], expr#4=[<=($t2, $t3)], age2=[$t1], $condition=[$t4])\n EnumerableWindow(window#0=[window(partition {1} order by [1] rows between UNBOUNDED PRECEDING and CURRENT ROW aggs [ROW_NUMBER()])])\n EnumerableCalc(expr#0..2=[{inputs}], expr#3=[2], expr#4=[+($t2, $t3)], expr#5=[IS NOT NULL($t2)], state=[$t0], age2=[$t4], $condition=[$t5])\n CalciteEnumerableIndexScan(table=[[OpenSearch, opensearch-sql_test_index_account]], PushDownContext=[[PROJECT->[city, state, age], FILTER->>($2, 30), AGGREGATION->rel#:LogicalAggregate.NONE.[](input=RelSubset#,group={0, 1},avg_age=AVG($2)), SORT->[0 ASC FIRST]], OpenSearchRequestBuilder(sourceBuilder={\"from\":0,\"size\":0,\"timeout\":\"1m\",\"query\":{\"range\":{\"age\":{\"from\":30,\"to\":null,\"include_lower\":false,\"include_upper\":true,\"boost\":1.0}}},\"_source\":{\"includes\":[\"city\",\"state\",\"age\"],\"excludes\":[]},\"sort\":[{\"_doc\":{\"order\":\"asc\"}}],\"aggregations\":{\"composite_buckets\":{\"composite\":{\"size\":1000,\"sources\":[{\"state\":{\"terms\":{\"field\":\"state.keyword\",\"missing_bucket\":true,\"missing_order\":\"first\",\"order\":\"asc\"}}},{\"city\":{\"terms\":{\"field\":\"city.keyword\",\"missing_bucket\":true,\"missing_order\":\"first\",\"order\":\"asc\"}}}]},\"aggregations\":{\"avg_age\":{\"avg\":{\"field\":\"age\"}}}}}}, requestedTotalSize=2147483647, pageSize=null, startFrom=0)])\n"
}
}
Loading
Loading