boden
boden

Reputation: 1681

How can i use IN condition for DynamoDB

I need fetch data from DynamoDB by user ids, for it I want to use IN condition but I can't find instruction how it use, can you help me? I have some code, how replace userId = :id1 OR userId = :id2 to userId IN :ids ? How set userIds in :ids ?

public List<Data> getByUserIds(List<Long> userIds) {
    Table table = dynamoDB.getTable(getTableName());
    ScanSpec scanSpec = new ScanSpec()
            .withFilterExpression("userId = :id1 OR userId = :id2")
            .withValueMap(new ValueMap()
                    .withNumber(":id1", userIds.get(0))
                    .withNumber(":id2", userIds.get(1))
            );
    ItemCollection<ScanOutcome> scanOutcome = table.scan(scanSpec);
    return convertItemToData(scanOutcome.iterator());
}

Thanks!

Upvotes: 2

Views: 1183

Answers (2)

boden
boden

Reputation: 1681

I've implemented the solution below

public List<HistoricalData> getByUserIdAndLocation(List<Long> userIds) {
    Table table = dynamoDB.getTable(getTableName());
    ScanSpec scanSpec = new ScanSpec()
            .withFilterExpression("userId IN (" + buildInFilterExpression(userIds) + ")")
            .withValueMap(
                    buildValueMap(userIds)
            );
    ItemCollection<ScanOutcome> scanOutcome = table.scan(scanSpec);
    return convertItemToHistoricalData(scanOutcome.iterator());
}

private String buildInFilterExpression(List<Long> userIds) {
    StringBuilder builder = new StringBuilder();
    for (Long id : userIds) {
        builder.append(":user" + id + ",");
    }
    return builder.toString().substring(0, builder.length() - 1);
}

private ValueMap buildValueMap(List<Long> userIds) {
    ValueMap valueMap = new ValueMap();
    for (Long id : userIds) {
        valueMap.withNumber(":user" + id, id);
    }
    return valueMap;
}

I think that need to use valueMap.withList instead valueMap.withNumber but it does not work for me...

Upvotes: 3

Bruno Buccolo
Bruno Buccolo

Reputation: 1111

You can use the BatchGetItem API to fetch both users in the same query.

Upvotes: 0

Related Questions