0

I need to limit the number of results returned for the query

My lambda function is

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

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')

def lambda_handler(event, context):
    response = table.scan(
        FilterExpression=Attr('name').eq('test')
    )
    items = response['Items']
    return items

Please help me how can i add a limit to the number of results it will return

Rohit Goel
  • 3,396
  • 8
  • 56
  • 107

1 Answers1

0

You can try with pagination.

import boto3


def lambda_handler(event, context):
    client = boto3.client('dynamodb')
    paginator = client.get_paginator('scan')
    operation_parameters = {
      'TableName': 'foo',
      'FilterExpression': 'foo > :x',
      'ExpressionAttributeValues': {}
    }

    page_iterator = paginator.paginate(**operation_parameters)
    for page in page_iterator:
        # do something

boto3 source source2

If you want just limiting techinique take a look at this solution but it uses query method not scan.

def full_query(table, **kwargs):
    response = table.query(**kwargs)
    items = response['Items']
    while 'LastEvaluatedKey' in response:
        response = table.query(ExclusiveStartKey=response['LastEvaluatedKey'], **kwards)
        items.extend(response['Items'])
    return items
full_query(Limit=37, KeyConditions={...})

Source : https://stackoverflow.com/a/56468281/9592801

Shakeel
  • 1,869
  • 15
  • 23
  • thanks for the response, can you please tell me how can i use above with the filterexpression, because i cant use key and need to use attr and it can any number of attributes in a query. for eg FilterExpression=Attr('name').eq('test') & Attr('created_at').lt('2020-01-01T00:00:00') – Rohit Goel Oct 05 '20 at 12:50