RethinkDB: Insert Example

r.db('test')
 .table('users')
 .insert({
   'first_name': 'gary', 
   'last_name': 'sieling',
   'user_name': 'gsieling'
 })

By default, this returns you the IDs you requested:

{
  "deleted": 0 ,
  "errors": 0 ,
  "generated_keys": [
    "903e0943-8ffe-41ca-a22f-7b1a964b399d"
  ] ,
  "inserted": 1 ,
  "replaced": 0 ,
  "skipped": 0 ,
  "unchanged": 0
}

If you request the changes back, this will return you the values you inserted, in addition to the data inserted:

r.db('test')
 .table('users')
 .insert({
   'first_name': 'gary', 
   'last_name': 'sieling',
   'user_name': 'gsieling'
 }, {returnChanges: true})

This is what you get:

{
  "changes": [
    {
      "new_val": {
        "first_name":  "gary" ,
        "id":  "947a3ce6-d419-4d31-bd1e-874c721a9e6c" ,
        "last_name":  "sieling" ,
        "user_name":  "gsieling"
      } ,
      "old_val": null
    }
  ] ,
  "deleted": 0 ,
  "errors": 0 ,
  "generated_keys": [
    "947a3ce6-d419-4d31-bd1e-874c721a9e6c"
  ],
  "inserted": 1 ,
  "replaced": 0 ,
  "skipped": 0 ,
  "unchanged": 0
}

By default this sets durability to “hard” and doesn’t return the results, which should be a little faster. You can set durability to “soft” and it will insert a little faster, but risk losing data in a crash scenario:

r.db('test')
 .table('users')
 .insert({
   'first_name': 'gary', 
   'last_name': 'sieling',
   'user_name': 'gsieling'
 }, 
 {
    durability: 'soft'
 })

If instead of an insert, you want to replace an existing object, you can use ‘replace’:

r.db('test')
 .table('users')
  .get('1b223750-799d-402a-b378-74c993a9c10c')
  .replace(
    {
       user_name: 'test', 
       last_name: 'test', 
       first_name: 'test', 
       id: '1b223750-799d-402a-b378-74c993a9c10c'
    })

Leave a Reply

Your email address will not be published. Required fields are marked *