如何使用Azure DocumentDB执行UPSERT? [英] How can I perform an UPSERT using Azure DocumentDB?

查看:232
本文介绍了如何使用Azure DocumentDB执行UPSERT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Azure DocumentDB不支持UPSERT.是否有合理的方法来实现相同的功能?

Azure DocumentDB does not support UPSERT. Is there a reasonable work around to achieve the same functionality?

是否正在使用存储过程检查文档是否存在,以确定是否应该执行插入和更新策略?

Is using a stored procedure which checks if the document exists to determine whether and insert or update should be performed an effective strategy?

如果我需要批量执行数千个该怎么办?

What if I need to perform thousands of these in bulk?

为此功能投票:

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

更新-这是我尝试进行批量增补存储过程的步骤.

Update - Here is my attempt at a bulk upsert stored procedure.

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); 
        } 
    } 
} 

推荐答案

更新(2015-10-06): 是的,存储过程对upsert非常有用.

Yes, a store procedure would work great for upsert.

DocumentDB的Github上甚至提供了代码示例:

There are even code samples available on DocumentDB's Github:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