ElasticSearch索引操作入门
from datetime import datetime
from elasticsearch import Elasticsearch
# 连接到Elasticsearch
es = Elasticsearch("http://localhost:9200")
# 创建一个新索引
new_index = {
"mappings": {
"properties": {
"timestamp": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
}
}
}
}
response = es.indices.create(index='test-index', body=new_index)
print("索引创建结果:", response)
# 添加一条文档到索引
doc_id = 1
doc = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"message": "这是一条测试信息。"
}
response = es.index(index='test-index', id=doc_id, document=doc)
print("文档添加结果:", response)
# 获取并打印文档
response = es.get(index='test-index', id=doc_id)
print("获取的文档:", response['_source'])
# 更新文档
updated_doc = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"message": "这是一条更新后的测试信息。"
}
response = es.update(index='test-index', id=doc_id, document=updated_doc)
print("文档更新结果:", response)
# 删除索引
response = es.indices.delete(index='test-index')
print("索引删除结果:", response)
这段代码展示了如何在Python中使用Elasticsearch库来完成Elasticsearch索引的基本操作,包括创建索引、添加文档、获取文档、更新文档和删除索引。代码中使用了elasticsearch
库,需要先通过pip install elasticsearch
命令安装。
评论已关闭