Python简单实现与ElasticSearch交互插入数据

这篇具有很好参考价值的文章主要介绍了Python简单实现与ElasticSearch交互插入数据。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

直接上代码进行演示,对比三种方式耗时情况!

示例代码1:   【循环读取数据,一条一条插入es数据库】

import re
import time
from elasticsearch import Elasticsearch

# 默认连接本地elasticsearch
es = Elasticsearch("http://localhost:9200")

# 将文件所有内容读取到此字符串中
all_str = ''
# 此列表每一个元素均为一整个<entry>  </entry>全部内容
valid_list = []
# 保存所有的entry_touple元组  {id:entry_touple}
tuple_dict = {}
# 将元组一个个存进去
tuple_list = []
# 字典的索引id
id = []
# 保存文件读取行数  用于判断文件是否成功完全读取
total_num = 0

# 开始计时
time_start = time.time()
# 打开原始文件
file = open('./2007.xml', "r", encoding='UTF-8')

# 打开旧文件 逐行读
for line in file.readlines():
    total_num += 1
    line = line.replace('\n', '')  # 将回车全部去除
    line = line.replace(' ', '')  # 将空格全部去除
    all_str += line

# 结束计时
time_end = time.time()
print("共处理了", total_num, "行xml数据")
print("文件所有字符(字符串)长度为:", len(all_str))
print("文件处理花费了:", time_end - time_start, "秒")

# 正则表达式取字符串  <entry>  </entry>
re_str_entry = r'<entry>(.+?)</entry>'
d = re.compile(re_str_entry)
# 取出原文件中所有的  <entry>  </entry>  保存到列表中
list_entry = d.findall(all_str)
print('共有' + str(len(list_entry)) + '条<entry>数据')
sums = len(list_entry)

time_end2 = time.time()
print("取正则表达式取字符串<entry>  </entry>花费了:", time_end2 - time_end, "秒")

# 遍历每一个entry将其中数据取出来
for data in list_entry:
    # 正则表达式取字符串<name>  </name>
    re_str_name = r'<name>(.+?)</name>'
    d = re.compile(re_str_name)
    # 取出每个<entry>  </entry>中的name字段
    name = d.findall(data)
    # print(name)

    # 正则表达式取字符串<vuln-id>  </vuln-id>
    re_str_vul_id = r'<vuln-id>(.+?)</vuln-id>'
    d = re.compile(re_str_vul_id)
    vuln_id = d.findall(data)
    # print(vuln_id)

    # 正则表达式取字符串<published>  </published>
    re_str_published = r'<published>(.+?)</published>'
    d = re.compile(re_str_published)
    published = d.findall(data)
    # print(published)

    # 正则表达式取字符串<modified>  </modified>
    re_str_modified = r'<modified>(.+?)</modified>'
    d = re.compile(re_str_modified)
    modified = d.findall(data)
    # print(modified)

    # 正则表达式取字符串<source>  </source>
    re_str_source = r'<source>(.+?)</source>'
    d = re.compile(re_str_source)
    source = d.findall(data)
    # print(source)

    # 正则表达式取字符串<severity>  </severity>
    re_str_severity = r'<severity>(.+?)</severity>'
    d = re.compile(re_str_severity)
    severity = d.findall(data)
    # print(severity)

    # 正则表达式取字符串 <vuln-type>  </vuln-type>
    re_str_vuln_type = r'<vuln-type>(.+?)</vuln-type>'
    d = re.compile(re_str_vuln_type)
    # 取出每个<vuln-type>  </vuln-type>中的字段
    vuln_type = d.findall(data)
    # print(vuln_type)

    # 正则表达式取字符串  <thrtype>  </thrtype>
    re_str_thrtype = r'<thrtype>(.+?)</thrtype>'
    d = re.compile(re_str_thrtype)
    thrtype = d.findall(data)
    # print(thrtype)

    # 正则表达式取字符串  <vuln-descript>  </vuln-descript>
    re_str_vuln_descript = r'<vuln-descript>(.+?)</vuln-descript>'
    d = re.compile(re_str_vuln_descript)
    vuln_descript = d.findall(data)
    # print(vuln_descript)

    # 正则表达式取字符串  <product>  </product>
    re_str_product = r'<product>CPE:/(.+?):</product>'
    d = re.compile(re_str_product)
    # 注意product可能有多个
    product = d.findall(data)
    # print(product)

    # 正则表达式取字符串  <vuln-solution>  </vuln-solution>
    re_str_vuln_solution = r'<vuln-solution>(.+?)</vuln-solution>'
    d = re.compile(re_str_vuln_solution)
    # 注意vuln_solution可能有多个
    vuln_solution = d.findall(data)
    # print(vuln_solution)

    entry_tuple = (
        name, vuln_id, published, modified, source, severity, vuln_type, thrtype, vuln_descript, product, vuln_solution)
    # 将每一个<entry>  </entry>中的数据按既定顺序存到一个元祖中
    # 下一步再将所有的元组放到一个字典中,最后将字典的数据一条条放到数据库中
    # print(entry_tuple[0:-1])
    tuple_list.append(entry_tuple[0:])

