Python Boto3 查询 GSI 时的 DynamoDB Bug

0

【以下的问题经过翻译处理】 假设在DynamoDB中有以下3行数据

coin_transaction_idcoin_amountcustomer_idtransaction_time
027072a5-fdf3-48ed-b36e-90a317d63c3180bfbd221a-bc1f-4e96-943f-d809bb5e5af32022-06-15T18:52:40.044239+00:00
f074d831-5791-4ba1-a596-ab114d14eaac40bfbd221a-bc1f-4e96-943f-d809bb5e5af32022-06-15T17:42:36.830859+00:00
adafd372-03de-437a-887e-9027007517a2160bfbd221a-bc1f-4e96-943f-d809bb5e5af32022-06-15T17:42:36.830859+00:00

GSI 分区键:customer_id 排序键:transaction_time

当使用以下代码在lambda中通过Python boto 3查询数据时,与行3相同的GSI的行2无法检索出来。结果返回仅可检索到行1和行3。

      coinResp = coinTable.query(
                IndexName = "customer_id-transaction_time-index",
                KeyConditionExpression = 'customer_id = :ci and transaction_time between :date1 and :date2',
                ExpressionAttributeValues = {
                    ':ci' : customerID,
                    ':date1' : startDate,
                    ':date2' : endDate,
                },
                Limit = 1,
                ExclusiveStartKey = receivedLastEvaluatedKey,
                ScanIndexForward = False,
            )

这是一个bug吗?

profile picture
EXPERTE
gefragt vor 8 Monaten40 Aufrufe
1 Antwort
0

【以下的回答经过翻译处理】 您现在假设基表中的第二行将成为GSI中的第二行,但事实并非如此。基表中的项目按分区键分组并按排序键排序。而在GSI中,具有相同分区/排序键组合的多个项目可以具有多个项目,这意味着无法保证顺序。

至于您的问题,您在代码中将LEK设置为空字符串,导致您错过了响应中的最后一条记录。尝试以下代码片段:

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('cust1')
customerID = 'bfbd221a-bc1f-4e96-943f-d809bb5e5af3'
startDate = '2022-06-14T17:42:36.830859+00:00'
endDate = '2022-06-16T18:52:40.044239+00:00'

def processItems(items):
    print(items)

kwargs = {
    'IndexName' : "my-index",
    'KeyConditionExpression' : 'customer_id = :ci and transaction_time between :date1 and :date2',
    'ExpressionAttributeValues' : {
        ':ci' : customerID,
        ':date1' : startDate,
        ':date2' : endDate,
    },
    'Limit' : 1,
    'ScanIndexForward' : False
}
   

while True:
    response = table.query( **kwargs )
    processItems( response[ u'Items' ] )
    if 'LastEvaluatedKey' in response:
        kwargs[ 'ExclusiveStartKey' ] = response[ 'LastEvaluatedKey' ]
    else:
        break

profile picture
EXPERTE
beantwortet vor 8 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen