如何从Elasticsearch中删除文档

Jac*_*ian 18 python elasticsearch

我找不到任何从ElasticsearchPython 中删除文档的示例.我现在看到的是定义deletedelete_by_query功能.但由于某些原因,文档甚至没有提供使用这些功能的微观示例.单个参数列表并没有告诉我太多,如果我不知道如何正确地将它们输入函数调用.所以,让我们说,我刚刚插入了一个新的doc,如下所示:

doc = {'name':'Jacobian'}
db.index(index="reestr",doc_type="some_type",body=doc)
Run Code Online (Sandbox Code Playgroud)

世界上谁知道我现在如何使用delete和删除此文档delete_by_query

Ser*_*kan 32

由于在索引文档时没有给出文档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)
Run Code Online (Sandbox Code Playgroud)

在另一种情况下,您需要查看返回值;

 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'])
Run Code Online (Sandbox Code Playgroud)

delete_by_query的另一个例子.假设在添加了几个名为'Jacobian'的文档后,运行以下命令删除name ='Jacobian'的所有文档:

 db.delete_by_query(index='reestr',doc_type='some_type', q={'name': 'Jacobian'})
Run Code Online (Sandbox Code Playgroud)

  • 而不是"q"参数,你必须现在提供"body"参数`body = {'query':{'term':{'name':'Jacobian'}}} (3认同)

Cha*_*ste 8

出于多种原因,已从版本2中的ES核心中删除了"按查询删除"API.这个功能成为了一个插件.您可以在此处查找更多详细信息:

为什么Delete-By-Query是一个插件

按查询插件删除

因为我不想添加另一个依赖项(因为我以后需要在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
Run Code Online (Sandbox Code Playgroud)

我希望有助于未来的googlers;)

  • 看起来按查询删除已恢复,并且该插件现已被终止。https://www.elastic.co/guide/en/elasticsearch/reference/5.6/docs-delete-by-query.html (3认同)

Jay*_*tel 5

人们还可以做这样的事情:

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'])
Run Code Online (Sandbox Code Playgroud)

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