一.关于集群的基本操作

#!/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. Spring-IOC(DI)的三种注入方式

    spring为方便不同的需求,为我们提供了3中不同的注入方式分别是set.get方法注入,构造注入还有p命名空间注入,老规矩,直接上代码 首先创建实体类Student public class Stu ...

  2. vue-cli3初始化项目

    1 npm install -g @vue/cli 创建配置 创建 1 vue create vue-app 选择配置 1234 ? Please pick a preset: (Use arrow ...

  3. tftpd64-SE使用

    使用场景: 把windows下的文件写入到linux(嵌入式设备中): 下载地址: https://bitbucket.org/phjounin/tftpd64/wiki/Download%20Tft ...

  4. Linux和git使用

    一.Linux ​ cd . .. - ~ ls -a h l 通配符 mkdir bouch nano vim cat clear cp -r ./db/ ./lib/ mv -r rm -r wh ...

  5. IIS6.0远程命令执行

    0X00 漏洞信息: 漏洞编号:CVE-2017-7269 漏洞简述:开启WebDAV服务的IIS 6.0被爆存在缓存区溢出漏洞导致远程代码执行,目前针对 Windows Server2003 R2 ...

  6. classnames

    在React中编写模板时给标签添加class. 如果是固定的className="XX"就可以了. 如果要根据状态值动态应用或去除, 或使用多个class时就麻烦了. 可以使用cl ...

  7. Object.defineProperty注意事项

    Object.defineProperty() 方法设置属性时,属性不能同时声明访问器属性( set 和 get )和 writable 或者 value 属性. 意思就是,某个属性设置了 writa ...

  8. NERDTree快捷键

    切换工作台和目录 ctrl + w + h 光标 focus 左侧树形目录ctrl + w + l 光标 focus 右侧文件显示窗口ctrl + w + w 光标自动在左右侧窗口切换ctrl + w ...

  9. 虚拟桌面软件CitrixReceiver相关问题

    由于安过一次,卸载再次安装程序报错: 原因:卸载不干净,导致再次安装部分插件未成功安装 解决: 1.在控制面板卸载Citrix receiver 2.删除C:\Program Files (x86)\ ...

  10. 使用Python生成自己的特色二维码

    二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据 ...