【问题标题】:DynamoDB Can I query just the values of a GSI Index when it is a GSI with sort KeyDynamoDB 当 GSI 是具有排序键的 GSI 时,我可以只查询 GSI 索引的值吗
【发布时间】:2016-05-26 14:57:11
【问题描述】:
我有一个 DynamoDB 表“音乐”。在这方面,它有一个 GSI,其分区键为“Category”,排序键为“UserRating”。
作为示例,我可以轻松查询“类别”=“说唱”和“用户评分”=1 中的歌曲
我想做的是查询并取回所有“类别”。因为这是一个 GSI 和分区键,我听说你可以这样做,但我不确定如何。
是否有可能或者我必须在没有排序键的“类别”上创建一个单独的 GSI。
感谢您的帮助。
【问题讨论】:
标签:
amazon-web-services
amazon-dynamodb
【解决方案1】:
当您不想按键过滤时。您可能需要扫描索引。下面的解决方案是扫描索引以获取所有类别(不是所有不同的类别)。
请在下面找到 Java 代码以从 GSI 获取所有类别。相应地替换以下代码中的二级索引名称。
List<String> categoryList = new ArrayList<>();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Table table = dynamoDB.getTable("Music");
Index index = table.getIndex("Secondary Index Name");
ItemCollection<ScanOutcome> items = null;
ScanSpec scanSpec = new ScanSpec().withSelect(Select.SPECIFIC_ATTRIBUTES).withAttributesToGet("Category");
items = index.scan(scanSpec);
Iterator<Item> pageIterator = items.iterator();
while (pageIterator.hasNext() ) {
categoryList.add(pageIterator.next().getString("Category"));
}