python写数据到elasticsearch
环境:
elasticsearch:6.8.5
开发工具:PyCharm
1.windows机器安装与服务器器相同版本的es
pip3 install elasticsearch==6.8.0
2.创建index
#!/usr/bin/env python #coding=utf-8 from elasticsearch import Elasticsearch import time es = Elasticsearch('http://192.168.1.135:19200') mappings = { "mappings": { "type_doc_test": { #type_doc_test为doc_type "properties": { "id": { "type": "long", "index": "false" }, "serial": { "type": "keyword", #keyword不会进行分词,text会分词 "index": "false" #不建索引 }, #tags可以存json格式,访问tags.content "tags": { "type": "object", "properties": { "content": { "type": "keyword", "index": True }, "dominant_color_name": { "type": "keyword", "index": True }, "skill": { "type": "keyword", "index": True }, } }, "hasTag": { "type": "long", "index": True }, "status": { "type": "long", "index": True }, "createTime": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" }, "updateTime": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" } } } } } res = es.indices.create(index ='index_test',body =mappings) print(res)
2.写入数据
#!/usr/bin/env python #coding=utf-8 from elasticsearch import Elasticsearch import time es = Elasticsearch('http://192.168.1.135:19200') action ={ "id": "1111122222", "serial":"版本", #以下tags.content是错误的写法 #"tags.content" :"标签2", #"tags.dominant_color_name": "域名的颜色黄色", #正确的写法如下: "tags":{"content":"标签3","dominant_color_name": "域名的颜色黄色"}, #按照字典的格式写入,如果用上面的那种写法,会直接写成一个tags.content字段。 #而不是在tags中content添加数据,这点需要注意 "tags.skill":"分类信息", "hasTag":"123", "status":"11", "createTime" :"2019-10-2", "updateTime":"2019-10-3", } es.index(index="index_test",doc_type="type_doc_test",body = action)