Elasticsearch Mapping字段类型之boolean
一、boolean简介
boolean
类型非常简单,它就接受真
或假
。
传给ES的值 | 判断为 |
---|---|
true,“true” | 真 |
false,“false”, “”(空字符) | 假 |
null | ES会忽略值为null的字段 |
二、创建boolean类型的字段
创建一个books索引,name
是书名,is_published
为是否发行。
PUT books
{
"mappings":{
"properties":{
"name":{
"type":"keyword"
},
"is_published":{
"type":"boolean"
}
}
}
}
三、新增数据记录
创建如下7条记录,注意看他们的is_published
都不一样。
PUT books/_doc/1
{
"name": "Java编程思想",
"is_published": true #为真
}
PUT books/_doc/2
{
"name": "孙哥说Spring5",
"is_published": "true" #为真
}
PUT books/_doc/3
{
"name": "雷丰阳Spring注解",
"is_published": false #为假
}
PUT books/_doc/4
{
"name": "小码哥Vue.js教程",
"is_published": "false" #为假
}
PUT books/_doc/5
{
"name": "易学教育Flink教程",
"is_published": "" #为假
}
PUT books/_doc/6
{
"name": "尚硅谷Flink教程",
"is_published": null #null字段会被忽略
}
PUT books/_doc/7
{
"name": "图灵Java面试指导" #该文档不存在is_published字段
}
#上面7个都能成功,这一个会插入失败
PUT books/_doc/8
{
"name": "尚硅谷Java面试指导",
"is_published": "啥也不是"
}
返回:
"type" : "illegal_argument_exception",
"reason" : "Failed to parse value [啥也不是] as only [true] or [false] are allowed."
}
四、验证boolean类型查询
4.1 查询is_published=true
GET books/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"is_published": true
}
}
]
}
}
}
返回如下:true
和"true"
是等价的
{
"hits":[
{
"_index":"books",
"_type":"_doc",
"_id":"2",
"_score":0,
"_source":{
"name":"孙哥说Spring5",
"is_published":"true"
}
},
{
"_index":"books",
"_type":"_doc",
"_id":"1",
"_score":0,
"_source":{
"name":"Java编程思想",
"is_published":true
}
}
]
}
4.2 查询is_published=false
GET books/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"is_published": false
}
}
]
}
}
}
返回如下:false
,"false"
和""
这3个是等价的
{
"hits":[
{
"_index":"books",
"_type":"_doc",
"_id":"4",
"_score":0,
"_source":{
"name":"小码哥Vue.js教程",
"is_published":"false"
}
},
{
"_index":"books",
"_type":"_doc",
"_id":"3",
"_score":0,
"_source":{
"name":"雷丰阳Spring注解",
"is_published":false
}
},
{
"_index":"books",
"_type":"_doc",
"_id":"5",
"_score":0,
"_source":{
"name":"易学教育Flink教程",
"is_published":""
}
}
]
}
4.3 对于null
和缺失字段
- 总有7条记录,还有2条记录它们不是true也不是false。
- 对
is_published
字段进行exists
查询,可查出这2条记录。 - 在日常开发中一定要注意这些值,否则容易漏处理它们。
GET books/_search
{
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "is_published"
}
}
]
}
}
}
返回出在is_published
上不存在值的2个文档
{
"hits":[
{
"_index":"books",
"_type":"_doc",
"_id":"6",
"_score":0,
"_source":{
"name":"尚硅谷Flink教程",
"is_published":null
}
},
{
"_index":"books",
"_type":"_doc",
"_id":"7",
"_score":0,
"_source":{
"name":"图灵Java面试指导"
}
}
]
}
五、在boolean上进行聚合查询
在boolean上进行terms
聚合时,聚合结果中key
为0(假)和1(真),key_as_string
为false和true。
按照is_published
进行分组聚合:
GET books/_search
{
"aggs": {
"publish_state": {
"terms": {
"field": "is_published"
}
}
},
"sort": [ "is_published" ]
}
返回结果如下:
"buckets" : [
{
"key" : 0,
"key_as_string" : "false",
"doc_count" : 3
},
{
"key" : 1,
"key_as_string" : "true",
"doc_count" : 2
}
]
如果感觉这篇文章对你有帮助,点个免费的赞和关注吧。