Warm tip: This article is reproduced from serverfault.com, please click

How to insert data into marklogic database in already existing file using curl RESTAPI

发布于 2020-12-12 19:45:34

I searched over the internet and found nothing about this making me rethink that "may be we can't insert data into already existing file in Marklogic".But, I want to verify here I know using curl PUT command we can update or create a new document I have created a json using following query

**curl -v -X PUT \
  --digest --user rest-writer:x \
  -d'{"recipe": {"name" :"Apple pie", "fromScratch":true, "ingredients":"The Universe"}}' \
  'http://localhost:8011/LATEST/documents?uri=/example/recipe.json'**

After creating this, i wanted to add another recipe such as below in the same file /example/recipe.json

"name" :"Chocolate Cake", "fromScratch":yes, "ingredients":"Coca"

How can i achieve this using curl in Marklogic?

Questioner
user2708013
Viewed
0
Fiona Chen 2020-12-13 13:57:18

You can certainly insert other JSON objects in an existing JSON document. Being a multi-model database, data model should be the first consideration.

In order to facilitate JSON object update, the JSON model should be:

{
  "recipe" : {
    "recipe1":{
      "name" : "Apple pie", 
      "fromScratch" : true, 
      "ingredients" : "The Universe"
    }
  }
}

Then construct an update JSON content (choose one of below options) called add-recipe.json:

  1. Add JSON object after recipe1
{ 
  "patch": [
   { "insert": {
       "context": "/recipe/recipe1",
         "position": "after",
           "content":   
            { "recipe2": {
                "name" : "Chocolate Cake", 
                "fromScratch" : true, 
                "ingredients" : "Coca"
            }}
    
    }}
] }

  1. Add JSON object before recipe1:
{ 
  "patch": [
   { "insert": {
       "context": "/recipe/recipe1",
         "position": "before",
           "content":   
            { "recipe2": {
                "name" : "Chocolate Cake", 
                "fromScratch" : true, 
                "ingredients" : "Coca"
            }}
    
    }}
] }
  1. Add JSON object following the last child (if you have nested JSON objects):
{ 
  "patch": [
   { "insert": {
       "context": "/recipe",
         "position": "last-child",
           "content":   
            { "recipe2": {
                "name" : "Chocolate Cake", 
                "fromScratch" : true, 
                "ingredients" : "Coca"
            }}
    
    }}
] }

Finally, perform a patch REST API request to complete the operation:

curl --anyauth --user {username}:{password} -X PATCH -d @./add-recipe.json -i -H "Content-type: application/json" "http://{hostname}:{port-number}/v1/documents?uri=/example/recipe.json"