elasticsearch:根据字段值查询对象的最大计数

piah890a  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(393)

对于下面索引中的示例文档,我希望找到索引中所有文档中基于组件名称的最大操作计数。你能帮我想个办法吗。
假设索引中只存在一个文档,则得到预期结果:

  1. comp1 -> action1 -> max 2 times
  2. comp1 -> action2 -> max 1 time
  3. comp2 -> action2 -> max 1 time
  4. comp2 -> action3 -> max 1 time

示例文档:

  1. {
  2. "id": "AC103902:A13A_AC140008:01BB_5FA2E8FA_1C08:0007",
  3. "tokens": [
  4. {
  5. "name": "comp1",
  6. "items": [
  7. {
  8. "action": "action1",
  9. "attr": "value"
  10. },
  11. {
  12. "action": "action1",
  13. "attr": "value"
  14. },
  15. {
  16. "action": "action2",
  17. "attr": "value"
  18. }
  19. ]
  20. },
  21. {
  22. "name": "comp2",
  23. "items": [
  24. {
  25. "action": "action2",
  26. "attr": "value"
  27. },
  28. {
  29. "action": "action3",
  30. "attr": "value"
  31. }
  32. ]
  33. }
  34. ]
  35. }

elasticsearch版本:7.9我可以循环浏览每个文档并在客户端进行计算,但我很好奇是否已经有一个es查询可以帮助从索引中的文档中获取这个摘要。

jdgnovmf

jdgnovmf1#

您需要定义 tokens 数组和 tokens.items 阵列组件 nested 为了得到正确的数据。
然后,假设您的Map看起来与

  1. {
  2. "mappings": {
  3. "properties": {
  4. "tokens": {
  5. "type": "nested",
  6. "properties": {
  7. "items": {
  8. "type": "nested"
  9. }
  10. }
  11. }
  12. }
  13. }
  14. }

可以执行以下查询:

  1. GET index_name/_search
  2. {
  3. "size": 0,
  4. "aggs": {
  5. "by_token_name": {
  6. "nested": {
  7. "path": "tokens"
  8. },
  9. "aggs": {
  10. "token_name": {
  11. "terms": {
  12. "field": "tokens.name.keyword"
  13. },
  14. "aggs": {
  15. "by_max_actions": {
  16. "nested": {
  17. "path": "tokens.items"
  18. },
  19. "aggs": {
  20. "max_actions": {
  21. "terms": {
  22. "field": "tokens.items.action.keyword"
  23. }
  24. }
  25. }
  26. }
  27. }
  28. }
  29. }
  30. }
  31. }
  32. }

生产这些桶:

  1. [
  2. {
  3. "key" : "comp1", <--
  4. "doc_count" : 1,
  5. "by_max_actions" : {
  6. "doc_count" : 3,
  7. "max_actions" : {
  8. "doc_count_error_upper_bound" : 0,
  9. "sum_other_doc_count" : 0,
  10. "buckets" : [
  11. {
  12. "key" : "action1", <--
  13. "doc_count" : 2
  14. },
  15. {
  16. "key" : "action2", <--
  17. "doc_count" : 1
  18. }
  19. ]
  20. }
  21. }
  22. },
  23. {
  24. "key" : "comp2", <--
  25. "doc_count" : 1,
  26. "by_max_actions" : {
  27. "doc_count" : 2,
  28. "max_actions" : {
  29. "doc_count_error_upper_bound" : 0,
  30. "sum_other_doc_count" : 0,
  31. "buckets" : [
  32. {
  33. "key" : "action2", <--
  34. "doc_count" : 1
  35. },
  36. {
  37. "key" : "action3", <--
  38. "doc_count" : 1
  39. }
  40. ]
  41. }
  42. }
  43. }
  44. ]

可以很容易地在客户端进行后期处理。

展开查看全部

相关问题