ElasticSearch设置字段的keyword属性

es查询时候,我们经常会遇到这种场景:对text类型的文档进行查询或者聚合,却发现聚合的字段被es分词了。

这个时候,我们就需要对该字段设置一个keyword属性,并将该keyword属性的type设置为keyword。这样,我们在查询或者在聚合时候,通过该属性下的keyword字段,可以实现完全匹配。

示例:
对一个nested对象下的name字段设置keyword属性。

(1)创建映射。

PUT /my_store/_mapping/products?pretty
{
? "properties": {
? ? "price": {
? ? ? "type": "long"
? ? },
? ? "name": {
? ? ? "type": "text"
? ? },
? ? "owner": {
? ? ? "type": "nested",
? ? ? "properties": {
? ? ? ? "name": {
? ? ? ? ? "type": "text"
? ? ? ? },
? ? ? ? "age": {
? ? ? ? ? "type": "long"
? ? ? ? }
? ? ? }
? ? }
? }
}

(2)插入数据。

POST /my_store/products/_bulk
{ "index": { "_id": 1 }}
{ "price" : 10, "name" : "XHDK-A-1293-#fJ3","owner":{"name" :"西安","age":30}}
{ "index": { "_id": 2 }}
{ "price" : 20, "name" : "KDKE-B-9947-#kL5" ,"owner":{"name" :"西安","age":50}}
{ "index": { "_id": 3 }}
{ "price" : 30, "name" : "JODL-X-1937-#pV7","owner":{"name" :"榆林","age":20} }
{ "index": { "_id": 4 }}
{ "price" : 40, "name" : "QQPX-R-3956-#aD8","owner":{"name" :"榆林","age":10} }

(3)给nested对象下的name字段设置keyword属性。

PUT /my_s*/_mapping/products
{
	"properties": {
		"owner": {
			"type": "nested",
			"properties": {
				"name": {
					"type": "text",
					"fields": {
						"keyword": {
							"type": "keyword",
							"ignore_above": 256
						}
					}
				}
			}
		}
	}
}

**建议:在创建映射的时候,直接对不需要分词的字段设置keyword属性。**如下所示:

PUT /my_store/_mapping/products?pretty
{
	"properties": {
		"price": {
			"type": "long"??
		},
		??"name": {???
			"type": "text"??
		},
		?"owner": {
			"type": "nested",
			"properties": {
				"name": {
					"type": "text",
					"fields": {
						"keyword": {
							"type": "keyword",
							"ignore_above": 256
						}
					}
				}
			}
		}
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值