Essentially, I'm trying to get the generated key for a single record insert. Something like:
rethinkdb.table('test').insert(request.data).pluck('generated_keys')[0].run(connection)
and have it return something like:
{
"id": "61fa30de-cfb1-4133-ae86-cf6e4f1a011e"
}
I just want to give some tips so that you can figure this out later. First, you can use typeOf
to find the type of data.
r.table('dummy').insert({f: "foo"}).typeOf()
"OBJECT"
So you know if returns an object. Next, you go to RethinkDB document, try to find some similar function. A good guess is get_field
http://rethinkdb.com/api/javascript/get_field/
And get_field can be called on object:
sequence.getField(attr) → sequence
singleSelection.getField(attr) → value
object.getField(attr) → value
Let's see what it returns it:
r.table('dummy').insert({f: "foo"}).getField('generated_keys').typeOf()
"ARRAY"
Let's find a command to return an element in array. You can go over the document again and will be noticed nth
command to return a n-th element from an array. Therefore, we can do this now:
r.table('dummy').insert({f: "foo"}).getField('generated_keys').nth(0)
"c2b1bf69-a926-4c27-b1a6-011d47c700df"
Let's try to simplify it. Using getField
is annyoing. To make it short, you can use bracket ()
to get a single field from object
r.table('dummy').insert({f: "foo"})('generated_keys').nth(0)
"77f4aca6-9219-494e-9998-23eb9abcd5e0"
But using nth
also field annyoying a bit. Can we make it short. Luckily bracket can also be call on array.http://rethinkdb.com/api/javascript/bracket/
The () command also accepts integer arguments as array offsets, like the nth command.
Combine everything we have:
r.table('dummy').insert({f: "foo"})('generated_keys')(0)
This is all run direcly on Data Explorer but I think you can easily convert them into Python by looking at JavaScript and translate into Python.