在DynamoDB中,可以对包含集合值的字段进行索引和查询。在创建表格时,可以通过设置“Global Secondary Index”选项并指定Projection属性来创建索引。其中Projection属性可以设置为“INCLUDE”或“ALL”,以允许对集合类型字段进行索引和查询。
示例代码:
创建表格:
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.create_table(
TableName='myTable',
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
{
'AttributeName': 'fieldname',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
},
{
'AttributeName': 'fieldname',
'AttributeType': 'SS'
}
],
GlobalSecondaryIndexes=[
{
'IndexName': 'myIndex',
'KeySchema': [
{
'AttributeName': 'fieldname',
'KeyType': 'HASH'
}
],
'Projection': {
'ProjectionType': 'INCLUDE',
'NonKeyAttributes': [
'myField1', 'myField2'
]
}
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
table.meta.client.get_waiter('table_exists').wait(TableName='myTable')
在创建索引时,注意Projection属性的设置。在查询时,可以使用“CONTAINS”运算符来查询集合中是否包含某个特定值:
response = table.query(
IndexName='myIndex',
KeyConditionExpression=Key('fieldname').eq('myValue') & Key('id').gte('myId'),
FilterExpression=Attr('myField1').contains('valueToSearch')
)