http://www.craigkerstiens.com/2015/05/08/upsert-lands-in-postgres-9.5/
replace the 'select count' and insert or update stuff in update function to make just one request of an upsert to postgres for new/changes to docs - i am guessing but is possible there could be a real performance boost by doing this ... need to test