Elasticsearch GET request with request body

2019-04-04 09:48发布

问题:

Isn't it against REST-style approach to pass a request body together with GET request?

For instance to filter some information in Elasticsearch

curl localhost:9200/megacorp/employee/_search -d '{"query" : {"filtered" : {"filter" : {"range" : {"age" : { "gt" : 30 }}},"query" : {"match" : {"last_name" : "smith"}}}}}'

some tools are even designed to avoid request body in GET request (like postman)

回答1:

From the RFC:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

In other words, it's not forbidden, but it's undefined behavior and should be avoided. HTTP clients, servers and proxies are free to drop the body and this would not go against the standard. It's absolutely a bad practice.

Further text from the HTTPBis working group (the group working on HTTP and related standards):

Finally, note that while HTTP allows GET requests to have a body syntactically, this is done only to allow parsers to be generic; as per RFC7231, Section 4.3.1, a body on a GET has no meaning, and will be either ignored or rejected by generic HTTP software.

source



回答2:

No. It's not.

In REST, using POST to query does not make sense. POST is supposed to modify the server. When searching you obviously don't modify the server.

GET applies here very well.

That being said, we are aware that some languages and tools don't allow that. Although the RFC does not mention that you can't have a body with GET.

So elasticsearch supports also POST.

This:

curl -XPOST localhost:9200/megacorp/employee/_search -d '{"query" : {"filtered" : {"filter" : {"range" : {"age" : { "gt" : 30 }}},"query" : {"match" : {"last_name" : "smith"}}}}}'

Will work the same way.