本文 Python 代码在 Python 3 中测试通过。
简介
源码地址: https://github.com/elastic/elasticsearch-py
对于 ES 7,建议安装 7.x.y 的版本。可以在 https://pypi.org/project/elasticsearch/#history 查看所有的版本号。
例如在个人目录安装 7.0.3:
pip3 install elasticsearch==7.0.5 --user
官方使用手册见:https://elasticsearch-py.readthedocs.io/en/master/ 。
使用示例
示例: 连接 ES ,创建索引
连接本地ES服务,创建 student 索引。
from elasticsearch import Elasticsearch
es = Elasticsearch(["127.0.0.1:9200"])
index_name = 'student'
request_body = {
"mappings" : {
"properties" : {
"name" : {
"type" : "keyword"
},
"age" : {
"type" : "integer"
},
"height": {
"type": "integer"
}
}
}
}
es.indices.create(index='student', body=request_body)
示例: 判断索引是否存在
from elasticsearch import Elasticsearch
es = Elasticsearch(["127.0.0.1:9200"])
index_name = 'student'
if es.indices.exists(index_name) == True:
print('索引存在')
else:
print('索引不存在')
示例: 删除索引
删除本地ES服务的 student 索引。
from elasticsearch import Elasticsearch
es = Elasticsearch(["127.0.0.1:9200"])
es.indices.delete(index='student')
示例: 索引数据
from elasticsearch import Elasticsearch
es = Elasticsearch(["127.0.0.1:9200"])
index_name = 'student'
request_body = {
"mappings" : {
"properties" : {
"name" : {
"type" : "keyword"
},
"age" : {
"type" : "integer"
},
"height": {
"type": "integer"
}
}
}
}
# 索引存在, 先删除索引
if es.indices.exists(index_name):
es.indices.delete(index=index_name)
# 创建索引
es.indices.create(index=index_name, body=request_body)
# 索引数据
es.index(index=index_name, id="1", body={
"name": "张三",
"age": 15
})
es.index(index=index_name, id="2", body={
"name": "李四",
"age": 16
})
执行完后, 在 Kibana Dev Tools 查询数据验证:
# 执行
GET student/_search
# 输出结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "student",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "张三",
"age" : 15
}
},
{
"_index" : "student",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "李四",
"age" : 16
}
}
]
}
}