You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DynamoDB LSI查询时触发Query condition missed key schema element错误

问题:DynamoDB LSI查询触发"Query condition missed key schema element"错误

问题场景

使用Python boto3操作DynamoDB,通过Local Secondary Index(LSI1)查询PK为ra且LSI排序键start_date大于指定值的数据,尝试用&连接两个Key()条件时,触发"Query condition missed key schema element"错误,即使第一个条件基于分区键。

错误原因

查询LSI时,键条件表达式误用了主表的排序键(SK),而非LSI自身的排序键(start_date)。从表创建代码可知,LSI1的键结构是PK(分区键)+start_date(排序键),但原代码中用Key(self.dynamo.sort_key)(对应主表的SK)作为范围条件的键,不符合LSI的键schema要求,导致报错。

修正后的代码

def get_associated_actions_by_ra(self, ra: str, amount: int, start: Optional[int] = None, end: Optional[int] = None, exclusive_start_key: Optional[str] = None) -> List[AssociatedAction]:
    '''
    Retrieves all associated actions of a member, filtered by an optional time range specified by start and end parameters. The method allows for pagination using the exclusive_start_key parameter to determine the starting point of the action list, and the amount parameter to determine the maximum number of actions to be retrieved.
    If no actions are found, returns []
    '''
    query_string = Key(self.dynamo.partition_key).eq(self.associated_action_partition_key_format(member_ra=ra))

    if start:
        # 替换为主表的SK为LSI1的排序键start_date
        query_string = query_string & Key('start_date').gte(start)
            
    resp = self.dynamo.query(IndexName="LSI1", key_condition_expression=query_string, Select='ALL_ATTRIBUTES')
    associated_actions = []
    for item in resp.get("Items"):
        if item.get("entity") == "associated_action":
            associated_actions.append(AssociatedActionDynamoDTO.from_dynamo(item).to_entity())
    
    return associated_actions

关键说明

  • LSI与主表共享分区键(PK),但拥有独立的排序键(此处为start_date),查询LSI时,键条件必须包含:
    1. 分区键的等值条件(PK = ra)
    2. LSI排序键的范围条件(start_date >= start)
  • 不能将主表的排序键(SK)用于LSI的查询条件中,否则会违反LSI的键schema定义。

内容的提问来源于stack exchange,提问作者Luigi Trevisan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:53:28