Search code examples
node.jsamazon-dynamodbdynamodb-queries

Dynamodb DB scan: Filter on embedded object in array


Trying to be able to filter on embedded object that looks like:

    "posts": [
        {
            "id": "10e85cf7-acd2-417b-a5dc-1dfb6de606bf",
            "references": [
                {
                    "type": "URL",
                    "title": "How to get dynamodb to only return certain columns",
                },
                {
                    "type": "HASHTAG",
                    "title": "#dynamodb",
                },
            ]
        },
...
]

I am trying to return all posts that have reference of type "HASHTAG" and VALUE "#dynamodb". I have tried this but it always returns null (running in node.js):

const params = {
  TableName: "tableName",
  ScanIndexForward: false,
  FilterExpression: "#references.#type = :referenceValue",
  ExpressionAttributeNames: {
    "#references": "references",
    "#type": "HASHTAG"
  },
  ExpressionAttributeValues: {
      ":referenceValue": "#dynamoDB"
  }
}
const response = await docClient.scan(params).promise();
console.log(response);

And only returns (successfully) an empty array.


Solution

  • Use the contains function to filter on items in a list. In your case, return posts that have an item like :map at the path indicated by #references.

    FilterExpression: 'contains(#references, :map)',
    ExpressionAttributeNames: { '#references': 'references' },
    ExpressionAttributeValues: {
      ':map': {
        type: 'HASHTAG',
        title: '#dynamodb',
      },
    },