我的项目使用ClusterPoint数据库,我想知道是否可以用随机分配的ID将文档插入数据库。
此文档似乎指定了"ID“。,但是如果它已经存在了呢?是否有更好的方法来生成唯一的标识符。
发布于 2015-03-13 07:47:21
您可以通过对序列使用单独的文档来实现自动增量功能,并使用事务来安全地增加它。当然,这可能会影响吞食速度,因为每次插入都需要额外的往返才能成功。
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) {
}发布于 2015-03-11 10:11:06
如果原始操作失败,我尝试重新插入数据,从而解决了问题。下面是我在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');
}我不确定这是不是最好的方法,但有效。
https://stackoverflow.com/questions/28968402
复制相似问题