在dynamoDb中查询全局二级索引



我正在尝试使用查询来检查基于全局辅助索引的表中是否有具有该值的项。我是dynamo的新手,我正在将java与AWS SDK v2一起使用。我不确定是否要进行查询,我只能用索引的名称进行查询,然后使用分区键和排序键。

public Integer checkIfExists(String serialNumber) {
String tableName = System.getenv("TABLE_NAME");
String partitionKeyName="GSI4PK";
String partitionKeyVal="GSI4SK";
String partitionAlias="#a";
// Set up an alias for the partition key name in case it's a reserved word
HashMap<String, String> attrNameAlias = new HashMap<String, String>();
attrNameAlias.put(partitionAlias, partitionKeyName);
// Set up mapping of the partition name with the value
HashMap<String, AttributeValue> attrValues = new HashMap<String, AttributeValue>();
attrValues.put(":val1", AttributeValue.builder().s(serialNumber).build());
QueryRequest queryReq = QueryRequest.builder().tableName(tableName)
.keyConditionExpression(partitionKeyName + " = :val1").
expressionAttributeValues(attrValues).indexName("CertificateDirect").build();
try {
QueryResponse response = dynamoDbClient.query(queryReq);
System.out.println(response.toString());
System.out.println(response.count());
return response.count();
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return -1;
}

我还看到了一个名为partitionAlias的值,我不确定它对有什么作用

这就是使用java和AWS SDK v2 进行查询的方法

private Map<String, AttributeValue> getDynamoQuery(String partitionKeyName, String sortingKeyName,
String partitionKey, String sortingKey, String tableName, String indexName) {
HashMap<String, AttributeValue> attrValues = new HashMap<>();
attrValues.put(":val1", AttributeValue.builder().s(partitionKey).build());
attrValues.put(":val2", AttributeValue.builder().s(sortingKey).build());
QueryRequest queryReq = QueryRequest.builder().tableName(tableName).indexName(indexName)
.keyConditionExpression(partitionKeyName + " = :val1 and " + sortingKeyName + " = :val2")
.expressionAttributeValues(attrValues).build();
QueryResponse response = dynamoDbClient.query(queryReq);
return response.items().get(0);
}

相关内容

  • 没有找到相关文章

最新更新