以下是在Elasticsearch中创建索引和映射的步骤:
一、创建索引
-
使用RESTful API(以curl命令为例)
- 可以使用Elasticsearch提供的RESTful API来创建索引。基本的curl命令格式如下:
curl -X PUT "http://localhost:9200/your_index_name"
- 这里,
-X PUT
表示使用PUT方法,http://localhost:9200
是Elasticsearch的默认地址和端口(如果是远程服务器则替换为相应的地址和端口),your_index_name
是要创建的索引名称。例如,要创建一个名为my_index
的索引:
curl -X PUT "http://localhost:9200/my_index"
- 如果成功创建索引,会得到类似以下的响应:
{ "acknowledged": true, "shards_acknowledged": true, "index": "my_index" }
-
使用Elasticsearch客户端(以Python为例)
- 首先安装
elasticsearch - python
库。 - 然后可以使用以下代码创建索引:
from elasticsearch import Elasticsearch es = Elasticsearch() index_name = "my_index" res = es.indices.create(index = index_name) if res["acknowledged"]: print(f"Index {index_name} created successfully.")
- 首先安装
二、创建映射
-
直接在创建索引时指定映射(使用RESTful API)
- 在创建索引的PUT请求中,可以包含映射信息。映射定义了索引中的字段类型、分析器等信息。例如:
curl -X PUT "http://localhost:9200/my_index" -H 'Content - type:application/json' -d ' { "mappings": { "properties": { "title": { "type": "text" }, "price": { "type": "double" }, "published_date": { "type": "date" } } } } '
- 在这个例子中,我们创建了一个名为
my_index
的索引,并定义了三个字段:title
(类型为text
)、price
(类型为double
)和published_date
(类型为date
)。
-
单独更新索引的映射(使用RESTful API)
- 如果索引已经创建,也可以单独更新映射。但是需要注意的是,Elasticsearch不允许对已存在字段的类型进行修改(除了某些特殊情况)。
curl -X PUT "http://localhost:9200/my_index/_mapping" -H 'Content - type:application/json' -d ' { "properties": { "new_field": { "type": "keyword" } } } '
- 这里我们向已经存在的
my_index
索引中添加了一个新的字段new_field
,类型为keyword
。
-
使用Elasticsearch客户端(以Python为例)创建映射
- 当使用
elasticsearch - python
库时,可以在创建索引或者更新索引映射时指定映射信息。以下是在创建索引时指定映射的示例:
from elasticsearch import Elasticsearch es = Elasticsearch() index_name = "my_index" mapping = { "mappings": { "properties": { "title": { "type": "text" }, "price": { "type": "double" }, "published_date": { "type": "date" } } } } res = es.indices.create(index = index_name, body = mapping) if res["acknowledged"]: print(f"Index {index_name} with mapping created successfully.")
- 当使用