使用python生成大量数据写入es数据库并查询操作(2)


Posted in Python onSeptember 23, 2022

前言 :

模拟学生个人信息写入es数据库,包括姓名、性别、年龄、特点、科目、成绩,创建时间。

方案一

在写入数据时未提前创建索引mapping,而是每插入一条数据都包含了索引的信息。

示例代码:【多线程写入数据】【一次性写入10000*1000条数据】  【本人亲测耗时3266秒】

from elasticsearch import Elasticsearch
from elasticsearch import helpers
from datetime import datetime
from queue import Queue
import random
import time
import threading
es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)
 
names = ['刘一', '陈二', '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十']
sexs = ['男', '女']
age = [25, 28, 29, 32, 31, 26, 27, 30]
character = ['自信但不自负,不以自我为中心',
             '努力、积极、乐观、拼搏是我的人生信条',
             '抗压能力强,能够快速适应周围环境',
             '敢做敢拼,脚踏实地;做事认真负责,责任心强',
             '爱好所学专业,乐于学习新知识;对工作有责任心;踏实,热情,对生活充满激情',
             '主动性强,自学能力强,具有团队合作意识,有一定组织能力',
             '忠实诚信,讲原则,说到做到,决不推卸责任',
             '有自制力,做事情始终坚持有始有终,从不半途而废',
             '肯学习,有问题不逃避,愿意虚心向他人学习',
             '愿意以谦虚态度赞扬接纳优越者,权威者',
             '会用100%的热情和精力投入到工作中;平易近人',
             '为人诚恳,性格开朗,积极进取,适应力强、勤奋好学、脚踏实地',
             '有较强的团队精神,工作积极进取,态度认真']
subjects = ['语文', '数学', '英语', '生物', '地理']
grades = [85, 77, 96, 74, 85, 69, 84, 59, 67, 69, 86, 96, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86]
create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
def save_to_es(num):
    """
    批量写入数据到es数据库
    :param num:
    :return:
    """
    start = time.time()
    action = [
        {
            "_index": "personal_info_10000000",
            "_type": "doc",
            "_id": i,
            "_source": {
                "id": i,
                "name": random.choice(names),
                "sex": random.choice(sexs),
                "age": random.choice(age),
                "character": random.choice(character),
                "subject": random.choice(subjects),
                "grade": random.choice(grades),
                "create_time": create_time
            }
        } for i in range(10000 * num, 10000 * num + 10000)
    ]
    helpers.bulk(es, action)
    end = time.time()
    print(f"{num}耗时{end - start}s!")
 
def run():
    global queue
    while queue.qsize() > 0:
        num = queue.get()
        print(num)
        save_to_es(num)

if __name__ == '__main__':
    start = time.time()
    queue = Queue()
    # 序号数据进队列
    for num in range(1000):
        queue.put(num)
 
    # 多线程执行程序
    consumer_lst = []
    for _ in range(10):
        thread = threading.Thread(target=run)
        thread.start()
        consumer_lst.append(thread)
    for consumer in consumer_lst:
        consumer.join()
    end = time.time()
    print('程序执行完毕!花费时间:', end - start)

运行结果:

使用python生成大量数据写入es数据库并查询操作(2)

使用python生成大量数据写入es数据库并查询操作(2)

使用python生成大量数据写入es数据库并查询操作(2)

 自动创建的索引mapping:

GET personal_info_10000000/_mapping
{
  "personal_info_10000000" : {
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "character" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "create_time" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "grade" : {
          "type" : "long"
        },
        "id" : {
          "type" : "long"
        },
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "sex" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "subject" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

方案二

1.顺序插入5000000条数据

先创建索引personal_info_5000000,确定好mapping后,再插入数据。

新建索引并设置mapping信息:

PUT personal_info_5000000
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 32
          }
        }
      },
      "sex": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 8
          }
        }
      },
      "age": {
        "type": "long"
      },
      "character": {
        "type": "text",
        "analyzer": "ik_smart",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "subject": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "grade": {
        "type": "long"
      },
      "create_time": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
      }
    }
  }
}

