2
votes

I have a table as : AdvgCountries which has two columns a. CountryId (String) (Parition Key) b. CountryName(String) Sort Key While creating the table , I created with only Partition Key and then later added a Global Secondary Index with Index name as:

CountryName-index
Type : GSI
Partition key : CountryId
Sort Key : CountryName

I am able to retrieve CountryName based upon CountryId but unable to retrieve CountryId based upon CountryName. Based upon my reading I found that there are options to do this by providing indexname but I get the following error:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the Query operation: Query condition missed key schema element: CountryId

import boto3
import json
import os
from boto3.dynamodb.conditions import Key, Attr

def query_bycountryname(pCountryname, dynamodb=None):
    if not dynamodb:
        dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

    table = dynamodb.Table('AdvgCountires')
    print(f"table")
    attributes = table.query(
        IndexName="CountryName-index",
        KeyConditionExpression=Key('CountryName').eq(pCountryname),
    )
    if 'Items' in attributes and len(attributes['Items']) == 1:
        attributes = attributes['Items'][0]

    print(f"before return")
    return attributes

if __name__ == '__main__':


    CountryName = "India"
    print(f"Data for {CountryName}")
    countries = query_bycountryname(CountryName)
    for country in countries:
       print(country['CountryId'], ":", country['CountryName'])

Any help is appreciated.

1

1 Answers

1
votes

You can't be able to fetch primary key value based on sort key. DynamoDB does not work like this.

In Dynamodb, each item’s location is determined by the hash value of its partition key.

The Query operation in Amazon DynamoDB finds items based on primary key values.

KeyConditionExpression are used to write conditional statements by using comparison operators that evaluate against a key and limit the items returned. In other words, you can use special operators to include, exclude, and match items by their sort key values.