2
假設我的數據結構有幾個數據成員DynamoDBMapper:查詢取決於多個條件
class Data {
@DynamoDBHashKey
@DynamoDBAutoGeneratedKey
String id;
String id1;
String id2;
....
}
現在我想做基於id1
和id2
查詢,如SQL where id1 ="id1" and id2 = "id2"
。我不知怎麼知道我應該讓他們爲全球次要鑰匙狀的方式如下兩種:
製作ID1和ID2不同的指標是這樣的:
@DynamoDBIndexHashKey(globalSecondaryIndexName = "INDEX_ID1") String id1; @DynamoDBIndexHashKey(globalSecondaryIndexName = "INDEX_ID2") String id2; //And then do query it by any of the index name: DynamoDBQueryExpression<Data> query = new DynamoDBQueryExpression<Data>() .withIndexName("INDEX_ID1") //or INDEX_ID2 here .withConsistentRead(false) //GSIs do not support consistent reads .withKeyConditionExpression("id1 = :id1 AND id2 = :id2") .withExpressionAttributeValues(ImmutableMap.of(":id1", new AttributeValue(id1), ":id2", new AttributeValue(id2)));
製作ID1和ID2作爲分區鍵和排序在相同的索引名鍵:
@DynamoDBIndexHashKey(globalSecondaryIndexName = "INDEX_ID1_ID2") String id1; @DynamoDBIndexRangeKey(globalSecondaryIndexName = "INDEX_ID1_ID2") String id2; //And then do query it by the only index name: DynamoDBQueryExpression<Data> query = new DynamoDBQueryExpression<Data>() .withIndexName("INDEX_ID1_ID2") .withConsistentRead(false) //GSIs do not support consistent reads .withKeyConditionExpression("id1 = :id1 AND id2 = :id2") .withExpressionAttributeValues(ImmutableMap.of(":id1", new AttributeValue(id1), ":id2", new AttributeValue(id2)));
哪條路是正確的還是更好?
另外,如果我想根據兩個以上的條件進行查詢(比如說有一個id3),那我該怎麼做呢?
您可以隨時掃描整個表格並根據條件過濾掉。但是,如果你對許多屬性的查詢聽起來很複雜,那麼DynamoDB可能不適合你的需要。 – doorstuck