0

I have created the following table in DynamoDB:

Field1: messageId / Type: String / Example value: 4873dd28-190a-4363-8299-403c535e160f

Field2: microtime / Type: Number / Example value: 14143960092414

Field3: data / Type: nested JSON-Array / Example value: {"foo":"bar","other":{"nested":1}}

I am performing the following request using PHP SDK for DynamoDB to create an entry

$raw = '{"foo":"bar","other":{"nested":1}}';
$result = $client->putItem(array(
    'TableName' => 'requests2',
    'Item' => array(
        'messageId'   => array('S' => '4873dd28-190a-4363-8299-403c535e160f'),
        'microtime' => array('N' => microtime(true)*10000),
        'data'   => array('S' => $raw),
    )
));

I want then to query the table and filter using variables within the JSON-array data field. Is my above solution to entering the data the right approach? The JSON-array gets stored as string, as to my understanding. Do we need another datatype? Basically, I can already query the table like below to retrieve messages that were added within the last minute:

$iterator = $client->getIterator('Query', array(
    'TableName'     => 'requests2',
    'KeyConditions' => array(
        'messageId' => array(
            'AttributeValueList' => array(
                array('S' => '4873dd28-190a-4363-8299-403c535e160f')
            ),
            'ComparisonOperator' => 'EQ'
        ),
        'microtime' => array(
            'AttributeValueList' => array(
                array('N' => strtotime("-1 minutes")*10000)
            ),
            'ComparisonOperator' => 'GT'
        )
    )
));

foreach ($iterator as $item) {
    echo $item['messageId']['S']." ";
}

But how can I modify my request to allow querying by ANY value within the data-field? For example, filter by only those who have [data][other][nested]=1

I've spent the past hours on this issue and I can't get it to work... I am very grateful for any tips, thanks in advance!

4

2 回答 2

1

我知道这是在 2014 年发布的,但我一直在寻找这个答案,所以我想将我的搜索结果分享给将来会遇到这个问题的任何人。

最佳实践是将 JSON 存储为字符串,但使用Marshaler对象将 JSON 转换为 DynamoDB 可以消化的内容,并且您也可以查询:

使用marshalJSON方法,您可以转换为 JSON,正如您在此 amazon链接中所描述的那样

对于那些正在寻找快速示例的人,我在此过程的关键部分下方添加:

如果您有如下 JSON

{
  "id": "5432c69300594",
  "name": {
    "first": "Jeremy",
    "middle": "C",
    "last": "Lindblom"
  },
  "age": 30,
  "phone_numbers": [
    {
      "type": "mobile",
      "number": "5555555555",
      "preferred": true
    },
    {
      "type": "home",
      "number": "5555555556",
      "preferred": false
    }
  ]
} 

存储在字符串变量$json中,你可以简单地做

use AwsDynamoDbDynamoDbClient;
use AwsDynamoDbMarshaler;

$client = DynamoDbClient::factory(/* your config */);
$marshaler = new Marshaler();

$client->putItem([
    'TableName' => 'YourTable',
    'Item'      => $marshaler->marshalJson($json)
]);
于 2019-03-07T17:02:34.827 回答
0

我认为适用于 DynamoDB 的 AWS PHP SDK 尚未实现对基于 JSON 的文档存储的支持。他们最近于 2014 年 10 月 8 日在其博客上发布的通知中提到仅在 Java、.NET、Ruby 和 JS SDK 中支持此新功能。

于 2014-11-11T09:57:41.417 回答