Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 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?


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

1 Answer

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"
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...