Python連接es筆記之創(chuàng)建和刪除操作示例詳解
索引和數(shù)據(jù)的創(chuàng)建和刪除
其實對于索引來說,如果可以接觸到 kibana 的話,可以很方便的在界面進行操作,這里簡單介紹一下如何使用代碼來操作索引的創(chuàng)建和刪除。
索引的創(chuàng)建和刪除操作
使用的還是 es 的連接:
from elasticsearch_dsl import connections
connections.configure(
default={"hosts": "localhost:9200"},
)
conn = connections.connections.get_connection("default")創(chuàng)建索引
index_name = "test_create" conn.indices.create(index_name)
檢測索引是否存在
print(conn.indices.exists(index_name))
返回的是一個布爾型數(shù)據(jù)。
刪除索引
conn.indices.delete(index_name)
數(shù)據(jù)的創(chuàng)建和刪除
創(chuàng)建單條數(shù)據(jù)
還是默認使用剛剛創(chuàng)建的索引 test_create,我們需要往里面加入一條數(shù)據(jù),示例如下:
index_name = "test_create"
conn.index(
index=index_name,
id=1,
body={
"name": "李白"
}
)這樣就往里面寫入了一條 id=1 的數(shù)據(jù),如果不指定 id 參數(shù),系統(tǒng)會為我們自動分配一個 id:
conn.index(
index=index_name,
body={
"name": "李白"
}
)這種創(chuàng)建方式也是允許的。
批量創(chuàng)建數(shù)據(jù)
這里用到在批量更新時候的使用過的 elasticsearch.helpers 函數(shù)。
示例如下:
action_1 = {
"_op_type": "index",
"_index": "test_create",
"doc": {"age": 20, "name": "楊過", "address": "終南山"},
}
action_2 = {
"_op_type": "index",
"_index": "test_create",
"doc": {"age": 21, "name": "郭靖", "address": "桃花島"},
}
action_list = [action_1, action_2]
helpers.bulk(conn, actions=action_list)在這里,因為是創(chuàng)建數(shù)據(jù),所以 _op_type 的值為 index,剩下的使用方法和之前更新的操作一致。
刪除操作
刪除操作在第一篇筆記介紹查詢數(shù)據(jù)的時候帶過一筆,就是通過 Search() 方法加入條件后,不執(zhí)行 execute(),而是執(zhí)行 delete() 函數(shù)進行刪除:
s = Search(using="default").index("exam").query("match", name="張三豐")
s.delete()還有一種 es 連接直接操作的 delete_by_query() 函數(shù),示例如下:
conn = connections.connections.get_connection("default")
q1 = ES_Q("term", name="楊過")
conn.delete_by_query(
index="exam",
body={
"query": q1
}
)以上就是Python連接es筆記之創(chuàng)建和刪除操作示例詳解的詳細內(nèi)容,更多關于Python連接es創(chuàng)建刪除操作的資料請關注腳本之家其它相關文章!

