首页 文章

DynamoDB当我是一个带有排序键的GSI时,我可以只查询GSI索引的值

提问于
浏览
0

我有一个DynamoDB表“音乐” . 在此它有一个GSI与分区键“类别”和排序键“UserRating” .

我可以轻松地查询“Category”=“Rap”和“UserRating”= 1的歌曲的示例

我想做的是查询并返回所有“类别” . 因为这是一个GSI和分区密钥,我听说你可以做到,但我不知道如何 .

是否有可能或者我必须在没有排序键的情况下在“类别”上创建单独的GSI .

谢谢你的帮助 .

1 回答

  • 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"));
        }
    

相关问题