Métodos de gravação
Tablestore oferece as operações PutRow, UpdateRow e BatchWriteRow para gravar dados. Selecione o método mais adequado ao seu cenário.
|
Método de gravação |
Descrição |
Cenários |
|
Chame a operação PutRow para inserir uma nova linha. Se a linha já existir, o Tablestore exclui a linha original com todas as colunas e versões e insere a nova linha. |
Indicado para gravar um pequeno volume de dados. |
|
|
Chame a operação UpdateRow para atualizar uma linha. Você pode adicionar ou excluir colunas de atributo, remover versões específicas de uma coluna de atributo ou atualizar valores das colunas existentes. Se a linha especificada não existir, o sistema insere uma nova linha. |
Recomendado para atualizar dados existentes, como excluir colunas de atributo, remover uma versão específica de uma coluna ou modificar valores de colunas de atributo. |
|
|
Chame a operação BatchWriteRow para executar várias operações de gravação em uma única solicitação ou gravar dados em várias tabelas simultaneamente. Uma operação BatchWriteRow consiste em múltiplas suboperações de PutRow, UpdateRow e DeleteRow. O processo de construção dessas suboperações é idêntico ao de chamar as operações PutRow, UpdateRow e DeleteRow individualmente. |
Ideal para cenários que exigem gravação, exclusão ou atualização de grandes volumes de dados, ou uma combinação dessas operações. |
Pré-requisitos
Instância OTSClient inicializada. Para mais informações, consulte Inicializar uma instância OTSClient.
Tabela de dados criada e com dados já gravados. Para mais informações, consulte Criar tabelas de dados e Gravar dados.
Inserir uma única linha de dados
Interface
/// <summary>
/// Writes a row of data based on the specified table name, primary key, and properties. Returns the capacity unit consumed by this operation.
/// </summary>
/// <param name="request">The request to insert data.</param>
/// <returns>The capacity unit consumed by this operation.</returns>
public PutRowResponse PutRow(PutRowRequest request);
/// <summary>
/// The asynchronous version of PutRow.
/// </summary>
public Task<PutRowResponse> PutRowAsync(PutRowRequest request);
Parâmetros
|
Parâmetro |
Descrição |
|
tableName |
Nome da tabela de dados. |
|
primaryKey |
Chave primária da linha. Inclui o nome, o tipo e o valor de cada coluna de chave primária. Importante
|
|
attribute |
Colunas de atributo da linha. Cada item inclui o nome do atributo, o tipo do atributo (opcional), o valor do atributo e o timestamp (opcional).
|
|
condition |
Use uma atualização condicional para definir uma condição de existência para a linha original ou uma condição de valor para uma coluna na linha original. Para mais informações, consulte Atualização condicional. Nota
|
Exemplos
Inserir uma linha de dados
O exemplo a seguir demonstra como inserir uma linha de dados.
// Define the primary key of the row. It must be consistent with the definition in the TableMeta of the table.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Define the attribute columns to be written to the row.
var attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(0));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
try
{
// Construct a request object to insert data. RowExistenceExpectation.IGNORE indicates that new data is inserted regardless of whether the row exists.
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
// Call the PutRow operation to insert the data.
otsClient.PutRow(request);
// If no exception is thrown, the operation is successful.
Console.WriteLine("Put row succeeded.");
}
catch (Exception ex)
{
// If an exception is thrown, the operation failed. Handle the exception.
Console.WriteLine("Put row failed, exception:{0}", ex.Message);
}
Para o código de exemplo completo, consulte PutRow@GitHub.
Usar condições de coluna e linha ao inserir dados
O exemplo a seguir executa uma operação de inserção apenas se a linha existir e col0 for maior que 24.
// Define the primary key of the row. It must be consistent with the definition in the TableMeta of the table.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Define the attribute columns to be written to the row.
AttributeColumns attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(0));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
// Allow inserting the row again and overwriting the original value if the value of the col0 column is greater than 24.
try
{
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.EXPECT_EXIST),
primaryKey, attribute);
request.Condition.ColumnCondition = new RelationalCondition("col0",
CompareOperator.GREATER_THAN,
new ColumnValue(24));
otsClient.PutRow(request);
Console.WriteLine("Put row succeeded.");
}
catch (Exception ex)
{
Console.WriteLine("Put row failed. error:{0}", ex.Message);
}
Para o código de exemplo completo, consulte ConditionPutRow@GitHub.
Inserir dados de forma assíncrona
O exemplo a seguir mostra como inserir várias linhas de dados de maneira assíncrona.
Cada invocação assíncrona inicia um thread. Se você iniciar muitas invocações assíncronas demoradas consecutivamente, poderá ocorrer um tempo limite.
try
{
var putRowTaskList = new List<Task<PutRowResponse>>();
for (int i = 0; i < 100; i++)
{
// Define the primary key of the row. It must be consistent with the definition in the TableMeta of the table.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(i));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Define the attribute columns to be written to the row.
var attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(i));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
putRowTaskList.Add(otsClient.PutRowAsync(request));
}
// Wait for each asynchronous call to return and print the consumed CU value.
foreach (var task in putRowTaskList)
{
task.Wait();
Console.WriteLine("consumed read:{0}, write:{1}", task.Result.ConsumedCapacityUnit.Read,
task.Result.ConsumedCapacityUnit.Write);
}
// If no exception is thrown, the operation is successful.
Console.WriteLine("Put row async succeeded.");
}
catch (Exception ex)
{
// If an exception is thrown, the operation failed. Handle the exception.
Console.WriteLine("Put row async failed. exception:{0}", ex.Message);
}
Para o código de exemplo completo, consulte PutRowAsync@GitHub.
Atualizar uma única linha de dados
Interface
/// <summary>
/// Updates the data of a specified row. If the row does not exist, a new row is created. If the row exists, the values of specified columns are added, modified, or deleted based on the request.
/// </summary>
/// <param name="request">The request object.</param>
public UpdateRowResponse UpdateRow(UpdateRowRequest request);
/// <summary>
/// The asynchronous version of UpdateRow.
/// </summary>
/// <param name="request">The request object.</param>
/// <returns></returns>
public Task<UpdateRowResponse> UpdateRowAsync(UpdateRowRequest request);
Parâmetros
|
Parâmetro |
Descrição |
|
tableName |
Nome da tabela de dados. |
|
primaryKey |
Chave primária da linha. Inclui o nome, o tipo e o valor da coluna de chave primária. Importante
A quantidade e os tipos das colunas de chave primária definidos devem ser idênticos aos definidos na tabela de dados. |
|
condition |
Em uma atualização condicional, você pode definir condições sobre a existência da linha original ou sobre os valores das colunas da linha original. Para mais informações, consulte Atualizações condicionais. |
|
attribute |
Colunas de atributo a serem atualizadas. |
Exemplo
O exemplo a seguir demonstra como atualizar uma linha de dados.
// Define the primary key of the row. The primary key must be the same as the one defined in TableMeta when the table was created.
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Define the attribute columns to write to the row.
UpdateOfAttribute attribute = new UpdateOfAttribute();
attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
attribute.AddAttributeColumnToPut("col1", new ColumnValue("b")); // Change the original value 'a' to 'b'.
attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
try
{
// Construct a request object to update the row. RowExistenceExpectation.IGNORE indicates that the row is updated whether it exists or not.
var request = new UpdateRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
// Call the UpdateRow operation to update the data.
otsClient.UpdateRow(request);
// If no exception is thrown, the operation is successful.
Console.WriteLine("Update row succeeded.");
}
catch (Exception ex)
{
// If an exception is thrown, the operation failed. Handle the exception.
Console.WriteLine("Update row failed, exception:{0}", ex.Message);
}
Para o código de exemplo completo, consulte UpdateRow@GitHub.
Gravar dados em lote
Observações
API
/// <summary>
/// <para>Bulk inserts, updates, or deletes multiple rows of data in one or more tables.</para>
/// <para>The BatchWriteRow operation is a collection of multiple PutRow, UpdateRow, and DeleteRow operations. Each operation is executed independently, returns its own result, and consumes capacity units separately.</para>
/// <para>Compared to many single-row write operations, the BatchWriteRow operation reduces request response times and improves the data write speed.</para>
/// </summary>
/// <param name="request">The request instance.</param>
/// <returns>The response instance.</returns>
public BatchWriteRowResponse BatchWriteRow(BatchWriteRowRequest request);
/// <summary>
/// The asynchronous version of BatchWriteRow.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<BatchWriteRowResponse> BatchWriteRowAsync(BatchWriteRowRequest request);
Exemplo
O exemplo a seguir mostra como gravar 100 linhas de dados em lote.
var TableName = "SampleTable";
// Construct a batch write request object and set the primary keys for 100 rows of data.
var request = new BatchWriteRowRequest();
var rowChanges = new RowChanges(TableName);
for (int i = 0; i < 100; i++)
{
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(i));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Define the attribute columns to write to the row.
UpdateOfAttribute attribute = new UpdateOfAttribute();
attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
attribute.AddAttributeColumnToPut("col1", new ColumnValue("a"));
attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
rowChanges.AddUpdate(new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
}
request.Add(TableName, rowChanges);
try
{
// Call the BatchWriteRow API to write data.
var response = otsClient.BatchWriteRow(request);
var tableRows = response.TableRespones;
var rows = tableRows[TableName];
// A batch operation may partially succeed. Check the status of each row for success. For more information, see the GitHub link in the sample code.
}
catch (Exception ex)
{
// If an exception is thrown, the execution failed. Handle the exception.
Console.WriteLine("Batch put row failed, exception:{0}", ex.Message);
}
Para o código de exemplo completo, consulte BatchWriteRow@GitHub.
Perguntas frequentes
Referências
Use atualizações condicionais para modificar dados com base em condições específicas em aplicações de alta concorrência. Para mais informações, consulte Atualização condicional.
Para fornecer estatísticas em tempo real para aplicações online, como contagem de visualizações de página (PVs) em tempo real para publicações, use contadores atômicos. Para mais informações, consulte Contador atômico.
Após gravar os dados, leia ou exclua dados da tabela conforme necessário. Para mais informações, consulte Ler dados ou Excluir dados.