本文首發于公眾號:Hunter后端
原文鏈接:Python連接es筆記四之創建和洗掉操作
這一篇筆記介紹一下索引和資料的創建和洗掉,
其實對于索引來說,如果可以接觸到 kibana 的話,可以很方便的在界面進行操作,這里簡單介紹一下如何使用代碼來操作索引的創建和洗掉,
索引的創建和洗掉操作
使用的還是 es 的連接:
from elasticsearch_dsl import connections
connections.configure(
default={"hosts": "localhost:9200"},
)
conn = connections.connections.get_connection("default")
創建索引
index_name = "test_create"
conn.indices.create(index_name)
檢測索引是否存在
print(conn.indices.exists(index_name))
回傳的是一個布爾型資料,
洗掉索引
conn.indices.delete(index_name)
資料的創建和洗掉
創建單條資料
還是默認使用剛剛創建的索引 test_create,我們需要往里面加入一條資料,示例如下:
index_name = "test_create"
conn.index(
index=index_name,
id=1,
body={
"name": "李白"
}
)
這樣就往里面寫入了一條 id=1 的資料,如果不指定 id 引數,系統會為我們自動分配一個 id:
conn.index(
index=index_name,
body={
"name": "李白"
}
)
這種創建方式也是允許的,
批量創建資料
這里用到在批量更新時候的使用過的 elasticsearch.helpers 函式,
示例如下:
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)
在這里,因為是創建資料,所以 _op_type 的值為 index,剩下的使用方法和之前更新的操作一致,
洗掉操作
洗掉操作在第一篇筆記介紹查詢資料的時候帶過一筆,就是通過 Search() 方法加入條件后,不執行 execute(),而是執行 delete() 函式進行洗掉:
s = Search(using="default").index("exam").query("match", name="張三豐")
s.delete()
還有一種 es 連接直接操作的 delete_by_query() 函式,示例如下:
conn = connections.connections.get_connection("default")
q1 = ES_Q("term", name="楊過")
conn.delete_by_query(
index="exam",
body={
"query": q1
}
)
如果想獲取更多后端相關文章,可掃碼關注閱讀:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553944.html
標籤:Python
上一篇:Python潮流周刊#4:Python 2023 語言峰會
下一篇:返回列表
