Elasticsearch学习笔记(八):Python操作Elasticsearch

890 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第24天,点击查看活动详情

导语

Elasticsearch 是一个分布式的开源搜索和分析引擎,目前被广泛使用,本文介绍如何使用Python来操作Elasticsearch。

安装Elasticsearch的包

我们需要首先配置ES在Python中的第三方库,名字就叫做Elasticsearch。所以可以通过pip install或者conda install的方式来进行安装。这里需要注意的是,之前教程的内容基于Elasticsearch 7.5.2,所以这里安装时需要指定Elasticsearch的版本为7.6(或更高的7.*版本)即可。

pip install elasticsearch==7.6

安装完成后我们导入该库。

from elasticsearch import Elasticsearch 

使用Python连接ES

我们建立一个ES连接,并使用ping命令来检测是否连接正常。

es = Elasticsearch()
print(es.ping())

得到输出为:

True

索引操作

新建索引

新建索引时,我们首先需要指定这个索引的mapping。

mappings = {
    "mappings" : {
      "properties" : {
        "age" : {
            "type" : "long",
        },
        "hobby" : {
          "type" : "text",
        },
        "name" : {
          "type" : "text",
        }
      }
    }
}

例如,上述代码中,我们定义了一个具有三个field的index的mapping,其中age字段是long类型,hobby和name字段则是text类型。

接着,我们依据这个mapping进行索引的创建。

res = es.indices.create(index ='index_test',body =mappings, ignore=400)

删除索引

可以直接使用es.indeices.delete函数来删除索引,

es.indices.delete("index_test")

文档操作

插入文档

可以使用es.index函数直接将文档传入参数,例如:

es.index(index="index_test", id=0,body={"name":"Tom", "age":15, "hobby": "rap"})

这里,提前指定了该文档的id为0。

查询文档

可以使用es.get函数来进行文档的查询,例如:

es.get(index="index_test", id=0, ignore=404)

得到输出为:

{
    "_id":"0",
    "_index":"index_test",
    "_primary_term":1,
    "_seq_no":0,
    "_source":{
        "age":15,
        "hobby":"rap",
        "name":"Tom"
    },
    "_type":"_doc",
    "_version":1,
    "found":true
}

修改(更新)文档

修改(或者说更新)文档,可以使用es.update函数来实现,这里需要指定要更新的index名字、id的编号以及要更新的文档的内容。

例如,

res = es.update(index="index_test", id=0, body={"doc":{"age": 22}})
print(res)

得到输出为:

{
    "_id":"0",
    "_index":"index_test",
    "_primary_term":1,
    "_seq_no":1,
    "_shards":{
        "failed":0,
        "successful":1,
        "total":2
    },
    "_type":"_doc",
    "_version":2,
    "result":"updated"
}

删除文档

删除文档只需要使用es.delete函数,并提供index名称和文档id即可以进行文档删除,例如:

es.delete(index="index_test", id=0)

批量操作

之前我们介绍过可以使用bulk进行命令的批量操作,使用Python时,也完全可以实现这个功能,具体而言,我们需要使用es.bulk函数来进行批量操作,例如:

doc = [
     {"create": {"_index": "index_test", '_id': 0 }},
     {'name': 'Tom', 'age': 20, 'hobby': 'football rap'},
     {"create": {"_index": "index_test",  '_id': 1 }},
     {'name': 'Jerry', 'age': 29, 'hobby': 'basketball sing football'},
     {"create": {"_index": "index_test",  '_id': 2}},
     {'name': 'Bob', 'age': 12, 'hobby': 'football dance'},
     {"create": {"_index": "index_test",  '_id': 3}},
     {'name': 'Amy', 'age': 24, 'hobby': 'sing dance'},
     {"create": {"_index": "index_test",  '_id': 4}},
     {'name': 'Jack', 'age': 19, 'hobby': 'sing'},
 ]
res = es.bulk(index='index_test',  body=doc)

搜索操作

最后是搜索操作,这里仅以query DSL进行示例,主要使用es.search函数来实现,例如:

query = {
    "query": {
    "match": {
      "hobby": "sing"
    }
  }
  , "sort": [
    {
      "age": {
        "order": "asc"
      }
    }
  ]
}
result = es.search(index="index_test", body=query)