1
votes

I have this dynamodb query:

var unitsData = await(docClient.query({
                TableName:"test-units-" + config.stage,
                IndexName:"unitOwnerIndexDev",
                KeyConditionExpression : 'ownerName= :hkey',
                ExpressionAttributeValues : {
                    ':hkey': event.ownerName
                },
                Key:{"unitID": event.unitID
                }
            }).promise());

I am expecting it to return only one row with unique unitID and its owner. But returned data isn't unique with respect to unitID. It does filter out with respect to owner. unitID is primary key (HASH) and owner is global secondary index.

This is my table:

aws dynamodb create-table --table-name test-units-dev --attribute-definitions AttributeName=unitID,AttributeType=S AttributeName=ownerName,AttributeType=S --key-schema AttributeName=unitID,KeyType=HASH --global-secondary-indexes IndexName=unitOwnerIndexDev,KeySchema=["{AttributeName=ownerName,KeyType=HASH}"],Projection="{ProjectionType=ALL}",ProvisionedThroughput="{ReadCapacityUnits=1,WriteCapacityUnits=1}" --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --endpoint-url http://localhost:8000
1

1 Answers

2
votes

Please use FilterExpression to filter the data by non-key attributes. In the above case, unitID is not part of key in GSI.

The below params works fine for me (i.e. the result has only one item).

var params = {
    TableName : table,
    IndexName : "unitOwnerIndexDev",
    KeyConditionExpression : 'ownerName= :hkey',
    FilterExpression : 'unitID = :unitIdVal',  
    ExpressionAttributeValues : {
        ':hkey' : 'owner1',
        ':unitIdVal' : '1'
    }
};