print(len(tuple_list))
# 制作一个和tuple_list一样长的列表
for i in range(len(tuple_list)):
    id.append(i)

# 形成字典类型
cve_dict = dict(zip(id, tuple_list))

time_end3 = time.time()
print("循环处理所有的<entry>花费了:", time_end3 - time_end2, "秒")

# 开始写入es数据库
for i in range(len(tuple_list)):
    es.index(index='entry', id=i, body={
        'name': cve_dict[i][0],
        "vuln-id": cve_dict[i][1],
        "published": cve_dict[i][2],
        "modified": cve_dict[i][3],
        "source": cve_dict[i][4],
        "severity": cve_dict[i][5],
        "vuln-type": cve_dict[i][6],
        "thrtype": cve_dict[i][7],
        "vuln-descript": cve_dict[i][8],
        "product": cve_dict[i][9][0:],
        "vuln-solution": cve_dict[i][10]})

print("向数据库中插入花费了:", time.time() - time_end3, "秒")
file.close()

运行结果:

python elasticsearch插入数据,ElasticSearch,python,elasticsearch

示例代码2:  【循环读取数据,批量处理插入es数据库】

import re
import time
from elasticsearch import Elasticsearch
from elasticsearch import helpers  # 批量处理数据

# 默认连接本地elasticsearch
es = Elasticsearch("http://localhost:9200")

# 将文件所有内容读取到此字符串中
all_str = ''
# 此列表每一个元素均为一整个<entry>  </entry>全部内容
valid_list = []
# 保存所有的entry_touple元组  {id:entry_touple}
tuple_dict = {}
# 将元组一个个存进去
tuple_list = []
# 字典的索引id
id = []
# 保存文件读取行数  用于判断文件是否成功完全读取
total_num = 0

# 开始计时
time_start = time.time()
# 打开原始文件
file = open('./2007.xml', "r", encoding='UTF-8')

# 打开旧文件 逐行读
for line in file.readlines():
    total_num += 1
    line = line.replace('\n', '')  # 将回车全部去除
    line = line.replace(' ', '')  # 将空格全部去除
    all_str += line

# 结束计时
time_end = time.time()
print("共处理了", total_num, "行xml数据")
print("文件所有字符(字符串)长度为:", len(all_str))
print("文件处理花费了:", time_end - time_start, "秒")

# 正则表达式取字符串  <entry>  </entry>
re_str_entry = r'<entry>(.+?)</entry>'
d = re.compile(re_str_entry)
# 取出原文件中所有的  <entry>  </entry>  保存到列表中
list_entry = d.findall(all_str)
print('共有' + str(len(list_entry)) + '条<entry>数据')
sums = len(list_entry)

