מחבר Bigtable HBase Beam

כדי לעזור לכם להשתמש ב-Bigtable בצינור עיבוד נתונים של Dataflow, יש שני מחברי קלט/פלט של Bigtable Beam בקוד פתוח.

אם אתם עוברים מ-HBase ל-Bigtable או שהאפליקציה שלכם קוראת ל-HBase API, השתמשו במחבר Bigtable HBase Beam (CloudBigtableIO) שמתואר בדף הזה.

בכל שאר המקרים, צריך להשתמש במחבר Bigtable Beam (BigtableIO) בשילוב עם לקוח Cloud Bigtable ל-Java, שפועל עם ממשקי ה-API של Cloud Bigtable. כדי להתחיל להשתמש במחבר הזה, עיינו במאמר מחבר Bigtable Beam.

למידע נוסף על מודל התכנות של Apache Beam, קראו את המסמכים של Beam.

תחילת העבודה עם HBase

מחבר Bigtable HBase Beam כתוב ב-Java ומבוסס על לקוח Bigtable HBase ל-Java. הוא תואם ל-Dataflow SDK 2.x ל-Java, שמבוסס על Apache Beam. קוד המקור של המחבר נמצא במאגר googleapis/java-bigtable-hbase ב-GitHub.

בדף הזה מוסבר איך להשתמש בטרנספורמציות Read ו-Write.

מגדירים אימות

כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Java שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  3. אם אתם משתמשים במעטפת מקומית, צרו פרטי כניסה לאימות מקומי בחשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אתם לא צריכים לעשות את זה.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו שנכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

למידע נוסף על הגדרה של אימות בסביבת ייצור, ראו הגדרה של Application Default Credentials לקוד שפועל ב- Google Cloud.

הוספת המחבר לפרויקט Maven

כדי להוסיף את מחבר Bigtable HBase Beam לפרויקט Maven, צריך להוסיף את פריט המידע שנוצר ב-Maven לקובץ pom.xml בתור תלות:

<dependency>
  <groupId>com.google.cloud.bigtable</groupId>
  <artifactId>bigtable-hbase-beam</artifactId>
  <version>2.12.0</version>
</dependency>

הגדרת Bigtable

יוצרים ממשק של אפשרויות כדי לאפשר קלט להרצת צינור עיבוד הנתונים:

public interface BigtableOptions extends DataflowPipelineOptions {

  @Description("The Bigtable project ID, this can be different than your Dataflow project")
  @Default.String("bigtable-project")
  String getBigtableProjectId();

  void setBigtableProjectId(String bigtableProjectId);

  @Description("The Bigtable instance ID")
  @Default.String("bigtable-instance")
  String getBigtableInstanceId();

  void setBigtableInstanceId(String bigtableInstanceId);

  @Description("The Bigtable table ID in the instance.")
  @Default.String("mobile-time-series")
  String getBigtableTableId();

  void setBigtableTableId(String bigtableTableId);
}

כשקוראים מ-Bigtable או כותבים אליו, צריך לספק אובייקט הגדרה של CloudBigtableConfiguration. האובייקט הזה מציין את מזהה הפרויקט ומזהה המכונה של הטבלה, וגם את שם הטבלה עצמה:

CloudBigtableTableConfiguration bigtableTableConfig =
    new CloudBigtableTableConfiguration.Builder()
        .withProjectId(options.getBigtableProjectId())
        .withInstanceId(options.getBigtableInstanceId())
        .withTableId(options.getBigtableTableId())
        .build();

כדי לקרוא, צריך לספק אובייקט הגדרה של CloudBigtableScanConfiguration, שמאפשר לציין אובייקט Scan של Apache HBase שמגביל ומסנן את תוצאות הקריאה. פרטים נוספים זמינים במאמר קריאה מ-Bigtable.

קריאה מ-Bigtable

כדי לקרוא מטבלה ב-Bigtable, מפעילים טרנספורמציה של Read על התוצאה של פעולת CloudBigtableIO.read. הטרנספורמציה Read מחזירה PCollection של אובייקטים מסוג Result ב-HBase, כאשר כל רכיב ב-PCollection מייצג שורה אחת בטבלה.

p.apply(Read.from(CloudBigtableIO.read(config)))
    .apply(
        ParDo.of(
            new DoFn<Result, Void>() {
              @ProcessElement
              public void processElement(@Element Result row, OutputReceiver<Void> out) {
                System.out.println(Bytes.toString(row.getRow()));
              }
            }));

