Search code examples
amazon-web-servicesamazon-dynamodbaws-sdk-nodejs

AWS DynamoDB querying with values in an array


With the following (TableName: "Table"):

[
 {
  name: "name1",
  values: ["string1", "string2"]
 },
 {
  name: "name2",
  values: ["string1", "string2", "string3"]
 }
]

My partition key would be name, without any sort key. I am trying to query all the items with the same value field. The following is what I have tried:


docClient.query({
      TableName: "Table",
      KeyConditionExpression: "name = :name",
      FilterExpression: "contains(values, :value)",
      ExpressionAttributeValues: {
        ":name": "certain_name",
        ":value": "string1",
      },
    });

Suppose I want to query all the items with the value field of "string1". However, AWS DynamoDB requires the partition key which is unique for all my items. Are there any ways to query all the items with the same value field, without bothering about the partition key?

Or would a better approach be to just get all the items from DynamoDB, and just query with my own methods?

Thank you everyone!


Solution

  • I managed to make it work by using the .scan() method from the aws-sdk.

    const attributName = "values";
    const attributeValue = "string1";
    
    docClient.scan({
      TableName: "Table",
      ExpressionAttributeValues: {
        ":attribute": attributeValue,
      },
      FilterExpression: `contains(${attributName}, :attribute)`,
    });