简体   繁体   中英

Dynamodb - query by GSI using python boto3

I`m using python boto3 to work with dynamodb. I've created a table using the following script:

 cls.table = dynamodb.create_table(
        TableName='table-unittest',
        KeySchema=[
            {
                'AttributeName': 'id',
                'KeyType': 'HASH',
            },
            {
                'AttributeName': 'user_name',
                'KeyType': 'RANGE',
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'id',
                'AttributeType': 'N',
            },
            {
                'AttributeName': 'user_name',
                'AttributeType': 'S',
            },
            {
                'AttributeName': 'age',
                'AttributeType': 'N',
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 2,
            'WriteCapacityUnits': 2,
        },
        GlobalSecondaryIndexes=[
            {
                'IndexName': 'age-index',
                'KeySchema': [
                    {
                        'AttributeName': 'age',
                        'KeyType': 'HASH',
                    },
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY',
                },
                'ProvisionedThroughput': {
                    'ReadCapacityUnits': 2,
                    'WriteCapacityUnits': 2,
                }
            },
        ],
    )

But, when querying the table by its age-index global secondary index, i receive the following message:

Query condition missed key schema element: age

Here is the params i pass to the boto3 query method:

{
'ConsistentRead': False,
'IndexName': 'age-index',
'QueryFilter': {
    'age': {
        'ComparisonOperator': 'GT',
        'AttributeValueList': [18]
    }
},

'TableName': 'table-unittest',
'ScanIndexForward': False,
'KeyConditions': {
    'id': {
        'ComparisonOperator': 'EQ',
        'AttributeValueList': [222]
    }
}

}

you cant query your global secondary index using your table hash key as conditions (id)

you only can:

  1. Query only on your global secondary index (age) and in application level filter by id
  2. create local secondary index where hash is 'id' and range is 'age', then you can query where id=222 and age =23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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