Header Ads

Header ADS

Add multiple filters in query

 

DynamoDB তে read operations with multiple filter 


1️⃣ AWS CLI – Query with multiple filters

DynamoDB CLI এ মূলভাবে Query এবং Scan দুইটি read operation আছে।

  1. Query → Partition Key জানা থাকতে হবে, fast

  2. Scan → পুরো table traverse করে, slow কিন্তু flexible


🔹 Example Table

Table: Products
Partition Key: category
Sort Key: product_id

Attributes: name, price, stock

🔹 1. Query + Multiple Conditions

CLI syntax:

aws dynamodb query \
    --table-name Products \
    --key-condition-expression "category = :c AND product_id BETWEEN :start AND :end" \
    --filter-expression "price >= :p AND stock > :s" \
    --expression-attribute-values '{
        ":c": {"S": "Electronics"},
        ":start": {"S": "100"},
        ":end": {"S": "200"},
        ":p": {"N": "5000"},
        ":s": {"N": "0"}
    }' \
    --endpoint-url http://localhost:8000

Explanation:

  • key-condition-expression → Partition + Sort Key filter (must)

  • filter-expression → additional attribute filters

  • Only items matching both key and filter conditions return হবে


🔹 2. Scan + Multiple Conditions

যদি Partition Key না জানা থাকে, Scan করতে হবে:

aws dynamodb scan \
    --table-name Products \
    --filter-expression "category = :c AND price >= :p AND stock > :s" \
    --expression-attribute-values '{
        ":c": {"S": "Electronics"},
        ":p": {"N": "5000"},
        ":s": {"N": "0"}
    }' \
    --endpoint-url http://localhost:8000

Scan পুরো table traverse করবে

Filter-expression পরে apply হবে


2️⃣ Python boto3 – Query with multiple filters

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

dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:8000')
table = dynamodb.Table('Products')

response = table.query(
    KeyConditionExpression=Key('category').eq('Electronics') & Key('product_id').between('100', '200'),
    FilterExpression=Attr('price').gte(5000) & Attr('stock').gt(0)
)

for item in response['Items']:
    print(item)

3️⃣ Python boto3 – Scan with multiple filters

response = table.scan(
    FilterExpression=Attr('category').eq('Electronics') &
                     Attr('price').gte(5000) &
                     Attr('stock').gt(0)
)

for item in response['Items']:
    print(item)

🔑 Key Points

  1. Query = Partition Key + optional Sort Key → fast

  2. Scan = Full table → slow, use only when Partition Key unknown

  3. FilterExpression = attribute-based filtering

  4. Multiple conditions → & (AND) , | (OR)

  5. Comparison operators: .eq(), .gt(), .lt(), .gte(), .lte(), .between()



Powered by Blogger.