Writing documents
All data written with the Document API is stored as JSON documents stored in collections.
For more information about the database design of the Document API, see the blog post on the Documents API. |
Add document specifying a collection name
First, let’s add a document to a specified collection.
Send a POST
request to /api/rest/v2/namespaces/{namespace_name}/collections/{collections_name}
to add data to the collection fitness
.
The data is passed in the JSON body.
curl --location \
--request POST 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/myworld/collections/fitness' \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
"id": "some-stuff",
"other": "This is nonsensical stuff."
}'
{"documentId":"{docid}"}
Notice that the document-id
returned is a UUID if not specified.
Add document specifying collection name and document-id
Next, let’s add a document to a specified collection, but specify the document-id
.
Send a PUT
request to
/api/rest/v2/namespaces/{namespace_name}/collections/{collections_name}/{document-id}
to add data to the collection Janet
.
The document-id
can be any string.
The data is passed in the JSON body.
curl -L -X PUT 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/myworld/collections/fitness/Janet' \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
"firstname": "Janet",
"lastname": "Doe",
"email": "janet.doe@gmail.com",
"favorite color": "grey"
}'
{"documentId":"Janet"}
Note the difference between using POST
and PUT
. The POST
request
is used to insert new documents when you want the system to auto-generate the
documentId. The PUT
request is used to insert a new document when you want to
specify the documentId.
PUT
requests can also be used to update an existing
document. Let’s look at those examples, next.
Inserting a sub-document
You can also insert documents that have nested values, or sub-documents.
Send a PUT
request to
/api/rest/v2/namespaces/{namespace_name}/collections/{collections_name}/{document-id}
to add data to the existing collection.
The data is passed in the JSON body.
curl -L -X PUT 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/myworld/collections/fitness/Janet' \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
"firstname": "Joey",
"lastname": "Doe",
"weights": {
"type": "bench press",
"weight": 150,
"reps": 15
}
}'
{"documentId":"Joey"}