chamikaramj commented on code in PR #38376:
URL: https://github.com/apache/beam/pull/38376#discussion_r3270810729
##########
sdks/java/io/expansion-service/build.gradle:
##########
@@ -92,6 +92,7 @@ dependencies {
runtimeOnly project(path: ":sdks:java:io:iceberg:bqms", configuration:
"shadow")
}
+ runtimeOnly project(":sdks:java:io:mongodb")
runtimeOnly library.java.kafka_clients
Review Comment:
How much does this add to I/O the expansion service jar ?
Also, are there any potential transitive dependencies that could bring in
vulnerabilities ?
##########
sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbWriteSchemaTransformProvider.java:
##########
@@ -0,0 +1,212 @@
+/*
+ * 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.beam.sdk.io.mongodb;
+
+import com.google.auto.service.AutoService;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.StringUtf8Coder;
+import org.apache.beam.sdk.schemas.Schema.Field;
+import org.apache.beam.sdk.schemas.transforms.SchemaTransform;
+import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider;
+import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider;
+import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionRowTuple;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.sdk.values.TupleTag;
+import org.apache.beam.sdk.values.TupleTagList;
+import org.bson.BsonNull;
+import org.bson.Document;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/** An implementation of {@link TypedSchemaTransformProvider} for writing to
MongoDB. */
+@AutoService(SchemaTransformProvider.class)
+public class MongoDbWriteSchemaTransformProvider
+ extends
TypedSchemaTransformProvider<MongoDbWriteSchemaTransformConfiguration> {
+
+ public static class DocumentCoder extends AtomicCoder<Document> implements
Serializable {
+ private static final DocumentCoder INSTANCE = new DocumentCoder();
+
+ private DocumentCoder() {}
+
+ public static DocumentCoder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(Document value, OutputStream outStream) throws
java.io.IOException {
+ StringUtf8Coder.of().encode(value.toJson(), outStream);
+ }
+
+ @Override
+ public Document decode(InputStream inStream) throws java.io.IOException {
+ String json = StringUtf8Coder.of().decode(inStream);
+ return Document.parse(json);
+ }
+ }
+
+ private static final String INPUT_TAG = "input";
+ public static final TupleTag<Document> OUTPUT_TAG = new TupleTag<Document>()
{};
+ public static final TupleTag<Row> ERROR_TAG = new TupleTag<Row>() {};
+
+ private static final org.apache.beam.sdk.metrics.Counter errorCounter =
+ org.apache.beam.sdk.metrics.Metrics.counter(
+ MongoDbWriteSchemaTransformProvider.class,
"MongoDB-write-error-counter");
+
+ @Override
+ protected SchemaTransform from(MongoDbWriteSchemaTransformConfiguration
configuration) {
+ return new MongoDbWriteSchemaTransform(configuration);
+ }
+
+ @Override
+ public String identifier() {
+ return "beam:schematransform:org.apache.beam:mongodb_write:v1";
+ }
+
+ @Override
+ public List<String> inputCollectionNames() {
+ return Collections.singletonList(INPUT_TAG);
+ }
+
+ /** The {@link SchemaTransform} that performs the write operation. */
+ private static class MongoDbWriteSchemaTransform extends SchemaTransform {
+ private final MongoDbWriteSchemaTransformConfiguration configuration;
+
+ MongoDbWriteSchemaTransform(MongoDbWriteSchemaTransformConfiguration
configuration) {
+ configuration.validate();
+ this.configuration = configuration;
+ }
+
+ @Override
+ public PCollectionRowTuple expand(PCollectionRowTuple input) {
+ // Retrieve the input PCollection of Rows and its schema.
+ PCollection<Row> rows = input.get(INPUT_TAG);
+ org.apache.beam.sdk.schemas.Schema inputSchema = rows.getSchema();
+
+ // Determine if error handling is enabled and set up the error schema.
+ boolean handleErrors =
ErrorHandling.hasOutput(configuration.getErrorHandling());
+ org.apache.beam.sdk.schemas.Schema errorSchema =
ErrorHandling.errorSchema(inputSchema);
+
+ // Convert Beam Rows to BSON Documents, emitting errors to a separate
tag if enabled.
+ PCollectionTuple outputTuple =
+ rows.apply(
+ "ConvertToDocument",
+ ParDo.of(new RowToBsonDocumentFn(handleErrors, errorSchema))
+ .withOutputTags(OUTPUT_TAG, TupleTagList.of(ERROR_TAG)));
+
+ PCollection<Document> documents =
outputTuple.get(OUTPUT_TAG).setCoder(DocumentCoder.of());
+
+ // Configure the MongoDB write operation.
+ MongoDbIO.Write write =
+ MongoDbIO.write()
+ .withUri(configuration.getUri())
+ .withDatabase(configuration.getDatabase())
+ .withCollection(configuration.getCollection());
+
+ Long batchSize = configuration.getBatchSize();
+ if (batchSize != null) {
+ write = write.withBatchSize(batchSize);
+ }
+
+ // Apply the MongoDB write transform.
+ documents.apply("WriteToMongo", write);
+
+ // Extract and format the error collection.
+ PCollection<Row> errorOutput =
outputTuple.get(ERROR_TAG).setRowSchema(errorSchema);
Review Comment:
Seems like we are only reporting errors for the conversion part here. Are
there are any errors from the MongoDB write transform that we might be missing
here ?
##########
sdks/python/apache_beam/yaml/yaml_io.py:
##########
@@ -723,3 +717,50 @@ def write_to_tfrecord(
num_shards=num_shards,
shard_name_template=shard_name_template,
compression_type=getattr(CompressionTypes, compression_type))
+
+
[email protected]_fn
+@yaml_errors.maybe_with_exception_handling_transform_fn
+def write_to_mongodb(
+ pcoll,
+ *,
+ database: str,
+ collection: str,
+ connection_uri: str = "mongodb://localhost:27017",
Review Comment:
Why this default ?
Probably good to let it empty and give documentation/hints on how to
configure the connection URI ?
##########
sdks/python/apache_beam/yaml/integration_tests.py:
##########
@@ -200,6 +201,53 @@ def temp_bigtable_table(project, prefix='yaml_bt_it_'):
_LOGGER.warning("Failed to clean up instance")
[email protected]
+def temp_mongodb_table():
+ """
+ provides a temporary MongoDB instance.
+
+ starts a MongoDB container, creates a unique database
+ and collection name for test isolation, and yields them as a dictionary.
+
+ This allows YAML test files to get connection details without hardcoding
them.
+ Example usage in a YAML test file's fixture section:
+
+ fixtures:
+ - name: mongo_vars
+ type: path.to.this.file.mongodb_fixture
+
+ Then, in the pipeline definition, you can use placeholders like:
+ - uri: ${mongo_vars.URI}
+ - database: ${mongo_vars.DATABASE}
+ - collection: ${mongo_vars.COLLECTION}
+ """
+ _LOGGER.info("Setting up MongoDB fixture...")
+ mongo_container = MongoDbContainer("mongo:7.0.7")
Review Comment:
Probably move the version (7.0.7) to a constant.
##########
sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbWriteSchemaTransformProvider.java:
##########
@@ -0,0 +1,212 @@
+/*
+ * 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.beam.sdk.io.mongodb;
+
+import com.google.auto.service.AutoService;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.StringUtf8Coder;
+import org.apache.beam.sdk.schemas.Schema.Field;
+import org.apache.beam.sdk.schemas.transforms.SchemaTransform;
+import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider;
+import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider;
+import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionRowTuple;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.sdk.values.TupleTag;
+import org.apache.beam.sdk.values.TupleTagList;
+import org.bson.BsonNull;
+import org.bson.Document;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/** An implementation of {@link TypedSchemaTransformProvider} for writing to
MongoDB. */
+@AutoService(SchemaTransformProvider.class)
+public class MongoDbWriteSchemaTransformProvider
+ extends
TypedSchemaTransformProvider<MongoDbWriteSchemaTransformConfiguration> {
+
+ public static class DocumentCoder extends AtomicCoder<Document> implements
Serializable {
+ private static final DocumentCoder INSTANCE = new DocumentCoder();
+
+ private DocumentCoder() {}
+
+ public static DocumentCoder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(Document value, OutputStream outStream) throws
java.io.IOException {
+ StringUtf8Coder.of().encode(value.toJson(), outStream);
+ }
+
+ @Override
+ public Document decode(InputStream inStream) throws java.io.IOException {
+ String json = StringUtf8Coder.of().decode(inStream);
+ return Document.parse(json);
+ }
+ }
+
+ private static final String INPUT_TAG = "input";
+ public static final TupleTag<Document> OUTPUT_TAG = new TupleTag<Document>()
{};
+ public static final TupleTag<Row> ERROR_TAG = new TupleTag<Row>() {};
+
+ private static final org.apache.beam.sdk.metrics.Counter errorCounter =
+ org.apache.beam.sdk.metrics.Metrics.counter(
+ MongoDbWriteSchemaTransformProvider.class,
"MongoDB-write-error-counter");
+
+ @Override
+ protected SchemaTransform from(MongoDbWriteSchemaTransformConfiguration
configuration) {
+ return new MongoDbWriteSchemaTransform(configuration);
+ }
+
+ @Override
+ public String identifier() {
+ return "beam:schematransform:org.apache.beam:mongodb_write:v1";
+ }
+
+ @Override
+ public List<String> inputCollectionNames() {
+ return Collections.singletonList(INPUT_TAG);
+ }
+
+ /** The {@link SchemaTransform} that performs the write operation. */
+ private static class MongoDbWriteSchemaTransform extends SchemaTransform {
+ private final MongoDbWriteSchemaTransformConfiguration configuration;
+
+ MongoDbWriteSchemaTransform(MongoDbWriteSchemaTransformConfiguration
configuration) {
+ configuration.validate();
+ this.configuration = configuration;
+ }
+
+ @Override
+ public PCollectionRowTuple expand(PCollectionRowTuple input) {
+ // Retrieve the input PCollection of Rows and its schema.
+ PCollection<Row> rows = input.get(INPUT_TAG);
+ org.apache.beam.sdk.schemas.Schema inputSchema = rows.getSchema();
+
+ // Determine if error handling is enabled and set up the error schema.
+ boolean handleErrors =
ErrorHandling.hasOutput(configuration.getErrorHandling());
+ org.apache.beam.sdk.schemas.Schema errorSchema =
ErrorHandling.errorSchema(inputSchema);
+
+ // Convert Beam Rows to BSON Documents, emitting errors to a separate
tag if enabled.
+ PCollectionTuple outputTuple =
+ rows.apply(
+ "ConvertToDocument",
+ ParDo.of(new RowToBsonDocumentFn(handleErrors, errorSchema))
+ .withOutputTags(OUTPUT_TAG, TupleTagList.of(ERROR_TAG)));
+
+ PCollection<Document> documents =
outputTuple.get(OUTPUT_TAG).setCoder(DocumentCoder.of());
+
+ // Configure the MongoDB write operation.
+ MongoDbIO.Write write =
+ MongoDbIO.write()
+ .withUri(configuration.getUri())
+ .withDatabase(configuration.getDatabase())
+ .withCollection(configuration.getCollection());
+
+ Long batchSize = configuration.getBatchSize();
+ if (batchSize != null) {
+ write = write.withBatchSize(batchSize);
+ }
+
+ // Apply the MongoDB write transform.
+ documents.apply("WriteToMongo", write);
+
+ // Extract and format the error collection.
+ PCollection<Row> errorOutput =
outputTuple.get(ERROR_TAG).setRowSchema(errorSchema);
+
+ // Return the error collection as specified by the configuration.
+ ErrorHandling errorHandling = configuration.getErrorHandling();
+ return PCollectionRowTuple.of(
+ (handleErrors && errorHandling != null) ? errorHandling.getOutput()
: "errors",
+ errorOutput);
+ }
+ }
+
+ /** Converts a Beam {@link Row} to a BSON {@link Document}. */
+ static class RowToBsonDocumentFn extends DoFn<Row, Document> {
+ private final boolean handleErrors;
+ private final org.apache.beam.sdk.schemas.Schema errorSchema;
+
+ RowToBsonDocumentFn(boolean handleErrors,
org.apache.beam.sdk.schemas.Schema errorSchema) {
+ this.handleErrors = handleErrors;
+ this.errorSchema = errorSchema;
+ }
+
+ @ProcessElement
+ public void processElement(@Element Row row, MultiOutputReceiver receiver)
{
+ try {
+ Object converted = convertToBsonValue(row);
+ if (converted instanceof Document) {
+ receiver.get(OUTPUT_TAG).output((Document) converted);
+ } else {
+ throw new IllegalStateException(
+ "Expected Document but got "
+ + (converted != null ? converted.getClass().getName() :
"null"));
+ }
+ } catch (Exception e) {
+ if (!handleErrors) {
+ throw new RuntimeException(e);
+ }
+ errorCounter.inc();
+ receiver.get(ERROR_TAG).output(ErrorHandling.errorRecord(errorSchema,
row, e));
+ }
+ }
+ }
+
+ private static Object convertToBsonValue(@Nullable Object value) {
Review Comment:
Should this be a util (with testing) that should be accessible to MongoDB
sink users in general ?
##########
sdks/python/apache_beam/yaml/yaml_io.py:
##########
@@ -723,3 +717,50 @@ def write_to_tfrecord(
num_shards=num_shards,
shard_name_template=shard_name_template,
compression_type=getattr(CompressionTypes, compression_type))
+
+
[email protected]_fn
+@yaml_errors.maybe_with_exception_handling_transform_fn
+def write_to_mongodb(
+ pcoll,
+ *,
+ database: str,
+ collection: str,
+ connection_uri: str = "mongodb://localhost:27017",
+ batch_size: int = 100,
Review Comment:
Is there a reason to pick 100 here ?
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]