time_end2 = time.time()
print("取正则表达式取字符串<entry>  </entry>花费了:", time_end2 - time_end, "秒")

# 遍历每一个entry将其中数据取出来
for data in list_entry:
    # 正则表达式取字符串<name>  </name>
    re_str_name = r'<name>(.+?)</name>'
    d = re.compile(re_str_name)
    # 取出每个<entry>  </entry>中的name字段
    name = d.findall(data)
    # print(name)

    # 正则表达式取字符串<vuln-id>  </vuln-id>
    re_str_vul_id = r'<vuln-id>(.+?)</vuln-id>'
    d = re.compile(re_str_vul_id)
    vuln_id = d.findall(data)
    # print(vuln_id)

    # 正则表达式取字符串<published>  </published>
    re_str_published = r'<published>(.+?)</published>'
    d = re.compile(re_str_published)
    published = d.findall(data)
    # print(published)

    # 正则表达式取字符串<modified>  </modified>
    re_str_modified = r'<modified>(.+?)</modified>'
    d = re.compile(re_str_modified)
    modified = d.findall(data)
    # print(modified)

    # 正则表达式取字符串<source>  </source>
    re_str_source = r'<source>(.+?)</source>'
    d = re.compile(re_str_source)
    source = d.findall(data)
    # print(source)

    # 正则表达式取字符串<severity>  </severity>
    re_str_severity = r'<severity>(.+?)</severity>'
    d = re.compile(re_str_severity)
    severity = d.findall(data)
    # print(severity)

    # 正则表达式取字符串 <vuln-type>  </vuln-type>
    re_str_vuln_type = r'<vuln-type>(.+?)</vuln-type>'
    d = re.compile(re_str_vuln_type)
    # 取出每个<vuln-type>  </vuln-type>中的字段
    vuln_type = d.findall(data)
    # print(vuln_type)

    # 正则表达式取字符串  <thrtype>  </thrtype>
    re_str_thrtype = r'<thrtype>(.+?)</thrtype>'
    d = re.compile(re_str_thrtype)
    thrtype = d.findall(data)
    # print(thrtype)

    # 正则表达式取字符串  <vuln-descript>  </vuln-descript>
    re_str_vuln_descript = r'<vuln-descript>(.+?)</vuln-descript>'
    d = re.compile(re_str_vuln_descript)
    vuln_descript = d.findall(data)
    # print(vuln_descript)

    # 正则表达式取字符串  <product>  </product>
    re_str_product = r'<product>CPE:/(.+?):</product>'
    d = re.compile(re_str_product)
    # 注意product可能有多个
    product = d.findall(data)
    # print(product)

    # 正则表达式取字符串  <vuln-solution>  </vuln-solution>
    re_str_vuln_solution = r'<vuln-solution>(.+?)</vuln-solution>'
    d = re.compile(re_str_vuln_solution)
    # 注意vuln_solution可能有多个
    vuln_solution = d.findall(data)
    # print(vuln_solution)

    entry_tuple = (
        name, vuln_id, published, modified, source, severity, vuln_type, thrtype, vuln_descript, product, vuln_solution)
    # 将每一个<entry>  </entry>中的数据按既定顺序存到一个元祖中
    # 下一步再将所有的元组放到一个字典中,最后将字典的数据一条条放到数据库中
    # print(entry_tuple[0:-1])
    tuple_list.append(entry_tuple[0:])

print(len(tuple_list))
# 制作一个和tuple_list一样长的列表
for i in range(len(tuple_list)):
    id.append(i)

# 形成字典类型
cve_dict = dict(zip(id, tuple_list))

time_end3 = time.time()
print("循环处理所有的<entry>花费了:", time_end3 - time_end2, "秒")

