Query DynamoDB Items with Java By QueryRequest

使用java api:QueryRequest查询dynamodb时,无论什么情况下,必须得set hashkey

1.简单查询(hashkey或者hashkey+rangekey或者hashkey+attribute):

 

public Map<String,AttributeValue> getOne(String email) {
 
    Map<String,String> expressionAttributesNames = new HashMap<>();
    expressionAttributesNames.put("#email","email");
 
    Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
    expressionAttributeValues.put(":emailValue",new AttributeValue().withS(email));
 
    QueryRequest queryRequest = new QueryRequest()
            .withTableName(TABLE_NAME)
            .withKeyConditionExpression("#email = :emailValue")
            .withExpressionAttributeNames(expressionAttributesNames)
            .withExpressionAttributeValues(expressionAttributeValues);
 
    QueryResult queryResult = amazonDynamoDB.query(queryRequest);
 
    List<Map<String,AttributeValue>> attributeValues = queryResult.getItems();
 
    if(attributeValues.size()>0) {
        return attributeValues.get(0);
    } else {
        return null;
    }
}

2.复杂查询(hashkey+非hashkey的属性条件)

public List<Map<String ,AttributeValue>> queryBetween(String email, Date from, Date to) {
 
    List<Map<String,AttributeValue>> items = new ArrayList<>();
 
     val queryRequest = new QueryRequest()
     val expressionAttributesNames = new util.HashMap[String, String]()
     expressionAttributesNames.put("#userId", "userId")
          expressionAttributesNames.put("#appName", "appName")

          val expressionAttributeValues = new util.HashMap[String, AttributeValue]()
          expressionAttributeValues.put(":v_userId", new AttributeValue().withS(uid))
          expressionAttributeValues.put(":v_appName", new AttributeValue().withS(appName))
          queryRequest.withTableName(tableName)
            .withConsistentRead(false)
            .withKeyConditionExpression("#userId = :v_userId")
            .withFilterExpression("#appName = :v_appName")
            .withExpressionAttributeNames(expressionAttributesNames)
            .withExpressionAttributeValues(expressionAttributeValues)
 
    Map<String,AttributeValue> lastKey = null;
 
    do {
 
        QueryResult queryResult = amazonDynamoDB.query(queryRequest);
        List<Map<String,AttributeValue>> results = queryResult.getItems();
        items.addAll(results);
        lastKey = queryResult.getLastEvaluatedKey();
        queryRequest.setExclusiveStartKey(lastKey);
    } while (lastKey!=null);
 
    return items;
}

需要注意的是:dynamodb查询的时候是按照page进行返回的,如果查询结果有多页,则返回的时候需要last evaluated key 做判断处理

3.SCAN

public void downloadAllRecords() throws InterruptedException, IOException {
        final Object[] FILE_HEADER = {"id", "userId", "createdDate"};
        CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
        CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(tableName + ".csv"), csvFormat);
        csvPrinter.printRecord(FILE_HEADER);

        ScanRequest scanRequest = new ScanRequest()
                .withTableName(tableName)
                .withConsistentRead(false)
                .withLimit(100)
                .withAttributesToGet("id", "userId", "createdDate");
        int counter = 0;
        do {
            ScanResult result = client.scan(scanRequest);
            Map<String, AttributeValue> lastEvaluatedKey = result.getLastEvaluatedKey();
            for (Map<String, AttributeValue> item : result.getItems()) {
                List record = new ArrayList();
                System.out.println(item);
                AttributeValue userIdAttribute = item.getOrDefault("userId", new AttributeValue());
                AttributeValue idAttribute = item.getOrDefault("id", new AttributeValue());
                AttributeValue createdDateAttribute = item.getOrDefault("createdDate", new AttributeValue());
                record.add(idAttribute.getS());
                record.add(userIdAttribute.getS());
                record.add(createdDateAttribute.getS());
                csvPrinter.printRecord(record);
                TimeUnit.MILLISECONDS.sleep(50);
            }
            scanRequest.setExclusiveStartKey(lastEvaluatedKey); 
        } while (scanRequest.getExclusiveStartKey() != null);
        csvPrinter.flush();
        csvPrinter.close();
        System.out.println("CSV file generated successfully.");
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值