赞
踩
在插入一条Blog后,使用浏览器打开 http://localhost:9200/website/_mapping/blog?pretty 显示信息如下:
- {
- "website": {
- "mappings": {
- "blog": {
- "properties": {
- "author": {
- "type": "text",
- "fields": {
- "keyword": {
- "type": "keyword",
- "ignore_above": 256
- }
- }
- },
- "date": {
- "type": "long"
- },
- "id": {
- "type": "long"
- },
- "likes": {
- "type": "long"
- },
- "text": {
- "type": "text",
- "fields": {
- "keyword": {
- "type": "keyword",
- "ignore_above": 256
- }
- }
- }
- }
- }
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
上面JSON格式的内容中描述了四项关键信息:索引、类型、字段和映射。
内容中的"website",类比关系数据库中的库
内容中的"blog",类比关系数据库中的表
内容中的author、date、id、likes和text,类比关系数据库中的列
描述字段的保存方式等,如"type": "long",类比关系数据库中的列的数据类型。
注意author和text字段,除了本身被映射为text类型,还另外为其添加了名称为keyword、type为keyword的field,这使得查询时既可以对字段本身做Match Query,也可以对author.keyword做Term Query。
不同于关系型数据库要预先创建库和表,在添加第一个Blog时,Elasticsearch即使用动态映射猜测字段类型,得出上述映射。映射在创建后不可修改,如果需要自己指定映射类型,可以通过下面的方式。
1 删除原索引
elasticsearchTemplate.deleteIndex("website");
2 通过注解设置字段类型
- @Document(indexName = "website", type = "blog")
- public class Blog {
-
- private int id;
- private String author;
- private String text;
- private int likes;
-
- @Field(type = FieldType.Date)
- private Date date;
3 创建索引并设置映射
- elasticsearchTemplate.createIndex("website");
- elasticsearchTemplate.putMapping(Blog.class);
重新用 http://localhost:9200/website/_mapping/blog?pretty 查看映射,可以看到date字段已经设置为日期类型
- {
- "website" : {
- "mappings" : {
- "blog" : {
- "properties" : {
- "date" : {
- "type" : "date"
- }
- }
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。