当前位置:   article > 正文

ElasticSearch实战(二) 索引、类型、映射_elasticsearchtemplate.indexdelete创建映射作用和索引

elasticsearchtemplate.indexdelete创建映射作用和索引

在插入一条Blog后,使用浏览器打开 http://localhost:9200/website/_mapping/blog?pretty 显示信息如下:

  1. {
  2. "website": {
  3. "mappings": {
  4. "blog": {
  5. "properties": {
  6. "author": {
  7. "type": "text",
  8. "fields": {
  9. "keyword": {
  10. "type": "keyword",
  11. "ignore_above": 256
  12. }
  13. }
  14. },
  15. "date": {
  16. "type": "long"
  17. },
  18. "id": {
  19. "type": "long"
  20. },
  21. "likes": {
  22. "type": "long"
  23. },
  24. "text": {
  25. "type": "text",
  26. "fields": {
  27. "keyword": {
  28. "type": "keyword",
  29. "ignore_above": 256
  30. }
  31. }
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }

上面JSON格式的内容中描述了四项关键信息:索引、类型、字段和映射。

  • 索引(index)

内容中的"website",类比关系数据库中的库

  • 类型(type)

内容中的"blog",类比关系数据库中的表

  • 字段(field)

内容中的author、date、id、likes和text,类比关系数据库中的列

  • 映射(mapping)

描述字段的保存方式等,如"type": "long",类比关系数据库中的列的数据类型。

注意author和text字段,除了本身被映射为text类型,还另外为其添加了名称为keyword、type为keyword的field,这使得查询时既可以对字段本身做Match Query,也可以对author.keyword做Term Query。

不同于关系型数据库要预先创建库和表,在添加第一个Blog时,Elasticsearch即使用动态映射猜测字段类型,得出上述映射。映射在创建后不可修改,如果需要自己指定映射类型,可以通过下面的方式。

1 删除原索引

elasticsearchTemplate.deleteIndex("website");

2 通过注解设置字段类型

  1. @Document(indexName = "website", type = "blog")
  2. public class Blog {
  3. private int id;
  4. private String author;
  5. private String text;
  6. private int likes;
  7. @Field(type = FieldType.Date)
  8. private Date date;

3 创建索引并设置映射

  1. elasticsearchTemplate.createIndex("website");
  2. elasticsearchTemplate.putMapping(Blog.class);

重新用 http://localhost:9200/website/_mapping/blog?pretty 查看映射,可以看到date字段已经设置为日期类型

  1. {
  2. "website" : {
  3. "mappings" : {
  4. "blog" : {
  5. "properties" : {
  6. "date" : {
  7. "type" : "date"
  8. }
  9. }
  10. }
  11. }
  12. }
  13. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/981334
推荐阅读
相关标签
  

闽ICP备14008679号