The Walrus
The Walrus

Reputation: 1208

Query dynamodb for a specific field

how do I query dynamodb for all items that match a specific rule?

I am building an online shop (like Asos) and in dynamodb I have a products table. all of the products have the field 'category'. so I just want to do a simple query whereby I say something like

FROM products WHERE category == 'trainers'

I have managed to get it working so I scan the whole table and return me all the products but i want more specific queries now

I assume I want to use something like: KeyConditionExpression but I keep getting an error when I do this

edited question:

enter image description here

code:

componentDidMount() {
    console.log('mounted');
    const AWS = window.AWS;
    const params = {
      TableName: 'Products',
      FilterExpression: "category = trainers"
    };
...secret key code
ddb.scan(params, (err, data) => {
  if (err) {
    console.log(err, err.stack);
  } else {
    console.log(data);
    this.setState({ products: data })
  }
});

Upvotes: 5

Views: 12974

Answers (2)

F_SO_K
F_SO_K

Reputation: 14819

Try this

 var params = {
  ExpressionAttributeValues: {
   ":catval": {
     S: "trainers"
    }
  }, 
  FilterExpression: "category = :catval", 
  TableName: "Products"
 };
 dynamodb.scan(params, function(err, data) {
  if (err) console.log(err, err.stack);
  else     console.log(data);

EDIT: You can't use literals in expressions. You define an ExpressionAttributeValue, i've called yours ":catval" but you can call it anything you like. The 'S' means a string, so basically you define an ExpressionAttributeValue with type String and value "trainers". Then when you apply the FilterExpression you put in your ExpressionAttributeValue, not the literal.

Upvotes: 2

Deividi Silva
Deividi Silva

Reputation: 846

KeyConditionExpression is for when you want data filtered by primary key attributes. If that is not your case, you should use FilterExpression. A filter expression determines which items within the Scan results should be returned to you. All of the other results are discarded.

Upvotes: 1

Related Questions