DynamoDB查询使用辅助索引,如何使用不同的键进行查询



我使用的是带有dynamodb的无服务器框架[在本地]。尝试使用辅助索引字段进行查询。目标是像我们在Mongo:{url:'<Somevalue>'}中的基本查找查询一样,用很少的键进行查询,或者可能像这个{url:<somevalue>,ha:<somevalue>}

我当前使用的表配置:

无服务器.yml

resources:
Resources:
TableName:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: ${file(./serverless.js):Tables.TableName.name}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: 'id'
AttributeType: 'S'
- AttributeName: 'url'
AttributeType: 'S'
- AttributeName: 'ha'
AttributeType: 'S'
- AttributeName: 'GSI_1_PK'
AttributeType: 'S'
- AttributeName: 'GSI_1_SK'
AttributeType: 'S'
KeySchema:
- AttributeName: 'id'
KeyType: 'HASH'
GlobalSecondaryIndexes:
- IndexName: 'GSI_1'
KeySchema:
- AttributeName: 'GSI_1_PK'
KeyType: 'HASH'
- AttributeName: 'GSI_1_SK'
KeyType: 'RANGE'
Projection:
ProjectionType: 'ALL'
- IndexName: 'URI_1'
KeySchema:
- AttributeName: 'url'
KeyType: 'HASH'
Projection:
ProjectionType: 'ALL'
- IndexName: 'HASH_1'
KeySchema:
- AttributeName: 'ha'
KeyType: 'HASH'
Projection:
ProjectionType: 'ALL'
Outputs:
TableNameARN:
Value: { 'Fn::GetAtt': [TableName, Arn] }
Export:
Name: ${file(./serverless.js):Exports.TableNameARN}

有了这个,目前我只能用id字段、进行搜索

Q

1> 对于不同字段的查询,需要做哪些更改?[为二级索引,在查询中不使用id]

2> 如何使用多个属性进行搜索?[即:{url:<somevalue>,ha:<somevalue>}]

我正在使用的查询:

var params = {
TableName: '<TableName>',
IndexName:'URI_1',
Key: {
url: 'http://something.com'
}
};
docClient.get(params, function(err, data) {
if (err) ppJson(err); // an error occurred
else ppJson(data); // successful response
});

查询输出:

{
message:"One of the required keys was not given a value",
code:"ValidationException,
...
}
  • 您已经使用了允许使用辅助索引的GSI。但是您应该使用query而不是get,它允许您查询任何具有复合主键(分区键和排序键)的表或辅助索引
  • 只需使用FilterExpressionExpressionAttributeValues,就可以支持u使用多个条件

var params = {
TableName: '<TableName>',
IndexName : 'URI_1',
KeyConditionExpression : 'url = :url',
FilterExpression : 'ha = :ha',
ExpressionAttributeValues : {
':url': 'http://something.com',
':ha': 'aaaa'
}
};
docClient.query(params, function(err, data) {
if (err) console.log(err); // an error occurred
else console.log(data); // successful response
});

附加

我们可以使用三个表达式来查询条件,前两个用于Dynamodb.query,最后一个用于Dynamodb.updateItemDynamodb.putItem:

  • KeyConditionExpression-您需要在中指定分区键-必需-或排序键。默认情况下,它只能支持表键,如果您想使用GSI之类的索引,则应将其与IndexName一起使用
  • FilterExpression-在查询完成之后,但在返回结果之前应用,并且FilterExpression不能包含分区键或排序键属性
  • ConditionExpression-条件更新要成功,必须满足的条件

最新更新