簡體   English   中英

如何從 Elasticsearch 中刪除文檔

[英]How to delete documents from Elasticsearch

我找不到任何在 Python 中從Elasticsearch中刪除文檔的示例。 我現在看到的是deletedelete_by_query函數的定義。 但是由於某種原因, 文檔甚至沒有提供使用這些功能的微觀示例。 如果我不知道如何正確地將它們輸入到函數調用中,那么單個參數列表並不能告訴我太多。 所以,可以說,我剛剛插入了一個新文檔,如下所示:

doc = {'name':'Jacobian'}
db.index(index="reestr",doc_type="some_type",body=doc)

世界上誰知道我現在如何使用deletedelete_by_query刪除此文檔?

由於您在索引文檔時沒有提供文檔 ID,因此您必須從返回值中獲取自動生成的文檔 ID 並根據 ID 刪除。 或者您可以自己定義 id,嘗試以下操作:

 db.index(index="reestr",doc_type="some_type",id=1919, body=doc)

 db.delete(index="reestr",doc_type="some_type",id=1919)

在另一種情況下,您需要查看返回值;

 r = db.index(index="reestr",doc_type="some_type", body=doc)
 # r = {u'_type': u'some_type', u'_id': u'AU36zuFq-fzpr_HkJSkT', u'created': True, u'_version': 1, u'_index': u'reestr'}

 db.delete(index="reestr",doc_type="some_type",id=r['_id'])

delete_by_query 的另一個示例。 假設在添加了幾個 name='Jacobian' 的文檔后,運行以下命令刪除所有 name='Jacobian' 的文檔:

 db.delete_by_query(index='reestr',doc_type='some_type', q={'name': 'Jacobian'})

出於多種原因,Delete-By-Query API 在版本 2 中從 ES 核心中移除。 這個函數變成了一個插件。 您可以在此處查看更多詳細信息:

為什么 Delete-By-Query 是一個插件

按查詢刪除插件

因為我不想添加另一個依賴項(因為我稍后需要在 docker 映像中運行它)我編寫了一個自己的函數來解決這個問題。 我的解決方案是搜索具有指定索引和類型的所有引號。 之后,我使用批量 API 刪除它們:

def delete_es_type(es, index, type_):
    try:
        count = es.count(index, type_)['count']
        response = es.search(
            index=index,
            filter_path=["hits.hits._id"],
            body={"size": count, "query": {"filtered" : {"filter" : {
                  "type" : {"value": type_ }}}}})
        ids = [x["_id"] for x in response["hits"]["hits"]]
        if len(ids) > 0:
            return
        bulk_body = [
            '{{"delete": {{"_index": "{}", "_type": "{}", "_id": "{}"}}}}'
            .format(index, type_, x) for x in ids]
        es.bulk('\n'.join(bulk_body))
        # es.indices.flush_synced([index])
    except elasticsearch.exceptions.TransportError as ex:
        print("Elasticsearch error: " + ex.error)
        raise ex

我希望這對未來的谷歌人有所幫助;)

也可以這樣做:

def delete_by_ids(index, ids):
    query = {"query": {"terms": {"_id": ids}}}
    res = es.delete_by_query(index=index, body=query)
    pprint(res)

# Pass index and list of id that you want to delete.
delete_by_ids('my_index', ['test1', 'test2', 'test3'])

它將對批量數據執行刪除操作

我在尋找使用他們的 Python 庫 ElasticSearch-DSL 刪除 ElasticSearch 上的文檔的方法時遇到了這篇文章。

如果它對任何人有幫助,他們文檔的這一部分描述了文檔生命周期。 https://elasticsearch-dsl.readthedocs.io/en/latest/persistence.html#document-life-cycle

最后,它詳細說明了如何刪除文檔:

要刪除一個文檔,只需調用它的 delete 方法:

 first = Post.get(id=42) first.delete()

希望對你有幫助🤞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM