一.关于集群的基本操作

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author tom
from elasticsearch import Elasticsearch
from pprint import pprint # 连接es,直接传一个ip字符串参数也可以,他会帮你封装成列表的
es_host = 'XXX.XX.XX.XXX'
#es = Elasticsearch(es_host,)
#es=Elasticsearch(['192.168.10.10', '192.168.10.11', '192.168.10.12']) #连接集群
es = Elasticsearch([es_host],
# 在做任何操作之前,先进行嗅探
# sniff_on_start=True,
# 节点没有响应时,进行刷新,重新连接
# sniff_on_connection_fail=True,
# # 每 60 秒刷新一次
# sniffer_timeout=60
) ###########################关于基本信息的查看############
# #测试是否能连通
# pprint(es.ping())
# #查看集群的健康信息
# pprint(es.cluster.health())
# #查看当前集群的节点信息
# pprint(es.cluster.client.info())
# #查看集群的更多信息
# pprint(es.cluster.state())
# 使用cat查看更多信息
# pprint(es.cat.health())
# pprint(es.cat.master())
# pprint(es.cat.nodes())
# pprint(es.cat.count())

二.关于索引的基本操作

# 查看当前集群的所有的索引
# pprint(es.cat.indices())
# 创建索引
# 创建索引的时候可以指定body参数,就是mapping的type的配置信息
# mapping={}
# res=es.indices.create(index='my-index',ignore=True,body=mapping)
# pprint(res)
# pprint(es.cat.indices()) # 删除索引
# res=es.indices.delete(index='my-index')
# pprint(res) # 判断索引是否存在
# res=es.indices.exists(index='my-index')
# pprint(res)

三.操作单条数据

# 插入数据的时候指定的索引可以不存在,但是不建议这么做,最好先判断,不存在集创建,这样不易出问题

# 添加一条数据
# 使用index新增可以不指定id,会随机生成一个id,
# 如果指定了id,当id存在的时候,就会对这条数据进行更新,id不存在则新建
# 这边要注意一下,使用index更新,他会用新的字典,直接替换原来的整个字典,与update方法是不一样的
# body = {'name': 'xiaosan', 'age': 18, 'sex': 'girl', }
# res = es.index(index='my-index', body=body, id='OokS028BE9BB6NkUgJnI')
# pprint(res) #使用create新增一条数据
# 注意使用create新增数据必须指定id,create本质也是调用了index,如果id已经存在就会报错(ConflictError重复错误,所以少用)
# body = {'name': 'xiaosan', 'age': 18, 'sex': 'girl', }
# res=es.create(index='my-index',body=body,id=1) # 查询一条数据(通过id来查询)
# res=es.get(index='my-index',id='OYkK028BE9BB6NkUOZll')
# pprint(res) # 查询所有数据
# body = {'query': {'match_all': {}}}
# res = es.search(index='my-index', body=body)
# pprint(res) # 删除数据(通过指定索引和id进行删除)
# res=es.delete(index='my-index',id='O4kZ028BE9BB6NkUUpm4') #删除指定id
# pprint(res)
# print(es.delete_by_query(index='p2', body={"query": {"match": {"age": 20}}})) #删除符合条件 # 更新数据(指定id更新数据,在es7之后要更新的数据需要用一个大字典包裹着,并且,key为doc )
# body={'doc':{'heigh':180}} #这个更新操作是在原来的基础上增加一个字段,而如果字段原来存在就会进行替换
# res=es.update(index='my-index',id='OokS028BE9BB6NkUgJnI',body=body) #判断指定id的数据是否存在 pprint(es.exists(index='person1', id='xVywInIBMTX0DMkCECea'))

四.关于多条数据或者高级操作

