GetItem from secondary index with DynamoDB
I'm just getting started using DynamoDB and setting up an "accounts" table.
I have set up an additional index so that I can query the user and user api key. None of these values ββare primary keys, as they are volatile and subject to change.
The table is built with
TableName: "Accounts",
KeySchema: [
{ AttributeName: "id", KeyType: "HASH" },
{ AttributeName: "email", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "id", AttributeType: "S" },
{ AttributeName: "email", AttributeType: "S" }
]
And the index
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"
},
Now I am trying to get the uses account by querying the index ApiAccounts
.
I'm trying to
dynamoClient.get({
TableName: 'Accounts',
IndexName: 'ApiAccounts',
Key: {
name: nameKeyArray[0],
apiKey: nameKeyArray[1]
}, callback)
But I am getting an error One of the required keys was not given a value
, which leads me to believe that I cannot "get" by the index? Or am I referencing the index incorrectly. Can anyone clarify for me?
The API name and key are unique, so I think I want to avoid the request or scan if possible
source to share
I guess it's not that clear from the official docs. You can perform an operation Scan
or Query
with an index GSI
, but not an operation GetItem
.
For each entry / item in, Table
they must have unique keys HASH
and RANGE
.
those.
// 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
But for Index
keys Hash
and Range
are not unique, they can contain duplicate records / elements.
those.
// 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
those.
// 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
Java
Index
implements QueryApi
and ScanApi
, but not GetItemApi
.
JavaScript
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property
GetItem
does not take IndexName
as a parameter.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property
Query
takes IndexName
as parameter.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property
Scan
takes IndexName
as parameter.
source to share