Tablestore oferece métodos de leitura de linha única e de intervalo para acessar dados em tabelas de índice. Caso a tabela de índice contenha as colunas de atributo desejadas, leia os dados diretamente dela. Caso contrário, consulte os dados na tabela primária.
Pré-requisitos
Uma instância OTSClient inicializada. Para mais informações, consulte Inicializar um cliente Tablestore.
Um índice secundário criado. Para mais informações, consulte Criar um índice secundário.
Precauções
Tabelas de índice servem exclusivamente para leitura de dados.
A primeira coluna de chave primária de uma tabela de índice secundário local deve ser idêntica à primeira coluna de chave primária da tabela principal.
Se as colunas de atributo necessárias não estiverem na tabela de índice, busque os dados na tabela primária.
Ler uma única linha de dados
Chame a operação GetRow para ler uma única linha de dados. Para mais informações, consulte Ler dados de linha única.
Parâmetros
Ao chamar a operação GetRow para ler dados de uma tabela de índice, observe os seguintes pontos:
Defina table_name como o nome da tabela de índice.
O Tablestore adiciona automaticamente as colunas de chave primária da tabela de dados que não foram especificadas como colunas de índice à tabela de índice, tratando-as como colunas de chave primária desta última. Portanto, ao especificar as colunas de chave primária de uma linha na tabela de índice, inclua tanto as colunas de índice usadas na criação quanto as colunas de chave primária da tabela de dados.
Exemplos
O código de exemplo abaixo demonstra como ler uma linha de dados em uma tabela de índice com base na chave primária dessa linha:
# Construct the primary key. The primary key columns of the index table consist of definedcol1, pk1, and pk2. pk2 is the primary key column of the data table that is not specified as the index column of the index table. The three primary key columns are of the INTEGER type. The primary key value based on which you want to read data is 1 in the definedcol1 column, 101 in the pk1 column, and 11 in the pk2 column.
# If you want to read data from a local secondary index, the first primary key column of the index table must be the same as the first primary key column of the data table.
primary_key = [('definedcol1', 1), ('pk1', 101), ('pk2', 11)]
# Specify the attribute columns of the index table that you want to return. In this example, definedcol2 and definedcol3 are specified. If you set the columns_to_get parameter to [], all attribute columns of the index table are returned.
columns_to_get = ['definedcol2', 'definedcol3']
# Specify a filter for the columns. In this example, the filter is used to return the rows in which the value of the definedcol2 column is not equal to 1, and the value of the definedcol3 column is 'test'.
cond = CompositeColumnCondition(LogicalOperator.AND)
cond.add_sub_condition(SingleColumnCondition("definedcol2", 1, ComparatorType.NOT_EQUAL))
cond.add_sub_condition(SingleColumnCondition("definedcol3", 'test', ComparatorType.EQUAL))
try:
# Call the get_row operation to query data.
# Specify the name of the index table. The last parameter value 1 indicates that only one version of the value is returned.
consumed, return_row, next_token = client.get_row('<INDEX_NAME>', primary_key, columns_to_get, cond, 1)
print('Read succeed, consume %s read cu.' % consumed.read)
print('Value of primary key: %s' % return_row.primary_key)
print('Value of attribute: %s' % return_row.attribute_columns)
for att in return_row.attribute_columns:
# Display the key, value, and version of each column.
print('name:%s\tvalue:%s' % (att[0], att[1]))
# In most cases, client exceptions are caused by parameter errors or network exceptions.
except OTSClientError as e:
print('get row failed, http_status:%d, error_message:%s' % (e.get_http_status(), e.get_error_message()))
# In most cases, server exceptions are caused by parameter or throttling errors.
except OTSServiceError as e:
print('get row failed, http_status:%d, error_code:%s, error_message:%s, request_id:%s' % (e.get_http_status(), e.get_error_code(), e.get_error_message(), e.get_request_id()))
Ler dados com valores de chave primária dentro de um intervalo específico
Utilize a operação GetRange para ler dados cujos valores de chave primária estejam dentro de um intervalo definido. Para mais detalhes, consulte Ler dados com valores de chave primária dentro de um intervalo específico.
Parâmetros
Ao executar a operação GetRange para leitura em uma tabela de índice, atente-se aos seguintes itens:
É necessário definir table_name com o nome da tabela de índice.
O Tablestore inclui automaticamente as colunas de chave primária da tabela de dados não definidas como colunas de índice na tabela de índice, funcionando como chaves primárias desta. Assim, ao estabelecer a chave primária inicial e final do intervalo de consulta, especifique as colunas de índice base da criação e as chaves primárias originais da tabela de dados.
Exemplos
O trecho de código a seguir ilustra a leitura de dados com valores de chave primária dentro de um intervalo específico a partir de um índice secundário.
# Construct the start primary key of the range. If you want to read data from a local secondary index, the first primary key column of the index table must be the same as the first primary key column of the data table.
inclusive_start_primary_key = [('definedcol1', 1), ('pk1', INF_MIN), ('pk2', INF_MIN)]
# Construct the end primary key of the range.
exclusive_end_primary_key = [('definedcol1', 5), ('pk1', INF_MAX), ('pk2', INF_MIN)]
# Specify that all columns of the rows that meet the query conditions are returned.
columns_to_get = []
# Set the limit parameter to 90 to return a maximum of 90 rows of data. If a total of 100 rows meet the query conditions, the number of rows that are returned in the first read operation ranges from 0 to 90. The value of the next_start_primary_key parameter is not None.
limit = 90
# Specify a filter for the columns. In this example, the filter is used to return the rows in which the value of the definedcol2 column is smaller than 50, and the value of the definedcol3 column is 'China'.
cond = CompositeColumnCondition(LogicalOperator.AND)
# Specify the pass_if_missing parameter to determine whether a row meets the filter conditions if the row does not contain a specific column.
# If you do not specify the pass_if_missing parameter or set the parameter to True, a row meets the filter conditions if the row does not contain a specific column.
# If you set the pass_if_missing parameter to False, a row does not meet the filter conditions if the row does not contain a specific column.
cond.add_sub_condition(SingleColumnCondition("definedcol3", 'China', ComparatorType.EQUAL, pass_if_missing=False))
cond.add_sub_condition(SingleColumnCondition("definedcol2", 50, ComparatorType.LESS_THAN, pass_if_missing=False))
try:
# Call the get_range operation.
# Specify the name of the index table.
consumed, next_start_primary_key, row_list, next_token = client.get_range(
'<INDEX_NAME>', Direction.FORWARD,
inclusive_start_primary_key, exclusive_end_primary_key,
columns_to_get,
limit,
column_filter=cond,
max_version=1,
time_range=(1557125059000, 1557129059000) # Specify the time range of data. In this example, the start time is greater than or equal to 1557125059000. The end time is smaller than 1557129059000.
)
all_rows = []
all_rows.extend(row_list)
# If the next_start_primary_key parameter is not empty, continue to read data.
while next_start_primary_key is not None:
inclusive_start_primary_key = next_start_primary_key
consumed, next_start_primary_key, row_list, next_token = client.get_range(
'<INDEX_NAME>', Direction.FORWARD,
inclusive_start_primary_key, exclusive_end_primary_key,
columns_to_get, limit,
column_filter=cond,
max_version=1
)
all_rows.extend(row_list)
# Display the primary key columns and attribute columns.
for row in all_rows:
print(row.primary_key, row.attribute_columns)
print('Total rows: ', len(all_rows))
# In most cases, client exceptions are caused by parameter errors or network exceptions.
except OTSClientError as e:
print('get row failed, http_status:%d, error_message:%s' % (e.get_http_status(), e.get_error_message()))
# In most cases, server exceptions are caused by parameter or throttling errors.
except OTSServiceError as e:
print('get row failed, http_status:%d, error_code:%s, error_message:%s, request_id:%s' % (e.get_http_status(), e.get_error_code(), e.get_error_message(), e.get_request_id())
Perguntas frequentes
Referências
Para cenários que exigem consultas multidimensionais e análise de dados, crie um índice de pesquisa e defina os atributos necessários como campos desse índice. Isso permite realizar consultas e análises avançadas, como buscas por colunas que não são de chave primária, consultas booleanas e pesquisas difusas. Além disso, o índice de pesquisa possibilita obter valores máximos e mínimos, contar linhas e agrupar resultados. Para mais informações, consulte Índice de pesquisa.
Caso precise executar instruções SQL para consultar e analisar dados, utilize o recurso de consulta SQL. Para mais detalhes, consulte Consulta SQL.