Elasticsearch生成mapping的方式上有多种方式,我们可以把mapping做成配置文件,也可以用spring-data-elasticsearch基于注解生成。
在基于注解生成这种方式上spring-data的注解还是不错的,但是如果想深度定制化一些参数spring-data却是不支持的,比如针对分词的string类型字段的fielddata加载设置。
又如果项目中不想引入spring但又想使用基于注解方式生成mapping,这时spring-data就不行了,这里有另一种选择:elasticsearch-mapper。
elasticsearch-mapper支持绝大部分数据类型和相关参数的设置,使用是请参考官网对各种数据类型和相关参数:ES2.x官网mapping设置
下面是使用示例:
1 @Document(type = "book", _timestamp = true, _ttl = @TTL(enabled = true, _default = "5m")) 2 public class Book { 3 /*ID,只能是Long或者String类型*/ 4 @Id 5 private Long id; 6 7 /*数值类型*/ 8 @Field(type = FieldType.Double, ignoreMalformed = true) 9 private Double price; 10 11 /*数值类型*/ 12 @Field(type = FieldType.Integer) 13 private Integer pageCount; 14 15 /*未分词String型*/ 16 @Field(type = FieldType.String, index = FieldIndex.not_analyzed) 17 private String isnNo; 18 19 /*bool型*/ 20 @Field(type = FieldType.Boolean, nullValue = "false") 21 private Boolean isValid; 22 23 /*日期类型*/ 24 @Field(type = FieldType.Date, format = DateFormat.basic_time_no_millis) 25 private Date publishDate; 26 27 /*分词String类型,并设置fielddata加载限制(当然也可不设置用默认)*/ 28 @Field( 29 type = FieldType.String, 30 index = FieldIndex.analyzed, 31 analyzer = "ik_max_word", 32 searchAnalyzer = "ik_smart", 33 termVector = TermVector.with_positions_offsets, 34 fielddata = @Fielddata( 35 format = FielddataFormat.paged_bytes, 36 frequency = @FielddataFrequencyFilter( 37 enable = true, 38 min = 0.001, 39 max = 1.2, 40 minSegmentSize = 500 41 ), 42 loading = FielddataLoading.eager_global_ordinals 43 ) 44 45 ) 46 private String author; 47 48 /*multi field 类型(用于多字段搜索)*/ 49 @MultiField( 50 mainField = @Field(type = FieldType.String, index = FieldIndex.analyzed, analyzer = "ik_max_word", searchAnalyzer = "ik_smart"), 51 otherFields = { 52 @MultiNestedField(dotSuffix = "pinyin", nestedField = @Field( 53 type = FieldType.String, 54 index = FieldIndex.analyzed, 55 analyzer = "lc_index", 56 searchAnalyzer = "lc_search") 57 ), 58 @MultiNestedField(dotSuffix = "english", nestedField = @Field( 59 type = FieldType.String, 60 index = FieldIndex.analyzed, 61 analyzer = "standard") 62 ) 63 } 64 ) 65 private String title; 66 67 /*Completion Context Suggester配置(如果不配置CompletionContext则是Completion Suggester)*/ 68 @CompletionField(analyzer = "ik", payloads = true, context = { 69 @CompletionContext(name = "bookType", type = CompletionContextType.category, defaultVal = {"algorithm"}), 70 @CompletionContext(name = "bookColor", type = CompletionContextType.category, defaultVal = {"red"}) 71 }) 72 private String suggestContextField; 73 74 /*二进制类型*/ 75 @Field(type = FieldType.Binary) 76 private byte[] pdf; 77 78 /*内嵌类型*/ 79 @NestedObject(clazz = SalesArea.class) 80 private SalesArea salesArea; 81 82 }
[Reference]
[1] http://blog.csdn.net/chennanymy/article/details/52663589