Incrémenter une cellule

Envoyer une requête d'écriture qui incrémente une valeur numérique existante. Ce type d'écriture exécute une requête API ReadModifyWriteRow.

Pages de documentation incluant cet exemple de code

Pour afficher l'exemple de code utilisé en contexte, consultez la documentation suivante :

Exemple de code

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.


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

namespace Writes
{
    public class WriteIncrement
    {
        /// <summary>
        /// Increments a cell value in a row with an existing value at that cell.
        ///</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 writeIncrement(
            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");
            String COLUMN_FAMILY = "stats_summary";

            // Increment the value of stats_summary:connected_wifi by -1 (change 1 to 0 to show it's disconnected)
            ReadModifyWriteRowResponse readModifyWriteRowResponse = bigtableClient.ReadModifyWriteRow(
                tableName,
                rowkey,
                ReadModifyWriteRules.Increment(COLUMN_FAMILY, "connected_wifi", -1));
            return $"Successfully updated row {readModifyWriteRowResponse.Row.Key}";
        }
    }
}

C++

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

namespace cbt = ::google::cloud::bigtable;
[](cbt::Table table) {
  std::string row_key = "phone#4c410523#20190501";
  std::string column_family = "stats_summary";

  google::cloud::StatusOr<cbt::Row> row = table.ReadModifyWriteRow(
      row_key, cbt::ReadModifyWriteRule::IncrementAmount(
                   column_family, "connected_wifi", -1));

  if (!row) throw std::runtime_error(row.status().message());
  std::cout << "Successfully updated row" << row->row_key() << "\n";
}

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

import (
	"context"
	"fmt"
	"io"

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

func writeIncrement(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: %v", err)
	}
	defer client.Close()
	tbl := client.Open(tableName)
	columnFamilyName := "stats_summary"

	increment := bigtable.NewReadModifyWrite()
	increment.Increment(columnFamilyName, "connected_wifi", -1)

	rowKey := "phone#4c410523#20190501"
	if _, err := tbl.ApplyReadModifyWrite(ctx, rowKey, increment); err != nil {
		return fmt.Errorf("ApplyReadModifyWrite: %v", err)
	}

	fmt.Fprintf(w, "Successfully updated row: %s\n", rowKey)
	return nil
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.


import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.ReadModifyWriteRow;
import com.google.cloud.bigtable.data.v2.models.Row;
import java.nio.charset.Charset;

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

  public static void writeIncrement(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)) {
      // Get an existing row that has a cell with an incrementable value. A value can be incremented
      // if it is encoded as a 64-bit big-endian signed integer.
      String rowkey = "phone#4c410523#20190501";
      ReadModifyWriteRow mutation =
          ReadModifyWriteRow.create(tableId, rowkey)
              .increment(COLUMN_FAMILY_NAME, "connected_cell", -1);
      Row success = dataClient.readModifyWriteRow(mutation);

      System.out.printf(
          "Successfully updated row %s", success.getKey().toString(Charset.defaultCharset()));
    } catch (Exception e) {
      System.out.println("Error during WriteIncrement: \n" + e.toString());
    }
  }
}

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

/**
 * 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 writeIncrement() {
  const instance = bigtable.instance(instanceId);
  const table = instance.table(tableId);

  const row = table.row('phone#4c410523#20190501');
  await row.increment('stats_summary:connected_wifi', -1);

  console.log(`Successfully updated row ${row}`);
}

writeIncrement();

PHP

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\ReadModifyWriteRowRules;

/**
 * Increment an existing value 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 incremented
 */
function write_increment(
    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);

    $columnFamilyId = 'stats_summary';

    $rules = (new ReadModifyWriteRowRules)->increment($columnFamilyId, 'connected_wifi', 3);
    $row = $table->readModifyWriteRow('phone#4c410523#20190501', $rules);

    printf('Successfully updated row.' . PHP_EOL);
}

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

from google.cloud import bigtable

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

    column_family_id = "stats_summary"

    row_key = "phone#4c410523#20190501"
    row = table.append_row(row_key)

    # Decrement the connected_wifi value by 1.
    row.increment_cell_value(column_family_id, "connected_wifi", -1)
    row.commit()

    print('Successfully updated row {}.'.format(row_key))

Ruby

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la section Bibliothèques clientes Bigtable.

# instance_id = "my-instance"
# table_id    = "my-table"
table = bigtable.table instance_id, table_id
column_family = "stats_summary"

rowkey = "phone#4c410523#20190501"
decrement_rule = table.new_read_modify_write_rule(column_family, "connected_wifi")
                      .increment(-1)

row = table.read_modify_write_row rowkey, decrement_rule
puts "Successfully updated row #{row.key}"

Étape suivante

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.