python操作elasticsearch

Python Elasticsearch  api(官方文档)

安装Elasticsearch模块

pip install elasticsearch

添加数据

from elasticsearch import Elasticsearch

# 默认host为localhost,port为9200.但也可以指定host与port
es = Elasticsearch("http://localhost:9200")
# 添加或更新数据,index,doc_type名称可以自定义,id可以根据需求赋值,body为内容 如果不写id值的话会生成一个随机数的id 

es.index(index
="my_index",doc_type="test_type",id=1,body={"name":"python","addr":"深圳"})
{'_index': 'my_index', '_type': 'test_type', '_id': '9K3sSGoBL92egitcUv3j', '_score': 1.0, '_source': {'name': 'c', 'addr': '广州', 'tittle': '13 c学习', 'age': 13}}

删除数据

delete:删除指定index、type、id的文档

es.delete(index='indexName', doc_type='typeName', id='idValue') #当被删除的文档不存在的时候会报错

条件删除

body = {
   'query':{
       'range':{
           'age':{
               'gte':10,
               'lte':10
           }
       }
   }
}
#
es.delete_by_query(index='my_index',body=body)

查询数据

from elasticsearch import Elasticsearch

es = Elasticsearch()

# 获取索引为my_index,文档类型为test_type的所有数据,result为一个字典类型
result = es.search(index="my_index")

# 或者这样写:搜索id=1的文档
result = es.get(index="my_index",doc_type="test_type",id=1)

# 打印所有数据
for item in result["hits"]["hits"]:
    print(item["_source"])

参考文章:https://www.cnblogs.com/wangkun122/articles/10736507.html

posted @ 2019-12-14 20:14  腹肌猿  阅读(377)  评论(0编辑  收藏  举报