2017-05-02 32 views
2

我剛開始使用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密鑰是唯一的,所以我覺得我想避免的查詢或掃描如果可能的話

回答

6

我想它不是來自官方的文檔很清楚,但你可以在GSI指數進行ScanQuery,但不是GetItem

對於Table中的每個記錄/項目,它們必須具有唯一的HASHRANGE鍵。

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

Index「ES,HashRange鍵不是唯一的,他們可能已經重複記錄/項目。

// assume dummy api putItem(id, email, name, apiKey) 
account.putItem("1", "[email protected]", "john", "key1") // OK 
account.putItem("1", "[email protected]", "john", "key1") // OK 

// assume dummy api putItem(id, email, name, apiKey) 
account.putItem("1", "[email protected]", "john", "key1") // OK 
account.putItem("2", "[email protected]", "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作爲參數。

+0

感謝您的澄清,我是全部結束http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.JavaScript.html - 我假設查詢將最適合我的用例和性能? – pedalpete

+1

@pedalpete是的,但請注意,查詢索引時可能會有重複記錄返回,因爲索引的哈希和範圍鍵不是唯一的,這與Table不同。 –

相關問題