ToB企服应用市场:ToB评测及商务社交产业平台
标题:
怎样在 Elasticsearch 中创建索引和映射?
[打印本页]
作者:
莫张周刘王
时间:
7 小时前
标题:
怎样在 Elasticsearch 中创建索引和映射?
以下是在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.")
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4