python操作elasticsearch

一、安装库

pip install elasticsearch

二、连接库

from elasticsearch import  Elasticsearch
from datetime import datetime

#都有默认值,可以选择设置
es = Elasticsearch(
    ['127.0.0.1:9200',"0.0.0.0:9300", "0.0.0.0:9301", "0.0.0.0:9302"], # 连接集群,以列表的形式存放各节点的IP地址
    sniff_on_start=True,    # 连接前测试
    sniff_on_connection_fail=True,  # 节点无响应时刷新节点
    sniff_timeout=60,    # 设置超时时间
    # ignore=400,  # 忽略返回的400状态码
    # ignore=[400, 405, 502],  # 以列表的形式忽略多个状态码
    # http_auth=('elastic', 'changeme')  # 认证信息
    )

三、集群信息

#集群基本信息
print(es.info())
#状态信息
print(es.cluster.health())

四、创建索引

#默认分词器
#索引可以先创建,也可以插入数据时临时创建
es.indices.create(index='myindex')

#指定分词器
'''
ik分词器
	ik_max_word	最细粒度的拆分,例如:'北京大学'  -->  '北京大学'/'北京'/'大学'
	ik_smart	最粗粒度的拆分
'''
#创建索引时还可以做其他设置,详情搜索'es settings、mappings'里的设置信息
body = {
  "settings": {
    "index.analysis.analyzer.default.type": "ik_max_word"
    }
}
es.indices.create(index='myindex',body = body)

五、插入数据

#索引可以先创建,也可以插入数据时临时创建
es.indices.create(index='myindex')

#index,doc_type,id都一致时会覆盖
#插入数据
es.index(index="myindex",doc_type="mytype",id=1,body={"name":"张三","age":18,"time":datetime.now()})
es.index(index="myindex",doc_type="mytype",id=2,body={"name":"李四","age":20,"time":datetime.now()})
es.index(index="myindex",doc_type="mytype",id=4,body={"name1":"李四","name2":"张三","age":20,"time":datetime.now()})
es.index(index="myindex",doc_type="mytype",id=5,body={"name1":"张三","name2":"李四","age":20,"time":datetime.now()})
#没有索引就创建
es.index(index="testindex",doc_type="mytype",id=3,body={"name":"王五","age":20,"time":datetime.now()})

六、查询所有信息

#查看所有index
print(es.indices.get_alias("*"))
#查看所有信息(res['hits']['hits']里)
res = es.search()
print(res)

七、get查询数据

res = es.get(index="myindex", doc_type="mytype", id=1)
print(res)
print(res['_source'])

八、search查询数据

1)查询所有数据

#查询所有数据
res = es.search(index="myindex", body={"query":{"match_all":{}}})
print(res)
for hit in res['hits']['hits']:
    print(hit["_source"])

2)match与multi_match

'''
指定分词器查询(默认和创建的分词器一致):
body = {
    "query": {
        "match": {
            "name":{
                "query": "张三",
                "analyzer": "ik_smart"
            }

        }
    }
}
'''
# match:匹配name1分词中包含'张'关键字的数据
body = {
    "query": {
        "match": {
            "name1": "张"
        }
    }
}
res = es.search(index="myindex", doc_type="mytype", body=body)
print(res)

# multi_match:在name1和name2里匹配包含深圳关键字的数据
body = {
    "query": {
        "multi_match": {
            "query": "四",
            "fields": ["name1","name2"]
        }
    }
}
# # 查询name1和name2包含"四"关键字的数据
res = es.search(index="myindex", doc_type="mytype", body=body)
print(res)

3)term与terms

# term
body = {
    "query": {
        "term": {
            "age": 20
        }
    }
}

# 查询"age": 20的所有数据
res = es.search(index="myindex", doc_type="mytype", body=body)
print(res)

# terms
body = {
    "query": {
        "terms": {
            "age": [
                18, 20
            ]
        }
    }
}
# 搜索出"age": 18或"age": 20的所有数据
res = es.search(index="myindex", doc_type="mytype", body=body)
print(res)

4)ids