查看新建索引信息:

GET personal_info_5000000
 
{
  "personal_info_5000000" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "character" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          },
          "analyzer" : "ik_smart"
        },
        "create_time" : {
          "type" : "date",
          "format" : "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
        },
        "grade" : {
          "type" : "long"
        },
        "id" : {
          "type" : "long"
        },
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 32
            }
          }
        },
        "sex" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 8
            }
          }
        },
        "subject" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "3",
        "provided_name" : "personal_info_50000000",
        "creation_date" : "1663471072176",
        "number_of_replicas" : "1",
        "uuid" : "5DfmfUhUTJeGk1k4XnN-lQ",
        "version" : {
          "created" : "7170699"
        }
      }
    }
  }
}

开始插入数据:

示例代码: 【单线程写入数据】【一次性写入10000*500条数据】  【本人亲测耗时7916秒】

from elasticsearch import Elasticsearch
from datetime import datetime
from queue import Queue
import random
import time
import threading
es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)
names = ['刘一', '陈二', '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十']
sexs = ['男', '女']
age = [25, 28, 29, 32, 31, 26, 27, 30]
character = ['自信但不自负,不以自我为中心',
             '努力、积极、乐观、拼搏是我的人生信条',
             '抗压能力强,能够快速适应周围环境',
             '敢做敢拼,脚踏实地;做事认真负责,责任心强',
             '爱好所学专业,乐于学习新知识;对工作有责任心;踏实,热情,对生活充满激情',
             '主动性强,自学能力强,具有团队合作意识,有一定组织能力',
             '忠实诚信,讲原则,说到做到,决不推卸责任',
             '有自制力,做事情始终坚持有始有终,从不半途而废',
             '肯学习,有问题不逃避,愿意虚心向他人学习',
             '愿意以谦虚态度赞扬接纳优越者,权威者',
             '会用100%的热情和精力投入到工作中;平易近人',
             '为人诚恳,性格开朗,积极进取,适应力强、勤奋好学、脚踏实地',
             '有较强的团队精神,工作积极进取,态度认真']
subjects = ['语文', '数学', '英语', '生物', '地理']
grades = [85, 77, 96, 74, 85, 69, 84, 59, 67, 69, 86, 96, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86]
create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
# 添加程序耗时的功能
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print('id{}共耗时约 {:.2f} 秒'.format(*args, end - start))
        return res
 
    return wrapper
 
@timer
def save_to_es(num):
    """
    顺序写入数据到es数据库
    :param num:
    :return:
    """
    body = {
        "id": num,
        "name": random.choice(names),
        "sex": random.choice(sexs),
        "age": random.choice(age),
        "character": random.choice(character),
        "subject": random.choice(subjects),
        "grade": random.choice(grades),
        "create_time": create_time
    }
    # 此时若索引不存在时会新建
    es.index(index="personal_info_5000000", id=num, doc_type="_doc", document=body)
 
def run():
    global queue
    while queue.qsize() > 0:
        num = queue.get()
        print(num)
        save_to_es(num)
 
if __name__ == '__main__':
    start = time.time()
    queue = Queue()
    # 序号数据进队列
    for num in range(5000000):
        queue.put(num)
 
    # 多线程执行程序
    consumer_lst = []
    for _ in range(10):
        thread = threading.Thread(target=run)
        thread.start()
        consumer_lst.append(thread)
    for consumer in consumer_lst:
        consumer.join()
    end = time.time()
    print('程序执行完毕!花费时间:', end - start)

运行结果:

使用python生成大量数据写入es数据库并查询操作(2)

2.批量插入5000000条数据

先创建索引personal_info_5000000_v2,确定好mapping后,再插入数据。

新建索引并设置mapping信息:

