`
yucang52555
  • 浏览: 68178 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

elasticSearch源码分析之索引映射

阅读更多
    在搜索引擎中,我们需要将对应的文档数据转变成可处理的规则数据,就需要我们在这个流程中加一个映射,这就是搜索引擎中的Mapping。
    具体操作就是对索引库中索引的字段名及其数据类型进行定义,类似于关系数据库中表建立时要定义字段名及其数据类型那样,区别在于es的 mapping比数据库灵活很多,它可以动态添加字段。即使不指定mapping也可以,因为es会自动根据数据格式定义它的类型,如果你需要对某 些字段添加特殊属性(如:定义使用其它分词器、是否分词、是否存储等),就必须手动添加mapping。
    有两种添加mapping的方法,一种是定义在配置文件中,一种是运行时手动提交mapping,两种选一种就行了。
    第一种方式:在config目录下新建mappings文件夹,在这个目录下建立对应的索引文件[mapping名].json;一个mapping对应一个索引;也有一种默认的方式,定义一个默认的mapping[default-mapping.json]放到config目录下就行。
product-mapping.json:
{  
   "productIndex":{  
      "properties":{  
         "title":{  
            "type":"string",  
            "store":"yes"  
         },  
         "description":{  
            "type":"string",  
            "index":"not_analyzed"  
         },  
         "price":{  
            "type":"double"  
         },  
         "onSale":{  
            "type":"boolean"  
         },  
         "type":{  
            "type":"integer"  
         },  
         "createDate":{  
            "type":"date"  
         }  
      }  
   }  
}

    其中productIndex 为索引类型,properties下面的为索引里面的字段,type为数据类型,store为是否存储,"index":"not_analyzed"为 不对该字段进行分词。

    第二种方式:是用java api调用:
    首先,我们需要创建空索引:
@Test
    public void testIndexCreateByJson(){
        //创建空索引库
        Node node = NodeBuilder.nodeBuilder().build();
        node.client().admin().indices().prepareCreate("productIndex").execute().actionGet();
    }

    然后,添加映射:
@Test
    public void testIndexCreateByCode() throws IOException{
        //索引映射
        Node node = NodeBuilder.nodeBuilder().build();
        node.client().admin().indices().prepareCreate("productIndex").execute().actionGet();
        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                  .startObject("productIndex")
                  .startObject("properties")
                    .startObject("title").field("type", "string").field("store", "yes").endObject()    
                    .startObject("description").field("type", "string").field("index", "not_analyzed").endObject()  
                    .startObject("price").field("type", "double").endObject()  
                    .startObject("onSale").field("type", "boolean").endObject()  
                    .startObject("type").field("type", "integer").endObject()  
                    .startObject("createDate").field("type", "date").endObject()                 
                  .endObject()  
                 .endObject()  
               .endObject();  
          PutMappingRequest mappingRequest = Requests.putMappingRequest("productIndex").type("productIndex").source(mapping);  
          node.client().admin().indices().putMapping(mappingRequest).actionGet();
    }


程序猿行业技术生活交流群:181287753(指尖天下),欢迎大伙加入交流学习。
0
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics