es:python:指定索引的mapping和获取mapping

一,代码: 

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('连接失败')

index_name = "my_index2"

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


# 获取mapping信息
response = es.indices.get_mapping(index=index_name)
print("创建时未指定mapping,es自动获取的mapping:")
print(response)


index_name3 = "my_index3"
# 检查索引是否存在
is_exist = es.indices.exists(index=index_name3)
print("索引"+index_name3+"是否存在:"+str(is_exist))
if is_exist == False:
    # 指定mapping
    mapping = {
        "mappings": {
            "properties": {
                "name": {"type": "text"},
                "age": {"type": "integer"},
                "email": {"type": "keyword"}
            }
        }
    }
    # 创建索引
    es.indices.create(index=index_name3,body=mapping,ignore=400)

# 获取mapping信息
response3 = es.indices.get_mapping(index=index_name3)
print("mapping:")
print(response3)

 

二,测试结果:

$ python3 seek.py 
连接成功
索引my_index2是否存在:True
创建时未指定mapping,es自动获取的mapping:
{'my_index2': {'mappings': {'properties': {'content': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}}, 'timestamp': {'type': 'date'}, 'title': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}}}}}}
索引my_index3是否存在:False
/data/python/seek/seek.py:45: DeprecationWarning: Passing transport options in the API method is deprecated. Use 'Elasticsearch.options()' instead.
  es.indices.create(index=index_name3,body=mapping,ignore=400)
mapping:
{'my_index3': {'mappings': {'properties': {'age': {'type': 'integer'}, 'email': {'type': 'keyword'}, 'name': {'type': 'text'}}}}}

 

posted @ 2025-12-17 20:43  刘宏缔的架构森林  阅读(2)  评论(0)    收藏  举报