欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python調(diào)用Elasticsearch執(zhí)行增刪改查操作

 更新時(shí)間:2025年04月28日 11:10:17   作者:呆萌的代Ma  
Elasticsearch 是一種強(qiáng)大且靈活的分布式搜索引擎,而 Python 則以其易用性和強(qiáng)大的數(shù)據(jù)處理能力,成為開發(fā)者在數(shù)據(jù)操作中的理想選擇,本文將介紹二者如何結(jié)合實(shí)現(xiàn)增刪改查操作,感興趣的可以了解下

基本操作

1.連接Elasticsearch數(shù)據(jù)庫

首先連接Elasticsearch數(shù)據(jù)庫,然后創(chuàng)建一個(gè)自定義的索引

from elasticsearch import Elasticsearch
import random
from elasticsearch import helpers

# 連接到本地的 Elasticsearch 服務(wù)
es = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# 創(chuàng)建一個(gè)索引名為 "my_index" 的索引
if es.indices.exists(index=index_name):  # 如果索引存在,刪除
    es.indices.delete(index=index_name)
es.indices.create(index=index_name)  # 新建索引

2.新增隨機(jī)數(shù)據(jù)

這里我們創(chuàng)建隨機(jī)數(shù)據(jù)項(xiàng),包含value_num與value_choice項(xiàng),

# 新增隨機(jī)數(shù)據(jù)項(xiàng)
add_value_list: list = []
for _ in range(1000):
    num = random.randint(1, 100)
    add_value_list.append({
        "_index": index_name,  # 注意!個(gè)參數(shù)決定要插入到哪個(gè)索引中
        "value_num": random.randint(1, 100),
        "value_choice": ["c1", 'c2', 'c3'][random.randint(0, 2)],
    })
# 批量插入數(shù)據(jù)
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)
# 打印查詢的結(jié)果
for _hit in response["hits"]["hits"]:
    _value = _hit['_source']
    print("value_num:", _value["value_num"], " value_choice:", _value['value_choice'])

4.更新數(shù)據(jù)項(xiàng)

這里,我們將查詢出的數(shù)據(jù)中,通過文檔ID與修改的數(shù)據(jù)重新為數(shù)據(jù)賦值

# 更新操作
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.刪除數(shù)據(jù)項(xiàng)

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

更多查詢方法

1. 查詢?nèi)繑?shù)據(jù)

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

2. 針對(duì)某個(gè)確定的值/字符串的查詢:term、match

match會(huì)執(zhí)行多個(gè)term操作,term操作精度更高

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

3. 在多個(gè)選項(xiàng)中有一個(gè)匹配,就查出來:terms

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

4. 數(shù)值范圍查詢:range

查詢>=40且<=60的數(shù)據(jù)

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

5. 多個(gè)條件同時(shí)觸發(fā) bool

布爾查詢可以同時(shí)查詢多個(gè)條件,也稱為組合查詢,構(gòu)造查詢的字典數(shù)據(jù)時(shí),query后緊跟bool,之后再跟bool的判斷條件,判斷條件有下面幾個(gè):

  • filter:過濾器
  • must:類似and,需要所有條件都滿足
  • should:類似or,只要能滿足一個(gè)即可
  • must_not:需要都不滿足

寫完判斷條件后,在判斷條件的list里再緊跟查詢操作的具體細(xì)節(jié)

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

6. 指定返回值個(gè)數(shù) size

在構(gòu)造的字典中添加size關(guān)鍵字即可

_body_query = {
    "query": {
        "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 服務(wù)
es = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# 創(chuàng)建一個(gè)索引名為 "my_index" 的索引
if es.indices.exists(index=index_name):  # 如果索引存在,刪除
    es.indices.delete(index=index_name)
es.indices.create(index=index_name)  # 新建索引

# 生成隨機(jī)數(shù)據(jù)
add_value_list: list = []
for _ in range(1000):
    num = random.randint(1, 100)
    add_value_list.append({
        "_index": index_name,  # 注意!個(gè)參數(shù)決定要插入到哪個(gè)索引中
        "value_num": random.randint(1, 100),
        "value_choice": ["c1", 'c2', 'c3'][random.randint(0, 2)],
    })
# 批量插入數(shù)據(jù)
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條
# 打印查詢的結(jié)果
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'])

到此這篇關(guān)于python調(diào)用Elasticsearch執(zhí)行增刪改查操作的文章就介紹到這了,更多相關(guān)python Elasticsearch增刪改查操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論