Tablestore ofrece métodos de lectura de una sola fila y de rango para leer datos de las tablas de índices. Si la tabla de índices contiene las columnas de atributos que desea recuperar, lea los datos directamente desde ella. De lo contrario, consulte los datos en la tabla principal.
Requisitos previos
Inicialice una instancia de OTSClient. Para obtener más información, consulte Initialize a Tablestore client.
Cree un índice secundario. Para obtener más información, consulte Create a secondary index.
Precauciones
Las tablas de índices solo se pueden usar para leer datos.
La primera columna de clave principal de una tabla de índices secundarios locales debe ser igual a la primera columna de clave principal de la tabla principal.
Si las columnas de atributos que desea recuperar no están en la tabla de índices, busque los datos en la tabla principal.
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 a single row.
Parámetros
Cuando llame a la operación GetRow para leer datos de una tabla de índices, tenga en cuenta lo a continuación:
Establezca el parámetro tableName con el nombre de la tabla de índices.
Tablestore agrega automáticamente a la tabla de índices las columnas de clave principal de la tabla de datos que no se especificaron como columnas de índice. Estas se añaden como columnas de clave principal de la tabla de índices. Por lo tanto, al especificar las columnas de clave principal de una fila en la tabla de índices, incluya las columnas de índice con las que creó dicha tabla y las columnas de clave principal de la tabla de datos.
Ejemplos
Uso de índices secundarios globales
A continuación se muestra un ejemplo de código para leer una fila de datos en un índice secundario global a partir de su clave principal:
var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');
var params = {
// Specify the name of the index table.
tableName: "<INDEX_NAME>",
// Specify the information about the primary key of row in the index table.
primaryKey: [{ 'col1': Long.fromNumber(2) }, { 'pk1': Long.fromNumber(2) }, { 'pk2': Long.fromNumber(1) }]
};
client.getRow(params, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', JSON.stringify(data.row, null, 2));
});
Uso de índices secundarios locales
A continuación se muestra un ejemplo de código para leer una fila de datos en un índice secundario local a partir de su clave principal:
var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');
var params = {
// Specify the name of the index table.
tableName: "<INDEX_NAME>",
// Specify the information about the primary key of row in the index table. The first primary key column of the index table must be the same as the first primary key column of the data table.
primaryKey: [{ 'pk1': Long.fromNumber(1) }, { 'col1': Long.fromNumber(2) }, { 'pk2': Long.fromNumber(2) }]
};
client.getRow(params, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', JSON.stringify(data.row, null, 2));
});
Lectura de datos con valores de clave principal dentro de un rango específico
Llame a la operación GetRange para leer los datos cuyos valores de clave principal se encuentren dentro de un rango específico. Para obtener más información, consulte Read a range of data.
Parámetros
Cuando llame a la operación GetRange para leer datos de una tabla de índices, tenga en cuenta lo a continuación:
Establezca el parámetro tableName con el nombre de la tabla de índices.
Tablestore agrega automáticamente a la tabla de índices las columnas de clave principal de la tabla de datos que no se especificaron como columnas de índice. Estas se añaden como columnas de clave principal de la tabla de índices. Por lo tanto, al especificar la clave principal inicial y final del rango que desea consultar, incluya las columnas de índice con las que creó dicha tabla y las columnas de clave principal de la tabla de datos.
Ejemplos
Uso de índices secundarios globales
A continuación se muestra un ejemplo de código para leer datos con valores de clave principal dentro de un rango específico desde un índice secundario global. En este ejemplo, la primera columna de clave principal del índice secundario global es col1. El valor especificado para la columna col1 en el rango es 1.
var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');
var params = {
// Specify the name of the index table. In this example, col1 is the first primary key column of the index table. pk1 and pk2 are the primary key columns of the data table. Tablestore automatically adds pk1 and pk2 to the index table as the primary key columns of the index table.
tableName: "<INDEX_NAME>",
// Specify that data is read in the forward direction.
direction: TableStore.Direction.FORWARD,
// Specify the maximum number of versions of data that you want to return.
maxVersions: 10,
// Specify the start and end primary keys. The range of the primary key value is a left-closed, right-opened interval. INF_MIN indicates an infinitely small value. INF_MAX indicates an infinitely great value.
inclusiveStartPrimaryKey: [{ "col1": Long.fromNumber(1) }, { "pk1": TableStore.INF_MIN }, { "pk2": TableStore.INF_MIN }],
exclusiveEndPrimaryKey: [{ "col1": Long.fromNumber(1) }, { "pk1": TableStore.INF_MAX }, { "pk2": TableStore.INF_MAX }],
// Specify the maximum number of rows that can be returned for a call.
limit: 2
};
var resultRows = []
var getRange = function () {
client.getRange(params, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
resultRows = resultRows.concat(data.rows)
// If the data.next_start_primary_key parameter is not empty in the response, continue to read data.
if (data.nextStartPrimaryKey) {
params.inclusiveStartPrimaryKey = [
{ "col1": data.nextStartPrimaryKey[0].value },
{ "pk1": data.nextStartPrimaryKey[1].value },
{ "pk2": data.nextStartPrimaryKey[2].value }
];
getRange()
} else {
console.log(JSON.stringify(resultRows));
}
});
}
getRange()
Uso de índices secundarios locales
A continuación se muestra un ejemplo de código para leer los datos de todas las filas desde un índice secundario local:
var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');
var params = {
// Specify the name of the index table. In this example, pk1 and col1 are specified as the primary key columns of the index table. pk2 is the primary key column of the data table. Tablestore automatically adds pk2 to the index table as the primary key column of the index table.
tableName: "<INDEX_NAMW>",
// Specify that data is read in the forward direction.
direction: TableStore.Direction.FORWARD,
// Specify the maximum number of versions of data that you want to return.
maxVersions: 10,
// Specify the start and end primary keys. The range of the primary key value is a left-closed, right-opened interval. INF_MIN indicates an infinitely small value. INF_MAX indicates an infinitely great value.
inclusiveStartPrimaryKey: [{ "pk1": TableStore.INF_MIN }, { "col1": TableStore.INF_MIN }, { "pk2": TableStore.INF_MIN }],
exclusiveEndPrimaryKey: [{ "pk1": TableStore.INF_MAX }, { "col1": TableStore.INF_MAX }, { "pk2": TableStore.INF_MAX }],
// Specify the maximum number of rows that can be returned for a call.
limit: 2
};
var resultRows = []
var getRange = function () {
client.getRange(params, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
resultRows = resultRows.concat(data.rows)
// If the data.next_start_primary_key parameter is not empty in the response, continue to read data.
if (data.nextStartPrimaryKey) {
params.inclusiveStartPrimaryKey = [
{ "pk1": data.nextStartPrimaryKey[0].value },
{ "col1": data.nextStartPrimaryKey[1].value },
{ "pk2": data.nextStartPrimaryKey[2].value }
];
getRange()
} else {
console.log(JSON.stringify(resultRows));
}
});
}
getRange()
Preguntas frecuentes
Referencias
Si su negocio requiere consultas multidimensionales y análisis de datos, cree un índice de búsqueda y especifique los atributos obligatorios como campos de dicho índice. Después, podrá consultar y analizar los datos mediante el índice de búsqueda. Por ejemplo, úselo para ejecutar consultas basadas en columnas que no son de clave principal, consultas booleanas y consultas difusas. También sirve para obtener los valores máximo y mínimo, recopilar estadísticas sobre la cantidad de filas y agrupar los resultados de las consultas. Para obtener más información, consulte Search index.
Si necesita ejecutar instrucciones SQL para consultar y analizar datos, utilice la función de consulta SQL. Para obtener más información, consulte SQL query.