PUT personal_info_5000000_v2
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 32
          }
        }
      },
      "sex": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 8
          }
        }
      },
      "age": {
        "type": "long"
      },
      "character": {
        "type": "text",
        "analyzer": "ik_smart",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "subject": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "grade": {
        "type": "long"
      },
      "create_time": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
      }
    }
  }
}

查看新建索引信息:

GET personal_info_5000000_v2
 
{
  "personal_info_5000000_v2" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "character" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          },
          "analyzer" : "ik_smart"
        },
        "create_time" : {
          "type" : "date",
          "format" : "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
        },
        "grade" : {
          "type" : "long"
        },
        "id" : {
          "type" : "long"
        },
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 32
            }
          }
        },
        "sex" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 8
            }
          }
        },
        "subject" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "3",
        "provided_name" : "personal_info_5000000_v2",
        "creation_date" : "1663485323617",
        "number_of_replicas" : "1",
        "uuid" : "XBPaDn_gREmAoJmdRyBMAA",
        "version" : {
          "created" : "7170699"
        }
      }
    }
  }
}

批量插入数据:

通过elasticsearch模块导入helper,通过helper.bulk来批量处理大量的数据。首先将所有的数据定义成字典形式,各字段含义如下:

  • _index对应索引名称,并且该索引必须存在。
  • _type对应类型名称。
  • _source对应的字典内,每一篇文档的字段和值,可有有多个字段。

示例代码:  【程序中途异常,写入4714000条数据】

from elasticsearch import Elasticsearch
from elasticsearch import helpers
from datetime import datetime
from queue import Queue
import random
import time
import threading
es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)
names = ['刘一', '陈二', '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十']
sexs = ['男', '女']
age = [25, 28, 29, 32, 31, 26, 27, 30]
character = ['自信但不自负,不以自我为中心',
             '努力、积极、乐观、拼搏是我的人生信条',
             '抗压能力强,能够快速适应周围环境',
             '敢做敢拼,脚踏实地;做事认真负责,责任心强',
             '爱好所学专业,乐于学习新知识;对工作有责任心;踏实,热情,对生活充满激情',
             '主动性强,自学能力强,具有团队合作意识,有一定组织能力',
             '忠实诚信,讲原则,说到做到,决不推卸责任',
             '有自制力,做事情始终坚持有始有终,从不半途而废',
             '肯学习,有问题不逃避,愿意虚心向他人学习',
             '愿意以谦虚态度赞扬接纳优越者,权威者',
             '会用100%的热情和精力投入到工作中;平易近人',
             '为人诚恳,性格开朗,积极进取,适应力强、勤奋好学、脚踏实地',
             '有较强的团队精神,工作积极进取,态度认真']
subjects = ['语文', '数学', '英语', '生物', '地理']
grades = [85, 77, 96, 74, 85, 69, 84, 59, 67, 69, 86, 96, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86]
create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 添加程序耗时的功能
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print('id{}共耗时约 {:.2f} 秒'.format(*args, end - start))
        return res
 
    return wrapper
 
 
@timer
def save_to_es(num):
    """
    批量写入数据到es数据库
    :param num:
    :return:
    """
    action = [
        {
            "_index": "personal_info_5000000_v2",
            "_type": "_doc",
            "_id": i,
            "_source": {
                "id": i,
                "name": random.choice(names),
                "sex": random.choice(sexs),
                "age": random.choice(age),
                "character": random.choice(character),
                "subject": random.choice(subjects),
                "grade": random.choice(grades),
                "create_time": create_time
            }
        } for i in range(10000 * num, 10000 * num + 10000)
    ]
    helpers.bulk(es, action)
def run():
    global queue
    while queue.qsize() > 0:
        num = queue.get()
        print(num)
        save_to_es(num)
