ElasticSearch Mapping原理与代码实例讲解
    		       		warning:
    		            这篇文章距离上次修改已过435天,其中的内容可能已经有所变动。
    		        
        		                
                
from datetime import datetime
from elasticsearch import Elasticsearch
 
# 假设Elasticsearch服务器运行在本地,端口为9200
es = Elasticsearch("http://localhost:9200")
 
# 创建或更新索引的mapping
def create_or_update_mapping(index_name, mapping):
    try:
        es.indices.create(index=index_name, body={"mappings": mapping})
        print(f"索引 {index_name} 创建成功")
    except Exception as e:
        if "already_exists_exception" in str(e):
            es.indices.put_mapping(index=index_name, body=mapping)
            print(f"索引 {index_name} 更新成功")
        else:
            raise e
 
# 定义一个日志索引的mapping
log_index_mapping = {
    "properties": {
        "timestamp": {
            "type": "date",
            "format": "yyyy-MM-dd HH:mm:ss"
        },
        "message": {
            "type": "text"
        },
        "level": {
            "type": "keyword"
        }
    }
}
 
# 使用函数创建或更新日志索引的mapping
create_or_update_mapping("log_index", log_index_mapping)
 
# 示例:插入数据到索引
doc = {
    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    "message": "这是一条日志信息",
    "level": "INFO"
}
 
res = es.index(index="log_index", document=doc)
print(f"文档添加成功,ID: {res['result']}")这段代码首先创建了一个Elasticsearch客户端实例,然后定义了一个创建或更新索引mapping的函数。接着定义了一个日志索引的mapping,并调用函数来创建或更新这个索引的mapping。最后,演示了如何插入一条日志数据到这个索引。这个过程展示了如何在Elasticsearch中管理索引的mapping以及如何与Elasticsearch交互存储数据。
评论已关闭