简体   繁体   中英

Elasticsearch search using python

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

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)

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"}) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM