Elasticsearch全文检索之copy_to

版权声明:本文为博主原创文章,未经博主允许不得转载。交流请联系:351605040 https://blog.csdn.net/Arvinzr/article/details/83187253

全文检索场景在实际项目中,无界搜索具体查询某一个字段对于客户来说是不确定的,但是实际数据中需要检索的字段非常多。
在使用elasticsearch时遇见了这样的需求:es聚合指定字段时聚合的结果里面只显示聚合的字段。但是在做报表时,我们发现一个问题:如果我们对员工进行聚合,但是我们还希望查看当前员工所在的班组,部门等信息。这时如果查询es两次,对于效率来说是不好的。
这样,我们在设计的时候就需要将更多的字段合并成一个字段,这样查询的时候,开发人员只需要查询指定的那个字段就可以了,中间实现过程很简单,但是更多的会涉及到性能优化和分词优化。使用的步骤:

1、创建mapping

 
  1. PUT my_index

  2. {

  3.   "mappings": {

  4.     "my_type": {

  5.       "properties": {

  6.         "first_name": {

  7.           "type": "keyword",

  8.           "copy_to": "full_name"

  9.         },

  10.         "last_name": {

  11.           "type": "keyword",

  12.           "copy_to": "full_name"

  13.         },

  14.         "full_name": {

  15.           "type": "text",

  16.           "fielddata": true

  17.         }

  18.       }

  19.     }

  20.   }

  21. }

2、插入数据

  1. PUT my_index/my_type/1

  2. {

  3. "first_name": "John",

  4. "last_name": "Smith"

  5. }

3、查询校验

  1. GET my_index/_search

  2. {

  3. "query": {

  4. "match": {

  5. "full_name": {

  6. "query": "John Smith",

  7. "operator": "and"

  8. }

  9. }

  10. }

  11. }

4、结果展示

  1. {

  2. "took": 0,

  3. "timed_out": false,

  4. "_shards": {

  5. "total": 5,

  6. "successful": 5,

  7. "failed": 0

  8. },

  9. "hits": {

  10. "total": 1,

  11. "max_score": 0.51623213,

  12. "hits": [

  13. {

  14. "_index": "my_index",

  15. "_type": "my_type",

  16. "_id": "1",

  17. "_score": 0.51623213,

  18. "_source": {

  19. "first_name": "John",

  20. "last_name": "Smith"

  21. }

  22. }

  23. ]

  24. }

  25. }

5、聚合查询校验

  1. {

  2. "query": {

  3. },"aggs": {

  4. "1": {

  5. "terms": {

  6. "field": "full_name",

  7. "size": 10

  8. }

  9. }

  10. }

  11. }

6、查询结果

  1. {

  2. "took": 0,

  3. "timed_out": false,

  4. "_shards": {

  5. "total": 5,

  6. "successful": 5,

  7. "failed": 0

  8. },

  9. "hits": {

  10. "total": 1,

  11. "max_score": 1,

  12. "hits": [

  13. {

  14. "_index": "baobiaoceshi4",

  15. "_type": "my_type",

  16. "_id": "1",

  17. "_score": 1,

  18. "_source": {

  19. "first_name": "John",

  20. "last_name": "Smith"

  21. }

  22. }

  23. ]

  24. },

  25. "aggregations": {

  26. "1": {

  27. "doc_count_error_upper_bound": 0,

  28. "sum_other_doc_count": 0,

  29. "buckets": [

  30. {

  31. "key": "john",

  32. "doc_count": 1

  33. },

  34. {

  35. "key": "smith",

  36. "doc_count": 1

  37. }

  38. ]

  39. }

  40. }

  41. }

注意有这几个问题:

1、我们copy_to指向的字段字段类型要为:text

2、text类型字段如果希望进行聚合,设置属性:"fielddata": true

3、copy_to指向的字段不会在head插件查看时显示,但是能通过查询语句作为条件
总结:通过这种方式对我们的结果进行聚合,能够满足一次查询聚合多个字段。

 sapv博客之家,欢迎交流!

猜你喜欢

转载自blog.csdn.net/Arvinzr/article/details/83187253