Utilice Tablestore SDK for Java para leer datos mediante un índice secundario global o local.
Requisitos previos
Se inicializó una instancia de OTSClient. Para obtener más información, consulte Initialize a Tablestore client.
Se creó un índice secundario. Para obtener más información, consulte Create a secondary index.
Lectura de una sola fila de datos
Llame a la operación GetRow para leer una sola fila de datos. Para obtener más información, consulte Read single row data.
Parámetros
Al llamar a la operación GetRow para leer datos de una tabla de índices, tenga en cuenta los siguientes puntos:
Establezca table_name con el nombre de la tabla de índices.
Tablestore agrega automáticamente las columnas de clave principal de la tabla de datos no especificadas como columnas de índice a una tabla de índices y las asigna como columnas de clave principal de dicha tabla. Por lo tanto, al especificar las columnas de clave principal de una fila en una tabla de índices, debe indicar tanto las columnas de índice con las que creó la tabla como las columnas de clave principal de la tabla de datos.
Ejemplos
El siguiente código de ejemplo muestra cómo leer una fila de datos en una tabla de índices según la clave principal de dicha fila:
# 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()))
Lectura de datos con valores de clave principal dentro de un rango específico
Llame a la operación GetRange para leer datos cuyos valores de clave principal se encuentren dentro de un rango específico. Para obtener más información, consulte Read data whose primary key values are within a specific range.
Parámetros
Al llamar a la operación GetRange para leer datos de una tabla de índices, considere los siguientes aspectos:
Establezca table_name con el nombre de la tabla de índices.
Tablestore agrega automáticamente las columnas de clave principal de la tabla de datos no especificadas como columnas de índice a una tabla de índices y las asigna como columnas de clave principal de dicha tabla. Por consiguiente, al definir la clave principal inicial y final del rango que desea consultar, debe especificar las columnas de índice con las que creó la tabla y las columnas de clave principal de la tabla de datos.
Ejemplos
El siguiente fragmento de código ejemplifica la lectura de datos con valores de clave principal dentro de un rango específico desde un índice secundario.
# 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())
Referencias
Si su negocio requiere consultas multidimensionales y análisis de datos, cree un índice de búsqueda y especifique los atributos necesarios como campos de dicho índice. Posteriormente, podrá consultar y analizar datos mediante este recurso. Por ejemplo, un índice de búsqueda permite realizar consultas basadas en columnas que no son de clave principal, consultas booleanas y búsquedas difusas. También sirve para obtener valores máximos y mínimos, recopilar estadísticas sobre el número de filas y agrupar resultados de consulta. Para obtener más información, consulte Search index.
Para ejecutar instrucciones SQL y analizar datos, utilice la función de consulta SQL. Para obtener más información, consulte SQL query.