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