Auto-generate ID when adding new document

190 Views Asked by At

My project use ClusterPoint database and I wonder if it's possible to insert document into the database with randomly assigned ID.

This document seems to specify the "ID" but what if it exists already? Is there a better way to generate unique identifiers.

2

There are 2 best solutions below

0
On BEST ANSWER

You could achieve auto increment functionality by using separate doc for sequence and use transaction to increment it safely. Of course it might impact ingestion speed because each insert would require extra roundtrip for transaction to succeed.

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
On

I have solved by attempting to re-insert the data if original operation fails. Here is my method in 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');
}

I'm not sure if that's best approach, but it works.