首页 文章

通过哈希和范围键查询DynamoDB表

提问于
浏览
2

我想使用AWS SDK for Ruby V2通过哈希和范围键查询DynamoDB表 . 以下代码可以工作 .

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo'],
      comparison_operator: 'EQ'
    }
  }
)

但是,我想将多个项目设置为范围键条件 .

像这样:

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo', 'bar'],
      comparison_operator: 'EQ'
    }
  }
)

此代码返回 lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:incall': One or more parameter values were invalid: Invalid number of argument(s) for the EQ ComparisonOperator (Aws::DynamoDB::Errors::ValidationException)` .

我试过使用 IN 运算符 .

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
  table_name: TABLE_NAME,
  key_conditions: {
    HASH_KEY_NAME => {
      attribute_value_list: ['hoge'],
      comparison_operator: 'EQ'
    },
    RANGE_KEY_NAME => {
      attribute_value_list: ['foo', 'bar'],
      comparison_operator: 'IN'
    }
  }
)

它返回 lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:incall': Attempted conditional constraint is not an indexable operation (Aws::DynamoDB::Errors::ValidationException)` .

如何通过一个哈希键和多个范围键查询DynamoDB表?

1 回答

  • 0

    Query 操作仅允许 Range Key 上的以下运算符:

    EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN
    

    对于Query操作,Condition用于指定查询表或索引时要使用的KeyCondition . 对于KeyConditions,仅支持以下比较运算符:EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN来源:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html

    您仍然可以使用 FilterExpression 满足要求:

    :filter_expression => "RANGE_KEY_NAME in (:id1, :id2)",{ ":id1" => "hoge",":id2" => "foo"}
    

    但是,消耗的预配置吞吐量将基于查询返回的结果而不是筛选的结果集 .

    另一种选择是通过 BatchGetItem 发送多个 GetItem 请求(每个请求具有可能的 Range Key 值) . 结果将只包含匹配的记录:

    resp = dynamodb.batch_get_item(
      # required
      request_items: {
        "TableName" => {
          # required
          keys: [
            {
              "AttributeName" => "value", #<Hash,Array,String,Numeric,Boolean,nil,IO,Set>,
            },
          ],
          attributes_to_get: ["AttributeName", '...'],
          consistent_read: true,
          projection_expression: "ProjectionExpression",
          expression_attribute_names: { "ExpressionAttributeNameVariable" => "AttributeName" },
        },
      },
      return_consumed_capacity: "INDEXES|TOTAL|NONE",
    )
    

    资料来源:http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html

相关问题