And request in elasticsearch with curl

Enter some data in Elasticsearch

curl -XPUT 'localhost:9200/customer/external/1' -d '{ "author": "John", "published_from":"2016-08-03" }' curl -XPUT 'localhost:9200/customer/external/2' -d '{ "author": "Jeanne", "published_from":"2016-08-03" }' curl -XPUT 'localhost:9200/customer/external/3' -d '{ "author": "Jean", "published_from":"2016-08-05" }' 

I am trying to request a document with publish_from = 2016-08-03 and author = John. I am trying to do this with this curl command:

 curl -g "localhost:9200/customer/external/_search?pretty&filter_path=hits.hits._source.author&q=+author:John+published_from:2016-08-03" 

However, the output shows Jeanne

 { "hits" : { "hits" : [ { "_source" : { "author" : "John" } }, { "_source" : { "author" : "Jeanne" } } ] } } 

When I try to execute this curl command:

 curl "localhost:9200/customer/external/_search?pretty&filter_path=hits.hits._source.author&q=%2Bauthor%3AJohn+%2Bpublished_from%3A2016-08-03" 

The result is exactly what I want.

 { "hits" : { "hits" : [ { "_source" : { "author" : "John" } } ] } } 

Why is the first command not working as expected?

+7
curl elasticsearch lucene
source share
1 answer

The + sign in the first URL:

 ...&q=+author:John+published_from:2016-08-03 

are interpreted (on the server side) according to percent-encoding rules as spaces . Space is usually encoded as %20 , but for historical reasons + also a valid encoding of a space character.

This means that the query string that ElasticSearch receives looks like this:

 author:John published_from:2016-08-03 

According to the query string syntax , it will find any document containing one or more of author:John or published_from:2016-08-03 .

When you correctly encode the Elastic + operator (in the second URL), the request received:

 +author:John +published_from:2016-08-03 

Note that + was decoded as a space and %2B as + .

Simple encoding of request parameters in curl

To avoid manual (percent) encoding of requests, you can use the --data-urlencode option and provide raw key=value pairs.

For example:

 curl -G 'localhost:9200/customer/external/_search?pretty&filter_path=hits.hits._source.author' --data-urlencode 'q=+author:John +published_from:2016-08-03' 

Here curl will combine the query parameters with the url with the -d / --data-urlencode parameters. We need -G force the GET request, because -d / --data-urlencode uses the POST request by default.

+1
source share

All Articles