安装elasticsearch包
pip install elasticsearch # 豆瓣源 pip install -i https://pypi.doubanio.com/simple/ elasticsearch
python连接elasticsearch
from elasticsearch import Elasticsearch es=Elasticsearch() #默认连接本地的es # es = Elasticsearch(['127.0.0.1:9200']) # 连接本地9200端口
es = Elasticsearch( ["192.168.1.10", "192.168.1.11", "192.168.1.12"], # 连接集群,以列表的形式存放各节点的IP地址 sniff_on_start=True, # 连接前测试 sniff_on_connection_fail=True, # 节点无响应时刷新节点 sniff_timeout=60 # 设置超时时间
)
结果过滤
#既可以指定type类型又可以省略type类型 es.search(index='w2',filter_path=['hits.total','hits.hits._source']) es.search(index='w2',doc_type='doc') es.search(index='w2',doc_type='doc',filter_path=['hits.total'])
filter_path参数 : 参数用于减少es返回的响应,比如仅返回 'hits.total' , 'hits.hits._source .
filter_path还支持*的操作
print(es.search(index='py2', filter_path=['hits.*'])) print(es.search(index='py2', filter_path=['hits.hits._*'])) print(es.search(index='py2', filter_path=['hits.to*'])) # 仅返回响应数据的total print(es.search(index='w2', doc_type='doc', filter_path=['hits.hits._*'])) # 可以加上可选的type类型
es.index 向指定索引添加或更新文档,如果索引不存在,会先创建索引,然后在执行添加或者更新索引
es.index(index='w2',doc_type='doc',id='3',body={'name':'佐助'}) #如果不指定id,系统会默认生成一个id es.index(index='w2',doc_type='doc',body={'name':'小小樱'})
es.get 查询索引中指定文档(必须指定doc_type和id)
es.get(index='w2',doc_type='doc',id=5) #错误示范 print(es.get(index='w2', doc_type='doc')) # TypeError: get() missing 1 required positional argument: 'id' print(es.get(index='w2', id=5)) # TypeError: get() missing 1 required positional argument: 'doc_type'
es.search 执行搜索查询并获取与查询匹配的搜索匹配.可以跟复杂的查询条件
es.search(index='w2',doc_type='doc',body={'query':{'match':{'age':20}}}) #结果字段过滤 es.search(index='w2',doc_type='doc',body={'query':{'match':{'age':19}}},_source=['name','age'])
es.get_source ,通过索引,类型和ID获取文档的来源,其实,直接返回想要的字典
es.get_source(index='w2',doc_type='doc',id='1') # {'name': '王五', 'age': 19} 注意,这里返回的结果是一个字典
es.count 执行查询并获取该查询的匹配数.比如查询年龄是18的文档.
body = { "query": { "match": { "age": 18 } } } #获取到查询出来的匹配数 es.count(index='w2',doc_type='doc',body=body)
es.create 创建索引(索引不存在的话)并新增一条数据,索引存在仅新增(只能新增,如果重复执行会报错)
es.create(index='w2',doc_type='doc',id=1,body={'name':'王五'}) es.get(index='py3', doc_type='doc', id='3')
create在内部其实调用了index
es.delete 删除指定的文档.但不能删除仅只删除索引,如果想要删除索引,还需要es.indices.delete来处理
es.delete(index='py3', doc_type='doc', id='4')
es.delete_by_query,删除与查询匹配的所有文档.
es.delete_by_query(index='w2',doc_type='doc',body={"query":{'match':{'age':20}}})
es.exists 查询es中是否存在指定的文档,返回一个布尔值
#返回一个布尔值 es.exists(index='w2',doc_type='doc',id=1)
es.info 获取当前集群的基本信息
es.info()
Indices(es.indices)
es.indices.analyze,返回分词结果
print(es.indices.analyze(body={"analyzer":'ik_max_word','text':'泰国新加坡印度尼西亚'}))
es.indices.delete ,在es中删除索引
print(es.indices.delete(index='w2'))
es.indices.put_alias 为一个或多个索引创建别名,查询多个索引时,可以使用这个别名
print(es.indices.put_alias(index=["w1","w2"],name='alias_w12'))