Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Elasticsearch aggregations - OR in buckets

Say I have 5 docs:

{
  "owner": "joe",
  "color": "black"
},
{
  "owner": "joe",
  "color": "red"
},
{
  "owner": "joe",
  "color": "blue"
},
{
  "owner": "jack",
  "color": "black"
},
{
  "owner": "jack",
  "color": "white"
}

and aggregations:

{
  aggs: {
    owner: {
      "terms": {
        "field": "owner"
      }
    },
    color: {
      "terms": {
        "field": "color"
      }
    }
  }
}

to aggregate docs by owner and color.

If I run match all query I got:

owner
joe: 3
jack: 2

color
black: 2
red: 1
blue: 1
white: 1

What I want to achieve is: if I filter docs by owner: joe I want to get 3 docs where owner is joe, the color aggregation:

color
black: 1
red: 1
blue: 1

BUT I'd like to get the owner aggregation:

owner
joe: 3 [selected]
jack: 2 [possible to extend]

So get the number of other buckets that can be selected to extend the final result. So something like "OR" between the buckets.

How can I achieve this?

question from:https://stackoverflow.com/questions/65661723/elasticsearch-aggregations-or-in-buckets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual way to achieve this is by using a post_filter. The query below will return:

  • only joe's colors (using filtered_colors)
  • only joe's documents (using post_filter)
  • all owners that you can filter on (using a all_owners)

Query:

POST owners/_search
{
  "aggs": {
    "filtered_colors": {
      "filter": {
        "term": {
          "owner.keyword": "joe"
        }
      },
      "aggs": {
        "color": {
          "terms": {
            "field": "color.keyword"
          }
        }
      }
    },
    "all_owners": {
      "terms": {
        "field": "owner.keyword"
      }
    }
  },
  "post_filter": {
    "term": {
      "owner.keyword": "joe"
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...