开发者

python调用Elasticsearch执行增删改查操作

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

    基本操作

    1.连接Elasticsearch数据库

    首先连接Elasticsearch数据库,然后创建一个自定义的索引

    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)  # 新建索引
    

    2.新增随机数据

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

    # 新增随机数据项
    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)
    

    3.查询操作

    # 查询操作
    _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'])

    4.更新数据项

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

    # 更新操作
    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)
    

    5.删除数据项

    # 删除操作
    for _hit in response["hits"]["hits"]:
        res = es.delete(index=index_name, id=_hit['_id'])
    

    更多查询方法

    1. 查询全部数据

    _body_query = {
        "query":{
            "match_all":{}
        }
    }
    

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

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

    _body_query = {
        "query": {
            "match": {
                "value_choice": "c1"
            }
        }
    }
    
    _body_query = {
        "query": {
            "term": {
                "value_choice": "c1"
            }
        }
    }
    

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

    _body_query = {
        "query": {
            "terms": {
                "value_choice": ["c1", "c2"],
            }
        }
    }
    

    4. 数值范围查询:range

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

    _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里再紧跟查询操作的具体细节

    _body_query = {
        "query": {
            "bool": {
                "should": [
                    {
                        "match": {"value_choice": "c1"} # value_choice = "c1"
                    },
                   编程客栈 {
                        "range": {"value_num": {"lte": 50}} # v编程客栈alue_num <= 50
                    }
                ]
            }
        },
    }
    

    6. 指定返回值个数 size

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

    _body_query = {
        "phpquery": {
            "range": {
                "value_num": {
                    "gte": 40,  # >= 40
                    "lte": 60  # <= 60
                }
            }
        },
        "size": 20,
    }
    

    7. 返回指定列 _source

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

    完整示例程序

    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, 10android0)
        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"php], " 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'])
    

    到此这篇关于python调用Elasticsearch执行增删改查操作的文章就介绍到这了,更多相关python Elasticsearch增删改查操作内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