Gravar um valor condicionalmente

Enviar uma solicitação de gravação condicional. Esse tipo de gravação faz uma solicitação de API CheckAndMutateRow.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C++

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

namespace cbt = ::google::cloud::bigtable;
[](cbt::Table table) {
  auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::system_clock::now().time_since_epoch());

  std::string row_key = "phone#4c410523#20190501";
  cbt::SingleRowMutation mutation(row_key);
  std::string column_family = "stats_summary";
  cbt::Filter predicate = cbt::Filter::Chain(
      cbt::Filter::ColumnName(column_family, "os_build"),
      cbt::Filter::Latest(1), cbt::Filter::ValueRegex("PQ2A\\..*"));

  google::cloud::StatusOr<cbt::MutationBranch> branch =
      table.CheckAndMutateRow(
          row_key, std::move(predicate),
          {cbt::SetCell(column_family, "os_name", timestamp, "android")}, {});

  if (!branch) throw std::move(branch).status();
  if (*branch == cbt::MutationBranch::kPredicateMatched) {
    std::cout << "Successfully updated row\n";
  } else {
    std::cout << "The predicate was not matched\n";
  }
}

C#

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using System;
using Google.Cloud.Bigtable.V2;
using Google.Cloud.Bigtable.Common.V2;

namespace Writes
{
    public class WriteConditionalSample
    {
        /// <summary>
        /// Check if a row has a certain value then mutate the row if it does.
        ///</summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="instanceId">Your Google Cloud Bigtable Instance ID.</param>
        /// <param name="tableId">Your Google Cloud Bigtable table ID.</param>
        public string WriteConditional(
            string projectId = "YOUR-PROJECT-ID",
            string instanceId = "YOUR-INSTANCE-ID",
            string tableId = "YOUR-TABLE-ID")
        {
            BigtableClient bigtableClient = BigtableClient.Create();

            TableName tableName = new TableName(projectId, instanceId, tableId);
            BigtableByteString rowkey = new BigtableByteString("phone#4c410523#20190501");
            BigtableVersion timestamp = new BigtableVersion(DateTime.UtcNow);
            string COLUMN_FAMILY = "stats_summary";

            CheckAndMutateRowResponse checkAndMutateRowResponse = bigtableClient.CheckAndMutateRow(
                tableName,
                rowkey,
                RowFilters.Chain(
                    RowFilters.FamilyNameExact(COLUMN_FAMILY),
                    RowFilters.ColumnQualifierExact("os_build"),
                    RowFilters.ValueRegex("PQ2A\\..*")),
                Mutations.SetCell(COLUMN_FAMILY, "os_name", "android", timestamp));

            return $"Successfully updated row's os_name: {checkAndMutateRowResponse.PredicateMatched}";
        }
    }
}

Go

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigtable"
)

func writeConditionally(w io.Writer, projectID, instanceID string, tableName string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance-id"
	// tableName := "mobile-time-series"

	ctx := context.Background()
	client, err := bigtable.NewClient(ctx, projectID, instanceID)
	if err != nil {
		return fmt.Errorf("bigtable.NewAdminClient: %w", err)
	}
	defer client.Close()
	tbl := client.Open(tableName)
	columnFamilyName := "stats_summary"
	timestamp := bigtable.Now()

	mut := bigtable.NewMutation()
	mut.Set(columnFamilyName, "os_name", timestamp, []byte("android"))

	filter := bigtable.ChainFilters(
		bigtable.FamilyFilter(columnFamilyName),
		bigtable.ColumnFilter("os_build"),
		bigtable.ValueFilter("PQ2A\\..*"))
	conditionalMutation := bigtable.NewCondMutation(filter, mut, nil)

	rowKey := "phone#4c410523#20190501"
	if err := tbl.Apply(ctx, rowKey, conditionalMutation); err != nil {
		return fmt.Errorf("Apply: %w", err)
	}

	fmt.Fprintln(w, "Successfully updated row's os_name")
	return nil
}

Java

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS;

import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation;
import com.google.cloud.bigtable.data.v2.models.Filters.Filter;
import com.google.cloud.bigtable.data.v2.models.Mutation;
import com.google.cloud.bigtable.data.v2.models.TableId;

public class WriteConditionally {
  private static final String COLUMN_FAMILY_NAME = "stats_summary";

