使用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使用函数默认值实现函数静态变量的方法
Aug 18 Python
python中引用与复制用法实例分析
Jun 04 Python
django 使用 request 获取浏览器发送的参数示例代码
Jun 11 Python
python+opencv+caffe+摄像头做目标检测的实例代码
Aug 03 Python
Python实现App自动签到领取积分功能
Sep 29 Python
Python字典遍历操作实例小结
Mar 05 Python
Python基础学习之类与实例基本用法与注意事项详解
Jun 17 Python
python中PS 图像调整算法原理之亮度调整
Jun 28 Python
python+selenium定时爬取丁香园的新型冠状病毒数据并制作出类似的地图(部署到云服务器)
Feb 09 Python
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
May 11 Python
Pytorch DataLoader shuffle验证方式
Jun 02 Python
python_tkinter事件类型详情
Mar 20 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制作新闻系统的思路
2006/10/09 PHP
PHP 实现人民币小写转换成大写的方法及大小写转换函数
2017/11/17 PHP
PHP+ajax实现二级联动菜单功能示例
2018/08/10 PHP
Linux基于php-fpm模式的lamp搭建phpmyadmin的方法
2018/10/25 PHP
javascript自执行函数之伪命名空间封装法
2010/12/25 Javascript
jQuery中dequeue()方法用法实例
2014/12/29 Javascript
Node.js Streams文件读写操作详解
2016/07/04 Javascript
AngularJS自定义控件实例详解
2016/12/13 Javascript
js实现带简单弹性运动的导航条
2017/02/22 Javascript
Bootstrap模态框案例解析
2017/03/05 Javascript
BootStrap 导航条实例代码
2017/05/18 Javascript
浅谈webpack对样式的处理
2018/01/05 Javascript
使用vue2实现购物车和地址选配功能
2018/03/29 Javascript
Vuex 使用 v-model 配合 state的方法
2018/11/13 Javascript
详解json串反转义(消除反斜杠)
2019/08/12 Javascript
Python实现生成简单的Makefile文件代码示例
2015/03/10 Python
简单介绍利用TK在Python下进行GUI编程的教程
2015/04/13 Python
python通过pip更新所有已安装的包实现方法
2017/05/19 Python
tensorflow多维张量计算实例
2020/02/11 Python
Python模拟FTP文件服务器的操作方法
2020/02/18 Python
python 基于pygame实现俄罗斯方块
2021/03/02 Python
CSS3中的content属性使用示例
2015/07/20 HTML / CSS
HTML5 移动页面自适应手机屏幕四类方法总结
2017/08/17 HTML / CSS
what is the difference between ext2 and ext3
2015/08/25 面试题
EJB的角色和三个对象
2015/12/31 面试题
工地门卫岗位职责
2013/12/30 职场文书
社团招新策划书
2014/02/04 职场文书
班级旅游计划书
2014/05/03 职场文书
2014年项目工作总结
2014/11/24 职场文书
国家助学金感谢信
2015/01/21 职场文书
立案决定书范文
2015/06/24 职场文书
新闻稿标题
2015/07/18 职场文书
2015年国庆节寄语
2015/08/17 职场文书
三八红旗手先进事迹材料(2016推荐版)
2016/02/25 职场文书
详解MySQL多版本并发控制机制(MVCC)源码
2021/06/23 MySQL
K8s部署发布Golang应用程序的实现方法
2021/07/16 Golang