Search code examples
pythonboto3

How to concatenate Boto3 filter expression?


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)

Solution

  • 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