簡體   English   中英

如何使用Boto3在dynamodb中搜索地圖列表

[英]How to search for a list of maps in dynamodb using boto3

使用下面的dynamodb中的json,我如何在python中使用boto3搜索session.id == "12ghbcyg"項目?

{
    "name": "John",
    "sessions": [
        {
            "id": "12ghbcyg",
            "foo": "bar"
        }
    ]
}

這是使用contains進行掃描的示例。 請注意,如果表中有數百萬個項目,則掃描是一項昂貴的操作。 通常,如果您不知道分區鍵值,則使用掃描。 即使您不知道分區鍵值,最推薦的解決方案是使用全局二級索引(GSI)並直接查詢索引而不是查詢表。

您可能需要研究以上選項,並確定適合您的用例的方法。

下面的代碼給出了使用contains來使用SCAN API的想法。 如果知道分區鍵值,則可以在QUERY API上類似地使用CONTAINS。

使用包含的掃描:-

from __future__ import print_function # Python 2/3 compatibility
import boto3
from botocore.exceptions import ClientError
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('usertable')

print("Scanning...")

sessionData = {
        "id": "12ghbcyg",
        "foo": "bar"
       }

fe = Attr('sessions').contains(sessionData)

response = table.scan(
        FilterExpression=fe        
    )

for i in response['Items']:

    print(json.dumps(i, cls=DecimalEncoder))

while 'LastEvaluatedKey' in response:
    response = table.scan(        
        FilterExpression=fe,        
        ExclusiveStartKey=response['LastEvaluatedKey']
        )

    for i in response['Items']:
        print(json.dumps(i, cls=DecimalEncoder))

暫無
暫無

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

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