# 开始写入es数据库
# 批量写入数据
action = [
    {
        "_index": "entry_bulk",
        "_type": "doc",
        "_source": {
            "id": i,
            'name': cve_dict[i][0],
            "vuln-id": cve_dict[i][1],
            "published": cve_dict[i][2],
            "modified": cve_dict[i][3],
            "source": cve_dict[i][4],
            "severity": cve_dict[i][5],
            "vuln-type": cve_dict[i][6],
            "thrtype": cve_dict[i][7],
            "vuln-descript": cve_dict[i][8],
            "product": cve_dict[i][9][0:],
            "vuln-solution": cve_dict[i][10]
        }
    } for i in range(len(tuple_list))]
helpers.bulk(es, action)

print("向数据库中插入花费了:", time.time() - time_end3, "秒")
file.close()

运行结果:

python elasticsearch插入数据,ElasticSearch,python,elasticsearch

示例代码3:   【直接一次性读取数据,批量处理插入es数据库】

import re
import time
from elasticsearch import Elasticsearch
from elasticsearch import helpers  # 批量处理数据

# 默认连接本地elasticsearch
es = Elasticsearch("http://localhost:9200")

# 将文件所有内容读取到此字符串中
all_str = ''
# 此列表每一个元素均为一整个<entry>  </entry>全部内容
valid_list = []
# 保存所有的entry_touple元组  {id:entry_touple}
tuple_dict = {}
# 将元组一个个存进去
tuple_list = []
# 字典的索引id
id = []
# 保存文件读取行数  用于判断文件是否成功完全读取
total_num = 1

# 开始计时
time_start = time.time()
# 打开原始文件
file = open('./2007.xml', "r", encoding='UTF-8')

# # 打开旧文件 逐行读
# for line in file.readlines():
#     total_num += 1
#     line = line.replace('\n', '')  # 将回车全部去除
#     line = line.replace(' ', '')  # 将空格全部去除
#     all_str += line

# 将整个文件内容读取出来,存到all_str字符串变量中
data = file.read()
data = data.replace('\n', '')
all_str = data.replace(' ', '')

# 结束计时
time_end = time.time()
print("共处理了", total_num, "行xml数据")
print("文件所有字符(字符串)长度为:", len(all_str))
print("文件处理花费了:", time_end - time_start, "秒")

# 正则表达式取字符串  <entry>  </entry>
re_str_entry = r'<entry>(.+?)</entry>'
d = re.compile(re_str_entry)
# 取出原文件中所有的  <entry>  </entry>  保存到列表中
list_entry = d.findall(all_str)
print('共有' + str(len(list_entry)) + '条<entry>数据')
sums = len(list_entry)

time_end2 = time.time()
print("取正则表达式取字符串<entry>  </entry>花费了:", time_end2 - time_end, "秒")

