You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2022/11/15 07:55:46 UTC

[GitHub] [flink-ml] yunfengzhou-hub opened a new pull request, #175: [FLINK-29602] Add Transformer for SQLTransformer

yunfengzhou-hub opened a new pull request, #175:
URL: https://github.com/apache/flink-ml/pull/175

   ## What is the purpose of the change
   
   This PR adds the Transformer for the SQL transformer algorithm.
   
   ## Brief change log
   
     - Adds Transformer implementation of SQL transformer in Java and Python
     - Adds examples and documentation of SQL transformer
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): (no)
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (no)
   
   ## Documentation
   
     - Does this pull request introduce a new feature? (yes)
     - If yes, how is the feature documented? (docs / JavaDocs)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] lindong28 commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
lindong28 commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1024912755


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/SQLTransformerTest.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.sqltransformer.SQLTransformer;
+import org.apache.flink.ml.util.TestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/** Tests {@link SQLTransformer}. */
+public class SQLTransformerTest extends AbstractTestBase {
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(Row.of(0, 1.0, 3.0), Row.of(2, 2.0, 3.0));
+
+    private static final List<Row> EXPECTED_NUMERIC_DATA_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 4.0, 3.0), Row.of(2, 2.0, 3.0, 5.0, 6.0));
+
+    private static final List<Row> EXPECTED_BUILT_IN_FUNCTION_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 1.0), Row.of(2, 2.0, 3.0, Math.sqrt(2.0)));
+
+    private static final List<Row> EXPECTED_BATCH_AGGREGATION_OUTPUT =
+            Collections.singletonList(Row.of(3.0));
+
+    private static final List<Row> EXPECTED_STREAMING_AGGREGATION_OUTPUT =
+            Arrays.asList(
+                    Row.of(1.0),
+                    Row.ofKind(RowKind.UPDATE_BEFORE, 1.0),
+                    Row.ofKind(RowKind.UPDATE_AFTER, 3.0));
+
+    private StreamTableEnvironment tEnv;
+    private StreamExecutionEnvironment env;
+    private Table inputTable;
+
+    @Before
+    public void before() {
+        Configuration config = new Configuration();
+        config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, true);
+        env = StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(4);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+    }
+
+    @Test
+    public void testParam() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+        sqlTransformer.setStatement("SELECT * FROM __THIS__");
+        assertEquals("SELECT * FROM __THIS__", sqlTransformer.getStatement());
+    }
+
+    @Test
+    public void testInvalidSQLStatement() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+
+        try {
+            sqlTransformer.setStatement("SELECT * FROM __THAT__");
+            fail();
+        } catch (Exception e) {
+            assertEquals(
+                    "Parameter statement is given an invalid value SELECT * FROM __THAT__",
+                    e.getMessage());
+        }
+    }
+
+    @Test
+    public void testOutputSchema() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        assertEquals(
+                Arrays.asList("id", "v1", "v2", "v3", "v4"),
+                outputTable.getResolvedSchema().getColumnNames());
+    }
+
+    @Test
+    public void testTransformNumericData() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_NUMERIC_DATA_OUTPUT);
+    }
+
+    @Test
+    public void testBuiltInFunction() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT *, SQRT(v1) AS v3 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BUILT_IN_FUNCTION_OUTPUT);
+    }
+
+    @Test
+    public void testBatchAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BATCH_AGGREGATION_OUTPUT, false);
+    }
+
+    @Test
+    public void testStreamingAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_STREAMING_AGGREGATION_OUTPUT, false);

Review Comment:
   Is there any operator in Flink ML that can handle upsert events?
   
   If no, it seems better to have this query also output EXPECTED_BATCH_AGGREGATION_OUTPUT when runtimeMode=Batch.
   
   One benefit of this approach is to have all Flink ML operators be able to generate reason output (that can be used in the machine learning context) in streaming mode.



