ES索引库操作
from datetime import datetime
from elasticsearch import Elasticsearch
# 假设ES服务器地址为 "http://localhost:9200"
es = Elasticsearch(["http://localhost:9200"])
# 创建一个新的索引
def create_index(index_name):
body = {
"mappings": {
"properties": {
"timestamp": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"message": {
"type": "text"
}
}
}
}
response = es.indices.create(index=index_name, body=body)
print(response)
# 删除一个索引
def delete_index(index_name):
response = es.indices.delete(index=index_name)
print(response)
# 添加文档到索引
def add_document(index_name, timestamp, message):
document = {
"timestamp": timestamp,
"message": message
}
response = es.index(index=index_name, body=document)
print(response)
# 查询索引中的文档
def search_documents(index_name):
query = {
"query": {
"match_all": {}
}
}
response = es.search(index=index_name, body=query)
print(response)
# 使用示例
index_name = "my_index"
create_index(index_name)
add_document(index_name, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "This is a test message")
search_documents(index_name)
delete_index(index_name)
这段代码展示了如何使用Elasticsearch Python API来创建一个新的索引、添加文档、执行搜索和删除索引。代码中定义了索引的映射,包括时间戳和文本字段,并展示了如何格式化时间戳。在实际应用中,你需要根据自己的需求调整索引名称、映射和查询条件。
评论已关闭