怎样在 Elasticsearch 中创建索引和映射?

打印 上一主题 下一主题

主题 920|帖子 920|积分 2760

以下是在Elasticsearch中创建索引和映射的步骤:
一、创建索引


  • 使用RESTful API(以curl命令为例)

    • 可以使用Elasticsearch提供的RESTful API来创建索引。根本的curl命令格式如下:
    1. curl -X PUT "http://localhost:9200/your_index_name"
    复制代码
      

    • 这里,-X PUT体现使用PUT方法,http://localhost:9200是Elasticsearch的默认地址和端口(假如是长途服务器则替换为相应的地址和端口),your_index_name是要创建的索引名称。例如,要创建一个名为my_index的索引:
    1. curl -X PUT "http://localhost:9200/my_index"
    复制代码
      

    • 假如成功创建索引,会得到类似以下的响应:
    1. {
    2.   "acknowledged": true,
    3.   "shards_acknowledged": true,
    4.   "index": "my_index"
    5. }
    复制代码

  • 使用Elasticsearch客户端(以Python为例)

    • 起首安装elasticsearch - python库。
    • 然后可以使用以下代码创建索引:
    1. from elasticsearch import Elasticsearch
    2. es = Elasticsearch()
    3. index_name = "my_index"
    4. res = es.indices.create(index = index_name)
    5. if res["acknowledged"]:
    6.     print(f"Index {index_name} created successfully.")
    复制代码

二、创建映射


  • 直接在创建索引时指定映射(使用RESTful API)

    • 在创建索引的PUT哀求中,可以包罗映射信息。映射定义了索引中的字段范例、分析器等信息。例如:
    1. curl -X PUT "http://localhost:9200/my_index"
    2. -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不答应对已存在字段的范例举行修改(除了某些特殊情况)。
    1. curl -X PUT "http://localhost:9200/my_index/_mapping" -H 'Content - type:application/json' -d '
    2. {
    3.   "properties": {
    4.     "new_field": {
    5.       "type": "keyword"
    6.     }
    7.   }
    8. }
    9. '
    复制代码
      

    • 这里我们向已经存在的my_index索引中添加了一个新的字段new_field,范例为keyword。

  • 使用Elasticsearch客户端(以Python为例)创建映射

    • 当使用elasticsearch - python库时,可以在创建索引大概更新索引映射时指定映射信息。以下是在创建索引时指定映射的示例:
    1. from elasticsearch import Elasticsearch
    2. es = Elasticsearch()
    3. index_name = "my_index"
    4. mapping = {
    5.     "mappings": {
    6.         "properties": {
    7.             "title": {
    8.                 "type": "text"
    9.             },
    10.             "price": {
    11.                 "type": "double"
    12.             },
    13.             "published_date": {
    14.                 "type": "date"
    15.             }
    16.         }
    17.     }
    18. }
    19. res = es.indices.create(index = index_name, body = mapping)
    20. if res["acknowledged"]:
    21.     print(f"Index {index_name} with mapping created successfully.")
    复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莫张周刘王

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表