本文操作的ES版本是Elasticsearch7.13
设置为keyword类型的字段,插入很长的大段内容后,报字符超出异常,无法插入。
post 361323个字符的文档,报错如下:
- {
- "error": {
- "root_cause": [
- {
- "type": "illegal_argument_exception",
- "reason": "Document contains at least one immense term in field=\"mbody\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[60, 104, 116, 109, 108, 62, 60, 104, 101, 97, 100, 62, 13, 10, 60, 109, 101, 116, 97, 32, 104, 116, 116, 112, 45, 101, 113, 117, 105, 118]...', original message: bytes can be at most 32766 in length; got 361323"
- }
- ],
- "type": "illegal_argument_exception",
- "reason": "Document contains at least one immense term in field=\"mbody\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[60, 104, 116, 109, 108, 62, 60, 104, 101, 97, 100, 62, 13, 10, 60, 109, 101, 116, 97, 32, 104, 116, 116, 112, 45, 101, 113, 117, 105, 118]...', original message: bytes can be at most 32766 in length; got 361323",
- "caused_by": {
- "type": "max_bytes_length_exceeded_exception",
- "reason": "bytes can be at most 32766 in length; got 361323"
- }
- },
- "status": 400
- }
keyword类型的最大支持的长度为—32766个UTF-8类型的字符。
可以将字段改成text类型,text对字符长度没有限制。但是keyword和text也有区别的。
text类型:支持分词、全文检索,不支持聚合、排序操作。适合大字段存储,如:文章详情、content字段等;
keyword类型:支持精确匹配,支持聚合、排序操作。适合精准字段匹配,如:url、name、title等字段。
其实一个字符串字段可以映射为text字段用于全文本搜索,也可以映射为keyword字段用于排序或聚合,设置mapping如下:
- PUT my_index索引
-
- {
- "mappings": {
- "properties": {
-
- "字段名mbody": {
- "type":"text",
-
- "fields":{
-
- "keyword":{
-
- "ignore_above":256,
-
- "type":"keyword"
- }
- }
- }
- }
- }
- }
-
如果是将包含字符串的文档添加到 Elasticsearch,而之前没有定义字段的映射关系,那么 Elasticsearch 会自动创建一个包含Text和Keyword类型的动态映射(dynamic mappings)。 即使它适用于动态映射,也建议在文档添加之前定义索引的映射关系,以节省空间并提高写入速度。
如:未定义mapping,直接添加文档内容,发现"mbody”的数据类型是text,“mbody.keyword"的数据类型是keyword。如下图:
- {
- "mbody": {
- "type": "text",
- "fields": {
- "keyword": {
- "type": "keyword",
- "ignore_above": 256
- }
- }
- }
-
- }
ES5.X版本以后,字符串类型有重大变更,移除了string类型,string字段被拆分成两种新的数据类型: text和keyword。
keyword和text的区别:
text:
会分词,然后进行索引,用于全文搜索。
支持模糊、精确查询
不支持聚合
字符长度没有限制
keyword:
不进行分词,直接索引,keyword用于关键词搜索
支持模糊、精确查询
支持聚合、排序操作
最大支持的长度为32766个UTF-8个字符,也就是说term精确匹配的最大支持的长度为32766个UTF-8个字符。