skip to Main Content

I’m using python to query a dynamodb table,however I’m using two keys in the getitem call that are not part of the primary key or sort key.I created a global index that contains these two keys, but I still get the same error.

  response = table.get_item(
            Key={
                'player_id': 22892251,'type': 1
            }
        )
  item = response['Item']
  print(item)

enter image description here

2

Answers


  1. You cannot issue a GetItem against a secondary index as items are not unique.

    You must use a Query request.

    response = table.query(
    IndexName='player_id-type-index'
    KeyConditionExpression=Key('player_id').eq(22892251) & Key('type').eq(1) )
    items = response['Items']
    print(items)
    
    Login or Signup to reply.
  2. You’re trying to use GetItem to fetch data from a global secondary index. This is not supported. The GetItem API returns exactly 1 item, which is only possible because the Primary Key (Partition + Sort Key) is guaranteed to be unique in the base table.

    This is not the case for global secondary indexes, which is why GetItem is not supported here. It requires a guarantee that the underlying data structure does not give.

    The way to fetch this data is to use the Query operation that can return multiple items:

    import boto3
    
    from boto3.dynamodb.conditions import Key
    
    table = boto3.resource("dynamodb").Table("table_name")
    
    response = table.query(
        KeyConditionExpression=Key("player_id").eq(number) & Key("type").eq(number),
        IndexName="player_id-type-index"
    )
    
    items = response["Items"]
    
    if len(items) > 1:
        raise RuntimeError("Something broke our unique expectation")
    
    print(items[0])
    
    

    It’s on your app to ensure that the entries are unique if you require it. Here’s an example that lets you detect if this assumption got broken somehow.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search