使用 IN 子句查询 DynamoDB

Joh*_*ine 6 java amazon-dynamodb

我是 DynamoDB 的新手,想知道我们如何使用 Java 使用 IN 子句查询 DynamoDB 中的表。

我有一个名为items.It`s 模式的表是

1. Product (Partition Key of type String)
2. ID (Sort Key of type int)
3. Date ( attribute of type String)
Run Code Online (Sandbox Code Playgroud)

我想查询类似于

SELECT ID FROM items WHERE Product IN ("apple","orange"). 
Run Code Online (Sandbox Code Playgroud)

或者

SELECT Product FROM items WHERE ID IN (100,200). 
Run Code Online (Sandbox Code Playgroud)

not*_*est 6

由于要求是在没有分区键的情况下获取产品,因此有两个选项可用。

1) 在排序键属性上创建 GSI(全局二级索引)Id以使用 Query API

2)扫描整个表以获取产品 - 因为它扫描整个表效率不高

这两个选项都使用DynamoDB 上可用的IN 运算符

使用 ID 扫描的示例代码:-

Map<String, AttributeValue> attributeValues = new HashMap<>();
attributeValues.put(":id1", new AttributeValue().withN("100"));
attributeValues.put(":id2", new AttributeValue().withN("200"));

DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression()
                                                    .withFilterExpression("ID IN (:id1, :id2)")
                                                    .withExpressionAttributeValues(attributeValues);


PaginatedScanList<yourModelClass> scanList = dynamoDBMapper.scan(yourModelClass.class, dynamoDBScanExpression,
        new DynamoDBMapperConfig(DynamoDBMapperConfig.ConsistentReads.CONSISTENT));

Iterator<yourModelClass> iterator = scanList.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().getTitle());
}
Run Code Online (Sandbox Code Playgroud)

按产品查询:-

1) 不能对分区键使用IN 运算符

2)batchLoad不知道排序键就不能使用API

结论:-

有效的解决方案是在属性上创建 GSI(没有排序键)Id并使用batchLoadAPI。

注意: GSI 的分区键不需要唯一