如何从Elasticsearch中删除文档

2024-04-25 07:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中找不到从Elasticsearch中删除文档的任何示例。我现在看到的是deletedelete_by_query函数的定义。但由于某些原因,documentation甚至没有提供使用这些函数的微观示例。如果我不知道如何正确地将参数输入函数调用,那么单个参数列表不会告诉我太多信息。所以,我刚刚插入了一个新的文档,就像这样:

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

世界上谁知道我现在如何使用deletedelete_by_query删除此文档?


Tags: 函数文档示例参数indexbydoc定义
3条回答

由于在为文档编制索引时不提供文档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'])

按查询删除的另一个示例。假设添加了几个名为“Jacobian”的文档后,运行以下命令删除名为“Jacobian”的所有文档:

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

也可以这样做:

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'])

它将对大容量数据执行删除操作

由于几个原因,已从版本2中的ES核心中删除了Delete By Query API。这个函数变成了一个插件。您可以在此处查找更多详细信息:

Why Delete-By-Query is a plugin

Delete By Query Plugin

因为我不想添加另一个依赖项(因为我以后需要在docker映像中运行这个),所以我编写了一个自己的函数来解决这个问题。我的解决方案是搜索具有指定索引和类型的所有引号。之后,我使用Bulk 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

我希望这能帮助未来的谷歌用户;)

相关问题 更多 >