You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DynamoDB的query()方法代码改写为batch_get_item()实现批量查询

改写完成的代码
import json
import boto3

def lambda_handler(event, context):
    # 兼容两种参数获取场景:直接传cat_id / API Gateway查询字符串传id
    cat_ids_str = ""
    if 'cat_id' in event:
        cat_ids_str = event['cat_id']
    # 适配GET请求查询字符串参数,如/list?id=1,2,3
    elif 'queryStringParameters' in event and event['queryStringParameters'] and 'id' in event['queryStringParameters']:
        cat_ids_str = event['queryStringParameters']['id']
    else:
        return {
            'statusCode': 400,
            'body': json.dumps("Missing required parameter: cat_id or id")
        }
    
    cat_list = cat_ids_str.split(',')
    # 过滤空id,避免无效查询
    cat_list = [cid.strip() for cid in cat_list if cid.strip()]
    if not cat_list:
        return {
            'statusCode': 400,
            'body': json.dumps("No valid cat id provided")
        }
    
    dynamodb_client = boto3.client('dynamodb', region_name="us-east-2")
    try:
        # 构造batch_get_item请求参数
        request_items = {
            'CATS': {
                'Keys': [{'cat_id': {'S': cid}} for cid in cat_list]
            }
        }
        all_items = []
        
        # 循环处理未返回的条目,避免因吞吐量限制导致数据不全
        while request_items:
            response = dynamodb_client.batch_get_item(RequestItems=request_items)
            # 累加当前批次拿到的结果
            all_items.extend(response.get('Responses', {}).get('CATS', []))
            # 赋值未处理的键,继续查询直到全部完成
            request_items = response.get('UnprocessedKeys', {})
        
        return {
            'statusCode': 200,
            'body': all_items
        }
        
    except Exception as e:
        print(f"Query error: {str(e)}")
        return {
            'statusCode': 400,
            'body': json.dumps("We could not retrieve these cats.")
        }
关键说明
  • 参数兼容:同时支持直接传入cat_id参数,以及API Gateway触发GET请求时的查询字符串传参(如/list?id=1,2,3),符合业务需求。
  • 性能优化:相比循环调用query方法,batch_get_item大幅减少了网络请求次数,单批次最多支持查询100条数据,性能提升显著。
  • 鲁棒性处理:新增了空参数校验、无效id过滤,以及UnprocessedKeys循环查询逻辑,避免DynamoDB吞吐量限制导致的部分数据丢失问题,返回结果格式和原有逻辑完全兼容,无需调整下游调用。

内容的提问来源于stack exchange,提问作者Uncle Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:45:03