Python操作ElasticSearch
来自CloudWiki
(重定向自Python操作ElasticSeaarch)
介绍
官方文档:https://elasticsearch-py.readthedocs.io/en/master/
python提供了操作ElasticSearch 接口,因此要用python来操作ElasticSearch,
安装
首先要安装python的ElasticSearch包,可以用命令来安装
pip3 install elasticsearch==5.0.0 -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com
或下载安装:https://pypi.python.org/pypi/elasticsearch/5.4.0
第一个Python脚本
此脚本利用Python语言在ES中创建了一个索引。
import traceback from elasticsearch import Elasticsearch # 建立到Elasticsearch的连接 _es = Elasticsearch() # 初始化索引的Mappings设置 _index_mappings = { "mappings": { "user": { "properties": { "title": { "type": "text" }, "name": { "type": "text" }, "age": { "type": "integer" } } }, "blogpost": { "properties": { "title": { "type": "text" }, "body": { "type": "text" }, "user_id": { "type": "keyword" }, "created": { "type": "date" } } } } } # 如果索引不存在,则创建索引 if _es.indices.exists(index='blog_index') is not True: _es.indices.create(index='blog_index', body=_index_mappings) print("success")
运行此脚本:
[root@localhost py_test]# python3 es_py1.py
success
验证
在开启ES的情况下,可以执行以下查询命令,
可以看到ES中现在多了一个叫blog_index的索引。
[root@localhost py_test]# curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open company RqT3YjFeTVeUUTqmcpX0_A 5 1 0 0 810b 810b yellow open accounts AU-U-UhRTTuk41lj__iMoA 5 1 1 0 5.2kb 5.2kb yellow open blog_index jqd1be96TWikVoqkKLE0GA 5 1 0 0 324b 324b
参考文档:[1] https://blog.csdn.net/mydeman/article/details/54808267