Tuesday, September 14, 2021

Google bigtable: Writing / reading - Conditonal updates

 Sept. 14, 2021

Introduction

I like to take some time to read C# code related to BigTable writing / reading. 

Conditionally writing a value

The following code samples demonstrate how to send a conditional write request, which checks a row for a condition and then, depending on the result, writes data to that row. This type of write makes a CheckAndMutateRow API request.

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

namespace Writes
{
   
public class WriteConditional
   
{
       
/// <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}";
       
}
   
}
}

No comments:

Post a Comment