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);
    });
Adam Jungen
  • 407
  • 2
  • 7
  • 23

1 Answers1

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.

Dunedan
  • 7,848
  • 6
  • 42
  • 52
  • 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? – Adam Jungen Aug 13 '17 at 13:20
  • I'm not used to the AWS SDK for Javascript, but according to the [documentation](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property) you simply do a normal query, but specify the name of the GSI to query in the `IndexName` parameter. – Dunedan Aug 13 '17 at 13:48
  • Also check out other sources likes https://stackoverflow.com/questions/39239035/aws-lambda-querying-secondary-index or https://egkatzioura.com/2016/07/02/query-dynamodb-items-with-node-js/ – Dunedan Aug 13 '17 at 13:48
  • Thank you @Dunedan it works fine. Is that also possible to querying with contains? Or do i ask too much :)) – Adam Jungen Aug 13 '17 at 14:05
  • 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. – Dunedan Aug 13 '17 at 14:12