Home > Net >  Elasticsearch search using python
Elasticsearch search using python

Time:09-27

Query using curl.

curl -XGET http://localhost:9200/users/_search?pretty=true -H 'Content-Type: application/json' -d '
  { 
      "from" : 0, "size" : 5,
      "query" : {
          "query_string" : {
              "query" : "Port"
          }
      }
  }
'

Same thing i am trying to do in python requests:

url = f'{URL}/{INDEX}/_search/'
es_query = { 
    "query" : {
        "query_string" : {
            "query" : "Port"
        }
    }
}
res = requests.get(url, data=es_query) 
print(res.json())

I am getting below error while doing this.

`{'error': 'Content-Type header [application/x-www-form-urlencoded] is not supported', 'status': 406}`

Please take a look what can be the issue

CodePudding user response:

You can use curlconverter.com to easily convert cURL commands to Python requests. Here's the output for your cURL command:

import requests

params = {
    'pretty': 'true',
}

json_data = {
    'from': 0,
    'size': 5,
    'query': {
        'query_string': {
            'query': 'Port',
        },
    },
}

response = requests.get('http://localhost:9200/users/_search', params=params, headers=headers, json=json_data)

CodePudding user response:

Your URL is wrong

url = f'{URL}/{INDEX}/_bulk/'

Should be

url = f'{URL}/{INDEX}/_search/'

Also you need to specify the following request header

Content-type: application/json

Like this:

res = requests.get(url, json=es_query, headers={"Content-type": "application/json"}) 
  • Related