一.关于集群的基本操作

#!/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. 百度AI技术

    利用百度提供接口,实现智能语音 语音合成 -- TTS(text to speech) 注册 在 ai.baidu.com 页面中点击 控制台 ,弹出登陆 / 注册页面 创建应用 登陆成功后,点击左侧 ...

  2. org.apache.http.NoHttpResponseException

    org.apache.http.NoHttpResponseException 异常: org.apache.http.NoHttpResponseException: The target serv ...

  3. [LC] 746. Min Cost Climbing Stairs

    On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay ...

  4. 3DSMAX安装未完成,某些产品无法安装的解决方法

    3DSMAX提示安装未完成,某些产品无法安装该怎样解决呢?,一些朋友在win7或者win10系统下安装3DSMAX失败提示3DSMAX安装未完成,某些产品无法安装,也有时候想重新安装3DSMAX的时候 ...

  5. CAD卸载/完美解决安装失败/如何彻底卸载清除干净cad各种残留注册表和文件的方法

    在卸载cad重装CAD时发现安装失败,提示是已安装或安装失败.这是因为上一次卸载后没有清理干净,系统会误认为已经安装过了.有的同学是新装的系统也会出现安装失败的情况,这是因为C++ 或者.NET的原因 ...

  6. RxSwift学习笔记之Subject

    本文为原创文章,转载请标明出处 AsyncSubject 一个AsyncSubject只在原始Observable完成后,发射来自原始Observable的最后一个值.它会把这最后一个值发射给任何后续 ...

  7. CPU|MICGPU|FPGA|超算|Meta-data|

    生物医学大数据: 收集数据后对数据的分析,如同看相,而对数据信息的挖掘可以看作是算命.这两个过程是基于算法和软件这类工具之上的. 在存储方面:在硬件上,为了Parallel computing的目的, ...

  8. unittest(11)- get_data自定义取某几条测试数据

    在get_data中定义取全部用例和取部分用例两种模式 # 1. http_request.py import requests class HttpRequest: def http_request ...

  9. JavaScript深入浅出-闭包

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 function (){ var localVal ...

  10. MobX中@computed和自定义get函数的区别

    首先这两者解决方法都会得到一个相同的结果,但使用@computed的意义在于它能够由MobX进行更智能的优化. 如果我不使用computed属性,直接使用自定义的getTheValue函数的话,那么一 ...