0
votes

I have a DynamoDB Table "Music". On this it has a GSI with partition key "Category" and sort key "UserRating".

I can query easily as an example for songs that are in "Category" = "Rap" and "UserRating" = 1

What I would like to do is query and just get back all the "Categories". As this is a a GSI and the partition key I have heard you can do it but I am not sure how.

Is it possible or will I have to create a separate GSI on "Category" without the sort key.

Thanks for your help.

1

1 Answers

2
votes

When you don't want to filter by key. You may need to scan the index. The below solution is scanning the index to get all the category (not all distinct category).

Please find below the Java code to get all the Category from GSI. Replace the secondary index name in the below code accordingly.

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