使用DynamoDB从辅助索引获取GetItem

时间:2017-05-02 07:53:40

标签: amazon-dynamodb

我刚开始使用DynamoDB并设置了'帐户'表。

我已经设置了二级索引,因此我可以查询api用户和用户密钥。 这些值都不是主键,因为它们都是易变的并且可以更改。

表格是用

构建的
TableName: "Accounts",
        KeySchema:  [
            { AttributeName: "id", KeyType: "HASH" },
            { AttributeName: "email", KeyType: "RANGE" }
        ],
        AttributeDefinitions: [
            { AttributeName: "id", AttributeType: "S" },
            { AttributeName: "email", AttributeType: "S" }
        ]

索引是

 TableName: 'Accounts',
            AttributeDefinitions: [
                {AttributeName: 'name', AttributeType: 'S'},
                {AttributeName: 'apiKey', AttributeType: 'S'}
            ],
            GlobalSecondaryIndexUpdates: [
                {
                    Create: {
                        IndexName: "ApiAccounts",
                        ProvisionedThroughput: {
                            ReadCapacityUnits: 1, WriteCapacityUnits: 1
                        },
                        KeySchema: [
                            {AttributeName: 'name', KeyType: "HASH"},
                            {AttributeName: 'apiKey', KeyType: "STRING"} 
                        ],
                        Projection: {
                            ProjectionType: "KEYS_ONLY"
                        },

我现在正试图通过查询ApiAccounts索引来获取使用帐户。

我正在尝试

 dynamoClient.get({
            TableName: 'Accounts',
            IndexName: 'ApiAccounts',
            Key: {
                name: nameKeyArray[0],
                apiKey: nameKeyArray[1]
            }, callback)

但我收到错误One of the required keys was not given a value,这让我相信我不能对索引做'获取'?或者我没有正确引用索引。有人可以为我澄清一下吗?

名称和API密钥是唯一的,所以我想我想尽可能避免查询或扫描

1 个答案:

答案 0 :(得分:19)

我想从官方文档中不太清楚,但您可以在Scan索引上执行QueryGSI,但不能GetItem

对于Table中的每个记录/项目,他们必须拥有唯一的HASHRANGE个键。

// assume dummy api putItem(id, email, name, apiKey)
account.putItem("1", "abc@email.com", "john", "key1") // OK
account.putItem("1", "abc@email.com", "john", "key1") // NOT OK, id and email are table HASH and RANGE keys, must be unique

但对于IndexHashRange个键不是唯一的,它们可能有重复的记录/项目。

// assume dummy api putItem(id, email, name, apiKey)
account.putItem("1", "abc@email.com", "john", "key1") // OK
account.putItem("1", "bcd@email.com", "john", "key1") // OK

// assume dummy api putItem(id, email, name, apiKey)
account.putItem("1", "abc@email.com", "john", "key1") // OK
account.putItem("2", "abc@email.com", "john", "key1") // OK

<强>爪哇

http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/document/Index.html

Index实施QueryApiScanApi,但不是GetItemApi

<强>的JavaScript

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property

GetItem 接受IndexName作为参数。

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property

Query接受IndexName作为参数。

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property

Scan接受IndexName作为参数。