如何在 Elasticsearch 中创建索引和映射?

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

一、创建索引

  1. 使用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"
    }
    
  2. 使用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.")
    

二、创建映射

  1. 直接在创建索引时指定映射(使用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)。
  2. 单独更新索引的映射(使用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
  3. 使用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.")
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值