Python操作ElasticSearch
Python批量向ElasticSearch插入数据
Python 2的多进程不能序列化类方法, 所以改为函数的形式.
直接上代码:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import re
import json
import time
import elasticsearch
from elasticsearch.helpers import bulk
from multiprocessing import Pool
def write_file(doc_type, action_list):
""""""
with open("/home/{}_error.json".format(doc_type), "a") as f:
for i in action_list:
f.write(str(i))
def add_one(file_path, doc_type, index):
"""准备插入一条"""
print doc_type, index
es_client = elasticsearch.Elasticsearch(hosts=[{"host": "localhost", "port": "9200"}])
with open(file_path, "r") as f:
for line in f:
try:
line = re.sub("\n", "", line)
dict_obj = json.loads(line)
es_client.index(index=index, doc_type=doc_type, body=dict_obj)
except Exception as e:
print "出错了, 错误信息: {}".format(e)
def add_bulk(doc_type, file_path, bulk_num, index):
""""""
es_client = elasticsearch.Elasticsearch(hosts=[{"host": "localhost", "port": "9200"}])
action_list = []
# 文件过大, 先插入5000万试水
total = 50000000
num = 0
with open(file_path, "r") as f:
for line in f:
num += 0
if num >= total:
break
# 去除每一行数据中的"\n"字符, 也可以替换为"\\n"
line = line.replace("\n", "")
dict_obj = json.loads(line)
# 根据bulk_num的值发送一个批量插入请求
# action = {
# "_index": index,
# "_type": doc_type,
# "_source": {
# "ip": dict_obj.get("ip", "None"),
# "data": str(dict_obj.get("data", "None"))
# }
# }
# 如果动态插入,字段过长,会报错,导致插不进去, 转为字符串就可以
action = {
'_op_type': 'index',
"_index": index,
"_type": doc_type,
"_source": dict_obj
}
action_list.append(action)
if len(action_list) >= bulk_num:
try:
print "Start Bulk {}...".format(doc_type)
success, failed = bulk(es_client, action_list, index=index, raise_on_error=True)
print "End Bulk {}...".format(doc_type)
except Exception as e:
print "出错了, Type:{}, 错误信息:{}".format(doc_type, e[0])
write_file(doc_type, action_list)
finally:
del action_list[0:len(action_list)]
# 如果不是bulk_num的等值, 那么就判断列表是否为空, 再次发送一次请求
if len(action_list) > 0:
try:
success, failed = bulk(es_client, action_list, index=index, raise_on_error=True)
except Exception as e:
print "出错了, Type:{}, 错误信息:{}".format(doc_type, e[0])
write_file(doc_type, action_list)
finally:
del action_list[0:len(action_list)]
def mulit_process(path, index, bulk_num, data):
""""""
# 多进程执行
pool = Pool(10)
results = []
for i in data:
doc_type = i["doc_type"]
file_path = i["file_path"]
result = pool.apply_async(add_bulk, args=(doc_type, file_path, bulk_num, index))
results.append(result)
pool.close()
pool.join()
def all_info(path):
data = []
for i in os.listdir(path):
file_dict = {}
if i.endswith(".json"):
doc_type = i.split("_")[0]
file_path = path + i
if doc_type == "443":
continue
file_dict["doc_type"] = doc_type
file_dict["file_path"] = file_path
data.append(file_dict)
return data
def es_insert(process_func=None):
""""""
# 库
index = "test"
# 文件路径
path="/home/data/"
# 批量插入的数量, 如果是json整条数据插入的话, 可能会出现字段过长的问题, 导致插不进去, 适当调整bulk_num的值
bulk_num = 5000
if not path.endswith("/"):
path += "/"
data = all_info(path)
if process_func == "bulk":
# 插入多条, doc_type, file_path, bulk_num, index
add_bulk("80", path + "80_result.json", bulk_num, index)
elif process_func == "one":
# 插入单条file_path, doc_type, index
add_one(path + "80_result.json", "80", index)
else:
# 多进程
mulit_process(path, index, bulk_num, data)
if __name__ == "__main__":
# 计算脚本执行时间
start_time = time.time()
if not os.path.exists("/home/test"):
os.makedirs("/home/test")
# 插入数据
es_insert()
# 计算脚本执行时间
end_time = time.time()
print end_time - start_time
Python搜索ElasticSearch
示例:
#!/usr/bin/python
# -*- coding:utf -*-
import json
import elasticsearch
def es_login(host="localhost", port="9200"):
"""连接es"""
return elasticsearch.Elasticsearch(hosts=[{"host": host, "port": port}])
def get(es_client, _id):
"""获取一条内容"""
# result = es_client.get(index="test", doc_type="80", id=_id)
result = es_client.get(index="test", id=_id)
return json.dumps(result)
def search(es_client, query, field="_all"):
"""聚合搜索内容"""
result = es_client.search(index="test", body={
"query": {
"bool": {
"must": [
{
"query_string": {
# 指定字段
"default_field": field,
# 查询字段
"query": query
}
},
{
"match_all": {}
}
],
"must_not": [],
"should": []
}
},
"from": 0,
"size": 10,
"sort": [],
# 聚合
"aggs": {
# "all_interests":{
# "terms":{
# "field":"interests"
# }
# }
}
})
return json.dumps(result)
def main():
"""入口"""
# 连接es
es_client = es_login()
# result = search(es_client, query="123.125.115.110", field="_all")
result = get(es_client, "AWTv-ROzCxZ1gYRliWhu")
print result
if __name__ == "__main__":
main()
删除ElasticSearch全部数据
curl -X DELETE localhost:9200/test, test为自己的index名称
Python操作ElasticSearch的更多相关文章
- Python 操作 ElasticSearch
Python 操作 ElasticSearch 学习了:https://www.cnblogs.com/shaosks/p/7592229.html 官网:https://elasticsearch- ...
- python操作elasticsearch增、删、改、查
最近接触了个新东西--es数据库 这东西虽然被用的很多,但我是前些天刚刚接触的,发现其资料不多,学起来极其痛苦,写个文章记录下 导入库from elasticsearch import Elastic ...
- python操作Elasticsearch (一、例子)
E lasticsearch是一款分布式搜索引擎,支持在大数据环境中进行实时数据分析.它基于Apache Lucene文本搜索引擎,内部功能通过ReST API暴露给外部.除了通过HTTP直接访问El ...
- python实现elasticsearch操作-CRUD API
python操作elasticsearch常用API 目录 目录 python操作elasticsearch常用API1.基础2.常见增删改操作创建更新删除3.查询操作查询拓展类实现es的CRUD操作 ...
- python使用elasticsearch模块操作elasticsearch
1.创建索引 命令如下 from elasticsearch import Elasticsearch es = Elasticsearch([{"host":"10.8 ...
- java操作elasticsearch实现批量添加数据(bulk)
java操作elasticsearch实现批量添加主要使用了bulk 代码如下: //bulk批量操作(批量添加) @Test public void test7() throws IOExcepti ...
- 利用NEST2.0 在C#中操作Elasticsearch
前言:本文主要演示了如何通过c#来操作elasticsearch,分两个方面来演示: 索引数据 搜索数据 Note: 注意我索引数据和搜索数据是两个不同的例子,没有前后依赖关系 准备工作:需要在vis ...
- Python 和 Elasticsearch 构建简易搜索
Python 和 Elasticsearch 构建简易搜索 作者:白宁超 2019年5月24日17:22:41 导读:件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正 ...
- 笔记13:Python 和 Elasticsearch 构建简易搜索
Python 和 Elasticsearch 构建简易搜索 1 ES基本介绍 概念介绍 Elasticsearch是一个基于Lucene库的搜索引擎.它提供了一个分布式.支持多租户的全文搜索引擎,它可 ...
随机推荐
- WPF 海康威视网络摄像头回调方式实现断连提示,降低时延
原文:WPF 海康威视网络摄像头回调方式实现断连提示,降低时延 项目需要使用海康威视网络摄像头接入实时视频数据,使用海康威视官方SDK开发,发现没有断连提示的功能,故开发了一个断连提示的功能 在开发过 ...
- Windows系统时间(FILETIME和SYSTEMTIME)
转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/8654298 欢迎关注微博:http://weibo.com/MoreWi ...
- WPF路由
举例:窗口-用户控件-布局控件-…-按钮 按钮的点击事件:先由按钮的Click相应,然后….,然后布局控件,然后用户控件,然后窗口类似异常,直到“处理完成”(实际上一般按钮自己处理即可) 路由事件 ...
- 赵伟国辞去TCL集团董事等职位,紫光参与TCL定增浮盈已超7亿
集微网消息,TCL 集团于8月9日晚间发布公告称,公司董事会于近日收到董事赵伟国先生的书面辞职报告,赵伟国先生因个人原因申请辞去公司董事及公司战略委员会委员职务.辞任后,赵伟国先生不再担任公司任何职务 ...
- DOM解析xml实现读、写、增、删、改
qt提供了三种方式解析xml,不过如果想实现对xml文件进行增.删.改等操作,还是DOM方式最方便. 项目配置 pro文件里面添加QT+=xml include <QtXml>,也可以in ...
- 在IE浏览器 使用PHPExcel导出文件时时 文件名中文乱码
1.当我们使用IE内核的浏览器下在PHPExcel报表时(谷歌.火狐浏览器正常, IE浏览器,360浏览器的兼容模式报错),会出现如下错误: 2.解决办法: 在下载文件时,对当前的浏览器进行判断, 如 ...
- NuGet安装包重新安装
Update-Package -reinstall 引用: https://docs.microsoft.com/zh-cn/nuget/consume-packages/reinstalling-a ...
- C#中??操作符的使用
为了实现Nullable数据类型转换成non-Nullable型数据,就有了一个这样的操作符”??(两个问号)“,双问号操作符意思是取所赋值??左边的,如果左边为null,取所赋值??右边的, 比如i ...
- 新兴技术袭来,Web开发如何抉择?
土豆网同步更新:http://www.tudou.com/plcover/VHNh6ZopQ4E/ 使用HTML 创建Mac OS App 视频教程. 官方QQ群: (1)App实践出真知 434 ...
- 基于mipsel编译Qt4.6.2版本(有具体参数和编译时遇到的问题)
1.使用的configure配置为:./configure -embedded mips -little-endian -xplatform qws/linux-mips-g++ -prefix /o ...