python操作ES

建立链接

from elasticsearch import Elasticsearch
import json

es = Elasticsearch(
    ['localhost:9200'],
    # 启动前嗅探es集群服务器
    # sniff_on_start=True,
    # es集群服务器结点连接异常时是否刷新es节点信息
    # sniff_on_connection_fail=True,
    # 每60秒刷新节点信息
    # sniffer_timeout=60
)

 

创建索引

# 创建索引
index_mapping = {
    "mappings": {
        "properties": {
            "name": {
                "type": "text"
            },
            "sex": {
                "type": "test"
            },
        "age": {
                "type": "integer"
            }
        "school": {
                "type": "text"
            }

        }
    }
}
if es.indices.exists(index='index') is not True:
  rew = es.indices.create(index='index', body=index_mapping)
  print("该索引创建成功")
else:
  print("该索引已存在")
View Code 
# 在创建索引时忽略由 IndexAlreadyExistsException 引起的 400 已经存在
rs = es.indices.create(index='test', ignore=400)
print(json.dumps(rs, indent=2, ensure_ascii=False))

# 没有这样的索引 404  400 已删除
rs = es.indices.delete(index='test', ignore=[400, 404])
print(json.dumps(rs, indent=2, ensure_ascii=False))

一、插入

# 插入单条
body = {
    'name': '张三',
    'sex': 'man',
    'age': 10,
    'school': '清华'
}

# 插入多条
bodys = [
    {
     "name":  "python",
     "addr": "深圳",
     "age": 18,
     "time": 12,
    },
    {
        "name": "深圳",
        "addr": "北京",
        "age": 20,
        "time": 100,
    },
    {
        "name":  "c",
        "addr": "香港",
        "age": 11,
        "time": 1300,
    },
    {
        "name":  "ios",
        "addr": "美国",
        "age": 8,
        "time": 120,
    },
    {
        "name":  "呼和浩特",
        "addr": "澳大利亚",
        "age": 1,
        "time": 111,
    },
    {
        "name":  "清河",
        "addr": "菲律宾",
        "age": 15,
        "time": 50,
    },


]
for body in bodys:
    # 增加
    rs = es.index(index='index', doc_type='type', body=body)
View Code

二、查询

# 查找
# rs = es.get(index='index', doc_type='type', id='qCbY4H0B8m4STfI58yWM')

# 只需要获取_id数据,多个条件用逗号隔开
rs = es.search(index='index', doc_type='type', filter_path=["hits.hits._id"])

# 获取所有数据
rs = es.search(index="index", doc_type="type", filter_path=["hits.hits._*"])

print(json.dumps(rs, indent=2, ensure_ascii=False))
View Code

三、更新

# 更新
rs = es.update(index='index', doc_type='type', id='qSbY4H0B8m4STfI58yWO', body=body)

四、删除

# 删除
es.delete(index='index', doc_type='type', id='pCZP4H0B8m4STfI5_CU6')
posted @ 2021-12-27 16:08  长乐未央丫  阅读(308)  评论(0)    收藏  举报