Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

I am very new to Dynamo DB and maybe this is a very trivial question, but I went through the documents of Dynamo DB and stack overflow questions but I couldn't find a single link which tells how to query DDB for GSI which has only hash key and there are no range key specified for the same.

I get the exception Illegal query expression: No hash key condition is found in the query.

2 Answers

0 votes
by (44.4k points)

You should use this on your DynamoDB annotated model object:

To show that for the GSI it’s the hash key using this @DynamoDBIndexHashKey(globalSecondaryIndexName = "gsiIndexName) :

@DynamoDBTable(tableName = "myTable")

public class MyTable {

    ...

 

    @DynamoDBIndexHashKey(globalSecondaryIndexName = "myGsi")

    public String getGsiHk() {

        return gsiHk;

    }

 

    ...

}

Use the query method on DynamoDBMapper after that:

final MyTable gsiKeyObj = new MyTable();

gsiKeyObj.setGsiHk("myGsiHkValue");

final DynamoDBQueryExpression<MyTable> queryExpression = 

    new DynamoDBQueryExpression<>();

queryExpression.setHashKeyValues(gsiKeyObj);

queryExpression.setIndexName("myGsi");

queryExpression.setConsistentRead(false);   // cannot use consistent read on GSI

final PaginatedQueryList<MyTable> results = 

    mapper.query(MyTable.class, queryExpression);

0 votes
ago by (1.9k points)

To query DDB for GSI which has only a hash key and there are no range keys specified for the same. Since you have no range key in your GSI, query() operation can’t be used but you can use the scan() operation instead.

scan() operation:

  • This Operation scans all items in the table or a specific index.
  • It reads all items so it can be less efficient than query() for large tables
  • Allows you to filter results using FilterExpression to match your desired criteria based on your GSI hash key.
Code:

from boto3.dynamodb.conditions import Key, Attr

def query_gsi_with_hash_key_only(dynamodb_client, table_name, gsi_name, hash_key_value):

    try:

        table = dynamodb_client.Table(table_name)

        response = table.scan(

            IndexName=gsi_name,

            FilterExpression=Attr('hash_key_name').eq(hash_key_value) 

        )

        return response['Items']

    except Exception as e:

        print(f"Error querying GSI: {e}")

        return []

dynamodb_client = boto3.client('dynamodb') 

table_name = 'your_table_name'

gsi_name = 'your_gsi_name'

hash_key_value = 'your_hash_key_value'

results = query_gsi_with_hash_key_only(dynamodb_client, table_name, gsi_name, hash_key_value)

print(results)

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
asked Jul 27, 2019 in AWS by yuvraj (19.1k points)

31k questions

32.9k answers

507 comments

693 users

Browse Categories

...