1

Im new to DynamoDB and have a table which is "feeds" and partition key is "id" and i have 3 other attributes which are "category", "description", "pubDate".

I want to query the "category" attribute. But it doesn't work, because i can only query the partition key (hashkey), if im right.

Now my query is that which doesnt work;

let category = event.category;

    const params = {
        Key: {
            "category": {
                S: category
            }
        },
        TableName: "feeds"
    };
    dynamodb.getItem(params, function (err, data) {
        if (err) {
            console.log(err);
            callback(err);
        }
        else {
            console.log(data);
            callback(null, data);
        }
    });

How can i make it work? I tried to write a scan query but i couldn't understand the documentation of AWS good.

Edit: I did make it work with the help of Dunedan. Here is the working code,

var params = {
      TableName: 'feeds',
      IndexName: 'category-index',
      KeyConditionExpression: 'category = :category',
      ExpressionAttributeValues: {
        ':category': 'backup',
      }
    };

    var docClient = new AWS.DynamoDB.DocumentClient();

    docClient.query(params, function(err, data) {
       if (err) callback(err);
       else callback(null, data);
    });

1 Answer 1

1

If your application will regularly query for the category, you should check out Global Secondary Indexes (GSI), which allow you to generate a projection of your data with another key than the original hash key as the key you can use to query.

Scanning and filtering as you suggested doesn't scale very well, as it fetches all data in the table and just filters the results.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi @Dunedan, is there any good documentation about Global Secondary Indexes queries with Javascript? I mean can you give me an example? How can i query category?
I'm not used to the AWS SDK for Javascript, but according to the documentation you simply do a normal query, but specify the name of the GSI to query in the IndexName parameter.
Thank you @Dunedan it works fine. Is that also possible to querying with contains? Or do i ask too much :))
Afaik query with contains is not possible, so you'd either have to fall back to scanning the GSI with a filter or think about possiblities to strucuture your data differently so you don't need such queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.