【问题标题】:Auto-generate ID when adding new document添加新文档时自动生成 ID
【发布时间】:2015-03-10 16:00:03
【问题描述】:

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

This document seems to specify the "ID" 但如果它已经存在怎么办?有没有更好的方法来生成唯一标识符。

【问题讨论】:

  • 为什么需要随机 ID?为什么不使用顺序 ID?
  • 如果不是顺序 ID,为什么不是 guid?
  • 顺序 ID 在分布式数据库中可能很麻烦,所以我可以使用任何类型的 ID,只要它保证唯一。
  • 你总是可以生成一个随机的 id,对数据库进行 fetch 以查看该 id 是否已经存在,如果不存在则插入它。
  • @JamesSpence 这不再使插入操作成为原子操作,因为在我检查时可以插入另一条记录,尽管这种可能性非常低。现在我无论如何都在执行插入,如果返回错误,重新生成 ID 并再次插入。

标签: php database uniqueidentifier clusterpoint


【解决方案1】:

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

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) {

    }

【讨论】:

    【解决方案2】:

    如果原始操作失败,我已通过尝试重新插入数据来解决。这是我在 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');
    }
    

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

    【讨论】:

    • 我相信你设计这个是有原因的,但如果你想这样做,而不是有一个 for 循环,你可以只钩住 catch 用相同的数据重新运行相同的函数。当然,我假设你这样做是为了让它只尝试 3 次,之后它就失败了。
    • 是的,也不需要填满调用栈。我曾经在 ASM 中为 8086 开发,那时您会发现函数调用比 for() 循环更昂贵。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2018-08-27
    • 2021-03-29
    • 2022-09-30
    • 2015-06-02
    相关资源
    最近更新 更多