8

enter image description here

Hi dynamodb community,

So the table in question is MLA_USER_AUTH. As you see it has as partition key and as sort key. I want to be able to query the database using both user_id and email.

Sometimes I need to find the user associated with the email and sometimes the userid. Both email and userid attributes are unique for every visitor. is there any way it can be done?

This is my current query. This obviously doesnt work. As it throws the error: ValidationException: Query condition missed key schema element: UserID

var params = {
        TableName : 'MLA_USER_AUTH',
        KeyConditionExpression: "Email = :email",
        ExpressionAttributeValues:{
            ":email": { "S" : email } 
        }
    };
    dynamodb.query(params, function(err, data) { 

Are GSIs my only option. Any help appreciated

Thanks, Ninjasoar

Community
  • 1
  • 1
Rajan Soni
  • 163
  • 1
  • 2
  • 9

3 Answers3

14

A Secondary Index would do want you want.

// definition
{
    TableName: "MLA_USER_AUTH",
    AttributeDefinitions:[
    {
        AttributeName: "Email",
        AttributeType: "S"
    }
    ],
    GlobalSecondaryIndexUpdates: [
    {
        Create: {
            IndexName: "emailIndex",
            KeySchema: [
                {AttributeName: "Email", KeyType: "HASH"}
            ]
        }
    }
    ]
}

// Query
{
    TableName : "MLA_USER_AUTH",
    IndexName: "emailIndex",
    KeyConditionExpression: "Email = :email",
    ExpressionAttributeValues:{
        ":email": { "S" : email } 
    }
}

See http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.JsShell.06.html for more information on creating them.

kimmiju
  • 161
  • 1
  • 3
7

As Mark B said, you need partition-key to query- you can't do it using sort-key alone.

So, the only way out for you is to create a GSI with email as the partition-key.

ketan vijayvargiya
  • 5,409
  • 1
  • 21
  • 34
  • One can scan with those. I have not seen it scanned more than one record. I would recommend scanning with sort key and checkout performance. – Kannaiyan Sep 09 '17 at 17:21
0

You can't query without the partition key, but you can scan. http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.NodeJs.04.html#GettingStarted.NodeJs.04.Scan

Mark B
  • 183,023
  • 24
  • 297
  • 295