######### 使用term或者terms进行精确查询
body = {
"query":{
"term":{
"name":"python"
}
}
}
######### 查询name="python"的所有数据
es.search(index="my-index",doc_type="test_type",body=body)
body = {
"query":{
"terms":{
"name":[
"python","android"
]
}
}
}
# 搜索出name="python"或name="android"的所有数据
res=es.search(index="my_index",doc_type="test_type",body=body)
print(res) ########### match与multi_match
# match:匹配name包含python关键字的数据
body = {
"query":{
"match":{
"name":"python"
}
}
}
# 查询name包含python关键字的数据
es.search(index="my_index",doc_type="test_type",body=body) body = {
"query":{
"multi_match":{
"query":"深圳",
"fields":["name","addr"]
}
}
}
# 查询name和addr包含"深圳"关键字的数据
es.search(index="my_index",doc_type="test_type",body=body) ############ ids body = {
"query":{
"ids":{
"type":"test_type",
"values":[
"",""
]
}
}
}
# 搜索出id为1或2d的所有数据
es.search(index="my_index",doc_type="test_type",body=body) ########### 复合查询bool
#bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足) body = {
"query":{
"bool":{
"must":[
{
"term":{
"name":"python"
}
},
{
"term":{
"age":18
}
}
]
}
}
}
# 获取name="python"并且age=18的所有数据
es.search(index="my_index",doc_type="test_type",body=body) ############# 切片式查询
body = {
"query":{
"match_all":{}
},
"from":2, # 从第二条数据开始
"size":4 # 获取4条数据
}
# 从第2条数据开始,获取4条数据
es.search(index="my_index",doc_type="test_type",body=body) ###########范围查询 body = {
"query":{
"range":{
"age":{
"gte":18, # >=18
"lte":30 # <=30
}
}
}
}
# 查询18<=age<=30的所有数据
es.search(index="my_index",doc_type="test_type",body=body) #########前缀查询
body = {
"query":{
"prefix":{
"name":"p"
}
}
}
# 查询前缀为"赵"的所有数据
es.search(index="my_index",doc_type="test_type",body=body) ###### 通配符查询
body = {
"query":{
"wildcard":{
"name":"*id"
}
}
}
# 查询name以id为后缀的所有数据
es.search(index="my_index",doc_type="test_type",body=body) ######## 排序
body = {
"query":{
"match_all":{}
},
"sort":{
"age":{ # 根据age字段升序排序
"order":"asc" # asc升序,desc降序
}
}
} ########## filter_path
# 只需要获取_id数据,多个条件用逗号隔开
es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._id"]) ######### 获取所有数据
es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._*"]) #度量类聚合
#获取最小值 body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"min_age":{ # 最小值的key
"min":{ # 最小
"field":"age" # 查询"age"的最小值
}
}
}
}
# 搜索所有数据,并获取age最小的值
es.search(index="my_index",doc_type="test_type",body=body) body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"max_age":{ # 最大值的key
"max":{ # 最大
"field":"age" # 查询"age"的最大值
}
}
}
} ####### 搜索所有数据,并获取age最大的值
es.search(index="my_index",doc_type="test_type",body=body) body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"sum_age":{ # 和的key
"sum":{ # 和
"field":"age" # 获取所有age的和
}
}
}
}
# 搜索所有数据,并获取所有age的和
es.search(index="my_index",doc_type="test_type",body=body) #获取平均值
body = {
"query":{
"match_all":{}
},
"aggs":{ # 聚合查询
"avg_age":{ # 平均值的key
"sum":{ # 平均值
"field":"age" # 获取所有age的平均值
}
}
}
}
# 搜索所有数据,获取所有age的平均值
es.search(index="my_index",doc_type="test_type",body=body)

五.对返回的字段进行过滤

  filter_path参数用于过滤减少es返回信息,可以指定返回相关的内容,还支持一些通配符的操作*

# 主要是对_source同一级的字段进行过滤
print(es.search(index="p1", body=body, filter_path=["hits.hits"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._source"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._source", "hits.total"]))
print(es.search(index="p1", body=body, filter_path=["hits.*"]))
print(es.search(index="p1", body=body, filter_path=["hits.hits._*"]))

六.获取数据量

#########  count
#执行查询并获取该查询的匹配数 ######## 获取数据量
es.count(index="my_index",doc_type="test_type")
pprint(es.count(index='person'))
pprint(es.count(index='person')['count'])

  结果:

{'_shards': {'failed': 0, 'skipped': 0, 'successful': 1, 'total': 1},
'count': 1}
1

