Search code examples
elasticsearchcurlget

How can curl perform a get request with a data payload?


The introductory materials on ElasticSearch include the following example curl request:

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(new york city) OR (big apple)",
            "default_field" : "content"
        }
    }
}
'

This request has two parameter which I thought were incompatible:

  • -X GET, which specifies that the request is a GET.
  • -d [...], which specifies that the request has a data payload.

I thought that specifying a data payload was only possible in a PUT or POST requests, because GET requests do not have any concept of a data payload. Is this a valid curl command? What does it do, exactly?


Solution

  • Above curl request is a valid request, in fact, if you have index and data, then you can check the output of your command.

    I tried it in my system and ES index and it gave me proper response.

    curl -v -X GET "localhost:9500/querytime/_search?pretty" -H 'Content-Type: application/json' -d'
    {
        "query": {
            "query_string" : {
                "query" : "(avengers) OR (big apple)",
                "default_field" : "movie_name"
            }
        }
    }'
    *   Trying ::1...
    * TCP_NODELAY set
    * Connected to localhost (::1) port 9500 (#0)
    > GET /querytime/_search?pretty HTTP/1.1
    > Host: localhost:9500
    > User-Agent: curl/7.64.1
    > Accept: */*
    > Content-Type: application/json
    > Content-Length: 156
    >
    * upload completely sent off: 156 out of 156 bytes
    < HTTP/1.1 200 OK
    < content-type: application/json; charset=UTF-8
    < content-length: 905
    <
    {
      "took" : 4,
      "timed_out" : false,
      "_shards" : {
        "total" : 1,
        "successful" : 1,
        "skipped" : 0,
        "failed" : 0
      },
      "hits" : {
        "total" : {
          "value" : 3,
          "relation" : "eq"
        },
        "max_score" : 0.14874382,
        "hits" : [
          {
            "_index" : "querytime",
            "_type" : "_doc",
            "_id" : "1",
            "_score" : 0.14874382,
            "_source" : {
              "movie_name" : "Avengers: Infinity War"
            }
          }
        ]
      }
    }
    

    As mentioned in the official manual of curl command, if you are using *nix based system, then you can search below in the manual of curl.

    -G, --get When used, this option will make all data specified with -d, --data, --data-binary or --data-urlencode to be used in an HTTP GET request instead of the POST request that otherwise would be used. The data will be appended to the URL with a '?' separator

    As explained in this SO answer, it also depends on the web-server to parse the body in GET request.