כברירת מחדל, הפעולה CloudBigtableIO.read מחזירה את כל השורות בטבלה. אתם יכולים להשתמש באובייקט Scan של HBase כדי להגביל את הקריאה לטווח של מפתחות שורות בטבלה, או כדי להחיל מסננים על תוצאות הקריאה. כדי להשתמש באובייקט Scan, צריך לכלול אותו ב-CloudBigtableScanConfiguration.

לדוגמה, אפשר להוסיף Scan שמחזיר רק את הצמד הראשון של מפתח/ערך מכל שורה בטבלה, וזה שימושי כשסופרים את מספר השורות בטבלה:

import com.google.cloud.bigtable.beam.CloudBigtableIO;
import com.google.cloud.bigtable.beam.CloudBigtableScanConfiguration;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.util.Bytes;

public class HelloWorldRead {
  public static void main(String[] args) {
    BigtableOptions options =
        PipelineOptionsFactory.fromArgs(args).withValidation().as(BigtableOptions.class);
    Pipeline p = Pipeline.create(options);

    Scan scan = new Scan();
    scan.setCacheBlocks(false);
    scan.setFilter(new FirstKeyOnlyFilter());

    CloudBigtableScanConfiguration config =
        new CloudBigtableScanConfiguration.Builder()
            .withProjectId(options.getBigtableProjectId())
            .withInstanceId(options.getBigtableInstanceId())
            .withTableId(options.getBigtableTableId())
            .withScan(scan)
            .build();

    p.apply(Read.from(CloudBigtableIO.read(config)))
        .apply(
            ParDo.of(
                new DoFn<Result, Void>() {
                  @ProcessElement
                  public void processElement(@Element Result row, OutputReceiver<Void> out) {
                    System.out.println(Bytes.toString(row.getRow()));
                  }
                }));

    p.run().waitUntilFinish();
  }

  public interface BigtableOptions extends DataflowPipelineOptions {
    @Description("The Bigtable project ID, this can be different than your Dataflow project")
    @Default.String("bigtable-project")
    String getBigtableProjectId();

    void setBigtableProjectId(String bigtableProjectId);

    @Description("The Bigtable instance ID")
    @Default.String("bigtable-instance")
    String getBigtableInstanceId();

    void setBigtableInstanceId(String bigtableInstanceId);

    @Description("The Bigtable table ID in the instance.")
    @Default.String("mobile-time-series")
    String getBigtableTableId();

    void setBigtableTableId(String bigtableTableId);
  }
}

כתיבה ב-Bigtable

כדי לכתוב לטבלה של Bigtable, צריך apply פעולת CloudBigtableIO.writeToTable. תצטרכו לבצע את הפעולה הזו ב-PCollection של אובייקטים מסוג HBase Mutation, שיכולים לכלול אובייקטים מסוג Put ו-Delete.

טבלת Bigtable כבר צריכה להיות קיימת, וצריך להגדיר בה את קבוצות העמודות המתאימות. המחבר של Dataflow לא יוצר טבלאות וקבוצות של עמודות תוך כדי תנועה. אפשר להשתמש ב-CLI של cbt כדי ליצור טבלה ולהגדיר קבוצות עמודות, או לעשות זאת באופן פרוגרמטי.

לפני שכותבים ב-Bigtable, צריך ליצור צינור עיבוד נתונים ב-Dataflow כדי שאפשר יהיה לבצע סריאליזציה של פעולות הוספה ומחיקה ברשת:

BigtableOptions options =
    PipelineOptionsFactory.fromArgs(args).withValidation().as(BigtableOptions.class);
Pipeline p = Pipeline.create(options);

באופן כללי, תצטרכו לבצע טרנספורמציה, כמו ParDo, כדי לעצב את נתוני הפלט לאוסף של אובייקטים מסוג Put או Delete ב-HBase. בדוגמה הבאה מוצגת טרנספורמציה של DoFn, שבה הערך הנוכחי משמש כמפתח השורה של Put. לאחר מכן תוכלו לכתוב את האובייקטים של Put ב-Bigtable.

