添加新文档时自动生成 ID


Auto-generate ID when adding new document

我的项目使用ClusterPoint数据库,我想知道是否可以使用随机分配的ID将文档插入数据库。

此文档似乎指定了"ID",但如果它已经存在怎么办?有没有更好的方法来生成唯一标识符。

您可以通过使用单独的文档进行序列并使用事务安全地递增来实现自动递增功能。当然,这可能会影响引入速度,因为每个插入都需要额外的往返才能使事务成功。

try {          
          // Begin transaction
          $cpsSimple->beginTransaction();
          // Retrieve sequence document with id "sequence"
          $seq_doc = $cpsSimple->retrieveSingle("sequence", DOC_TYPE_ARRAY);
          //in sequence doc we store last id in field 'last_doc_id'
          $new_id = ++$seq_doc['last_doc_id'];
          $cpsSimple->updateSingle("sequence", $seq_doc);
          //commit
          $cpsSimple->commitTransaction();
          //add new document with allocated new id
          $doc = array('field1' => 'value1', 'field2' => 'value2');
          $cpsSimple->insertSingle($new_id, $doc);
    } catch (CPS_Exception $e) {
    }

我已经通过在原始操作失败时尝试重新插入数据来解决。这是我在 PHP 中的方法:

function cpsInsert($cpsSimple, $data){
    for ($i = 0; $i < 3; $i++){
        try {
            $id = uniqid();
            $cpsSimple->insertSingle($id, $data);
            return $id;
        }catch(CPS_Exception $e){
            if($e->getCode() != 2626) throw $e;
            // will go for another attempt
        }
    }
    throw new Exception('Unable to generete unique ID');
}

我不确定这是否是最好的方法,但它有效。