elasticsearch 创建索引 后 修改 索引的属性类型

 

首先 创建 索引 并且 添加 数据

PUT user
{
  "mappings": {
    "properties": {
      "age":{
        "type": "text"
      }
    }
  }
}
POST user/_doc
{
  "age":"22"
}
GET user/_search
{
  "query": {
    "match_all": {
    }
  }
}

  

创建 了 一个user 索引 包含 age 属性 类型 为 text  然后添加了 一个 age ="22" 的 索引数据

 

再创建一个 临时索引 

PUT usertemplate
{
  "mappings": {
    "properties": {
      "age":{
        "type": "integer"
      }
    }
  }
}

  

创建 一个  usertemplate 临时索引 包含属性 age 类型 为 integer 

然后 开始 将 user 索引的数据拷贝到  usertemplate 索引 中  注意 这是 text  integer  的类型 转换 

POST _reindex
{
  "source": {
    "index": "user"
  },
  "dest": {
    "index": "usertemplate"
  },
  "script": {
    "source": "ctx._source.age =Integer.parseInt( ctx._source.age)",
    "lang": "painless"
  }
}

  

注意 这段代码 是 转换 text integer  

 

测试 如果 不加 那段 转换类型的 代码 结果是什么呢

POST _reindex
{
  "source": {
    "index": "user"
  },
  "dest": {
    "index": "usertemplate"
  }
}

如果 执行 上面代码 再查询   usertemplate 结果是什么

GET usertemplate/_search
{
  "query": {
    "match_all": {
    }
  }
}

  

 

  

测试结果 是转换代码 可行的

那么 原来的 索引可以删掉 重新建立  然后 反向 拷贝 数据 那么 user 索引 就修改完成了

DELETE user

PUT user
{
  "mappings": {
    "properties": {
      "age":{
        "type": "integer"
      }
    }
  }
}

POST _reindex
{
  "source": {
    "index": "usertemplate"
  },
  "dest": {
    "index": "user"
  }
}

GET user/_search
{
  "query": {
    "match_all": {
    }
  }
}

最后 测试结果

 

c# 代码测试一手

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nest;

namespace ElasticsearchWebAPI.Controllers
{
  
    public class User
    {
      //  public string Name { get; set; }
        public int Age { get; set; }
    }

    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> logger;

        public TestController(ILogger<TestController> logger)
        {
            this.logger = logger;
        }

        [HttpGet]
        public ActionResult Get()
        {
            //通常,您可能需要将其他配置选项传递给客户端,例如 Elasticsearch 的地址(如果它正在运行)。 远程计算机。这就是进来的地方; 可以实例化实例以向客户端提供不同的 配置。ConnectionSettings
            var settings = new ConnectionSettings(new Uri("http://192.168.0.168:9200")).DefaultIndex("user");
            var client = new ElasticClient(settings);
         
            var userDoc = client.Search<User>(user =>
              {
                  return user.Query(q => q
                      .Match(m => m
                         .Field(f => f.Age)
                         .Query("22")
                      )
                     );

              }).Documents.ToList();

            return Ok(userDoc);
        }
    }
}

  结果 可以

 

posted on 2023-11-27 15:17  是水饺不是水饺  阅读(165)  评论(0)    收藏  举报

导航