How to concatenate Boto3 filter expression?

Question:

I would like to dynamically create Boto3 filter expression. My goal is to make tool to fetch easily data from DynamoDb with most used filters. I’m trying to store filter expressions in list and then combine them to one expression.

So, if I have this list:

list_of_expressions = [
    Attr("ProcessingStatus").eq("status1"),
    Attr("TransportType").eq("transport_type1"),
]

How can I concatenate it with ‘&’ to get this expression?

filter = Attr("ProcessingStatus").eq("status1") & Attr("TransportType").eq("transport_type1")

So that I could pass it to table.scan like this:

self.table.scan(FilterExpression=filter)
Asked By: RamiR

||

Answers:

A filter expression is a logical expression. If you want to logically AND all the expressions, then you’d want to create a filter expression that looks like this (below example illustrates in a Scan() API call):

Scan({
   "TableName":   "ups1",
   "ReturnConsumedCapacity":   "NONE",
   "FilterExpression":   "#abaa1 = :vbaa1 AND #abaa2 = :vbaa2",
   "ExpressionAttributeNames":   {
      "#abaa1":   "ProcessingStatus",
      "#abaa2":   "TransportType"
   },
   "ExpressionAttributeValues":   {
      ":vbaa1":   {
         "S":   "status1"
      },
      ":vbaa2":   {
         "S":   "Type1"
      }
   },
   "ConsistentRead":   false
})
Answered By: amrith

This is how I resolved the issue:

def construct_filter_expression(self):

    # Initialize an empty filter expression
    filter_expression = None

    # Iterate over the filters
    for filter_ in self.filters:

        if filter_expression is None:
            filter_expression = new_filter_expression
        else:
            new_filter_expression = filter_expression & new_filter_expression
    
    return filter_expression
Answered By: RamiR
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.