if __name__ == '__main__':
    start = time.time()
    queue = Queue()
    # 序号数据进队列
    for num in range(500):
        queue.put(num)
 
    # 多线程执行程序
    consumer_lst = []
    for _ in range(10):
        thread = threading.Thread(target=run)
        thread.start()
        consumer_lst.append(thread)
    for consumer in consumer_lst:
        consumer.join()
    end = time.time()
    print('程序执行完毕!花费时间:', end - start)

运行结果:

使用python生成大量数据写入es数据库并查询操作(2)

使用python生成大量数据写入es数据库并查询操作(2)

3.批量插入50000000条数据

先创建索引personal_info_5000000_v2,确定好mapping后,再插入数据。

此过程是在上面批量插入的前提下进行优化,采用python生成器。

建立索引和mapping同上,直接上代码:

示例代码: 【程序中途异常,写入3688000条数据】

from elasticsearch import Elasticsearch
from elasticsearch import helpers
from datetime import datetime
from queue import Queue
import random
import time
import threading
es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)
 
names = ['刘一', '陈二', '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十']
sexs = ['男', '女']
age = [25, 28, 29, 32, 31, 26, 27, 30]
character = ['自信但不自负,不以自我为中心',
             '努力、积极、乐观、拼搏是我的人生信条',
             '抗压能力强,能够快速适应周围环境',
             '敢做敢拼,脚踏实地;做事认真负责,责任心强',
             '爱好所学专业,乐于学习新知识;对工作有责任心;踏实,热情,对生活充满激情',
             '主动性强,自学能力强,具有团队合作意识,有一定组织能力',
             '忠实诚信,讲原则,说到做到,决不推卸责任',
             '有自制力,做事情始终坚持有始有终,从不半途而废',
             '肯学习,有问题不逃避,愿意虚心向他人学习',
             '愿意以谦虚态度赞扬接纳优越者,权威者',
             '会用100%的热情和精力投入到工作中;平易近人',
             '为人诚恳,性格开朗,积极进取,适应力强、勤奋好学、脚踏实地',
             '有较强的团队精神,工作积极进取,态度认真']
subjects = ['语文', '数学', '英语', '生物', '地理']
grades = [85, 77, 96, 74, 85, 69, 84, 59, 67, 69, 86, 96, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86]
create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
# 添加程序耗时的功能
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print('id{}共耗时约 {:.2f} 秒'.format(*args, end - start))
        return res
 
    return wrapper
@timer
def save_to_es(num):
    """
    使用生成器批量写入数据到es数据库
    :param num:
    :return:
    """
    action = (
        {
            "_index": "personal_info_5000000_v3",
            "_type": "_doc",
            "_id": i,
            "_source": {
                "id": i,
                "name": random.choice(names),
                "sex": random.choice(sexs),
                "age": random.choice(age),
                "character": random.choice(character),
                "subject": random.choice(subjects),
                "grade": random.choice(grades),
                "create_time": create_time
            }
        } for i in range(10000 * num, 10000 * num + 10000)
    )
    helpers.bulk(es, action)
 
def run():
    global queue
    while queue.qsize() > 0:
        num = queue.get()
        print(num)
        save_to_es(num)
 
if __name__ == '__main__':
    start = time.time()
    queue = Queue()
    # 序号数据进队列
    for num in range(500):
        queue.put(num)
 
    # 多线程执行程序
    consumer_lst = []
    for _ in range(10):
        thread = threading.Thread(target=run)
        thread.start()
        consumer_lst.append(thread)
    for consumer in consumer_lst:
        consumer.join()
    end = time.time()
    print('程序执行完毕!花费时间:', end - start)

运行结果:

使用python生成大量数据写入es数据库并查询操作(2)

使用python生成大量数据写入es数据库并查询操作(2)