# 遍历每一个entry将其中数据取出来
for data in list_entry:
    # 正则表达式取字符串<name>  </name>
    re_str_name = r'<name>(.+?)</name>'
    d = re.compile(re_str_name)
    # 取出每个<entry>  </entry>中的name字段
    name = d.findall(data)
    # print(name)

    # 正则表达式取字符串<vuln-id>  </vuln-id>
    re_str_vul_id = r'<vuln-id>(.+?)</vuln-id>'
    d = re.compile(re_str_vul_id)
    vuln_id = d.findall(data)
    # print(vuln_id)

    # 正则表达式取字符串<published>  </published>
    re_str_published = r'<published>(.+?)</published>'
    d = re.compile(re_str_published)
    published = d.findall(data)
    # print(published)

    # 正则表达式取字符串<modified>  </modified>
    re_str_modified = r'<modified>(.+?)</modified>'
    d = re.compile(re_str_modified)
    modified = d.findall(data)
    # print(modified)

    # 正则表达式取字符串<source>  </source>
    re_str_source = r'<source>(.+?)</source>'
    d = re.compile(re_str_source)
    source = d.findall(data)
    # print(source)

    # 正则表达式取字符串<severity>  </severity>
    re_str_severity = r'<severity>(.+?)</severity>'
    d = re.compile(re_str_severity)
    severity = d.findall(data)
    # print(severity)

    # 正则表达式取字符串 <vuln-type>  </vuln-type>
    re_str_vuln_type = r'<vuln-type>(.+?)</vuln-type>'
    d = re.compile(re_str_vuln_type)
    # 取出每个<vuln-type>  </vuln-type>中的字段
    vuln_type = d.findall(data)
    # print(vuln_type)

    # 正则表达式取字符串  <thrtype>  </thrtype>
    re_str_thrtype = r'<thrtype>(.+?)</thrtype>'
    d = re.compile(re_str_thrtype)
    thrtype = d.findall(data)
    # print(thrtype)

    # 正则表达式取字符串  <vuln-descript>  </vuln-descript>
    re_str_vuln_descript = r'<vuln-descript>(.+?)</vuln-descript>'
    d = re.compile(re_str_vuln_descript)
    vuln_descript = d.findall(data)
    # print(vuln_descript)

    # 正则表达式取字符串  <product>  </product>
    re_str_product = r'<product>CPE:/(.+?):</product>'
    d = re.compile(re_str_product)
    # 注意product可能有多个
    product = d.findall(data)
    # print(product)

    # 正则表达式取字符串  <vuln-solution>  </vuln-solution>
    re_str_vuln_solution = r'<vuln-solution>(.+?)</vuln-solution>'
    d = re.compile(re_str_vuln_solution)
    # 注意vuln_solution可能有多个
    vuln_solution = d.findall(data)
    # print(vuln_solution)

    entry_tuple = (
        name, vuln_id, published, modified, source, severity, vuln_type, thrtype, vuln_descript, product, vuln_solution)
    # 将每一个<entry>  </entry>中的数据按既定顺序存到一个元祖中
    # 下一步再将所有的元组放到一个字典中,最后将字典的数据一条条放到数据库中
    # print(entry_tuple[0:-1])
    tuple_list.append(entry_tuple[0:])

print(len(tuple_list))
# 制作一个和tuple_list一样长的列表
for i in range(len(tuple_list)):
    id.append(i)

# 形成字典类型
cve_dict = dict(zip(id, tuple_list))

time_end3 = time.time()
print("循环处理所有的<entry>花费了:", time_end3 - time_end2, "秒")

# 开始写入es数据库
# 批量写入数据
action = [
    {
        "_index": "fask_entry_bulk",
        "_type": "doc",
        "_source": {
            "id": i,
            'name': cve_dict[i][0],
            "vuln-id": cve_dict[i][1],
            "published": cve_dict[i][2],
            "modified": cve_dict[i][3],
            "source": cve_dict[i][4],
            "severity": cve_dict[i][5],
            "vuln-type": cve_dict[i][6],
            "thrtype": cve_dict[i][7],
            "vuln-descript": cve_dict[i][8],
            "product": cve_dict[i][9][0:],
            "vuln-solution": cve_dict[i][10]
        }
    } for i in range(len(tuple_list))]
helpers.bulk(es, action)

print("向数据库中插入花费了:", time.time() - time_end3, "秒")
file.close()

运行结果:

python elasticsearch插入数据,ElasticSearch,python,elasticsearch

插入数据后在数据库中查看:

python elasticsearch插入数据,ElasticSearch,python,elasticsearch文章来源地址https://www.toymoban.com/news/detail-596506.html

