Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
Para leer datos de Cloud Storage en Dataflow, usa el TextIO o el AvroIOconector de entrada/salida de Apache Beam.
Incluir la dependencia de la biblioteca de Google Cloud Platform
Para usar el conector TextIO o AvroIO con Cloud Storage, incluye la siguiente dependencia. Esta biblioteca proporciona un controlador de esquemas para nombres de archivo "gs://".
Habilitar gRPC en el conector de E/S de Apache Beam en Dataflow
Puedes conectarte a Cloud Storage mediante gRPC a través del conector de E/S de Apache Beam en Dataflow. gRPC es un framework de llamadas a procedimientos remotos (RPC) de código abierto de alto rendimiento desarrollado por Google que puedes usar para interactuar con Cloud Storage.
Para acelerar las solicitudes de lectura de tu tarea de Dataflow en Cloud Storage, puedes habilitar el conector de E/S de Apache Beam en Dataflow para usar gRPC.
Puedes configurar el conector de entrada/salida de Apache Beam en Dataflow para generar métricas relacionadas con gRPC en Cloud Monitoring. Las métricas relacionadas con gRPC pueden ayudarte a hacer lo siguiente:
Monitoriza y optimiza el rendimiento de las solicitudes gRPC a Cloud Storage.
Solucionar y depurar problemas.
Obtén estadísticas sobre el uso y el comportamiento de tu aplicación.
Para obtener información sobre cómo configurar el conector de E/S de Apache Beam en Dataflow para generar métricas relacionadas con gRPC, consulta Usar métricas del lado del cliente.
Si no necesitas recoger métricas para tu caso práctico, puedes inhabilitar la recogida de métricas.
Para obtener instrucciones, consulta Inhabilitar las métricas del lado del cliente.
Paralelismo
Los conectores TextIO y AvroIO admiten dos niveles de paralelismo:
Los archivos individuales se identifican por separado para que varios trabajadores puedan leerlos.
Si los archivos no están comprimidos, el conector puede leer subintervalos de cada archivo por separado, lo que da lugar a un nivel de paralelismo muy alto. Esta división solo es posible si cada línea del archivo es un registro significativo. Por ejemplo, no está disponible de forma predeterminada para los archivos JSON.
Rendimiento
En la siguiente tabla se muestran las métricas de rendimiento de la lectura de Cloud Storage. Las cargas de trabajo se ejecutaron en un e2-standard2 trabajador con el SDK de Apache Beam 2.49.0 para Java. No usaron Runner v2.
Estas métricas se basan en sencillas canalizaciones por lotes. Su objetivo es comparar el rendimiento entre conectores de E/S y no representan necesariamente las canalizaciones del mundo real.
El rendimiento de las canalizaciones de Dataflow es complejo y depende del tipo de VM, los datos que se procesan, el rendimiento de las fuentes y los receptores externos, y el código de usuario. Las métricas se basan en la ejecución del SDK de Java y no representan las características de rendimiento de otros SDKs de lenguaje. Para obtener más información, consulta Rendimiento de Beam IO.
Prácticas recomendadas
No uses watchForNewFiles con Cloud Storage. Este enfoque no se adapta bien a las grandes cadenas de producción, ya que el conector debe mantener una lista de archivos vistos en la memoria. La lista no se puede vaciar de la memoria, lo que reduce la memoria de trabajo de los trabajadores con el tiempo. Te recomendamos que utilices las notificaciones de Pub/Sub para Cloud Storage. Para obtener más información, consulta Patrones de procesamiento de archivos.
Si tanto el nombre del archivo como su contenido son datos útiles, usa la clase FileIO para leer los nombres de los archivos. Por ejemplo, un nombre de archivo puede contener metadatos que sean útiles al procesar los datos del archivo. Para obtener más información, consulta Acceder a nombres de archivo.
En la FileIOdocumentación también se muestra un ejemplo de este patrón.
Ejemplo
En el siguiente ejemplo se muestra cómo leer datos de Cloud Storage.
importorg.apache.beam.sdk.Pipeline;importorg.apache.beam.sdk.PipelineResult;importorg.apache.beam.sdk.io.TextIO;importorg.apache.beam.sdk.options.Description;importorg.apache.beam.sdk.options.PipelineOptions;importorg.apache.beam.sdk.options.PipelineOptionsFactory;importorg.apache.beam.sdk.transforms.MapElements;importorg.apache.beam.sdk.values.TypeDescriptors;publicclassReadFromStorage{publicstaticPipelinecreatePipeline(Optionsoptions){varpipeline=Pipeline.create(options);pipeline// Read from a text file..apply(TextIO.read().from("gs://"+options.getBucket()+"/*.txt")).apply(MapElements.into(TypeDescriptors.strings()).via((x->{System.out.println(x);returnx;})));returnpipeline;}}
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-10 (UTC)."],[[["\u003cp\u003eTo read data from Cloud Storage to Dataflow, use the Apache Beam \u003ccode\u003eTextIO\u003c/code\u003e or \u003ccode\u003eAvroIO\u003c/code\u003e I/O connector and include the Google Cloud library dependency, which provides a schema handler for \u003ccode\u003e"gs://"\u003c/code\u003e filenames.\u003c/p\u003e\n"],["\u003cp\u003eEnabling gRPC through the Apache Beam I/O connector on Dataflow can accelerate Dataflow job read requests to Cloud Storage, using the pipeline option \u003ccode\u003e--additional-experiments=use_grpc_for_gcs\u003c/code\u003e or \u003ccode\u003e--experiments=use_grpc_for_gcs\u003c/code\u003e, and requires Apache Beam SDK version 2.55.0 or later.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eTextIO\u003c/code\u003e and \u003ccode\u003eAvroIO\u003c/code\u003e connectors offer parallelism by allowing multiple workers to read individual files separately, and for uncompressed files, sub-ranges of each file can be read separately, enhancing parallelism.\u003c/p\u003e\n"],["\u003cp\u003eAvoid using \u003ccode\u003ewatchForNewFiles\u003c/code\u003e with Cloud Storage in large production pipelines, and use Pub/Sub notifications instead to prevent memory issues, and use \u003ccode\u003eFileIO\u003c/code\u003e class when both the filename and file contents are valuable data.\u003c/p\u003e\n"],["\u003cp\u003ePerformance metrics for reading from Cloud Storage using the Apache Beam SDK 2.49.0 for Java on an \u003ccode\u003ee2-standard2\u003c/code\u003e worker showed throughputs of 320 MBps and 320,000 elements per second for 100M records with 1 kB and 1 column.\u003c/p\u003e\n"]]],[],null,["To read data from Cloud Storage to Dataflow, use the\nApache Beam `TextIO` or `AvroIO`\n[I/O connector](https://beam.apache.org/documentation/io/connectors/).\n| **Note:** Depending on your scenario, consider using one of the [Google-provided Dataflow templates](/dataflow/docs/guides/templates/provided-templates). Several of these templates read from Cloud Storage.\n\nInclude the Google Cloud Platform library dependency\n\nTo use the `TextIO` or `AvroIO` connector with Cloud Storage, include\nthe following dependency. This library provides a schema handler for `\"gs://\"`\nfilenames. \n\nJava \n\n \u003cdependency\u003e\n \u003cgroupId\u003eorg.apache.beam\u003c/groupId\u003e\n \u003cartifactId\u003ebeam-sdks-java-io-google-cloud-platform\u003c/artifactId\u003e\n \u003cversion\u003e${beam.version}\u003c/version\u003e\n \u003c/dependency\u003e\n\nPython \n\n apache-beam[gcp]==\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eVERSION\u003c/span\u003e\u003c/var\u003e\n\nGo \n\n import _ \"github.com/apache/beam/sdks/v2/go/pkg/beam/io/filesystem/gcs\"\n\nFor more information, see\n[Install the Apache Beam SDK](/dataflow/docs/guides/installing-beam-sdk).\n\nEnable gRPC on Apache Beam I/O connector on Dataflow\n\nYou can [connect to Cloud Storage using gRPC](/storage/docs/enable-grpc-api) through the\nApache Beam I/O connector on Dataflow. [gRPC](https://grpc.io/) is a\nhigh performance open-source remote procedure call (RPC) framework developed by\nGoogle that you can use to interact with\nCloud Storage.\n\nTo speed up your Dataflow job's read requests to Cloud Storage, you\ncan enable the Apache Beam I/O connector on Dataflow to use gRPC.\n\nCommand line\n\n1. Ensure that you use the [Apache Beam SDK](https://beam.apache.org/documentation/programming-guide/#configuring-pipeline-options) version [2.55.0](https://beam.apache.org/get-started/beam-overview/) or later.\n2. To run a Dataflow job, use `--additional-experiments=use_grpc_for_gcs` pipeline option. For information about the different pipeline options, see [Optional flags](/sdk/gcloud/reference/dataflow/jobs/run#--additional-experiments).\n\nApache Beam SDK\n\n1. Ensure that you use the [Apache Beam SDK](https://beam.apache.org/documentation/programming-guide/#configuring-pipeline-options) version [2.55.0](https://beam.apache.org/get-started/beam-overview/) or later.\n2. To run a Dataflow job, use `--experiments=use_grpc_for_gcs` pipeline option. For information about the different pipeline options, see [Basic\n options](/dataflow/docs/reference/pipeline-options#basic_options).\n\nYou can configure Apache Beam I/O connector on Dataflow to generate gRPC\nrelated metrics in Cloud Monitoring. The gRPC related metrics can help you to do the following:\n\n- Monitor and optimize the performance of gRPC requests to Cloud Storage.\n- Troubleshoot and debug issues.\n- Gain insights into your application's usage and behavior.\n\n\u003cbr /\u003e\n\nFor information about how to configure Apache Beam I/O connector on Dataflow to generate gRPC related metrics, see [Use client-side metrics](/storage/docs/client-side-metrics). If gathering metrics isn't necessary for your use case, you can choose to opt-out of metrics collection. For instructions, see [Opt-out of client-side\nmetrics](/storage/docs/client-side-metrics#opt_out_of_client-side_metrics).\n\n\u003cbr /\u003e\n\nParallelism\n\nThe `TextIO` and `AvroIO` connectors support two levels of parallelism:\n\n- Individual files are keyed separately, so that multiple workers can read them.\n- If the files are uncompressed, the connector can read sub-ranges of each file separately, leading to a very high level of parallelism. This splitting is only possible if each line in the file is a meaningful record. For example, it's not available by default for JSON files.\n\nPerformance\n\nThe following table shows performance metrics for reading from\nCloud Storage. The workloads were run on one `e2-standard2` worker,\nusing the Apache Beam SDK 2.49.0 for Java. They did not use Runner v2.\n\n| 100 M records \\| 1 kB \\| 1 column | Throughput (bytes) | Throughput (elements) |\n|--------------------------------------------------------------------------------------------------------------------------------------------------|--------------------|-----------------------------|\n| [Read](https://github.com/apache/beam/blob/master/it/google-cloud-platform/src/test/java/org/apache/beam/it/gcp/storage/FileBasedIOLT.java#L162) | 320 MBps | 320,000 elements per second |\n\n\nThese metrics are based on simple batch pipelines. They are intended to compare performance\nbetween I/O connectors, and are not necessarily representative of real-world pipelines.\nDataflow pipeline performance is complex, and is a function of VM type, the data\nbeing processed, the performance of external sources and sinks, and user code. Metrics are based\non running the Java SDK, and aren't representative of the performance characteristics of other\nlanguage SDKs. For more information, see [Beam IO\nPerformance](https://beam.apache.org/performance/).\n\n\u003cbr /\u003e\n\nBest practices\n\n- Avoid using [`watchForNewFiles`](https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/io/TextIO.Read.html#watchForNewFiles-org.joda.time.Duration-org.apache.beam.sdk.transforms.Watch.Growth.TerminationCondition-) with\n Cloud Storage. This approach scales poorly for large production\n pipelines, because the connector must keep a list of seen files in memory. The\n list can't be flushed from memory, which reduces the working memory of workers\n over time. Consider using\n [Pub/Sub notifications for Cloud Storage](/storage/docs/pubsub-notifications)\n instead. For more information, see\n [File processing patterns](https://beam.apache.org/documentation/patterns/file-processing/).\n\n- If both the filename and the file contents are useful data, use the\n [`FileIO`](https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/io/FileIO.html) class to read filenames. For example, a filename might\n contain metadata that is useful when processing the data in the file. For more\n information, see\n [Accessing filenames](https://beam.apache.org/documentation/patterns/file-processing/).\n The [`FileIO` documentation](https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/io/FileIO.html) also shows an example of this pattern.\n\nExample\n\nThe following example shows how to read from Cloud Storage. \n\nJava\n\n\nTo authenticate to Dataflow, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import org.apache.beam.sdk.Pipeline;\n import org.apache.beam.sdk.PipelineResult;\n import org.apache.beam.sdk.io.TextIO;\n import org.apache.beam.sdk.options.Description;\n import org.apache.beam.sdk.options.PipelineOptions;\n import org.apache.beam.sdk.options.PipelineOptionsFactory;\n import org.apache.beam.sdk.transforms.MapElements;\n import org.apache.beam.sdk.values.TypeDescriptors;\n\n public class ReadFromStorage {\n public static Pipeline createPipeline(Options options) {\n var pipeline = Pipeline.create(options);\n pipeline\n // Read from a text file.\n .apply(TextIO.read().from(\n \"gs://\" + options.getBucket() + \"/*.txt\"))\n .apply(\n MapElements.into(TypeDescriptors.strings())\n .via(\n (x -\u003e {\n System.out.println(x);\n return x;\n })));\n return pipeline;\n }\n }\n\n\u003cbr /\u003e\n\nWhat's next\n\n- Read the [`TextIO`](https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/io/TextIO.html) API documentation.\n- See the list of [Google-provided templates](/dataflow/docs/guides/templates/provided-templates)."]]