Elasticsearch中mapping值得注意的一些小细节

简介

在Elasticsearch中mapping有很多可以配置的地方,但是使用多了就会发现,一般情况有关mapping最常用、也最实用的就简单的几个需要注意的地方。

下面就简单的介绍一下关于这些mapping中值得注意的地方。

当然,如果想要了解更多关于mapping的知识,可以参考后面给的参考链接。

添加mapping

# 添加为索引添加mapping
curl -X PUT http://localhost:9200/index-name/_mapping
# 查看索引的mapping
curl -X GET http://localhost:9200/index-name/_mapping

下面是添加mapping的body部分:

{
    
    
  "mappings": {
    
    
      "dynamic": "strict",
      "properties": {
    
    
        "title": {
    
    
          "type": "text",
          "norms":false,
          "doc_values":false
        },
        "name": {
    
    
          "type": "keyword"
        },
        "attach": {
    
    
          "type": "text",
          "enable":false
        }
      }
  }
}

在mapping中,dynamic参数建议设置为"strict",这样当添加的文档中有mapping中没有的字段就可以获取到异常。当然,如果你只想有多的字段也无所谓,可以将dynamic设置为false,这样mapping中没有的字段就会被忽略。

默认dynamic为true,如果文档中有mapping中没有的字段,就会在mapping中添加相应的字段,并且做出类型推断。这样虽然最方便,但是不利于维护的。

字段中值得考虑设置的参数:

  1. 如果不需要排序、聚合doc_values最好设置为false,例如邮箱、用户名等
  2. 对于text类型,如果不需要参与评分,norms最好设置为false
  3. 如果只是存储,不想搜索字段,enable可以设置为false
  4. 如果需要字段参与评分,但是不对字段分词,可以设置index为false

更新mapping

curl -X PUT http://localhost:9200/index-name/_mapping
{
    
    
  "properties": {
    
    
    "gid": {
    
    
      "type": "text",
      "index": false
    }
  }
}

更新索引的mapping也是使用的PUT,值得注意的点是:

  1. mapping不能删除、修改字段和参数,只能添加字段和参数
  2. 与添加mapping不同,更新mapping,最外层没有mapping,直接从properties开始

如果,不需要设置动态模板、dynamic等参数的话,添加mapping的时候也可以直接从properties开始

Java 方式添加mapping

@Test
public void addMapping() throws Exception {
    
    
    HttpHost httpHostOne = new HttpHost("127.0.0.1", 9200, "http");
    RestClientBuilder builder = RestClient.builder(httpHostOne);
    RestHighLevelClient client = new RestHighLevelClient(builder);
    String indexName = "index-name";
    IndicesClient indicesClient = client.indices();
//        mapping是针对索引,所以先添加索引,当然也可以在添加索引的时候就设置
    CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName).settings(getDefaultSetting());
    indicesClient.create(createIndexRequest, RequestOptions.DEFAULT);

    XContentBuilder mapping = XContentFactory.jsonBuilder()
            .startObject()
            .startObject("properties")
            .startObject("gid").field("type", "keyword").field("doc_values",false).endObject()
            .startObject("serverId").field("type", "integer").endObject()
            .endObject()
            .endObject();
    PutMappingRequest putMappingRequest = new PutMappingRequest(indexName).source(mapping);
    indicesClient.putMapping(putMappingRequest, RequestOptions.DEFAULT);
}

private static Settings getDefaultSetting(){
    
    
    return Settings.builder()
            .put("index.refresh_interval", "60s")
            .put("index.number_of_shards", "3")
            .put("index.number_of_replicas", "1")
            .build();
}

参考

mapping
mapping模板

猜你喜欢

转载自blog.csdn.net/trayvontang/article/details/107919853
今日推荐