How to Query Dynamodb Based on Partition Key and Sort Key [Java]

How to query DynamoDB based on Partition Key and Sort Key [Java]?

In order to get the data from DynamoDB using partition key and sort key. You can use the load method present on DynamoDBMapper class.

DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
String product = "ball";
Integer id = 1;
Item itemObj = mapper.load(Items.class, product, id);

Model class i.e. in your case Item class:-

You should have the Item class defined with proper annotation for Hash and Range key.

@DynamoDBTable(tableName = "Items")
public class Item {

private String product;
private Integer id;

@DynamoDBHashKey(attributeName = "Product")
public String getProduct() {
return autoID;
}
@DynamoDBRangeKey(attributeName = "ID")
public String getId() {
return id;
}
}

Dynamodb get a single item based on sort key only

So I finally figured it out, I needed to create create a GSI (Global Secondary Index)

When creating the GCI you define the the sort key as hash key and than you can query the index.

create table:

aws dynamodb create-table \
--table-name customer \
--key-schema \
AttributeName=id,KeyType=HASH \
AttributeName=status,KeyType=RANGE \
--attribute-definitions \
AttributeName=id,AttributeType=S \
AttributeName=status,AttributeType=S \
--provisioned-throughput \
ReadCapacityUnits=5,WriteCapacityUnits=5 \
--table-class STANDARD \
--global-secondary-index '[
{
\"IndexName\": \"id-status\",
\"KeySchema\": [
{
\"AttributeName\": \"status\",
\"KeyType\": \"HASH\"
},
{
\"AttributeName\": \"id\",
\"KeyType\": \"RANGE\"
}
],
\"Projection\": {
\"ProjectionType\": \"ALL\"
},
\"ProvisionedThroughput\": {
\"ReadCapacityUnits\": 1,
\"WriteCapacityUnits\": 1
}
}
]'

My model in Java:

@DynamoDbBean
public class Customer {

private String id;
private String status;
private Instant created;
private Instant updated;

public Customer(){


@DynamoDbPartitionKey
@DynamoDbSecondarySortKey(indexNames = "id-status")
public String getId() {
return id;
}

@DynamoDbSortKey
@DynamoDbSecondaryPartitionKey(indexNames = "id-status")
public String getStatus() {
return status;
}


@DynamoDbAutoGeneratedTimestampAttribute
@DynamoDBTypeConverted(converter = InstantToStringTypeConverter.class)
public Instant getCreated() {
return created;
}

@DynamoDbAutoGeneratedTimestampAttribute
@DynamoDBTypeConverted(converter = InstantToStringTypeConverter.class)
public Instant getUpdated() {
return updated;
}
}

Than query the db:

@Service
public class customerDAO {

static final TableSchema<customer> CUSTOMER_TABLE =
TableSchema.fromBean(Customer.class);

@Autowired
private DynamoDbEnhancedClient dynamoDbEnhancedClient;


public Customer findByStatus() {


DynamoDbTable<Customer> customerTable = dynamoDbEnhancedClient.table("customer", CUSTOIMER_TABLE);



DynamoDbIndex<Customer> secIndex = customerTable.index("id-status");



QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder().partitionValue("PENDING").
build());


PageIterable<Customer> results =
(PageIterable<Customer>) secIndex.query(QueryEnhancedRequest.builder().
.queryConditional(queryConditional)
.build());
results.forEach(p -> p.items().forEach(item -> System.out.println(customer)));

}
}

how to get the records using partition key from a composite primary key in dynamodb

GetItem fetches a specific item, which requires you to specify the complete primary key. If you want to retrieve all items with a common partition key, I believe the method you're looking for is the Query method.

See more here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html

The code would look something like this:

QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("Id = :v_id")
.withValueMap(new ValueMap()
.withString(":v_id", "Amazon DynamoDB#DynamoDB Thread 1"));

how to query or search with one Primary Key and One Attribute in DynamoDb

You seem to be mixing multiple issues here...

For your DynamoDB query:
I think, you should probably use a KeyConditionExpression to filter for symbol (because that is your partition key) combined with a FilterExpression for savetime. The docs provide some examples: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html

Be aware: DynamoDB will load all entries which match the KeyConditionExpression (i.e. this is the load you will pay for) and apply the FilterExpression afterwards. But that is the expected behaviour, you can restrict the query only by your keys.

For your log4j warning, please check the answers to the questions here:

  • Please initialize the log4j system properly warning
  • How to initialize log4j properly?


Related Topics



Leave a reply



Submit