I am making use of Delete By Query API to delete a bunch of documents. Below curl is working perfect:

POST /tom-access/doc/_delete_by_query
{
  "query": {
    "terms": {
      "_id": [
        "xxxxx",
        "yyyyy"
      ]
    }
  }
}

Now, I want to make use of requests library in Python to achieve the same.

import requests,json

url = "http://elastic.tool.com:80/tom-access/doc/_delete_by_query"
headers = {"Content-type": "application/json", "Accept": "application/json", "Authorization": "Basic asdadsasdasdasd"}

data = {
        'query':{
                'terms':{
                        '_id':[
                                'xxxxx',
                                'yyyyy'
                        ]
                }
        }
}

try:
    r = requests.post(url,
                 headers=headers,
                 data=data,
                 verify=False)
except blablaaa

response_dict = r.json()
print(response_dict)

I am getting below error:

{'error': {'root_cause': [{'type': 'json_parse_exception', 'reason': "Unrecognized token 'query': was expecting ('true', 'false' or 'null')\n at [Source: [email protected]; line: 1, column: 7]"}], 'type': 'json_parse_exception', 'reason': "Unrecognized token 'query': was expecting ('true', 'false' or 'null')\n at [Source: [email protected]; line: 1, column: 7]"}, 'status': 500}

What am i doing wrong?

2 Answers

1
toomaas On Best Solutions

I think you should try using double quotes ("") in the data variable instead of single quotes (''). Also, convert the query using json.dumps().
Here is an example from https://marcobonzanini.com/2015/02/02/how-to-query-elasticsearch-with-python/, where it shows the use of the requests library:

def search(uri, term):
    """Simple Elasticsearch Query"""
    query = json.dumps({
        "query": {
            "match": {
                "content": term
            }
        }
    })
    response = requests.get(uri, data=query)
    results = json.loads(response.text)
    return results

There is also the official elasticsearch client for python elasticsearch-py.

1
Chr0nicl3 On

you need to change the way you are firing the request from python.

so instead of,

r = requests.post(url,
                 headers=headers,
                 data=data,
                 verify=False)

try using,

r = requests.post(url,
                 headers=headers,
                 data=json.dumps(data),
                 verify=False)