##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/SQLTransformerTest.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.sqltransformer.SQLTransformer;
+import org.apache.flink.ml.util.TestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/** Tests {@link SQLTransformer}. */
+public class SQLTransformerTest extends AbstractTestBase {
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(Row.of(0, 1.0, 3.0), Row.of(2, 2.0, 3.0));
+
+    private static final List<Row> EXPECTED_NUMERIC_DATA_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 4.0, 3.0), Row.of(2, 2.0, 3.0, 5.0, 6.0));
+
+    private static final List<Row> EXPECTED_BUILT_IN_FUNCTION_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 1.0), Row.of(2, 2.0, 3.0, Math.sqrt(2.0)));
+
+    private static final List<Row> EXPECTED_BATCH_AGGREGATION_OUTPUT =
+            Collections.singletonList(Row.of(3.0));
+
+    private static final List<Row> EXPECTED_STREAMING_AGGREGATION_OUTPUT =
+            Arrays.asList(
+                    Row.of(1.0),
+                    Row.ofKind(RowKind.UPDATE_BEFORE, 1.0),
+                    Row.ofKind(RowKind.UPDATE_AFTER, 3.0));
+
+    private StreamTableEnvironment tEnv;
+    private StreamExecutionEnvironment env;
+    private Table inputTable;
+
+    @Before
+    public void before() {
+        Configuration config = new Configuration();
+        config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, true);
+        env = StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(4);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+    }
+
+    @Test
+    public void testParam() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+        sqlTransformer.setStatement("SELECT * FROM __THIS__");
+        assertEquals("SELECT * FROM __THIS__", sqlTransformer.getStatement());
+    }
+
+    @Test
+    public void testInvalidSQLStatement() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+
+        try {
+            sqlTransformer.setStatement("SELECT * FROM __THAT__");
+            fail();
+        } catch (Exception e) {
+            assertEquals(
+                    "Parameter statement is given an invalid value SELECT * FROM __THAT__",
+                    e.getMessage());
+        }
+    }
+
+    @Test
+    public void testOutputSchema() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        assertEquals(
+                Arrays.asList("id", "v1", "v2", "v3", "v4"),
+                outputTable.getResolvedSchema().getColumnNames());
+    }
+
+    @Test
+    public void testTransformNumericData() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_NUMERIC_DATA_OUTPUT);
+    }
+
+    @Test
+    public void testBuiltInFunction() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT *, SQRT(v1) AS v3 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BUILT_IN_FUNCTION_OUTPUT);
+    }
+
+    @Test
+    public void testBatchAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BATCH_AGGREGATION_OUTPUT, false);
+    }
+
+    @Test
+    public void testStreamingAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);

Review Comment:
   Runtime mode is streaming by default. It seems better to remove this line for consistency with existing tests.



##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/SQLTransformerTest.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.sqltransformer.SQLTransformer;
+import org.apache.flink.ml.util.TestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/** Tests {@link SQLTransformer}. */
+public class SQLTransformerTest extends AbstractTestBase {
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(Row.of(0, 1.0, 3.0), Row.of(2, 2.0, 3.0));
+
+    private static final List<Row> EXPECTED_NUMERIC_DATA_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 4.0, 3.0), Row.of(2, 2.0, 3.0, 5.0, 6.0));
+
+    private static final List<Row> EXPECTED_BUILT_IN_FUNCTION_OUTPUT =
+            Arrays.asList(Row.of(0, 1.0, 3.0, 1.0), Row.of(2, 2.0, 3.0, Math.sqrt(2.0)));
+
+    private static final List<Row> EXPECTED_BATCH_AGGREGATION_OUTPUT =
+            Collections.singletonList(Row.of(3.0));
+
+    private static final List<Row> EXPECTED_STREAMING_AGGREGATION_OUTPUT =
+            Arrays.asList(
+                    Row.of(1.0),
+                    Row.ofKind(RowKind.UPDATE_BEFORE, 1.0),
+                    Row.ofKind(RowKind.UPDATE_AFTER, 3.0));
+
+    private StreamTableEnvironment tEnv;
+    private StreamExecutionEnvironment env;
+    private Table inputTable;
+
+    @Before
+    public void before() {
+        Configuration config = new Configuration();
+        config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, true);
+        env = StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(4);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+    }
+
+    @Test
+    public void testParam() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+        sqlTransformer.setStatement("SELECT * FROM __THIS__");
+        assertEquals("SELECT * FROM __THIS__", sqlTransformer.getStatement());
+    }
+
+    @Test
+    public void testInvalidSQLStatement() {
+        SQLTransformer sqlTransformer = new SQLTransformer();
+
+        try {
+            sqlTransformer.setStatement("SELECT * FROM __THAT__");
+            fail();
+        } catch (Exception e) {
+            assertEquals(
+                    "Parameter statement is given an invalid value SELECT * FROM __THAT__",
+                    e.getMessage());
+        }
+    }
+
+    @Test
+    public void testOutputSchema() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        assertEquals(
+                Arrays.asList("id", "v1", "v2", "v3", "v4"),
+                outputTable.getResolvedSchema().getColumnNames());
+    }
+
+    @Test
+    public void testTransformNumericData() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer()
+                        .setStatement("SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_NUMERIC_DATA_OUTPUT);
+    }
+
+    @Test
+    public void testBuiltInFunction() {
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT *, SQRT(v1) AS v3 FROM __THIS__");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BUILT_IN_FUNCTION_OUTPUT);
+    }
+
+    @Test
+    public void testBatchAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BATCH_AGGREGATION_OUTPUT, false);
+    }
+
+    @Test
+    public void testStreamingAggregation() {
+        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA, new RowTypeInfo(Types.INT, Types.DOUBLE, Types.DOUBLE));
+        inputTable = tEnv.fromDataStream(inputStream).as("id", "v1", "v2");
+
+        SQLTransformer sqlTransformer =
+                new SQLTransformer().setStatement("SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2");
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_STREAMING_AGGREGATION_OUTPUT, false);
+    }
+
+    @Test
+    public void testWindow() {
+        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
+        tEnv = StreamTableEnvironment.create(env);
+
+        Schema schema =
+                Schema.newBuilder()
+                        .column("id", DataTypes.INT())
+                        .column("v1", DataTypes.DOUBLE())
+                        .column("v2", DataTypes.DOUBLE())
+                        .columnByExpression("time_ltz", "TO_TIMESTAMP_LTZ(id * 1000, 3)")
+                        .watermark("time_ltz", "time_ltz - INTERVAL '5' SECOND")
+                        .build();
+
+        DataStream<Row> inputStream =
+                env.fromCollection(
+                        INPUT_DATA,
+                        new RowTypeInfo(
+                                new TypeInformation[] {Types.INT, Types.DOUBLE, Types.DOUBLE},
+                                new String[] {"id", "v1", "v2"}));
+        inputTable = tEnv.fromDataStream(inputStream, schema);
+
+        String statement =
+                "SELECT SUM(v1) AS v3 "
+                        + "FROM TABLE(TUMBLE(TABLE __THIS__, DESCRIPTOR(time_ltz), INTERVAL '10' MINUTES)) "
+                        + "GROUP BY window_start, window_end";
+
+        SQLTransformer sqlTransformer = new SQLTransformer().setStatement(statement);
+
+        Table outputTable = sqlTransformer.transform(inputTable)[0];
+
+        verifyOutputResult(outputTable, EXPECTED_BATCH_AGGREGATION_OUTPUT, false);

Review Comment:
   It seems a bit confusing to verify that the output of this query is `EXPECTED_BATCH_AGGREGATION_OUTPUT` when this query is actually executed with streaming mode.



##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformer.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * SQLTransformer implements the transformations that are defined by SQL statement.
+ *
+ * <p>Currently we only support SQL syntax like 'SELECT ... FROM __THIS__ ...' where "__THIS__"

Review Comment:
   Can we also support `GROUP BY`? 
   
   When the statement includes `group by`, this operator can emit results at the end of stream, similar to the behavior of many existing operators in Flink ML.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] lindong28 commented on pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
