问题
Content-Type header [application/x-www-form-urlencoded] is not supported
场景
curl -s -XPOST "localhost:9200/get-together/group/1" -d'{
"name": "Denver Clojure",
"organizer": ["Daniel", "Lee"],
"description": "Group of Clojure enthusiasts from Denver who want to hack on code together and learn more about Clojure",
"created_on": "2012-06-15",
"tags": ["clojure", "denver", "functional programming", "jvm", "java"],
"members": ["Lee", "Daniel", "Mike"],
"location_group": "Denver, Colorado, USA"
}'
在执行上述创建索引的时候,报如下错误:
{"error":"Content-Type header [application/x-www-form-urlencoded] is not supported","status":406}%
问题原因
strict-content-type-checking-for-elasticsearch-rest-requests
是因为在ES6.0之后,ES对content-type的检测更为严格,在ES的早期版本中,content-type是可选的,如果缺省或者ES无法辨别,ES会根据请求内容进行猜测。
这个功能最先出现在5.3版本,http.content_type.required
是在配置中的,在5.x版本中,默认参数是false,但是在6.0版本中,这个参数是true,并且不能改变。
为什么要对这个做出改变呢,是因为随着ES的发展,ES认为可靠性和可预测性更重要,猜测一定会猜错,但是增加了一点点内容,有助于安全和清晰,这是非常明智的。
解决方案
在请求时增加content-type类型
curl -H 'Content-Type: application/json' -s -XPOST "localhost:9200/get-together/group/1" -d'{
"name": "Denver Clojure",
"organizer": ["Daniel", "Lee"],
"description": "Group of Clojure enthusiasts from Denver who want to hack on code together and learn more about Clojure",
"created_on": "2012-06-15",
"tags": ["clojure", "denver", "functional programming", "jvm", "java"],
"members": ["Lee", "Daniel", "Mike"],
"location_group": "Denver, Colorado, USA"
}'
注:如果是一个脚本中,有很多行,可批量修改,方法如下:
:%s#curl -s #curl -s -H "Content-Type: application/json" #g
请求结果
{"_index":"get-together","_type":"group","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}%
[2020-04-27T12:26:33,915][INFO ][o.e.c.m.MetaDataCreateIndexService] [***MacBook-Pro.local] [get-together] creating index, cause [auto(bulk api)], templates [], shards [1]/[1], mappings []
[2020-04-27T12:26:34,323][INFO ][o.e.c.m.MetaDataMappingService] [***MacBook-Pro.local] [get-together/ytrnXYzCSo2_hRuSAR1U3g] create_mapping [group]