python使用elasticsearch模块操作elasticsearch

1、创建索引

命令如下

  from elasticsearch import Elasticsearch
    es = Elasticsearch([{"host":"10.87.6.3","port":9200},])

    s = "test" + "python"
    try:
        ret = es.indices.create(index=s)
    except Exception as e:
        print(e)
    else:
        print("创建成果")
        print(ret)

返回的结果如下,证明创建成果

{'acknowledged': True, 'shards_acknowledged': True, 'index': 'testpython'}

返回的结果如下,证明创建失败

RequestError(400, 'resource_already_exists_exception', 'index [testpython/yEzYUZEiTjaZWxtN0RM_Uw] already exists')

2、删除索引

代码如下

    try:
        ret = es.indices.delete(index=s)
    except Exception as e:
        print(e)
    else:
        print("删除成果")
        print(ret)

返回结果,证明删除成果

{'acknowledged': True}

返回结果,证明删除失败

NotFoundError(404, 'index_not_found_exception', 'no such index')

3、插入数据

    for i in range(100,100000):
        s = "python操作els的的实例" + str(i)
        print(s)
        data = {"title": s, "auther": "zgj"}
        index = "students"
        try:
            result = es.create(index = index,body=data,id=i,doc_type="class1")
        except Exception as e:
            print(e)
        else:
            print(result)

这里使用create方法需要指定文档的id,这里也可以采用index的方法,用index方法,则不需要传递id这个字段,elasticsearch会自动为我们生成id

 结果如下

{'_index': 'students', '_type': 'class1', '_id': '79406', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 2, 'failed': 0}, '_seq_no': 15816, '_primary_term': 1}
python操作els的的实例79407

4、更新文档

    data = {"doc":
                {"title": "我是一个众人过",
                "auther": "zgj",
                 "age":23}
            }

    ret = es.update(index="students",body=data,doc_type="class1",id=10000)
    print(ret)

这里需要注意,要更新的数据要要放在一个大字典的,k为字符串doc,v为我们要更新的数据

我们查看结果

[root@es2 index]# curl -XGET 'http://10.87.6.3:9200/students/class1/10000?pretty=true'
{
  "_index" : "students",
  "_type" : "class1",
  "_id" : "10000",
  "_version" : 3,
  "_seq_no" : 41345,
  "_primary_term" : 2,
  "found" : true,
  "_source" : {
    "title" : "我是一个众人过",
    "auther" : "zgj",
    "age" : 23
  }
}

5、删除文档

    for i in range(1,100000):
        ret = es.delete(index="students",doc_type="class1",id=i)
        print(ret)
原文地址:https://www.cnblogs.com/bainianminguo/p/10419848.html