lindong28 commented on PR #175:
URL: https://github.com/apache/flink-ml/pull/175#issuecomment-1321558329

   Thanks for the update! LGTM.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] lindong28 commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
lindong28 commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1026381410


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/SQLTransformerTest.java:
##########
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.sqltransformer.SQLTransformer;
+import org.apache.flink.ml.util.TestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/** Tests {@link SQLTransformer}. */
+public class SQLTransformerTest extends AbstractTestBase {
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(Row.of(0, 1.0, 3.0), Row.of(2, 2.0, 3.0));

Review Comment:
   Would you update this input data so that when it is used by the query `SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2`, we can have multiple distinct group-by keys in the output, and each key has multiple matched rows?



##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformer.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.api.common.functions.AggregateFunction;
+import org.apache.flink.api.common.functions.FlatMapFunction;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.common.datastream.EndOfStreamWindows;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * SQLTransformer implements the transformations that are defined by SQL statement.
+ *
+ * <p>Currently we only support SQL syntax like `SELECT ... FROM __THIS__ ...` where `__THIS__`
+ * represents the input table and cannot be modified.
+ *
+ * <p>The select clause specifies the fields, constants, and expressions to display in the output.
+ * Except the cases described in the note section below, it can be any select clause that Flink SQL
+ * supports. Users can also use Flink SQL built-in function and UDFs to operate on these selected
+ * columns.
+ *
+ * <p>For example, SQLTransformer supports statements like:
+ *
+ * <ul>
+ *   <li>`SELECT a, a + b AS a_b FROM __THIS__`
+ *   <li>`SELECT a, SQRT(b) AS b_sqrt FROM __THIS__ where a > 5`
+ *   <li>`SELECT a, b, SUM(c) AS c_sum FROM __THIS__ GROUP BY a, b`
+ * </ul>
+ *
+ * <p>Note: This operator only generates append-only/insert-only table as its output. If the output
+ * table could possibly contain retract messages(e.g. perform `SELECT ... FROM __THIS__ GROUP BY
+ * ...` operation on a table in streaming mode), this operator would aggregate all changelogs and
+ * only output the final state. The records in the final state would be output in the order they
+ * were last modified.
+ */
+public class SQLTransformer
+        implements Transformer<SQLTransformer>, SQLTransformerParams<SQLTransformer> {
+    static final String TABLE_IDENTIFIER = "__THIS__";
+
+    private static final String INSERT_ONLY_EXCEPTION_PATTERN =
+            "^.* doesn't support consuming .* changes which is produced by node .*$";
+
+    private final Map<Param<?>, Object> paramMap = new HashMap<>();
+
+    public SQLTransformer() {
+        ParamUtils.initializeMapWithDefaultValues(paramMap, this);
+    }
+
+    @Override
+    public Table[] transform(Table... inputs) {
+        Preconditions.checkArgument(inputs.length == 1);
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) inputs[0]).getTableEnvironment();
+        String statement = getStatement().replace(TABLE_IDENTIFIER, inputs[0].toString());
+
+        Table outputTable = tEnv.sqlQuery(statement);
+
+        if (!isInsertOnlyTable(tEnv, outputTable)) {
+            Schema schema =
+                    Schema.newBuilder().fromResolvedSchema(outputTable.getResolvedSchema()).build();
+            DataStream<Row> outputStream = tEnv.toChangelogStream(outputTable, schema);
+
+            outputStream =
+                    outputStream
+                            .windowAll(EndOfStreamWindows.get())
+                            .aggregate(
+                                    new ChangeLogStreamToDataStreamFunction(),
+                                    Types.LIST(outputStream.getType()),
+                                    Types.LIST(outputStream.getType()))
+                            .flatMap(new FlattenListFunction<>(), outputStream.getType());
+
+            outputTable = tEnv.fromDataStream(outputStream, schema);
+        }
+
+        return new Table[] {outputTable};
+    }
+
+    @Override
+    public void save(String path) throws IOException {
+        ReadWriteUtils.saveMetadata(this, path);
+    }
+
+    public static SQLTransformer load(StreamTableEnvironment tEnv, String path) throws IOException {
+        return ReadWriteUtils.loadStageParam(path);
+    }
+
+    @Override
+    public Map<Param<?>, Object> getParamMap() {
+        return paramMap;
+    }
+
+    private boolean isInsertOnlyTable(StreamTableEnvironment tEnv, Table table) {
+        try {
+            tEnv.toDataStream(table);
+            return true;
+        } catch (Exception e) {
+            if (e instanceof TableException
+                    && e.getMessage() != null
+                    && e.getMessage().matches(INSERT_ONLY_EXCEPTION_PATTERN)) {
+                return false;
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * A function that converts a bounded changelog stream to an insert-only datastream. It
+     * aggregates all records in a bounded changelog stream and outputs each record in the
+     * aggregation result. Records are output according to their last modification time.
+     */
+    private static class ChangeLogStreamToDataStreamFunction
+            implements AggregateFunction<Row, List<Row>, List<Row>> {
+        @Override
+        public List<Row> createAccumulator() {
+            return new ArrayList<>();
+        }
+
+        @Override
+        public List<Row> add(Row value, List<Row> accumulator) {
+            switch (value.getKind()) {
+                case INSERT:
+                    accumulator.add(value);

Review Comment:
   I am not sure if buffering the row will prevent this operator from being used with object-reuse enabled.
   
   Could you update `SQLTransformerTest` to enable object re-use?
   
   We also need to update tests of all existing Flink ML operator to enable object-reuse. Can you open a separate PR to do this?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] jiangxin369 commented on pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
jiangxin369 commented on PR #175:
URL: https://github.com/apache/flink-ml/pull/175#issuecomment-1316653113

   Thanks for the update. LGTM overall.
   
   @lindong28  Could you please take a look at this PR?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] lindong28 merged pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
lindong28 merged PR #175:
URL: https://github.com/apache/flink-ml/pull/175


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] jiangxin369 commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
jiangxin369 commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1022554843


##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformer.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * SQLTransformer implements the transformations that are defined by SQL statement.
+ *
+ * <p>Currently only query operations are supported. These operations would have a SQL syntax like
+ * "SELECT ... FROM __THIS__ ...", where "__THIS__" represents the underlying table of the input
+ * table.

Review Comment:
   How about `These operations should have a SQL syntax like "SELECT ... FROM __THIS__ ...", where "__THIS__" represents the input table and cannot be modified.`.



##########
docs/content/docs/operators/feature/sqltransformer.md:
##########
@@ -0,0 +1,133 @@
+---
+title: "SQLTransformer"
+weight: 1
+type: docs
+aliases:
+- /operators/feature/sqltransformer.html
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+## SQLTransformer
+
+SQLTransformer implements the transformations that are defined by SQL statement.
+
+Currently only query operations are supported. These operations would have a SQL
+syntax like `"SELECT ... FROM __THIS__ ..."`, where `"__THIS__"` represents the
+underlying table of the input table.
+
+The select clause specifies the fields, constants, and expressions to display in
+the output, it can be any select clause that Flink SQL supports. Users can also
+use Flink SQL built-in function and UDFs to operate on these selected columns.
+
+### Parameters
+
+| Key       | Default | Type   | Required | Description    |
+|:----------|:--------|:-------|:---------|:---------------|
+| statement | `null`  | String | yes      | SQL statement. |
+
+### Examples
+
+{{< tabs examples >}}
+
+{{< tab "Java">}}
+
+```java
+package org.apache.flink.ml.examples.feature;

Review Comment:
   Could you remove the package importing to keep the same style as other documents?



##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformerParams.java:
##########
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.param.StringParam;
+import org.apache.flink.ml.param.WithParams;
+
+/**
+ * Params for {@link SQLTransformer}.
+ *
+ * @param <T> The class type of this instance.
+ */
+public interface SQLTransformerParams<T> extends WithParams<T> {
+    Param<String> STATEMENT = new StringParam("statement", "SQL statement.", null);
+
+    default String getStatement() {
+        return get(STATEMENT);
+    }
+
+    default T setStatement(String value) {
+        return set(STATEMENT, value);
+    }

Review Comment:
   How about adding a ParamValidator to check if the table name is `__THIS__`?



##########
flink-ml-python/pyflink/ml/lib/feature/tests/test_sqltransformer.py:
##########
@@ -0,0 +1,67 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+
+from pyflink.common import Types, Row
+
+from pyflink.ml.lib.feature.sqltransformer import SQLTransformer
+from pyflink.ml.tests.test_utils import PyFlinkMLTestCase
+
+
+class SQLTransformerTest(PyFlinkMLTestCase):
+    def setUp(self):
+        super(SQLTransformerTest, self).setUp()
+        self.input_table = self.t_env.from_data_stream(
+            self.env.from_collection([
+                (0, 1.0, 3.0),
+                (2, 2.0, 5.0),
+            ],
+                type_info=Types.ROW_NAMED(
+                    ['id', 'v1', 'v2'],
+                    [Types.INT(), Types.DOUBLE(), Types.DOUBLE()])))
+        self.expected_output = [
+            (0, 1.0, 3.0, 4.0, 3.0),
+            (2, 2.0, 5.0, 7.0, 10.0)
+        ]
+
+    def test_param(self):
+        sql_transformer = SQLTransformer()
+        self.assertEqual(None, sql_transformer.statement)

Review Comment:
   ```suggestion
           self.assertIsNone(sql_transformer.statement)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] yunfengzhou-hub commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1027464467


##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformer.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.api.common.functions.AggregateFunction;
+import org.apache.flink.api.common.functions.FlatMapFunction;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.common.datastream.EndOfStreamWindows;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * SQLTransformer implements the transformations that are defined by SQL statement.
+ *
+ * <p>Currently we only support SQL syntax like `SELECT ... FROM __THIS__ ...` where `__THIS__`
+ * represents the input table and cannot be modified.
+ *
+ * <p>The select clause specifies the fields, constants, and expressions to display in the output.
+ * Except the cases described in the note section below, it can be any select clause that Flink SQL
+ * supports. Users can also use Flink SQL built-in function and UDFs to operate on these selected
+ * columns.
+ *
+ * <p>For example, SQLTransformer supports statements like:
+ *
+ * <ul>
+ *   <li>`SELECT a, a + b AS a_b FROM __THIS__`
+ *   <li>`SELECT a, SQRT(b) AS b_sqrt FROM __THIS__ where a > 5`
+ *   <li>`SELECT a, b, SUM(c) AS c_sum FROM __THIS__ GROUP BY a, b`
+ * </ul>
+ *
+ * <p>Note: This operator only generates append-only/insert-only table as its output. If the output
+ * table could possibly contain retract messages(e.g. perform `SELECT ... FROM __THIS__ GROUP BY
+ * ...` operation on a table in streaming mode), this operator would aggregate all changelogs and
+ * only output the final state. The records in the final state would be output in the order they
+ * were last modified.
+ */
+public class SQLTransformer
+        implements Transformer<SQLTransformer>, SQLTransformerParams<SQLTransformer> {
+    static final String TABLE_IDENTIFIER = "__THIS__";
+
+    private static final String INSERT_ONLY_EXCEPTION_PATTERN =
+            "^.* doesn't support consuming .* changes which is produced by node .*$";
+
+    private final Map<Param<?>, Object> paramMap = new HashMap<>();
+
+    public SQLTransformer() {
+        ParamUtils.initializeMapWithDefaultValues(paramMap, this);
+    }
+
+    @Override
+    public Table[] transform(Table... inputs) {
+        Preconditions.checkArgument(inputs.length == 1);
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) inputs[0]).getTableEnvironment();
+        String statement = getStatement().replace(TABLE_IDENTIFIER, inputs[0].toString());
+
+        Table outputTable = tEnv.sqlQuery(statement);
+
+        if (!isInsertOnlyTable(tEnv, outputTable)) {
+            Schema schema =
+                    Schema.newBuilder().fromResolvedSchema(outputTable.getResolvedSchema()).build();
+            DataStream<Row> outputStream = tEnv.toChangelogStream(outputTable, schema);
+
+            outputStream =
+                    outputStream
+                            .windowAll(EndOfStreamWindows.get())
+                            .aggregate(
+                                    new ChangeLogStreamToDataStreamFunction(),
+                                    Types.LIST(outputStream.getType()),
+                                    Types.LIST(outputStream.getType()))
+                            .flatMap(new FlattenListFunction<>(), outputStream.getType());
+
+            outputTable = tEnv.fromDataStream(outputStream, schema);
+        }
+
+        return new Table[] {outputTable};
+    }
+
+    @Override
+    public void save(String path) throws IOException {
+        ReadWriteUtils.saveMetadata(this, path);
+    }
+
+    public static SQLTransformer load(StreamTableEnvironment tEnv, String path) throws IOException {
+        return ReadWriteUtils.loadStageParam(path);
+    }
+
+    @Override
+    public Map<Param<?>, Object> getParamMap() {
+        return paramMap;
+    }
+
+    private boolean isInsertOnlyTable(StreamTableEnvironment tEnv, Table table) {
+        try {
+            tEnv.toDataStream(table);
+            return true;
+        } catch (Exception e) {
+            if (e instanceof TableException
+                    && e.getMessage() != null
+                    && e.getMessage().matches(INSERT_ONLY_EXCEPTION_PATTERN)) {
+                return false;
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * A function that converts a bounded changelog stream to an insert-only datastream. It
+     * aggregates all records in a bounded changelog stream and outputs each record in the
+     * aggregation result. Records are output according to their last modification time.
+     */
+    private static class ChangeLogStreamToDataStreamFunction
+            implements AggregateFunction<Row, List<Row>, List<Row>> {
+        @Override
+        public List<Row> createAccumulator() {
+            return new ArrayList<>();
+        }
+
+        @Override
+        public List<Row> add(Row value, List<Row> accumulator) {
+            switch (value.getKind()) {
+                case INSERT:
+                    accumulator.add(value);

Review Comment:
   I agree. I'll enable object re-use for `SQLTransformerTest` now and open a separate PR for all other algorithms.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] lindong28 commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
lindong28 commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1026381410


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/SQLTransformerTest.java:
##########
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.sqltransformer.SQLTransformer;
+import org.apache.flink.ml.util.TestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+/** Tests {@link SQLTransformer}. */
+public class SQLTransformerTest extends AbstractTestBase {
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(Row.of(0, 1.0, 3.0), Row.of(2, 2.0, 3.0));

Review Comment:
   Could you update this input data so that when it is used by the query `SELECT SUM(v1) AS v3 FROM __THIS__ GROUP BY v2`, we can have multiple distinct group-by keys in the output, and each key has multiple matched rows?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [flink-ml] jiangxin369 commented on a diff in pull request #175: [FLINK-29602] Add Transformer for SQLTransformer

Posted by GitBox <gi...@apache.org>.
jiangxin369 commented on code in PR #175:
URL: https://github.com/apache/flink-ml/pull/175#discussion_r1022554843


##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/sqltransformer/SQLTransformer.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.feature.sqltransformer;
+
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * SQLTransformer implements the transformations that are defined by SQL statement.
+ *
+ * <p>Currently only query operations are supported. These operations would have a SQL syntax like
+ * "SELECT ... FROM __THIS__ ...", where "__THIS__" represents the underlying table of the input
+ * table.

Review Comment:
   How about `Currently we only support SQL syntax like 'SELECT ... FROM __THIS__ ...' where "__THIS__" represents the input table and cannot be modified.`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org