Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUT vs POST when adding documents in elastic search

I am new to Elasticsearch and trying to add documents in elastic index. I have got confused between PUT and POST here as both are producing same results in below scenario:

curl -H "Content-Type: application/json" -XPUT "localhost:9200/products/mobiles/1?pretty" -d"
{
"name": "iPhone 7",
"camera": "12MP",
"storage": "256GB",
"display": "4.7inch",
"battery": "1,960mAh",
"reviews": ["Incredibly happy after having used it for one week", "Best iPhone so far", "Very expensive, stick to Android"]
}
"

vs

curl -H "Content-Type: application/json" -XPOST "localhost:9200/products/mobiles/1?pretty" -d"
{
"name": "iPhone 7",
"camera": "12MP",
"storage": "256GB",
"display": "4.7inch",
"battery": "1,960mAh",
"reviews": ["Incredibly happy after having used it for one week", "Best iPhone so far", "Very expensive, stick to Android"]
}
"
like image 853
Vishwajeet Avatar asked Jan 01 '23 20:01

Vishwajeet


2 Answers

  • POST :used to achieve auto-generation of ids.
  • PUT :used when you want to specify an id.

see this

like image 198
LinPy Avatar answered Jan 03 '23 11:01

LinPy


They both are among safe methods of HTTP.

usually we use POST to create a resource and PUT to modify that. besides if you're free to set-up the server side, you can use both of them because they both have similar properties like: they both have body, they are safe, data is not shown in URL, and .... though it is better to consider standard rules that I said one of them before: usually we use POST to create a resource and PUT to modify that. this way your code is more readable, changeable ...

for going deeper you can consider these tips according to put-versus-post:

Deciding between POST and PUT is easy: use PUT if and only if the endpoint will follow these 2 rules:

  1. The endpoint must be idempotent: so safe to redo the request over and over again;
  2. The URI must be the address to the resource being updated.

When we use PUT, we’re saying that we want the resource that we’re sending in our request to be stored at the given URI. We’re literally “putting” the resource at this address.

like image 39
Majid Roustaei Avatar answered Jan 03 '23 09:01

Majid Roustaei