2

I'm trying to learn how to use the lambda function to resolve conflicts when inserting into a table with rethinkdb and python, like the last example on this page. I would like to compare a timestamp field between the old_doc and new_doc and keep the more recent document.

r.table(import_table).insert(documents, conflict=lambda id, old_doc, new_doc: new_doc if new_doc['timestamp'] > old_doc['timestamp'] else old_doc).run()```

This gives the following error

rethinkdb.errors.ReqlQueryLogicError: Expected type DATUM but found FUNCTION

I can't find much documentation on this error or using lambda functions for conflict resolution. Running something simpler like:

r.table(import_table).insert(documents, conflict=lambda id, old_doc, new_doc: new_doc).run()

gives the same error which makes me think that I'm not writing this correctly. Any help would be appreciated.

DevLounge
  • 8,313
  • 3
  • 31
  • 44
chacalle
  • 33
  • 5

2 Answers2

1

It seems to me that you are just looking for r.branch

r.table(import_table).insert(
    documents,
    conflict=lambda id, old_doc, new_doc: r.branch(
        new_doc['timestamp'] > old_doc['timestamp'],
        new_doc,
        old_doc
    )     
).run()

In cased of conflict, insert expects a datum, you were just returning a function (lambda). Here, the conflict resolution lambda will return the result of the r.branch comparison, which will be a datum this time.

EDIT:

I just tries it in the data explorer, in javascript, and it works for me:

r.table('foo').insert(
  [{id: 0, a: 3}, {id: 1, a: 2}],
  {
    conflict: function(id, old_doc, new_doc){
    return r.branch(
      old_doc('a').lt(new_doc('a')),
      new_doc,
      old_doc
    )}
  })

It seems to be the same than the python syntax I gave above, no?

DevLounge
  • 8,313
  • 3
  • 31
  • 44
1

Conflict function for inserting was implemented in rethinkdb 2.3.0 so this works after updating to that version or newer.

chacalle
  • 33
  • 5