es: python添加、更新、删除doc

一,代码:

from elasticsearch import Elasticsearch

# 连接到 Elasticsearch,替换为实际的 IP 地址和密码
# , basic_auth=('elastic', 'Elastic_j625sz')
es = Elasticsearch('http://127.0.0.1:9200')

# 检查连接
if es.ping():
    print('连接成功')
else:
    print('连接失败')


# 检查索引是否存在
is_exist = es.indices.exists(index="my_index")
print("索引my_index是否存在:"+str(is_exist))
if is_exist == False:
    # 创建索引
    es.indices.create(index="my_index")

# 添加文档
doc1 = {
    "title": "测试文档1",
    "content": "这是一个测试文档1",
    "timestamp": "2024-12-07"
}
doc2 = {
    "title": "测试文档2",
    "content": "这是一个测试文档2",
    "timestamp": "2024-12-01"
}
# 指定ID插入
es.index(index="my_index", id="1", document=doc1)
# 自动生成ID插入
es.index(index="my_index", document=doc2)

# 获取文档
result = es.get(index="my_index", id="1")
print(result)



# 更新文档
update_doc = {
    "doc": {
        "title": "更新后的标题"
    }
}
es.update(index="my_index", id="1", body=update_doc)
print(es.get(index="my_index", id="1"))

# 查询指定索引中,指定ID记录是否存在
is_id_exist = es.exists(index='my_index', id='1')
print("id为1的doc是否存在:"+str(is_id_exist))
# 删除文档
es.delete(index="my_index", id="1")

# 查询指定索引中,指定ID记录是否存在
is_id_exist = es.exists(index='my_index', id='1')
print("id为1的doc是否存在:"+str(is_id_exist))

二,测试效果:

$ python3 seek.py 
连接成功
索引my_index是否存在:True
{'_index': 'my_index', '_id': '1', '_version': 5, '_seq_no': 6, '_primary_term': 1, 'found': True, '_source': {'title': '测试文档1', 'content': '这是一个测试文档1', 'timestamp': '2024-12-07'}}
{'_index': 'my_index', '_id': '1', '_version': 6, '_seq_no': 8, '_primary_term': 1, 'found': True, '_source': {'title': '更新后的标题', 'content': '这是一个测试文档1', 'timestamp': '2024-12-07'}}
id为1的doc是否存在:True
id为1的doc是否存在:False

 

posted @ 2025-12-16 23:13  刘宏缔的架构森林  阅读(12)  评论(0)    收藏  举报