按哈希和范围键查询DynamoDB表

3
我希望你能使用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:in `call': 一个或多个参数值无效:对于 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:in `call': 尝试的条件约束不是可索引操作 (Aws::DynamoDB::Errors::ValidationException)

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


你不能这样做。KeyConditions 不支持 IN 运算符。请参考这个问题中的我的回答。 - mkobit
非常感谢。这意味着query方法不能将多个范围键设置为查询条件吗? - necojackarc
1个回答

2
“查询”操作仅允许在“范围键(Range Key)”上使用以下运算符:
EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN

对于查询操作,条件用于指定在查询表或索引时使用的KeyConditions。对于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

batch_get_item就是解决方案!谢谢! - necojackarc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接