CouchDB Document Update Handlers (in-place updates)

后端 未结 2 725
孤独总比滥情好
孤独总比滥情好 2020-12-02 09:12

http://wiki.apache.org/couchdb/Document_Update_Handlers

CouchDB ( 0.10 and above ) supports in-place updates now. I\'m having trouble understanding how it works. I t

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 10:01

    The example function in-place is not the same as "in-place" updates in other databases. CouchDB still uses an append-only architecture; document update handlers still create a new doc revision, etc.

    Still, update handlers are quite convenient and worth learning.

    Suppose you have a document with an accumulator. You want to accumulate an integer in a document with just one HTTP query, specifying the increment amount using an amount parameter. Consider the following commands:

    curl -X PUT http://localhost:5984/db
    # Returns {"ok":true}
    
    curl -H "Content-Type:application/json" -X POST http://localhost:5984/db/_bulk_docs -d @-
    {"docs":
      [
        {"_id": "my_doc", "number": 23},
        {"_id": "_design/app",
          "updates": {
            "accumulate": "function (doc, req) {
                             var inc_amount = parseInt(req.query.amount);
                             doc.number = doc.number + inc_amount;
                             return [doc, \"I incremented \" +
                                          doc._id + \" by \" +
                                          inc_amount];
                           }"
          }
        }
      ]
    }
    # Returns [{"id":"my_doc","rev":"1-8c9c19a45a7e2dac735005bbe301eb15"},
    #          {"id":"_design/app","rev":"1-83ec85978d1ed32ee741ce767c83d06e"}]
    

    (Remember to press end-of-file, ^D, after the JSON object in the POST.)

    Next confirm the document for accumulation (my_doc) exists:

    curl http://localhost:5984/db/my_doc
    # Returns {"_id":"my_doc","_rev":"1-8c9c19a45a7e2dac735005bbe301eb15",
    #          "number":23}
    

    Now you can call the accumulate update handler with an amount parameter to update the field.

    curl -X PUT \
     http://localhost:5984/db/_design/app/_update/accumulate/my_doc?amount=15
    # Returns: I incremented my_doc by 15
    
    curl http://localhost:5984/db/my_doc
    # Returns {"_id":"my_doc","_rev":"2-",
    #          "number":38}
    

    Notice that the new number value is 38, the value of 23 + 15.

提交回复
热议问题