一、简述

布尔字段接受JSON true和false值,但也可以接受解释为true或false的字符串 (即是:”true”,”false”):

布尔值 es值
true true,”true”
false false,”false”

二、实例

1、定义Boolean类型字段

定义文档字段 is_published 为Boolean类型:

  1. PUT boolean_index
  2. {
  3. "mappings": {
  4. "_doc": {
  5. "properties": {
  6. "is_published": {
  7. "type": "boolean"
  8. }
  9. }
  10. }
  11. }
  12. }

2、插入布尔类型字符串

2.1 插入布尔类型字符串:”true” , “false”

  1. POST boolean_index/_doc/1
  2. {
  3. "is_published": "true"
  4. }
  5. POST boolean_index/_doc/2
  6. {
  7. "is_published": "false"
  8. }

2.2 查询布尔值为true的文档

执行查询

  1. GET boolean_index/_search
  2. {
  3. "query": {
  4. "term": {
  5. "is_published": true
  6. }
  7. }
  8. }

查询结果

  1. {
  2. "took" : 0,
  3. "timed_out" : false,
  4. "_shards" : {
  5. "total" : 5,
  6. "successful" : 5,
  7. "skipped" : 0,
  8. "failed" : 0
  9. },
  10. "hits" : {
  11. "total" : 1,
  12. "max_score" : 0.2876821,
  13. "hits" : [
  14. {
  15. "_index" : "boolean_index",
  16. "_type" : "_doc",
  17. "_id" : "1",
  18. "_score" : 0.2876821,
  19. "_source" : {
  20. "is_published" : "true"
  21. }
  22. }
  23. ]
  24. }
  25. }

三、布尔字段聚合

像term聚合使用1和0作为键,使用字符串“true”和“false”作为键字符串。布尔字段在脚本中使用时,返回1和0:

3.1 聚合查询布尔字段

  1. GET boolean_index/_search
  2. {
  3. "aggs": {
  4. "publish_state": {
  5. "terms": {
  6. "field": "is_published"
  7. }
  8. }
  9. },
  10. "script_fields": {
  11. "is_published": {
  12. "script": {
  13. "lang": "painless",
  14. "source": "doc['is_published'].value"
  15. }
  16. }
  17. }
  18. }

3.2 聚合结果

  1. {
  2. "took" : 1,
  3. "timed_out" : false,
  4. "_shards" : {
  5. "total" : 5,
  6. "successful" : 5,
  7. "skipped" : 0,
  8. "failed" : 0
  9. },
  10. "hits" : {
  11. "total" : 2,
  12. "max_score" : 1.0,
  13. "hits" : [
  14. {
  15. "_index" : "boolean_index",
  16. "_type" : "_doc",
  17. "_id" : "2",
  18. "_score" : 1.0,
  19. "fields" : {
  20. "is_published" : [
  21. false
  22. ]
  23. }
  24. },
  25. {
  26. "_index" : "boolean_index",
  27. "_type" : "_doc",
  28. "_id" : "1",
  29. "_score" : 1.0,
  30. "fields" : {
  31. "is_published" : [
  32. true
  33. ]
  34. }
  35. }
  36. ]
  37. },
  38. "aggregations" : {
  39. "publish_state" : {
  40. "doc_count_error_upper_bound" : 0,
  41. "sum_other_doc_count" : 0,
  42. "buckets" : [
  43. {
  44. "key" : 0,
  45. "key_as_string" : "false",
  46. "doc_count" : 1
  47. },
  48. {
  49. "key" : 1,
  50. "key_as_string" : "true",
  51. "doc_count" : 1
  52. }
  53. ]
  54. }
  55. }
  56. }

四、布尔字段定义参数解析

详见:布尔字段定义参数