python elasticsearch 客户端在创建索引期间设置映射

python elasticsearch client set mappings during create index

我可以像这样设置在 curl 命令中创建的索引的映射:

{  
  "mappings":{  
    "logs_june":{  
      "_timestamp":{  
        "enabled":"true"
      },
      "properties":{  
        "logdate":{  
          "type":"date",
          "format":"dd/MM/yyy HH:mm:ss"
        }
      }
    }
  }
}

但我需要在 python 中使用 elasticsearch 客户端创建该索引并设置映射.. 方法是什么?我在下面尝试了一些但没有用:

self.elastic_con = Elasticsearch([host], verify_certs=True)
self.elastic_con.indices.create(index="accesslog", ignore=400)
params = "{\"mappings\":{\"logs_june\":{\"_timestamp\": {\"enabled\": \"true\"},\"properties\":{\"logdate\":{\"type\":\"date\",\"format\":\"dd/MM/yyy HH:mm:ss\"}}}}}"
self.elastic_con.indices.put_mapping(index="accesslog",body=params)

您可以像这样在 create 调用中简单地添加映射:

from elasticsearch import Elasticsearch

self.elastic_con = Elasticsearch([host], verify_certs=True)
mapping = '''
{  
  "mappings":{  
    "logs_june":{  
      "_timestamp":{  
        "enabled":"true"
      },
      "properties":{  
        "logdate":{  
          "type":"date",
          "format":"dd/MM/yyy HH:mm:ss"
        }
      }
    }
  }
}'''
self.elastic_con.indices.create(index='test-index', ignore=400, body=mapping)

好吧,使用一般 python 语法有更简单的方法:

from elasticsearch import Elasticsearch
# conntect es
es = Elasticsearch([{'host': config.elastic_host, 'port': config.elastic_port}])
# delete index if exists
if es.indices.exists(config.elastic_urls_index):
    es.indices.delete(index=config.elastic_urls_index)
# index settings
settings = {
    "settings": {
        "number_of_shards": 1,
        "number_of_replicas": 0
    },
    "mappings": {
        "urls": {
            "properties": {
                "url": {
                    "type": "string"
                }
            }
        }
     }
}
# create index
es.indices.create(index=config.elastic_urls_index, ignore=400, body=settings)

Python API 客户端可能很难使用,它通常需要您将 JSON 规范文档的内部部分提供给关键字参数。

对于 put_mapping 方法,与其提供完整的 "mappings" JSON 文档,您必须为其提供 document_type 参数并且仅提供 "mappings" 文档的内部 部分如下所示:

self.client.indices.put_mapping(
    index="accesslog",
    doc_type="logs_june",
    body={
        "_timestamp": {  
            "enabled":"true"
        },
        "properties": {  
            "logdate": {  
                "type":"date",
                "format":"dd/MM/yyy HH:mm:ss"
            }
        }
    }
)

关于如何通过创建索引提高字段限制的另一个 python 客户端示例

from elasticsearch import Elasticsearch

es = Elasticsearch([{'host': config.elastic_host, 'port': 
config.elastic_port}])
settings = {
    'settings': {
        'index.mapping.total_fields.limit': 100000
    }
}

es.indices.create(index='myindex', body=settings)