DynamoDB Query FilterExpression 多条件链接 Python

lis*_*son 6 python amazon-web-services amazon-dynamodb boto3

我正在尝试根据用户提供的特定属性的参数(我们称之为“ ATTRIBUTE1”)以编程方式在 Python 中为 DynamoDB 查询创建 FilterExpression 。

我需要过滤的所有用户提供的参数都在列表中。例如:['Parameter1', 'Parameter2']

然后将采用以下形式 Attr('ATTRIBUTE1').eq(PARAMETER1)&Attr.('ATTRIBUTE1').eq(PARAMETER2)

如何以编程方式为我的 FilterExpression 创建一个 Attr 像上面那样基于用户提供的参数数量的变化?

有时我可能有['Parameter1'],有时我可能有,分别['Parameter1', 'Parameter2', 'Parameter3']需要变成Attr('ATTRIBUTE1').eq('Parameter1')Attr('ATTRIBUTE1').eq('Parameter1')&Attr('ATTRIBUTE1').eq('Parameter2')&Attr('ATTRIBUTE1').eq('Parameter3')

我还没有找到解决方案,希望得到任何指导。提前致谢。

Jac*_*sey 10

这是我能够使其工作的一种紧凑方法:

from functools import reduce
from boto3.dynamodb.conditions import Key, And

response = table.scan(FilterExpression=reduce(And, ([Key(k).eq(v) for k, v in filters.items()])))

Run Code Online (Sandbox Code Playgroud)

例如,filters将是dict这样的:

{
    'Status': 'Approved', 
    'SubmittedBy': 'JackCasey'
}
Run Code Online (Sandbox Code Playgroud)

  • 当我不知道有多少条件时正是我想要的 (2认同)

小智 2

字符串形式的 FilterExpression 和 ExpressionAttributeValues 的组合可以工作,请考虑以下示例:

attrs = ["attribute1", "attribute2", "attribute3"]
user_input = ["parameter1", "paramater2", "parameter3"]
ExpressionAttributeValues = {}
FilterExpression = "";
for index, input in enumerate(attrs):
    if(len(attrs)-1 == index): FilterExpression += input+"=:"+input
    else: FilterExpression += input+" = :"+input + " AND ";

for index, input in enumerate(user_input):
    AttrName = ":" + attrs[index]
    ExpressionAttributeValues[AttrName] = {
        "S" : input
    }

print(ExpressionAttributeValues) 
print(FilterExpression)
Run Code Online (Sandbox Code Playgroud)

那么您可以在查询中使用这两个,更多信息请参见http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#client