DynamoDB - 如何查询嵌套属性 boto3

DynamoDB - How to query a nested attribute boto3

我正在学习 DynamoDB python 教程。此步骤显示如何根据特定键查询 table:http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.04.html.

这是此查询的代码:

from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('Movies')

print("Movies from 1992 - titles A-L, with genres and lead actor")

response = table.query(
    ProjectionExpression="#yr, title, info.genres, info.actors[0]",
    ExpressionAttributeNames={ "#yr": "year" }, # Expression Attribute Names for Projection Expression only.
    KeyConditionExpression=Key('year').eq(1992) & Key('title').between('A', 'L')
)

for i in response[u'Items']:
    print(json.dumps(i, cls=DecimalEncoder))

一个示例响应项目是

{
    "title": "Juice",
    "year": "1992",
    "info": {
        "actors": [
            "Omar Epps"
        ],
        "genres": [
            "Crime",
            "Drama",
            "Thriller"
        ]
    }
}

table有两个关键属性'title'和'year'以及嵌套属性'info'。我想做的是查询数据库并按流派过滤电影,例如获取所有戏剧电影。我不确定如何执行此操作,因为流派键嵌套在信息中。

我试图像这样获取 1992 年的所有剧情片,但结果是空白。

response = table.query(
    KeyConditionExpression=Key('year').eq(1992),
    FilterExpression=Attr('info.genres').eq('Drama')
)

如何使用嵌套信息属性正确过滤此查询?

您可以使用 containsList 数据类型中过滤数据。

流派 - 属性存储为 info 属性中的列表 info 地图数据类型

FilterExpression=Attr('info.genres').contains('Drama')

与已接受的答案不同,要能够过滤具有该属性的所有项目,您需要使用 scan() 而不是 query()query() 需要 KeyCondition,这在您的情况下是不必要的,并迫使您创建包含 f.e 的条件。年.

因此

table.scan(FilterExpression=Attr('info.genres').contains('Drama'))

应该做这份工作