簡體   English   中英

使用 Python 檢索 DynamoDB 表的最后一個元素

[英]Retrieving the last element of a DynamoDB table using Python

代碼:

import json
import boto3
from boto3.dynamodb.conditions import Key


dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('sample_table')

def lambda_handler(event, context):

    response = table.query(KeyConditionExpression=Key('visit_id').eq('0'),ScanIndexForward=False,Limit = 1)

    return response['Items']['visit_counter']ype here

我收到以下錯誤消息:

{
  "errorMessage": "list indices must be integers or slices, not str",
  "errorType": "TypeError",
  "requestId": "e3fe7fb8-e6e0-41e1-b8e0-d3716f5c4737",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 14, in lambda_handler\n    return response['Items']['visit_counter']\n"
  ]
}

我不知道如何獲得此信息,而且我也沒有在網上找到太多資源來提供此信息。 任何幫助,將不勝感激。

我試過調整傳遞給 KeyConditionExpression 的參數,並調整如何引用傳遞給響應的參數……不確定這些術語是否正確。 這對我來說是比較新的。

即使不知道其他任何事情,閱讀該錯誤在這種情況下實際上也很有用。 它告訴您您正在嘗試從列表中獲取項目,但試圖訪問列表元素,就好像它是一個dict

所以你可以推斷出 response['Items']` 在這種情況下可能是一個列表,你會使用像這樣的索引

response['Items'][0]  # for the first element or
response['Items'][-1] # for the last element

如有疑問,請檢查 AWS sdk 以獲取返回值,或者如果您有能力,請打印/檢查您返回的 object。

如果您查看 boto3 文檔中 dynamodb 的“查詢”: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.query

你會看到 items 實際上是一個列表:

    Response Syntax

{
    'Items': [
        {
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        },
    ],
    'Count': 123,

你在最后一行把ype here當成垃圾。 看起來您沒有完全刪除入門文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM