Python 3 针对 elasticsearch 的增删改查操作

学习笔记 马富天 2018-12-10 13:58:13 236 0

【摘要】本文记录一下使用 python 3 对 elasticsearch 的增删改查基本操作,批量插入、批量修改等等可能出现的操作,用于方便以后的使用。

一共有三个文件,每个文件包含的头部是一样的如下:

  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. import sys
  4. import random
  5. import time
  6. from elasticsearch import Elasticsearch
  7. from elasticsearch import helpers
  8. # 绿色表示一切正常, 黄色表示所有的数据可用但是部分副本还没有分配,红色表示部分数据因为某些原因不可用
  9. # 以下所有的增删改查都可以追本溯源,在《Elasticsearch 权威指南(中文版)》一书中可以找到对应的方法,
  10. # 操作形式不同,但是原理上是一致的,链接地址是:https://es.xiaoleilu.com/
  11. #### 索引 ####
  12. index_name = "bangbangas" # 索引名称
  13. type_name  = "my-type" # 类型名称
  14. alias_name = "bangbang" # 索引别名
  15. host_name  = "127.0.0.1"
  16. port       = 9200
  17. es = Elasticsearch([{'host':host_name,'port':port}])

为了避免由于每个操作之间互相造成的影响,所以将其分为三个部分,每个操作的顶部都是一样的共同部分。

操作 1 :

  1. # 判断索引是否存在,若存在先删除则创建
  2. if es.indices.exists(index=index_name) == True:
  3.     es.indices.delete(index=index_name) # 刪除索引
  4. # 创建索引
  5. settings = {
  6.     "settings": {
  7.         "number_of_shards" : 5,
  8.         "number_of_replicas" : 1
  9.     }
  10. }
  11. es.indices.create(index=index_name,body=settings)
  12. # 查询索引别名是否存在
  13. if es.indices.exists_alias(index=index_name,name=alias_name) == True:
  14.     es.indices.delete_alias(index=index_name,name=alias_name) # 若已存在,则删除别名
  15. es.indices.put_alias(index=index_name,name=alias_name) # 若不存在,则创建索引别名
  16.  
  17. result = es.indices.get_alias() # 查看所有索引及对应别名
  18. result = es.indices.get_alias().keys() # 查询所有索引的名称
  19. result = es.indices.get(index_name) # 查询索引信息,包含 mapping settings 信息
  20. result = es.indices.get_mapping(index_name) # 查看索引的 mapping 信息
  21. result = es.indices.get_settings(index_name) # 查看索引的 settings 信息
  22. #### 文档操作 ####
  23. data = {
  24.     "name":"hello world",
  25.     "age":18
  26. }
  27. # 使用 create 方法创建文档时,必须指定 id ,并且 id 不能是已经存在的
  28. es.create(index=index_name,doc_type=type_name,id=1,body=data)
  29. # 判断指定 id 的文档是否存在
  30. if es.exists(index=index_name,doc_type=type_name,id=2) == False:
  31.     data = {
  32.         "name":"english",
  33.         "age":20
  34.     }
  35.     es.create(index=index_name,doc_type=type_name,id=2,body=data)
  36. # 使用 index 方法来创建文档,可以不设置 id ,id 也可以已经存在的。
  37. # 若 id 没有设置,则随机生成一个 22 位的字符串;若 id 已存在,则修改文档内容
  38. data = {
  39.     "name":"hi",
  40.     "age":18
  41. }
  42. es.index(index_name,doc_type=type_name,id=1,body=data) # 修改 id 为 1 的文档
  43. es.index(index_name,doc_type=type_name,body=data) # 创建一个 id 自动生成的文档
  44. # 批量插入文档,使用 helper.bulk()
  45. i = 3
  46. actions = []
  47. data = [
  48.     {"name":"福建省龙岩市永定县","age":30},
  49.     {"name":"山东省青岛市黄岛区","age":16},
  50.     {"name":"江苏省无锡市滨湖区","age":24},
  51.     {"name":"北京市朝阳区双井街","age":18},
  52.     {"name":"福建省龙岩市新罗区","age":16},
  53.     {"name":"aabbcc","age":17},
  54.     {"name":"aaccbb","age":17},
  55.     {"name":"bbaacc","age":17},
  56.     {"name":"bbccaa","age":17},
  57.     {"name":"ccaabb","age":17},
  58.     {"name":"ccbbaa","age":17},
  59. ]
  60. for j in data:
  61.     action = {
  62.         "_index":index_name,
  63.         '_type':type_name,
  64.         '_id':i,
  65.         '_source':j,
  66.     }
  67.     i += 1
  68.     actions.append(action)
  69. helpers.bulk(es,actions)