到了这里,关于Python简单实现与ElasticSearch交互插入数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【毕设必备】手把手带你用Python搭建一个简单的后端服务- API的创建,前后端交互的数据传递,GET,POST,JSON,FLASK

    Python是一种 流行 的高级编程语言,具有易于学习和使用的特性,被广泛应用于各种领域。 简单易学 :Python的语法清晰简洁,易于理解和学习。与其他编程语言相比,Python的语法设计非常直观,使得编程新手也能快速上手。 强大的标准库和丰富的第三方库 :Python拥有一个庞

    2024年02月04日
    浏览(40)
  • 将网页数据读入数据库+将数据库数据读出到网页——基于python flask实现网页与数据库的交互连接【全网最全】

    【全网最全!保姆级教学!!】 本篇博客基于flask技术,实现数据库和网页端的交互。 实现效果:在网页端输入数据,能够将数据存入数据库。反向操作时,能将数据库的数据取出,显示在网页端。不仅如此,还支持数据的查询和修改。  读取网页数据存入数据库,效果如下

    2024年02月13日
    浏览(33)
  • 使用python搭建简单的区块链,并实现数据上链

    目录 一、引入库文件 二、编写消息类 三、编写区块类 四、编写区块链 五、编写主函数 六、运行 引入所需的库文件,其中hashlib为核心文件。 通过编写消息类,将消息读入并进行哈希运算,与前面的消息进行连接等操作。 通过编写区块类,使用前一区块的哈希值与时间戳等

    2024年02月12日
    浏览(30)
  • 简单的用Python抓取动态网页数据,实现可视化数据分析

    一眨眼明天就周末了,一周过的真快! 今天咱们用Python来实现一下动态网页数据的抓取 最近不是有消息说世界首富马上要变成中国人了吗,这要真成了,可就是历史上首位中国世界首富了! 那我们就以富豪排行榜为例,爬取一下2023年国内富豪五百强,最后实现一下可视化分

    2024年02月05日
    浏览(39)
  • Maven和MyBatis框架简单实现数据库交互

    MyBatis是一种基于Java语言的持久层框架,它的主要目的是简化与数据库的交互过程。MyBatis通过XML或注解配置来映射Java对象和数据库表之间的关系,并提供了灵活的查询方式和结果集处理机制。MyBatis还提供了事务管理、缓存机制、插件扩展等特性。 使用MyBatis可以将SQL语句和

    2024年01月17日
    浏览(38)
  • python+django+sql实现简单的数据信息管理系统

    今天分享一个博客适合刚准备学习Pythonweb开发的小伙伴。 系统涉及功能: 1:运用django+mysql实现了数据的增删改查以及搜索。 2:实现了对前端语言和前端bootstrap库的基本运用。 3:实现了自定义分页的功能以及指定页码跳转。 项目涉及技术: Python的django框架,ORM数据*(库)

    2024年02月03日
    浏览(38)
  • 简单易用,灵活强大:用SQLAlchemy实现Python操作数据库

    什么是SQLAlchemy? SQLAlchemy是一个Python的SQL工具和ORM框架,可以通过Python代码直接操作关系型数据库,也可以使用ORM模型进行对象关系映射。它支持多种数据库,并提供了强大的SQL表达式和查询API。 SQLAlchemy可以分为两个部分:Core和ORM。 Core:提供了底层的SQL表达式和查询API,

    2024年02月04日
    浏览(61)
  • 【python】python postgresql获取插入数据的id

    在Python中使用PostgreSQL数据库插入数据后,可以通过 RETURNING 子句来获取插入数据的id。以下是一个示例: 在上面的示例中,我们首先连接到PostgreSQL数据库,然后创建一个游标对象。接下来,我们执行插入数据的SQL语句,并使用 RETURNING id 子句来获取插入数据的id。然后,我们

    2024年02月11日
    浏览(27)
  • 简单的用Python实现一下JS逆向解密,采集空气质量数据

    最近天气降温厉害,咱们用 Python 来分析一下空气质量如何~ 话不多说,我们直接开始上手。 环境使用 Python 3.8 Pycharm nodejs 模块使用 import requests import execjs import json requests 和 execjs 都是第三方模块,需要手动安装,直接pip install 加上模块名字即可。 明确需求: 明确采集的网站

    2024年02月05日
    浏览(45)
  • python批量插入数据到mysql

    使用python批量插入数据到mysql的三种方法 单条insert的话插入5w条数据大约用时5秒左右,相对来说效率不高

    2024年02月10日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包