When you make the requests post you dumped the json again, when all you had to do was send test_json.
See if this works:
requests.post(elastic_url + 'test/_doc/1',
json=test_json,
headers=headers)
That might fix the mapping error! If you still receive the mapping parsing exception like below, either update your mapping or check the data you're submitting.
'caused_by': {'type': 'not_x_content_exception',
'reason': 'Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes'}}
Mapping example:
# mapping tells es what kind of data each field contains
mapping = {
"mappings": {
"properties": {
"id": {
"type": "long"
},
"foo": {
"type": "text"
}
}
}
}
Do you need to use requests for this post?
If not, may I suggest the python elasticsearch client? You can do it like below. I often have to create an index and mapping and upload documents to elasticsearch and this is how I do it. (note - i wrap all these up into easy to use functions but figured I'd just show you the guts!)
from elasticsearch import Elasticsearch
from elasticsearch import helpers
# bulk generator function with the es required formatting for successful bulk upload.
# the required dict is the index and source line below
def bulk_gen(json_data):
bulk_action = ({"_index": es_index,"_source": j,} for j in json_data if json_data is not None)
for b in bulk_action:
yield b
print(f'processed {es_index}')
# connect to elasticsearch
es = Elasticsearch(cloud_id=cloud_id,
http_auth=('username', 'password')
# name index
es_index = 'index name here'
# create index, add mapping
es.indices.create(index=es_index, body=mapping, ignore=400)
# process your json data
json_data = json.loads({"id": 1, "foo": "bar"})
# finally, let's upload everything!
# we've already created an index and mapping and processed the json data into bulk upload format, now we let 'er rip
try:
helpers.bulk(es, bulk_gen(json_data))
print('Imported resource succesfully')
except Exception as e:
print(f'there was an error: {e}')
Hope this helps. I struggled and then started using the es python client and things got a lot easier.