操作 2 :

  1. #### 查询文档 ####
  2. # 获取指定 id 的文档
  3. if es.exists(index=index_name,doc_type=type_name,id=1) == True:
  4.     res = es.get(index=index_name, doc_type=type_name, id=1) # 获取 id 为 1 的文档
  5. # 查询所有文档,默认显示前 10 条
  6. query = {
  7.     'query': {
  8.         'match_all': {}
  9.     }
  10. }
  11. res = es.search(index=index_name,body=query) # 查询索引的所有文档
  12. total = res['hits']['total'] # 查询的总数
  13. if total > 0 :
  14.     numberOne = res['hits']['hits'][0] # 返回结果中第一个记录
  15. res = es.search(body=query) # 查询所有索引的所有文档,默认显示十条
  16. # 全文搜索
  17. query = {
  18.     'query':{
  19.         'match':{
  20.             "name":"龙岩 永定"
  21.         }
  22.     }
  23. }
  24. res = es.search(index=index_name,doc_type=type_name,body=query)
  25. #### 修改文档 ####
  26. # 使用 update 修改文档,必须指定 id,且采用 {"doc":{}} 格式
  27. doc = {
  28.     "doc":{
  29.         "name":"hello world",
  30.         "age":20
  31.     }
  32. }
  33. if es.exists(index=index_name,doc_type=type_name,id=1) == True:
  34.     res = es.update(index=index_name,doc_type=type_name,id=1,body=doc) # 修改 id 为 1 的文档
  35. # 休眠 2 秒,避免发生冲突
  36. time.sleep(2)
  37. # 使用 update_by_query 批量修改符合条件的文档
  38. query = {
  39.     "script":{
  40.         "lang": "painless",
  41.         "inline": "ctx._source.age=" + str(random.randint(10,30))
  42.     },
  43.     "query":{
  44.         "range":{
  45.             "age":{
  46.                 "lte":30,
  47.                 "gte":18
  48.             }
  49.         }
  50.     }
  51. }
  52. try:
  53.     # 执行更新的时候可能会发生冲突,所有为了保证程序的正常运行,需要对异常进行处理
  54.     res = es.update_by_query(index=index_name,doc_type=type_name,body=query) # 将 age >= 18 && age <= 28 的文档 age 修改为 24
  55. except Exception as e:
  56.     print("error")
  57. ### 注意 ###
  58. # 这里在短时间内先修改 id = 1 的文档,而后又批量修改所有文档,对于 id = 1 的文档容易发生冲突问题,要避免冲突问题,所以采用休眠 2 秒的方法来避免短时间内发生冲突的可能

操作 3 :

  1. #### 删除文档 ####
  2. # 删除指定 id 的文档,必须指定 id,且 id 必须存在
  3. if es.exists(index=index_name,doc_type=type_name,id=100) == True:
  4.     res = es.delete(index=index_name, doc_type=type_name, id=100)
  5. if es.exists(index=index_name,doc_type=type_name,id=1) == True:
  6.     res = es.delete(index=index_name,doc_type=type_name,id=1)
  7. # 停顿 2 秒,避免冲突
  8. time.sleep(2)
  9. # 按条件批量删除符合条件的文档
  10. query = {
  11.     "query":{
  12.         "match":{
  13.             "age":16
  14.         }
  15.     }
  16. }
  17. query = {
  18.     "query":{
  19.         "range":{
  20.             "age":{
  21.                 "gte":18,
  22.                 "lte":30
  23.             }
  24.         }
  25.     }
  26. }
  27. try:
  28.     res = es.delete_by_query(index=index_name,body=query)
  29. except Exception as e:
  30.     print("error")

后续如果有新的操作,会更新本文的。

版权归 马富天个人博客 所有

本文标题:《Python 3 针对 elasticsearch 的增删改查操作》

本文链接地址:http://www.mafutian.com/399.html

转载请务必注明出处,小生将不胜感激,谢谢! 喜欢本文或觉得本文对您有帮助,请分享给您的朋友 ^_^

0

0

上一篇《 MySQL 5.7 版本的安装方法(win) 》 下一篇《 QQ、微信内置浏览器的 UA(useragent) 》

暂无评论

评论审核未开启
表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情
验证码

TOP10

  • 浏览最多
  • 评论最多