python对接elasticsearch的基本操作的更多相关文章

  1. django使用haystack对接Elasticsearch实现商品搜索

    # 原创,转载请留言联系 前言: 在做一个商城项目的时候,需要实现商品搜索功能. 说到搜索,第一时间想到的是数据库的 select * from tb_sku where name like %苹果手 ...

  2. Elasticsearch使用系列-.NET6对接Elasticsearch

    Elasticsearch使用系列-ES简介和环境搭建 Elasticsearch使用系列-ES增删查改基本操作+ik分词 Elasticsearch使用系列-基本查询和聚合查询+sql插件 Elas ...

  3. python selenium webdriver入门基本操作

    python selenium webdriver入门基本操作 未经作者允许,禁止转载! from selenium import webdriver import time driver=webdr ...

  4. Python数据分析库pandas基本操作

    Python数据分析库pandas基本操作2017年02月20日 17:09:06 birdlove1987 阅读数:22631 标签: python 数据分析 pandas 更多 个人分类: Pyt ...

  5. Python 操作 ElasticSearch

    Python 操作 ElasticSearch 学习了:https://www.cnblogs.com/shaosks/p/7592229.html 官网:https://elasticsearch- ...

  6. Python 和 Elasticsearch 构建简易搜索

    Python 和 Elasticsearch 构建简易搜索 作者:白宁超 2019年5月24日17:22:41 导读:件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正 ...

  7. Python操作ElasticSearch

    Python批量向ElasticSearch插入数据 Python 2的多进程不能序列化类方法, 所以改为函数的形式. 直接上代码: #!/usr/bin/python # -*- coding:ut ...

  8. python对接常用数据库,快速上手!

    python对接常用数据库,快速上手! 很多同学在使用python进行自动化测试的时候,会涉及到数据库数据校验的问题,因为不知道如何在python中如何对数据库,这个时候会一脸茫然,今天在这里给大家汇 ...

  9. 笔记13:Python 和 Elasticsearch 构建简易搜索

    Python 和 Elasticsearch 构建简易搜索 1 ES基本介绍 概念介绍 Elasticsearch是一个基于Lucene库的搜索引擎.它提供了一个分布式.支持多租户的全文搜索引擎,它可 ...

随机推荐

  1. 总结verilog产生随机数的$random和seed

      $random(seed)是verilog中最简单的产生随机数的系统函数. 在调用系统函数$random(seed)时,可以写成三种样式:1)$random,2)$random(),3)$rand ...

  2. @Value默认值填null

    @Value("${topology.position.spout.maxpending:#{null}}") private Integer spoutMaxPending; @ ...

  3. python3之scrapy数据存储问题(MySQL)

    这次我用的是python3.6,scrapy在python2.7,3.5的使用方法都不同所以要特别注意, 列如 在python3.5的开发环境下scrapy 的主爬虫文件可以使用 from urlli ...

  4. 吴裕雄--天生自然python学习笔记:Python3 迭代器与生成器

    迭代器 迭代是Python最强大的功能之一,是访问集合元素的一种方式. 迭代器是一个可以记住遍历的位置的对象. 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束.迭代器只能往前不会后退 ...

  5. Ubuntu gnome安装Monaco字体,FontForge module is probably not installed

    首先下载原始Monaco字体,注意我只找到了这一款在ubuntu的gnome下可见,其他的各种monaco即使安装了也看不到. https://gist.github.com/epegzz/16342 ...

  6. byte的取值范围是-128~127,那么包含-128和127吗?

    本帖最后由 王德升老师 于 2019-12-27 17:56 编辑 byte的取值范围为什么是-128~127?如果面试官问你取值范围包含127吗?1. 首先我们知道Java中byte类型是1个字节占 ...

  7. devexpress设置选中行

    版本2009.3 gvTagInfo.FocusedRowHandle = k; ;   //有效  gvTagInfo.FocusedRowHandle = k;              //这种 ...

  8. mode|平均数|方差|标准差|变异系数|四分位数|几何平均数|异众比率|偏态|峰态

    应用统计学 数据的概括性度量 集中趋势 Mode众数是唯一描述无序类别数据,由图可知众数便是图形中的峰. 对于类别变量,众数就是某一种类别. 中位数和平均数都可能不是样本中的值. 中位数不受极值影响, ...

  9. Luogu_2061_[USACO07OPEN]城市的地平线City Horizon

    题目描述 Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the cit ...

  10. Dockerfile创建zabbix监控体系

    使用for循环将zabbix的镜像导入到容器中 for n in `ls *.tar.gz`;do docker load -i $n ;done 使用docker运行zabbix-server do ...