  public static void writeConditionally(String projectId, String instanceId, String tableId) {
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";
    // String tableId = "mobile-time-series";

    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      long timestamp = System.currentTimeMillis() * 1000;

      String rowkey = "phone#4c410523#20190501";

      Mutation mutation =
          Mutation.create().setCell(COLUMN_FAMILY_NAME, "os_name", timestamp, "android");

      Filter filter =
          FILTERS
              .chain()
              .filter(FILTERS.family().exactMatch(COLUMN_FAMILY_NAME))
              .filter(FILTERS.qualifier().exactMatch("os_build"))
              .filter(FILTERS.value().regex("PQ2A\\..*"));

      ConditionalRowMutation conditionalRowMutation =
          ConditionalRowMutation.create(TableId.of(tableId), rowkey)
              .condition(filter)
              .then(mutation);

      boolean success = dataClient.checkAndMutateRow(conditionalRowMutation);

      System.out.printf("Successfully updated row's os_name: %b", success);

    } catch (Exception e) {
      System.out.println("Error during WriteConditionally: \n" + e.toString());
      e.printStackTrace();
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const instanceId = 'YOUR_INSTANCE_ID';
// const tableId = 'YOUR_TABLE_ID';

const {Bigtable} = require('@google-cloud/bigtable');

const bigtable = new Bigtable();

async function writeConditionally() {
  const instance = bigtable.instance(instanceId);
  const table = instance.table(tableId);

  const timestamp = new Date();
  const row = table.row('phone#4c410523#20190501');
  const filter = [
    {
      column: 'os_build',
      value: {
        start: 'PQ2A',
        end: 'PQ2A',
      },
    },
  ];

  const config = {
    onMatch: [
      {
        method: 'insert',
        data: {
          stats_summary: {
            os_name: 'android',
            timestamp,
          },
        },
      },
    ],
  };

  await row.filter(filter, config);

  console.log("Successfully updated row's os_name");
}

writeConditionally();

PHP

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\Filter;
use Google\Cloud\Bigtable\Mutations;

/**
 * Write data conditionally in a table
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance
 * @param string $tableId The ID of the table where the data needs to be written
 */
function write_conditionally(
    string $projectId,
    string $instanceId,
    string $tableId = 'mobile-time-series'
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $timestampMicros = time() * 1000 * 1000;
    $columnFamilyId = 'stats_summary';

    $mutations = (new Mutations())->upsert($columnFamilyId, 'os_name', 'android', $timestampMicros);
    $predicateFilter = Filter::chain()
    ->addFilter(Filter::family()->exactMatch($columnFamilyId))
    ->addFilter(Filter::qualifier()->exactMatch('os_build'))
    ->addFilter(Filter::value()->regex('PQ2A.*'));
    $options = ['predicateFilter' => $predicateFilter, 'trueMutations' => $mutations];

    $table->checkAndMutateRow('phone#4c410523#20190501', $options);

    printf('Successfully updated row\'s os_name' . PHP_EOL);
}

Python

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import datetime

from google.cloud import bigtable
from google.cloud.bigtable import row_filters


def write_conditional(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)

    timestamp = datetime.datetime.utcnow()
    column_family_id = "stats_summary"

    row_key = "phone#4c410523#20190501"

    row_filter = row_filters.RowFilterChain(
        filters=[
            row_filters.FamilyNameRegexFilter(column_family_id),
            row_filters.ColumnQualifierRegexFilter("os_build"),
            row_filters.ValueRegexFilter("PQ2A\\..*"),
        ]
    )
    row = table.conditional_row(row_key, filter_=row_filter)
    row.set_cell(column_family_id, "os_name", "android", timestamp)
    row.commit()

    print("Successfully updated row's os_name.")

Ruby

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

# instance_id = "my-instance"
# table_id    = "my-table"
table = bigtable.table instance_id, table_id
column_family = "stats_summary"
timestamp = (Time.now.to_f * 1_000_000).round(-3)

rowkey = "phone#4c410523#20190501"
predicate_filter = Google::Cloud::Bigtable::RowFilter.chain
                                                     .family(column_family)
                                                     .qualifier("os_build")
                                                     .value("PQ2A\\..*")

on_match_mutations = Google::Cloud::Bigtable::MutationEntry.new
on_match_mutations.set_cell(
  column_family,
  "os_name",
  "android",
  timestamp: timestamp
)

response = table.check_and_mutate_row(
  rowkey,
  predicate_filter,
  on_match: on_match_mutations
)

puts "Successfully updated row's os_name: #{response}"

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.