【发布时间】:2017-02-14 19:25:33
【问题描述】:
假设我的数据结构有几个数据成员
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 可能不适合您的需求。
标签: amazon-web-services amazon-dynamodb nosql