• ElasticSearch Python API教程


    目录

    一、安装es python包

    二、python API 基本使用

    1. 创建es客户端连接

    2. 创建索引

    3. 插入数据

    4. 删除索引

    5. 查询

    5.1 条件查询: match、match_all

    5.2 条件查询: term、terms

    5.3 条件查询: 指定页码和大小

    5.4 range查询 

    5.5 bool 查询 : 合并多个过滤条件查询结果的布尔逻辑

    5.6 exist 查询: 存在或不存在某个字段的数据

    5. 7 wildcards : 使用标准的shell通配符查询

    5.8 prefix 查询: 查询以什么字符开头的

    6. 删除数据

    7. 修改数据


    一、安装es python包

    注意: 版本要与es 环境保持一致

     pip install elasticsearch==7.8.0

    二、python API 基本使用

    1. 创建es客户端连接

    1. # 使用python操作ElasticSearch
    2. from elasticsearch import Elasticsearch, helpers
    3. # 连接ES
    4. es = Elasticsearch(hosts="http://192.168.21.103:9200", request_timeout=3600)

    2. 创建索引

    说明 :指定mapping可以为对应字段构建索引,便于检索

    1. def create_index(es, index_name):
    2. mappings = {
    3. "settings": {
    4. "index": {
    5. "number_of_shards": 1,
    6. "number_of_replicas": 1
    7. }
    8. },
    9. "mappings": {
    10. "properties": {
    11. "id": {
    12. "type": "keyword"
    13. },
    14. "url": {
    15. "type": "keyword"
    16. },
    17. "summary": {
    18. "type": "text"
    19. },
    20. "author": {
    21. "properties": {
    22. "value": {
    23. "type": "text"
    24. }
    25. }
    26. },
    27. "title": {
    28. "type": "text"
    29. },
    30. "periodical": {
    31. "properties": {
    32. "name": {
    33. "type": "text"
    34. }
    35. }
    36. },
    37. "doi": {
    38. "type": "keyword"
    39. },
    40. "citations": {
    41. "type": "keyword"
    42. },
    43. "year": {
    44. "type": "keyword"
    45. },
    46. }
    47. }
    48. }
    49. # ignore : 如果索引已存在, 则忽略报错信息不进行创建
    50. if not es.indices.exists(index_name):
    51. result = es.indices.create(index=index_name, body=mappings, ignore=400)
    52. if result.get("acknowledged"):
    53. print("索引创建成功")
    54. else:
    55. print(f"索引创建失败:{result}")
    56. else:
    57. print("索引已存在无需重复创建!")

    3. 插入数据

    单条插入:

    1. def insert_data(es, index_name, data):
    2. if data.get("id"): # 指定id
    3. es.index(index=index_name, id=data.get("id"), body=data)
    4. print("插入成功")
    5. else: # 不指定id, 会自动生成id
    6. es.index(index=index_name, body=data)

    批量插入

    1. from elasticsearch import helpers
    2. def bulk_list(es, index_name, data_list):
    3. """
    4. 批量插入数据
    5. :param es:
    6. :param index_name:
    7. :param data_list:
    8. """
    9. actions = []
    10. for data in data_list:
    11. action = {
    12. "_index": index_name,
    13. "_type": "_doc",
    14. "_id": data.get("id"),
    15. "_source": data
    16. }
    17. actions.append(action)
    18. if len(actions) % 100 == 0:
    19. helpers.bulk(es, actions)
    20. print(f"数据批量插入成功,数据大小:{len(actions)}, 索引:{index_name}")
    21. actions.clear()
    22. if actions:
    23. helpers.bulk(es, actions)
    24. print(f"数据批量插入成功,数据大小:{len(actions)}, 索引:{index_name}")
    25. actions.clear()

    4. 删除索引

    1. def delete_index(es, index_name):
    2. if es.indices.exists(index_name):
    3. es.indices.delete(index_name)
    4. print("索引删除成功")
    5. else:
    6. print("索引不存在")

    5. 查询

    5.1 条件查询: match、match_all

    match_all : 查询到所有文档,默认返回一页

    match :使用关键词match,默认根据_socre降序排列

    multi_match : 同时搜索多个字段

    match_phrase : 短语查询

    1. body = {
    2. "query": {
    3. "match_all": {
    4. }
    5. }
    6. }
    7. body = {
    8. "query": {
    9. "match": {
    10. "title": "Compliance, identification, and internalization three processes of attitude change"
    11. }
    12. }
    13. }
    14. # multi_match 查询–match查询的基础上同时搜索多个字段,在多个字段中同时查一个
    15. body = {
    16. "query": {
    17. "multi_match": {
    18. "query": "comprehensive",
    19. "fields": ["title", "summary"]
    20. }
    21. }
    22. }
    23. # 短语匹配
    24. body = {
    25. "query": {
    26. "match_phrase": {
    27. "title": "modern marketing"
    28. }
    29. }
    30. }
    31. es.search(index=index_name, body=body)

    5.2 条件查询: term、terms

    term : 过滤–term主要用于精确匹配哪些值,比如数字,日期,布尔值或 not_analyzed 的字符串(未经切词的文本数据类型)

    terms : 允许指定多个匹配条件

    1. body = {
    2. "query": {
    3. "term": {
    4. "year": 1958
    5. }
    6. }
    7. }
    8. body = {
    9. "query": {
    10. "terms": {
    11. "year": [1958, 2010]
    12. }
    13. }
    14. }
    15. es.search(index=index_name, body=body)

    5.3 条件查询: 指定页码和大小

    1. # 指定返回的数量大小
    2. body = {
    3. "query": {
    4. "match_all": {
    5. }
    6. },
    7. "from": 1, # 页码
    8. "size": 2 # 一页大小
    9. }
    10. es.search(index=index_name, body=body)

    5.4 range查询 

    按照指定范围查询数据:

    gt :  大于

    gte: 大于等于

    lt : 小于

    lte : 小于等于

    1. body = {
    2. "query": {
    3. "range": {
    4. "year": {
    5. "gt": 2018
    6. }
    7. }
    8. }
    9. }
    10. es.search(index=index_name, body=body)

    5.5 bool 查询 : 合并多个过滤条件查询结果的布尔逻辑

    must :: 多个查询条件的完全匹配,相当于 and。
    must_not :: 多个查询条件的相反匹配,相当于 not。
    should :: 至少有一个查询条件匹配, 相当于 or。

    1. body = {
    2. "query": {
    3. "bool": {
    4. "must": [
    5. {"term": {"year": 1958}},
    6. {"term": {"doi": "10.5694/j.1326-5377.1958.tb67127.x"}}
    7. ]
    8. }
    9. }
    10. }
    11. body = {
    12. "query": {
    13. "bool": {
    14. "must": [
    15. {"term": {"year": 1958}},
    16. {"range": {"citations": {"gt": 3000}}}
    17. ]
    18. }
    19. }
    20. }
    21. body = {
    22. "query": {
    23. "bool": {
    24. "must": {
    25. "term": {"year": 1958}
    26. },
    27. "must_not": {
    28. "exists": {
    29. "field": "name"
    30. }
    31. }
    32. }
    33. }
    34. }
    35. es.search(index=index_name, body=body)

    5.6 exist 查询: 存在或不存在某个字段的数据

    1. # 查询存在year字段的数据
    2. body = {
    3. "query": {
    4. "exists": {
    5. "field": "year"
    6. }
    7. }
    8. }
    9. # 查询不存在year字段的数据
    10. body = {
    11. "query": {
    12. "bool": {
    13. "must_not": {
    14. "exists": {
    15. "field": "year"
    16. }
    17. }
    18. }
    19. }
    20. }

    5. 7 wildcards : 使用标准的shell通配符查询

    1. # wildcards 查询–使用标准的shell通配符查询
    2. body = {
    3. "query": {
    4. "wildcard": {
    5. "title": "*Structure*"
    6. }
    7. }
    8. }
    9. # wildcards 查询–使用标准的shell通配符查询
    10. body = {
    11. "query": {
    12. "regexp": {
    13. "year": "20.*"
    14. }
    15. }
    16. }

    5.8 prefix 查询: 查询以什么字符开头的

    1. # prefix 查询 – 以什么字符开头的
    2. body = {
    3. "query": {
    4. "prefix": {
    5. "id": "f1803ea131a96817d14290077"
    6. }
    7. }
    8. }

    6. 删除数据

    按照id删除

        es.delete(index=index_name, id='f1803ea131a96817d142900777cc1c73b41ee6c4')

    删除符合条件的所有数据

    1. # 删除符合条件的所有数据
    2. body = {
    3. "query": {
    4. "match": {
    5. "year": 1958
    6. }
    7. }
    8. }
    9. es.delete_by_query(index=index_name, body=body)

    7. 修改数据

    lang: 指定脚本语言,painless是内置的脚本语言

    script: 代表脚本内容,ctx 代表es上下文,_source代表当前的文档,

    1. # 修改字段值,如果没有这个字段会自动添加
    2. doc_body = {
    3. "doc": {
    4. "citations": 2532
    5. }
    6. }
    7. # 增加字段
    8. doc_body = {
    9. 'script': "ctx._source.source = 'kgPlat'"
    10. }
    11. # 字段
    12. doc_body = {
    13. 'script': "ctx._source.remove('source')"
    14. }
    15. id = "727f736f07d9b0fd5ad95208079a09ee506e99e2"
    16. es.update(index=index_name, id=id, body=doc_body)
    17. # update_by_query:更新满足条件的所有数据,写法同上删除和查询
    18. query = {
    19. "query": {
    20. "match": {
    21. "year": 1991
    22. }
    23. },
    24. "script": {
    25. "source": "ctx._source.citations = params.citations;ctx._source.citations2 = params.citations2",
    26. "lang": "painless",
    27. "params": {
    28. "citations": 0,
    29. "citations2": 0
    30. },
    31. }
    32. }
    33. es.update_by_query(index=index_name, body=query)

  • 相关阅读:
    chatgpt综述和报告
    前端基于excljs导出xlsx时图片资源的处理及踩坑实录
    redis集群之主从复制集群的原理和部署
    ARCGIS进行视域分析及地形图制作
    Flutter高仿微信-第28篇-好友详情-查看个人头像
    深入理解C++11
    动态调整系统主题色(4): CssVar 与 Variant 方案的探索
    白话数据结构之基本概念篇(6)_查找算法
    git创建新分支将项目挂载到新分支操作
    提高采购效率,采购管理的五大原则及实现方法
  • 原文地址:https://blog.csdn.net/anglemanyi/article/details/126684668