1.下载安装elasticsearch模块
pip install elasticsearch
2.python连接elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch(["192.168.229.140:9200"])#连接自己的localhost
3.创建一篇文档\查询文档\删除文档
#创建一篇文档
es.index(index='p2',id=2,body={"name":"zhang"})
#查询文档
print(es.get(index='p2',doc_type="doc",id=1))
#删除文档
es.delete(index='p2',id=2)
4.match查询
格式和在kilbana中格式类似
body1 = {
"query":{
"match":{
"name":'LISI'
}
}
}
print(es.search(index='s1',body=body1))
5.match查询加上filter过滤
因为查询出的数据有太多的字段包裹不方便查看因此可以使用filter_path进行一个过滤方便查看
print(es.search(index='s1',body=body1,filter_path=['hits.hits']))
可以使用filter_path查询索引下的文档的个数
print(es.search(index='s1',body=body1,filter_path=['hits.hits','hits.total']))
过滤后
6.count函数的应用
查询某一数据出现的次数
body = {
"query":{
"match":{
"name":"lou2"
}
}
}
print(es.count(index='s1',body=body))
7.按照条件删除
删除name为lou2的文档
print(es.delete_by_query(index="s1",body=body))
8.es.exists 查询此文档是否存在
print(es.exists(index='s1',id=1))
返回True是存在 返回false是不存在
9.es创建索引并设置mappings
body2 = {
"mappings":{
"properties":{
"name":{
"type":"text"
},
"age":{
"type":"long"
}
}
}
}
print(es.indices.create(index='s15',body=body2))
查看mappings
print(es.indices.get_mapping(index='s15'))
10.es.indices.analyse返回分词结果
print(es.indices.analyze(body={"analyzer":"ik_smart","text":"哈士奇是只狗"}))
11.别名的创建
Es中创建别名可以简单的认为是mysql中的视图,别名仅仅支持查询操作
#别名的创建
# print(es.indices.put_alias(index='s1',name='s1-1'))
#删除别名
# print(es.indices.delete_alias(index='s1',name='s1-1'))
#别名的查询
# print(es.indices.get_alias(index='s1'))