body = {
    "query":{
        "ids":{
            # "type":"mytype",
            "values":[
                "1","2"
            ]
        }
    }
}
# 搜索出id为1或2d的所有数据
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

5)复合查询bool

#bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足)
body = {
    "query":{
        "bool":{
            "should":[
                {
                    "term":{
                        "name":"张三"
                    }
                },
                {
                    "term":{
                        "age":20
                    }
                }
            ]
        }
    }
}
# 获取name="张三"或者age=20的所有数据
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

6)范围查询

'''
range不支持:
    eq 等于  
    neq 不等于
    
range支持:
    gt: greater than 大于
    gte: greater than or equal 大于等于
    lt: less than 小于
    lte: less than or equal 小于等于
'''

body = {
    "query":{
        "range":{
            "age":{
                "gte":18,       # >=18
                "lte":30        # <=30
            }
        }
    }
}
# 查询18<=age<=30的所有数据
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

7)切片查询

body = {
    "query":{
        "match_all":{}
    },

    "sort": [{"age": {"order": "asc"}}],  # 排序,asc是指定列按升序排列,desc则是指定列按降序排列
    "from":0,    # 从第1条数据开始
    "size":4    # 获取4条数据
}

res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

8)前缀查询

body = {
    "query":{
        "prefix":{
            "name":"张"
        }
    }
}
# 查询前缀为"张"的所有数据
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

9)通配符查询

body = {
    "query":{
        "wildcard":{
            "name":"*三"
        }
    }
}
# 查询name以'三'为后缀的所有数据
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

10)排序

body = {
    "query":{
        "match_all":{}
    },
    "sort":{
        "age":{                 # 根据age字段升序排序
            "order":"asc"       # asc升序,desc降序
        }
    }
}
res = es.search(index="myindex",doc_type="mytype",body=body)
print(res)

11)响应过滤

# 只需要获取_id数据,多个条件用逗号隔开
res = es.search(index="myindex", doc_type="mytype", filter_path=["hits.hits._id"])
print(res)
res = es.search(index="myindex", doc_type="mytype", filter_path=["hits.hits._index,hits.hits._id"])
print(res)

# 获取所有数据
res = es.search(index="myindex", doc_type="mytype", filter_path=["hits.hits._*"])
print(res)

12)count,匹配数量

# 匹配数量
res = es.count(index="myindex", doc_type="mytype")
print(res)

13)获取聚合值

'''
min:最小
max:最大
sum:求和
avg:平均值
'''
# 最小值
body = {
    "query":{
        "match_all":{}
    },
    "aggs":{                        # 聚合查询
        "min_age":{                 # 最小值的key
            "min":{                 # 最小
                "field":"age"       # 查询"age"的最小值
            }
        }
    }
}

res = es.search(index="myindex", doc_type="mytype",body=body)
print(res)
print(res['aggregations'])

九、更新数据

#更新一条数据,需要指定index,doc_type,id
es.update(index="myindex",doc_type="mytype",id=1,body={"doc":{"age":10}})
#条件更新
'''
其中script的语法为painless,具体语法参考:https://www.elastic.co/guide/en/elasticsearch/reference/6.2/painless-api-reference.html
"script": {
    "source": "def a=ctx._source['ip'].lastIndexOf('.');def sec=ctx._source['ip'].substring(0,a);ctx._source['ipSection']=sec+'.0'"
  }
  
'''
query = {"script": {
                "source": "ctx._source['age']=1"  #改为字符串时要加引号,"ctx._source['age']='张三'"
                    },
         'query': {
             'range': {
                 'age': {
                     'lt': 30
                 }
             }
         }
}
res = es.update_by_query(index="myindex",doc_type="mytype",body=query)
print(res)

十、删除index

es.indices.delete('testindex')
es.delete(index="testindex",doc_type='mytype',id='2')

十一、删除数据

es.delete_by_query(index="myindex", body={'query':{'match':{'any':'data'}}})

十二、es分词结果

#实时分词
result= es.indices.analyze(body={"analyzer":'ik_max_word','text':'上海自来水来自上海'})
print(result)

#存储的倒序后的分词结果
res = es.termvectors(index="myindex", doc_type="mytype", id=1,fields='name')
print(res)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值