我需要通过与其主键不同的键来查询DynamoDB表。我试图为其创建一个全球二级索引。但是我收到此错误:“查询键条件不支持dynamodb”。通过查看一些示例,看起来我无法按二级索引查询,除非我也包括一级索引/键,这对吗?假设我需要由在某个城市工作的所有员工查询,如果没有employeeID,我可以这样做吗?
更新的信息也许未创建我的索引?
表信息:
GSI:
当我从节点查询时,我将城市和索引名称作为参数发送:
const filter = { city: city};
return this.getRecordsFromDb(filter, { IndexName: "myIndexName" })
.then(records => __.head(records));
注意:-由于您没有提供完整的代码,因此很难模拟和识别问题。但是,我创建了类似的表和索引。这对我来说可以。您可以参考下面的代码以获取更多详细信息。
这是表创建脚本和查询索引。
如果需要,可以更改表名和索引名。我遵循了您在帖子中提到的相同关键属性结构。
这已经过测试并且工作正常。
1)使用索引“ city_index”创建表“ city”:-
var params = {
TableName: 'city',
KeySchema: [ // The type of of schema. Must start with a HASH type, with an optional second RANGE.
{ // Required HASH type attribute
AttributeName: 'id',
KeyType: 'HASH',
},
{ // Required HASH type attribute
AttributeName: 'name',
KeyType: 'RANGE',
}
],
AttributeDefinitions: [ // The names and types of all primary and index key attributes only
{
AttributeName: 'id',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
{
AttributeName: 'name',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
{
AttributeName: 'city',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
],
ProvisionedThroughput: { // required provisioned throughput for the table
ReadCapacityUnits: 400,
WriteCapacityUnits: 400,
},
GlobalSecondaryIndexes: [ // optional (list of GlobalSecondaryIndex)
{
IndexName: 'city_index',
KeySchema: [
{ // Required HASH type attribute
AttributeName: 'city',
KeyType: 'HASH',
}
],
Projection: { // attributes to project into the index
ProjectionType: 'ALL' // (ALL | KEYS_ONLY | INCLUDE)
},
ProvisionedThroughput: { // throughput to provision to the index
ReadCapacityUnits: 400,
WriteCapacityUnits: 400,
},
},
// ... more global secondary indexes ...
],
};
dynamodb.createTable(params, function(err, data) {
if (err){ console.log("error :" +JSON.stringify(err));} // an error occurred
else console.log("success :" +JSON.stringify(data)); // successful response
});
2)在城市表中插入一些数据
3)使用索引查询:
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "city";
var params = {
TableName : table,
IndexName : 'city_index',
KeyConditionExpression : 'city = :cityVal',
ExpressionAttributeValues : {
':cityVal' : 'london'
}
};
docClient.query(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句