简体   繁体   English

使用 FilterExpression 的 Dynamodb 查询涉及带有 boto3 的嵌套属性

[英]Dynamodb query using FilterExpression involving nested attributes with boto3

I have below data in my dynamodb table with name as partition-key.我的 dynamodb 表中有以下数据,名称为分区键。

{
    "name":"some-name",
    "age": 30,
    "addresses":[
        "addr-1",
        "addr-2"
    ],
    "status":"active"
}

I have a GSI defined with partition-key on status field.我有一个在状态字段上使用分区键定义的 GSI。

Now, I have to run a query which returns all records whose status is active and whose address list contains a given address.现在,我必须运行一个查询,该查询返回所有状态为活动且地址列表包含给定地址的记录。

   kwargs = {
        'IndexName': 'status-index',
        'KeyConditionExpression': Key('status').eq('active'),
        'FilterExpression': 'contains(#filter, :val)',
        'ExpressionAttributeNames': {
            '#filter': 'addresses'
        },
        'ExpressionAttributeValues': {
            ':val': addr
        }
    }
    response = table.query(**kwargs)

Here, addr is the parameter passes to the function.这里addr是传给function的参数。

All this works great.这一切都很好。 But when I change the record format in the table to below, the query stops working.但是当我将表中的记录格式更改为下面时,查询停止工作。

updated-record-format更新记录格式

(addresses are now nested one level inside - in home key) (地址现在嵌套在内部一层 - 在主键中)

{
    "name":"some-name",
    "age": 30,
    "addresses":{
        "home":[
            "addr-1",
            "addr-2"
        ]
    },
    "status":"active"
}

updated-query更新查询

kwargs = {
            'IndexName': 'status-index',
            'KeyConditionExpression': Key('status').eq('active'),
            'FilterExpression': 'contains(#filter, :val)',
            'ExpressionAttributeNames': {
                '#filter': 'addresses.home' #nested home key on addresses
            },
            'ExpressionAttributeValues': {
                ':val': addr
            }
        }
        response = table.query(**kwargs)

How should I change the query in order to use nested list?我应该如何更改查询以使用嵌套列表?

You've created a string called "addresses.home" , which is not a pointer to a nested attribute.您已经创建了一个名为"addresses.home"的字符串,它不是指向嵌套属性的指针。 Use these args:使用这些参数:

kwargs = {
            'IndexName': 'status-index',
            'KeyConditionExpression': Key('status').eq('active'),
            'FilterExpression': 'contains(#add.#hom, :val)',
            'ExpressionAttributeNames': {
                '#add': 'addresses',
                '#hom': 'home'
            },
            'ExpressionAttributeValues': {
                ':val': addr
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM