search

Home  >  Q&A  >  body text

ConditionExpression attribute_not_exists()

I tried using ConditionExpression when inserting items in the database but it doesn't work, the php script breaks when the Putitem() function runs.

If the item does not exist, I want to insert the item.

$response = $client->putItem(array(
    'TableName' => 'tablename',
    'Item' => array(
        'serialNumber'   => array('S' => 'test123'),
        'deviceType' => array('S' => '1')
    ),
    'ConditionExpression' => 'attribute_not_exists(serialNumber)'
));

I tried var_dump $response but the code breaks on the function above.

serialNumber It is a partition key and should work as expected.

The code below works fine, but he replaces the existing items with new values, which is what I don't want to happen.

$response = $client->putItem(array(
    'TableName' => 'tablename',
    'Item' => array(
        'serialNumber'   => array('S' => 'test123'),
        'deviceType' => array('S' => '1')
    )
));

P粉132730839P粉132730839246 days ago444

reply all(1)I'll reply

  • P粉667649253

    P粉6676492532024-03-30 00:46:00

    When the condition you set evaluates to false, you are expected to return a CondidtionCheckFailedException. Try wrapping the code in a try/catch block and see if it works as expected?

    try {
    $response = $client->putItem(array(
        'TableName' => 'tablename',
        'Item' => array(
            'serialNumber'   => array('S' => 'test123'),
            'deviceType' => array('S' => '1')
        )
    ));
    }
    catch(Exception $e) {
      echo $e->getMessage();
    }

    reply
    0
  • Cancelreply