如何使用Azure DocumentDB执行UPSERT操作?

3
Azure DocumentDB不支持UPSERT。有没有合理的解决方法来实现相同的功能?
使用存储过程来检查文档是否存在以确定应执行插入还是更新是否是一种有效的策略?
如果我需要批量执行数千个操作怎么办?

在这里为该功能投票:

http://feedback.azure.com/forums/263030-documentdb/suggestions/7075256-provide-for-upsert


更新 - 这是我尝试编写的批量 upsert 存储过程。

function bulkImport(docs) { 
    var collection = getContext().getCollection(); 
    var collectionLink = collection.getSelfLink(); 
    var count = 0; 

    if (!docs) throw new Error('Docs parameter is null'); 

    var docsLength = docs.length; 
    if (docsLength == 0) { 
        getContext().getResponse().setBody(0); 
    } 

    tryUpsert(docs[count], callback); 

    function tryUpsert(doc, callback) {

        var query = { query: ""select * from root r where r.id = @id"", parameters: [ {name: ""@id"", value: doc.id}]};

        var isAccepted = collection.queryDocuments(collectionLink, query, function(err, resources, options) {
            if (err) throw err;                           

            if(resources.length > 0) {
                // Perform a replace       
                var isAccepted = collection.replaceDocument(resources[0]._self, doc, callback);     
                if (!isAccepted) getContext().getResponse().setBody(count);                          
            }
            else {
                // Perform a create
                var isAccepted = collection.createDocument(collectionLink, doc, callback);   
                if (!isAccepted) getContext().getResponse().setBody(count);                             
            }
        });  

        if (!isAccepted) getContext().getResponse().setBody(count); 
    }

    function callback(err, doc, options) { 
        if (err) throw err; 

        // One more document has been inserted, increment the count. 
        count++; 

        if (count >= docsLength) { 
            // If we have created all documents, we are done. Just set the response. 
            getContext().getResponse().setBody(count); 
        } else { 
            // Create next document. 
            tryUpsert(docs[count], callback); 
        } 
    } 
} 
1个回答

4

更新(2015年10月6日): Azure DocumentDB 现在支持原子插入更新


是的,存储过程非常适合upsert操作。

DocumentDB的Github上甚至有可用的代码示例:


太好了,谢谢。我正在将这些概念合并到批量导入脚本中。将一组文档发送到执行每个插入的存储过程与从我的代码逐个调用存储过程相比,是否有显着的性能提升?也许它可以减少RUs的使用? - Vyrotek
发送一组文档(而不是逐个发送)可以通过减少应用程序和数据库之间的网络往返次数来获得大量性能提升。然而,就 RU 方面而言,差异微不足道。 - Andrew Liu
1
链接已失效。 - Jeffpowrs
脚本示例存储库已经迁移到:https://github.com/Azure/azure-documentdb-js-server/tree/master/samples - Andrew Liu
1
@AndrewLiu,批量插入更新(bulk upsert)去哪了?甚至在链接或GitHub存储库中都找不到。 - Atul Chaudhary
@AtulChaudhary 我已经修复了前两个链接。 - Ruben Bartelink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接