python操作Elasticsearch执行增删改查

文章目录

  • 基本操作
  • 更多查询方法
    • [1. 查询全部数据](#1. 查询全部数据)
    • [2. 针对某个确定的值/字符串的查询:term、match](#2. 针对某个确定的值/字符串的查询:term、match)
    • [3. 在多个选项中有一个匹配,就查出来:terms](#3. 在多个选项中有一个匹配,就查出来:terms)
    • [4. 数值范围查询:range](#4. 数值范围查询:range)
    • [5. 多个条件同时触发 bool](#5. 多个条件同时触发 bool)
    • [6. 指定返回值个数 size](#6. 指定返回值个数 size)
    • [7. 返回指定列 _source](#7. 返回指定列 _source)
  • 完整示例程序

基本操作

  1. 首先连接Elasticsearch数据库,然后创建一个自定义的索引
py 复制代码
from elasticsearch import Elasticsearch
import random
from elasticsearch import helpers

# 连接到本地的 Elasticsearch 服务
es = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# 创建一个索引名为 "my_index" 的索引
if es.indices.exists(index=index_name):  # 如果索引存在,删除
    es.indices.delete(index=index_name)
es.indices.create(index=index_name)  # 新建索引
  1. 新增随机数据

这里我们创建随机数据项,包含value_num与value_choice项,

py 复制代码
# 新增随机数据项
add_value_list: list = []
for _ in range(1000):
    num = random.randint(1, 100)
    add_value_list.append({
        "_index": index_name,  # 注意!个参数决定要插入到哪个索引中
        "value_num": random.randint(1, 100),
        "value_choice": ["c1", 'c2', 'c3'][random.randint(0, 2)],
    })
# 批量插入数据
helpers.bulk(es, add_value_list)
  1. 查询操作
py 复制代码
# 查询操作
_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
    "size": 20,  # 查询20条
}
response = es.search(index=index_name, body=_body_query)
# 打印查询的结果
for _hit in response["hits"]["hits"]:
    _value = _hit['_source']
    print("value_num:", _value["value_num"], " value_choice:", _value['value_choice'])
  1. 更新数据项

这里,我们将查询出的数据中,通过文档ID与修改的数据重新为数据赋值

py 复制代码
# 更新操作
for _hit in response["hits"]["hits"]:
    update_body = {"doc": {
        "value_choice": "c4",  # 更新value_choice字段为c4
    }}
    res = es.update(index=index_name, id=_hit['_id'], body=update_body)
  1. 删除数据项
py 复制代码
# 删除操作
for _hit in response["hits"]["hits"]:
    res = es.delete(index=index_name, id=_hit['_id'])

更多查询方法

1. 查询全部数据

py 复制代码
_body_query = {
    "query":{
        "match_all":{}
    }
}

2. 针对某个确定的值/字符串的查询:term、match

match会执行多个term操作,term操作精度更高

py 复制代码
_body_query = {
    "query": {
        "match": {
            "value_choice": "c1"
        }
    }
}
py 复制代码
_body_query = {
    "query": {
        "term": {
            "value_choice": "c1"
        }
    }
}

3. 在多个选项中有一个匹配,就查出来:terms

py 复制代码
_body_query = {
    "query": {
        "terms": {
            "value_choice": ["c1", "c2"],
        }
    }
}

4. 数值范围查询:range

查询>=40且<=60的数据

py 复制代码
_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    }
}

5. 多个条件同时触发 bool

布尔查询可以同时查询多个条件,也称为组合查询,构造查询的字典数据时,query后紧跟bool,之后再跟bool的判断条件,判断条件有下面几个:

  • filter:过滤器
  • must:类似and,需要所有条件都满足
  • should:类似or,只要能满足一个即可
  • must_not:需要都不满足

写完判断条件后,在判断条件的list里再紧跟查询操作的具体细节

py 复制代码
_body_query = {
    "query": {
        "bool": {
            "should": [
                {
                    "match": {"value_choice": "c1"} # value_choice = "c1"
                },
                {
                    "range": {"value_num": {"lte": 50}} # value_num <= 50
                }
            ]
        }
    },
}

6. 指定返回值个数 size

在构造的字典中添加size关键字即可

py 复制代码
_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
    "size": 20,
}

7. 返回指定列 _source

py 复制代码
_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
     "_source": ["value_num"] # 这里指定返回的fields
}

完整示例程序

py 复制代码
from elasticsearch import Elasticsearch
import random
from elasticsearch import helpers

# 连接到本地的 Elasticsearch 服务
es = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# 创建一个索引名为 "my_index" 的索引
if es.indices.exists(index=index_name):  # 如果索引存在,删除
    es.indices.delete(index=index_name)
es.indices.create(index=index_name)  # 新建索引

# 生成随机数据
add_value_list: list = []
for _ in range(1000):
    num = random.randint(1, 100)
    add_value_list.append({
        "_index": index_name,  # 注意!个参数决定要插入到哪个索引中
        "value_num": random.randint(1, 100),
        "value_choice": ["c1", 'c2', 'c3'][random.randint(0, 2)],
    })
# 批量插入数据
helpers.bulk(es, add_value_list)

# ================== 开始增删改查 ==================
_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
    "size": 20,
}

response = es.search(index=index_name, body=_body_query)  # 查询10条
# 打印查询的结果
for _hit in response["hits"]["hits"]:
    _value = _hit['_source']
    print("value_num:", _value["value_num"], " value_choice:", _value['value_choice'])

# 更新操作
for _hit in response["hits"]["hits"]:
    update_body = {"doc": {
        "value_choice": "c4",  # 更新value_choice字段为c4
    }}
    res = es.update(index=index_name, id=_hit['_id'], body=update_body)

# 删除操作
for _hit in response["hits"]["hits"]:
    res = es.delete(index=index_name, id=_hit['_id'])
相关推荐
长和信泰光伏储能14 小时前
京津冀光伏发电:绿色能源的未来之路
python·能源
浦信仿真大讲堂14 小时前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
Gu Gu Study15 小时前
ScoutLoop开放域深度研究引擎(agent的初步设计想法)
人工智能·python
卷无止境15 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境16 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
lpfasd12316 小时前
MediaCrawler 项目深度分析
chrome·python·chrome devtools
Dxy123931021616 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
bamb0017 小时前
一个项目带你入门AI应用开发01
python
05664617 小时前
Python康复训练——常用标准库
开发语言·python·学习
昆曲之源_娄江河畔17 小时前
Python如何安装flask, pymssql
开发语言·python·flask·pymssql