【问题标题】:boto3 resource for querying dynamodb : Query condition missed key schema element用于查询 dynamodb 的 boto3 资源:查询条件缺少关键架构元素
【发布时间】:2020-08-03 13:59:13
【问题描述】:

我有一个表格:AdvgCountries,它有两列 一种。 CountryId(字符串)(分区键) 湾。 CountryName(String) 排序键 在创建表时,我只使用分区键创建,然后添加了一个全局二级索引,索引名称为:

CountryName-index
Type : GSI
Partition key : CountryId
Sort Key : CountryName

我可以根据CountryId 检索CountryName,但无法根据 CountryName 检索 CountryId。根据我的阅读,我发现可以通过提供 indexname 来执行此操作,但我收到以下错误:

botocore.exceptions.ClientError:发生错误 (ValidationException) 调用 Query 操作时:Query 条件缺少关键架构元素:CountryId

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

def query_bycountryname(pCountryname, dynamodb=None):
    if not dynamodb:
        dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

    table = dynamodb.Table('AdvgCountires')
    print(f"table")
    attributes = table.query(
        IndexName="CountryName-index",
        KeyConditionExpression=Key('CountryName').eq(pCountryname),
    )
    if 'Items' in attributes and len(attributes['Items']) == 1:
        attributes = attributes['Items'][0]

    print(f"before return")
    return attributes

if __name__ == '__main__':


    CountryName = "India"
    print(f"Data for {CountryName}")
    countries = query_bycountryname(CountryName)
    for country in countries:
       print(country['CountryId'], ":", country['CountryName'])

感谢任何帮助。

【问题讨论】:

    标签: amazon-dynamodb boto3


    【解决方案1】:

    您无法根据排序键获取主键值。 DynamoDB 不能这样工作。

    在 Dynamodb 中,每个项目的位置由 它的分区键。

    The Query operation in Amazon DynamoDB finds items based on primary key values.

    KeyConditionExpression 用于编写条件语句 使用比较运算符对键进行评估并限制 退回的物品。换句话说,您可以使用特殊运算符来 按排序键值包含、排除和匹配项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2019-09-30
      • 2018-05-20
      • 1970-01-01
      • 2020-07-15
      相关资源
      最近更新 更多