p.apply(Create.of("phone#4c410523#20190501", "phone#4c410523#20190502"))
    .apply(
        ParDo.of(
            new DoFn<String, Mutation>() {
              @ProcessElement
              public void processElement(@Element String rowkey, OutputReceiver<Mutation> out) {
                long timestamp = System.currentTimeMillis();
                Put row = new Put(Bytes.toBytes(rowkey));

                row.addColumn(
                    Bytes.toBytes("stats_summary"),
                    Bytes.toBytes("os_build"),
                    timestamp,
                    Bytes.toBytes("android"));
                out.output(row);
              }
            }))
    .apply(CloudBigtableIO.writeToTable(bigtableTableConfig));

כדי להפעיל את בקרת הזרימה של כתיבה באצווה, מגדירים את BIGTABLE_ENABLE_BULK_MUTATION_FLOW_CONTROL לערך true. התכונה הזו מגבילה באופן אוטומטי את קצב התנועה של בקשות כתיבה באצווה, ומאפשרת להוספה או להסרה של צמתים באופן אוטומטי באמצעות התאמה לעומס (autoscaling) ב-Bigtable כדי לטפל במשימת Dataflow.

CloudBigtableTableConfiguration bigtableTableConfig =
    new CloudBigtableTableConfiguration.Builder()
        .withProjectId(options.getBigtableProjectId())
        .withInstanceId(options.getBigtableInstanceId())
        .withTableId(options.getBigtableTableId())
        .withConfiguration(BigtableOptionsFactory.BIGTABLE_ENABLE_BULK_MUTATION_FLOW_CONTROL,
            "true")
        .build();
return bigtableTableConfig;

זאת הדוגמה המלאה לכתיבה, כולל הווריאציה שמאפשרת בקרת זרימה של כתיבה באצווה.


import com.google.cloud.bigtable.beam.CloudBigtableIO;
import com.google.cloud.bigtable.beam.CloudBigtableTableConfiguration;
import com.google.cloud.bigtable.hbase.BigtableOptionsFactory;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

public class HelloWorldWrite {

  public static void main(String[] args) {
    BigtableOptions options =
        PipelineOptionsFactory.fromArgs(args).withValidation().as(BigtableOptions.class);
    Pipeline p = Pipeline.create(options);

    CloudBigtableTableConfiguration bigtableTableConfig =
        new CloudBigtableTableConfiguration.Builder()
            .withProjectId(options.getBigtableProjectId())
            .withInstanceId(options.getBigtableInstanceId())
            .withTableId(options.getBigtableTableId())
            .build();

    p.apply(Create.of("phone#4c410523#20190501", "phone#4c410523#20190502"))
        .apply(
            ParDo.of(
                new DoFn<String, Mutation>() {
                  @ProcessElement
                  public void processElement(@Element String rowkey, OutputReceiver<Mutation> out) {
                    long timestamp = System.currentTimeMillis();
                    Put row = new Put(Bytes.toBytes(rowkey));

                    row.addColumn(
                        Bytes.toBytes("stats_summary"),
                        Bytes.toBytes("os_build"),
                        timestamp,
                        Bytes.toBytes("android"));
                    out.output(row);
                  }
                }))
        .apply(CloudBigtableIO.writeToTable(bigtableTableConfig));

    p.run().waitUntilFinish();
  }

  public interface BigtableOptions extends DataflowPipelineOptions {

    @Description("The Bigtable project ID, this can be different than your Dataflow project")
    @Default.String("bigtable-project")
    String getBigtableProjectId();

    void setBigtableProjectId(String bigtableProjectId);

    @Description("The Bigtable instance ID")
    @Default.String("bigtable-instance")
    String getBigtableInstanceId();

    void setBigtableInstanceId(String bigtableInstanceId);

    @Description("The Bigtable table ID in the instance.")
    @Default.String("mobile-time-series")
    String getBigtableTableId();

    void setBigtableTableId(String bigtableTableId);
  }

  public static CloudBigtableTableConfiguration batchWriteFlowControlExample(
      BigtableOptions options) {
    CloudBigtableTableConfiguration bigtableTableConfig =
        new CloudBigtableTableConfiguration.Builder()
            .withProjectId(options.getBigtableProjectId())
            .withInstanceId(options.getBigtableInstanceId())
            .withTableId(options.getBigtableTableId())
            .withConfiguration(BigtableOptionsFactory.BIGTABLE_ENABLE_BULK_MUTATION_FLOW_CONTROL,
                "true")
            .build();
    return bigtableTableConfig;
  }
}