es 數(shù)據(jù)庫(kù)
Elasticsearch是一個(gè)開源的高擴(kuò)展性搜索引擎,它可以快速地存儲(chǔ)、搜索和分析大量的數(shù)據(jù)。
使用Python語(yǔ)言和Elasticsearch,可以輕松地創(chuàng)建和操作“數(shù)據(jù)庫(kù)”和“數(shù)據(jù)庫(kù)表”,而且具備分布式和高擴(kuò)展性的特點(diǎn),適用于大規(guī)模數(shù)據(jù)存儲(chǔ)與搜索場(chǎng)景。
ES數(shù)據(jù)庫(kù)保存數(shù)據(jù)的格式是文件形式的嗎?
ES是一種文檔數(shù)據(jù)庫(kù),它并不像關(guān)系型數(shù)據(jù)庫(kù)一樣將每張表的每條記錄都保存在表里面,而是將所有文檔存儲(chǔ)在一個(gè)索引中。每個(gè)文檔都是一個(gè)JSON結(jié)構(gòu),包含多個(gè)字段。ES還支持對(duì)文檔進(jìn)行全文檢索和聚合查詢等高級(jí)功能。
在存儲(chǔ)上,ES將每個(gè)索引分成多個(gè)分片,每個(gè)分片都是一個(gè)Lucene實(shí)例。每個(gè)文檔被存儲(chǔ)到其中一個(gè)分片中,根據(jù)文檔ID生成一個(gè)唯一標(biāo)識(shí)符來(lái)定位分片。為了提高性能,ES會(huì)在內(nèi)存中緩存熱點(diǎn)數(shù)據(jù),并使用文件系統(tǒng)緩存來(lái)減少IO操作。
1. 創(chuàng)建“數(shù)據(jù)庫(kù)” | 索引(index)
在Elasticsearch中,“數(shù)據(jù)庫(kù)”被封裝為索引(Index)
,可以通過(guò)以下代碼來(lái)創(chuàng)建一個(gè)索引:
# 首先導(dǎo)入了Elasticsearch模塊
from elasticsearch import Elasticsearch
# 創(chuàng)建es數(shù)據(jù)庫(kù)句柄
es = Elasticsearch()
# 接著定義了一個(gè)索引名稱
index_name = "myindex"
# 通過(guò)`es.indices.exists()`方法來(lái)判斷索引是否存在
if not es.indices.exists(index_name):
# 如果索引不存在,則通過(guò)`es.indices.create()`方法來(lái)創(chuàng)建索引
es.indices.create(index=index_name)
2. 創(chuàng)建“數(shù)據(jù)庫(kù)表” | 文檔類型(doc_type)
在Elasticsearch中,每個(gè)索引可以包含多個(gè)文檔類型(Type)
,可以通過(guò)以下代碼來(lái)創(chuàng)建一個(gè)文檔類型:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-524999.html
# `es.indices.put_mapping()`方法,在指定的索引上創(chuàng)建了一個(gè)名稱為`type_name`的文檔類型,并定義了文檔類型中的字段
es.indices.put_mapping(
index=index_name, # 在指定的索引index_name上創(chuàng)建
body={ # 文檔中的字段
"properties": {
"field1": {
"type": "keyword"
},
"field2": {
"type": "text"
}
}
},
doc_type=type_name # 文檔名稱為type_name
)
3. 創(chuàng)建“數(shù)據(jù)庫(kù)表字段”
在上述代碼中,通過(guò)body
參數(shù)定義了文檔類型中的字段。其中,"type": "keyword"
表示該字段類型為字符串,且不需要分詞。"type": "text"
表示該字段類型為字符串,且需要分詞。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-524999.html
4. 常用的ES數(shù)據(jù)庫(kù)操作
插入數(shù)據(jù) | index | res [‘created’]
doc_id = 1
doc = {
"field1": "value1",
"field2": "value2"
}
res = es.index(index=index_name, doc_type=type_name, id=doc_id, body=doc)
if res["created"]:
print("Document created successfully")
查詢數(shù)據(jù) | get | res[’ _source’]
res = es.get(index=index_name, doc_type=type_name, id=doc_id)
doc = res["_source"]
更新數(shù)據(jù) | update | res[‘result’]
doc_id = n;
doc = {
"field1": "new_value1"
}
res = es.update(index=index_name, doc_type=type_name, id=doc_id, body={"doc": doc})
if res["result"] == "updated":
print("Document updated successfully")
刪除數(shù)據(jù) | delete | res[“result”]
res = es.delete(index=index_name, doc_type=type_name, id=doc_id)
if res["result"] == "deleted":
print("Document deleted successfully")
到了這里,關(guān)于【es數(shù)據(jù)庫(kù)】python 使用Elasticsearch數(shù)據(jù)庫(kù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!