到此这篇关于使用python生成大量数据写入es数据库并查询操作(2)的文章就介绍到这了,更多相关python生成 数据 内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python将html转成PDF的实现代码(包含中文)
Mar 04 Python
Django中使用Celery的教程详解
Aug 24 Python
[原创]Python入门教程1. 基本运算【四则运算、变量、math模块等】
Oct 28 Python
python 划分数据集为训练集和测试集的方法
Dec 11 Python
详解从Django Rest Framework响应中删除空字段
Jan 11 Python
Python实现的微信红包提醒功能示例
Aug 22 Python
python获取全国城市pm2.5、臭氧等空气质量过程解析
Oct 12 Python
Pandas DataFrame中的tuple元素遍历的实现
Oct 23 Python
keras实现VGG16方式(预测一张图片)
Jul 07 Python
Python配置pip国内镜像源的实现
Aug 20 Python
Django框架安装及项目创建过程解析
Sep 14 Python
使用Python制作一个数据预处理小工具(多种操作一键完成)
Feb 07 Python
Python sklearn分类决策树方法详解
详解Golang如何实现支持随机删除元素的堆
python中validators库的使用方法详解
Sep 23 #Python
Python pyecharts案例超市4年数据可视化分析
Aug 14 #Python
Python编写车票订购系统 Python实现快递收费系统
Aug 14 #Python
Golang Web 框架Iris安装部署
Aug 14 #Python
python manim实现排序算法动画示例
You might like
深入理解PHP+Mysql分布式事务与解决方案
2020/12/03 PHP
javascript 面向对象编程基础:封装
2009/08/21 Javascript
用Javascript实现Windows任务管理器的代码
2012/03/27 Javascript
jQuery选择器源码解读(一):Sizzle方法
2015/03/31 Javascript
IE浏览器下PNG相关功能
2015/07/05 Javascript
jQuery+ajax实现滚动到页面底部自动加载图文列表效果(类似图片懒加载)
2016/06/07 Javascript
兼容浏览器的js事件绑定函数(详解)
2017/05/09 Javascript
JS实现多级菜单中当前菜单不随页面跳转样式而发生变化
2017/05/30 Javascript
Javascript创建类和对象详解
2017/05/31 Javascript
js实现鼠标拖拽多选功能示例
2017/08/01 Javascript
js获取css的各种样式并且设置他们的方法
2017/08/22 Javascript
node.js 核心http模块,起一个服务器,返回一个页面的实例
2017/09/11 Javascript
angularJS开发注意事项
2018/05/26 Javascript
vue 设置路由的登录权限的方法
2018/07/03 Javascript
js实现敏感词过滤算法及实现逻辑
2018/07/24 Javascript
vue实现循环切换动画
2018/10/17 Javascript
vue使用@scroll监听滚动事件时,@scroll无效问题的解决方法详解
2019/10/15 Javascript
python3 实现的人人影视网站自动签到
2016/06/19 Python
利用python获取当前日期前后N天或N月日期的方法示例
2017/07/30 Python
Python文件和流(实例讲解)
2017/09/12 Python
python实现TF-IDF算法解析
2018/01/02 Python
浅谈django rest jwt vue 跨域问题
2018/10/26 Python
Pycharm无法显示动态图片的解决方法
2018/10/28 Python
Python小进度条显示代码
2019/03/05 Python
学习Python需要哪些工具
2020/09/04 Python
css 元素选择器的简单实例
2016/05/23 HTML / CSS
超市实习总结自我鉴定
2013/09/19 职场文书
办公室文秘岗位职责
2013/11/15 职场文书
安全生产先进个人材料
2014/02/06 职场文书
公务员转正鉴定材料
2014/02/11 职场文书
路政管理求职信
2014/06/18 职场文书
怎样写工作总结啊!
2019/06/18 职场文书
世界上超棒的8种逻辑思维
2019/08/06 职场文书
mysql5.6主从搭建以及不同步问题详解
2021/12/04 MySQL
Vue+Flask实现图片传输功能
2022/04/01 Vue.js
mysql 排序失效
2022/05/20 MySQL