Search code examples
node.jsamazon-dynamodbdynamodb-queries

Filter Expression for dynamoDB using Node.js


i have a data like this

{
    "ZipCode": 896754,
    "TruckDetails":[
        {
            "truckName":"classic",
            "TruckType":"mini truuck",
            "nos":12
        },
        {
            "truckname":"retro",
            "TruckType":"box",
            "nos":9
        }
    ]
},
{
    "ZipCode": 12234,
    "TruckDetails":[
        {
            "truckName":"test",
            "TruckType":"van",
            "nos":2
        }
    ],
}

Now, I want to filter the data by the TruckType key, and by using a contains expression its returning null value every single time as array has a key and value, how can i filter by the key that is inside of TruckDetails


Solution

  • Thats not something you can do in DynamoDB. You are essentially asking DynamoDB if a string value is contained within a list of maps, but DynamoDB is checking maps, not the strings within the maps.

    You can do something like this, which would return a response as you are checking for a map in the list.

    myMap =  {
                "truckname":"retro",
                "TruckType":"box",
                "nos":9
            }
    
    contains(TruckDetails, :myMap)
    

    To overcome this, you should denormalize your data, so that you have a single truck per item, rather than an item with a list of trucks:

    PK SK Type Name
    896754 12 classic mini truuck
    896754 9 retro box

    Then you create an index on Type, and you can get a list of trucks that match those types.

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html