Elasticsearch query using API manager

I am involved in a project for work where I have to query an Elasticsearch server using an API manager and Python. I have the below code but the error I'm getting indicates I'm using the wrong content-type. I'm not sure which one I should be using though.

import requests
import elasticsearch
from elasticsearch import Elasticsearch

headers = {
'apikey': 'myapikey',
'Content-Type': 'application/json'
}

data = {'query': '{"bool": { "must": [{ "match": { "message": "gmail.com yahoo.com" } },{ "range" : { "@timestamp": { "gte" : "now-7d"} } } ]}}}'}

r = requests.get('https://myapiserver/pastebin-*/_search', headers=headers, data=data)
print r.status_code
print r.text

The Error:

{"error":{"root_cause":[{"type":"json_parse_exception","reason":"Unrecognized token 'query': was expecting ('true', 'false' or 'null')\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@261eb2fe; line: 1, column: 7]"}],"type":"json_parse_exception","reason":"Unrecognized token 'query': was expecting ('true', 'false' or 'null')\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@261eb2fe; line: 1, column: 7]"},"status":500}

It's because you are using a generic http client library so data must be a full JSON string and you are using a slightly different syntax there. Try using the following instead:

data = '{"query": {"bool": { "must": [{ "match": { "message": "gmail.com yahoo.com" } },{ "range" : { "@timestamp": { "gte" : "now-7d"} } } ]}}}'

But you have imported the standard Elasticsearch client there, why not use that instead of requests?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.