以下所用版本为Elasticsearch 7.2.0
1.安装
pip3 install elasticsearch -i https://pypi.tuna.tsinghua.edu.cn/simple
知识兔2.连接ES
es = Elasticsearch([{'host': '127.0.0.1', 'port': 9200}])
知识兔3.创建index
index = 'index_tushare'
body = {
"mappings": {
"properties": {
"ts_code": {
"type": "keyword"
},
"symbol": {
"type": "keyword"
},
"ts_name": {
"type": "keyword"
},
"fullname": {
"type": "keyword"
},
"area": {
"type": "keyword"
},
"industry": {
"type": "keyword"
},
"list_date": {
"type": "keyword"
},
"tab_name": {
"type": "keyword"
}
}
}
}
# create an index in elasticsearch, ignore status code 400 (index already exists)
es.indices.create(index=index, body=body, ignore=400)
知识兔4.创建mapping之后,添加字段
index_daily_close = 'index_daily_close'
body_daily_close = {
"mappings": {
"properties": {
"trade_date": {
"type": "keyword"
}
}
}
}
es.indices.create(index=index_daily_close, body=body_daily_close, ignore=400)
properties = body_daily_close.get("mappings").get("properties")
def daily_close_add_tscodes(tscode):
properties.setdefault(tscode, {"type": "keyword"})
es.indices.put_mapping(index=index_daily_close, body=body_daily_close.get("mappings"))
print(body_daily_close.get("mappings"))
知识兔添加字段的时候要注意,elasticsearch默认最大字段数为1000,超过1000就会报错
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Limit of total fields [1000] in index [index_daily_close] has been exceeded"
}
],
"type": "illegal_argument_exception",
"reason": "Limit of total fields [1000] in index [index_daily_close] has been exceeded"
},
"status": 400
}
知识兔