[solved] How to do this query aggs?

My documents have this format:

{_id: 1, make: {_id: 12, name: "fiat"}, model: {_id: 121, name: 'strada'}}, {_id: 2, make: {_id: 12, name: "fiat"}, model: {_id: 122, name: 'palio'}}, {_id: 3, make: {_id: 12, name: "fiat"}, model: {_id: 123, name: 'ka'}}, {_id: 4, make: {_id: 12, name: "fiat"}, model: {_id: 124, name: 'uno'}}, {_id: 5, make: {_id: 12, name: "fiat"}, model: {_id: 121, name: 'strada'}}, {_id: 6, make: {_id: 12, name: "fiat"}, model: {_id: 122, name: 'palio'}}, {_id: 7, make: {_id: 13, name: "ford"}, model: {_id: 125, name: 'escort'}}, {_id: 8, make: {_id: 13, name: "ford"}, model: {_id: 126, name: 'fiesta'}}, {_id: 9, make: {_id: 14, name: "gm"}, model: {_id: 127, name: 'astra'}}

And I want something like this:
{ 'make': [ { _id: 12, name: 'fiat', count: 6, models: [ {_id: 121, name: 'strada', count: 2}, {_id: 122, name: 'palio', count: 2}, {_id: 123, name: 'ka', count: 1}, {_id: 124, name: 'uno', count: 1} ] }, { _id: 13, name: 'ford', count: 2, models: [ {_id: 125, name: 'escort', count: 1}, {_id: 126, name: 'fiesta', count: 1} ] }, { _id: 14, name: 'gm', count: 1, models: [ {_id: 127, name: 'astra', count: 1} ] } ] }

How to do this query?

Maybe a terms aggregation on make with a top_hits sub-aggregation?

Can you write a simple example? I am new in ES and I'm experiencing some difficulties with this query

It would look something like this:

{
  "aggs": {
    "by_make": {
      "terms": {
        "field": "make"
      },
      "aggs": {
        "top_models": {
          "top_hits": {}
        }
      }
    }
  }
}

This works:

But if a model have a compound name (like "new fiesta"), this is grouped as 2 different keys.
How to use model as a string?

To solve, I used new mapping to this field ("index": "not_analyzed")

1 Like