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

32 python pyelasticsearch elasticsearch-py

我可以在curl命令中设置索引的映射,如下所示:

{  
  "mappings":{  
    "logs_june":{  
      "_timestamp":{  
        "enabled":"true"
      },
      "properties":{  
        "logdate":{  
          "type":"date",
          "format":"dd/MM/yyy HH:mm:ss"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我需要在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)
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 47

你可以简单地在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)
Run Code Online (Sandbox Code Playgroud)

  • 如果我想在创建索引后更新映射怎么办? (3认同)

小智 26

好吧,使用常规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)
Run Code Online (Sandbox Code Playgroud)


Jam*_*rty 16

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

对于该put_mapping方法,您不必为它提供完整的"映射"JSON文档,而是必须为其提供document_type参数,并且只提供"映射"文档的内部部分,如下所示:

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"
            }
        }
    }
)
Run Code Online (Sandbox Code Playgroud)

  • 感谢put_mapping()而不是create()的示例! (3认同)