python对接elasticsearch的基本操作
一.关于集群的基本操作
#!/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的基本操作的更多相关文章
- django使用haystack对接Elasticsearch实现商品搜索
# 原创,转载请留言联系 前言: 在做一个商城项目的时候,需要实现商品搜索功能. 说到搜索,第一时间想到的是数据库的 select * from tb_sku where name like %苹果手 ...
- Elasticsearch使用系列-.NET6对接Elasticsearch
Elasticsearch使用系列-ES简介和环境搭建 Elasticsearch使用系列-ES增删查改基本操作+ik分词 Elasticsearch使用系列-基本查询和聚合查询+sql插件 Elas ...
- python selenium webdriver入门基本操作
python selenium webdriver入门基本操作 未经作者允许,禁止转载! from selenium import webdriver import time driver=webdr ...
- Python数据分析库pandas基本操作
Python数据分析库pandas基本操作2017年02月20日 17:09:06 birdlove1987 阅读数:22631 标签: python 数据分析 pandas 更多 个人分类: Pyt ...
- Python 操作 ElasticSearch
Python 操作 ElasticSearch 学习了:https://www.cnblogs.com/shaosks/p/7592229.html 官网:https://elasticsearch- ...
- Python 和 Elasticsearch 构建简易搜索
Python 和 Elasticsearch 构建简易搜索 作者:白宁超 2019年5月24日17:22:41 导读:件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正 ...
- Python操作ElasticSearch
Python批量向ElasticSearch插入数据 Python 2的多进程不能序列化类方法, 所以改为函数的形式. 直接上代码: #!/usr/bin/python # -*- coding:ut ...
- python对接常用数据库,快速上手!
python对接常用数据库,快速上手! 很多同学在使用python进行自动化测试的时候,会涉及到数据库数据校验的问题,因为不知道如何在python中如何对数据库,这个时候会一脸茫然,今天在这里给大家汇 ...
- 笔记13:Python 和 Elasticsearch 构建简易搜索
Python 和 Elasticsearch 构建简易搜索 1 ES基本介绍 概念介绍 Elasticsearch是一个基于Lucene库的搜索引擎.它提供了一个分布式.支持多租户的全文搜索引擎,它可 ...
随机推荐
- [LC] 362. Design Hit Counter
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
- PHP--修改数据库表前缀
<?php // error_reporting(0); //设置好相关信息 $dbserver='localhost';//连接的服务器一般为localhost $dbname='jfpay' ...
- windows 不能在本地计算机启动apache2。有关更多信息,查阅系统事件日志。如果这是非Microsoft服务,请与服务厂商联系,并参考特定服务错误代码1
今天使用apache的时候又无法启动了,之前也遇到过,这次重点说这一次的情况,其他情况可以查看博主apache相关的其他博文:网上关于apache服务端的设置的很多,但是都不适合我的情况: 一般使用a ...
- Nginx笔记总结十七:nginx生成缩略图配置(http_image_filter_module)
编译: ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_realip_module-- ...
- 中心极限定理|z分布|t分布|卡方分布
生物统计学 抽样分布:n个样本会得到n个统计量,将这n个统计量作为总体,该总体的分布即是抽样分布 根据辛钦大数定律,从一个非正态分布的总体中抽取的含量主n的样本,当n充分大时,样本平均数渐近服从正态分 ...
- js 实现排序算法 -- 归并排序(Merge Sort)
原文: 十大经典排序算法(动图演示) 归并排序 归并排序是建立在归并操作上的一种有效的排序算法.该算法是采用分治法(Divide and Conquer)的一个非常典型的应用.将已有序的子序列合并,得 ...
- if分支判断
# 控制语句 分支 循环语句 # 判断语句 if ..elif..else # if 条件语句(比较 逻辑 成员运算) # 空数据 == False # 非空数据 == True age = 20 i ...
- python基础实现简单的shell sed 替换功能
#coding:utf-8 from pygame.draw import lines import sys,os old_file = sys.argv[1] #接受外部设备上的参数 new_fil ...
- 递归遍历磁盘下的某一文件夹中所有文件,并copy文件生成文件和带文件夹的文件
package com.hudong.test; import java.io.File; import java.io.IOException; import java.util.ArrayList ...
- Apache JMeter--1基础介绍
一.JMeter 介绍 近期公司要做jmeter调研,将性能测试推广到全部测试组,便一边学习一边做记录. Apache JMeter是100%纯JAVA桌面应用程序,是一款优秀的开源性能测试工具,被设 ...