Mkaur
Mkaur

Reputation: 33

How to use filter in BatchGetItem

I am fetching multiple items from dynamodb using BatchGetItem. But I need to filter items based on some conditions .

For example: I have a task table having id and status. I need to fetch items of id 1, 2, 3 where status=done.

#set($ids = [1,2,3])
{    
    "operation" : "BatchGetItem",
    "tables" : {
        "userTable": {
            "keys": $util.toJson($ids)
        }
    }
}

Upvotes: 1

Views: 3639

Answers (1)

Tinou
Tinou

Reputation: 6158

Filter expressions are not supported in BatchGetItem. Think of BatchGetItem as a batched version of the GetItem operation. GetItem only supports retrieving an item based on its primary key.

In your example, if the status column is not part of the primary key, then BatchGetItem or GetItem will not work for you.

Provided the task table in your example has id as partition key and status as regular column, there are multiple ways you can achieve the same result depending on the size of your table and the number of items you are expecting to be returned back.

Use BatchGetItem with filtering items in code

If the number of input items is relatively small, you could just use BatchGetItem, and then filter out in code (here in VTL) the ones where status!=done.

Pros: You don't need to change your table schema or add indices

Cons: You will pay for all the Read Capacity Units necessary to retrieve the items before filtering. There will also be a latency cost since your API will download potentially unnecessary items.

Use Scan With IN expression

If the table is small you can scan the entire table and provide an IN filter expression.

Pros: You don't need to change your table schema or add indices

Cons: You will have to scan the entire table, this will be slow and costly for large tables.

These recommendations are valid if you do not wish to change your table key schema.

Upvotes: 7

Related Questions