azure - 如何使用 Azure DocumentDB 执行 UPSERT?

标签 azure upsert azure-cosmosdb

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

使用存储过程来检查文档是否存在以确定是否应该执行插入或更新是一种有效的策略吗?

如果我需要批量执行数千个这样的操作怎么办?

<小时/>

在此处投票支持该功能:

http://feedback.azure.com/forums/263030-documentdb/suggestions/7075256-provide-for-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); 
        } 
    } 
} 

最佳答案

更新(2015-10-06): Atomic upsert Azure DocumentDB 现在支持。

<小时/>

是的,存储过程非常适合更新插入。

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

关于azure - 如何使用 Azure DocumentDB 执行 UPSERT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586399/

相关文章:

c# - DocumentDB 替换文档失败

asp.net-mvc - 添加基于Azure Mobile Apps的实时聊天功能

azure - 有没有办法自动检索Azure资源命名限制

Azure服务总线: No session available to complete the message with the lock token

postgresql - Upsert 错误(On Conflict Do Update)指向重复的约束值

java - 在 Azure CosmosDB 上添加附件

Azure云服务部署

java - 是否可以使用 jOOQ 生成的记录类进行更新插入?

sql - 带有 WHERE 子句的 PostgreSQL ON CONFLICT

azure - cosmos db 模拟器的用户名和密码是什么