Search code examples
elasticsearchfacet

elasticsearch aggregations ( facet with sub facet )


I'm using elasticsearch to create facet. It working well for counting but i try a more complexe task. The problem is that i don't know the name of the task i want do....


My actual facet query :

"facets": {
  "name": {"terms": {"field": "name", "size": 20}}
}

the response :

"name": {
  "_type": "terms",
  "missing": 0,
  "total": 11,
  "other": 0,
  "terms": [
    {          "term": "liliales",      "count": 4        },
    {          "term": "commelinales",  "count": 3        },
    {          "term": "dioscoreales",  "count": 2        },
    {          "term": "arecales",      "count": 1        },
    {          "term": "poales",        "count": 1        }
  ] } }

this is an exemple of my data :

     name        |    rank       
_________________________________
liliales         | accepted
liliales         | accepted
liliales         | misapplied
liliales         | synonym

commelinales     | accepted
commelinales     | misapplied
commelinales     | synonym

dioscoreales     | misapplied
dioscoreales     | synonym

arecales         | accepted

poalesa          | synonym

I want to have for each term, a sub array with the count of "rank" like this :

"name" : {
    "_type" : "terms",
    "missing" : 0,
    "total" : 11,
    "other" : 0,
    "terms" : [{
            "term" : "liliales",
            "count" : 4,
            "rank" : {
                "accepted" : 2,
                "misapplied" : 1,
                "synonym" : 1
            }
        }, {
            "term" : "commelinales",
            "count" : 3,
            "rank" : {
                "accepted" : 1,
                "misapplied" : 1,
                "synonym" : 1
            }
        }, {
            "term" : "dioscoreales",
            "count" : 2,
            "rank" : {
                "misapplied" : 1,
                "synonym" : 1
            }
        }, {
            "term" : "arecales",
            "count" : 1,
            "rank" : {
                "accepted" : 1
            }
        }, {
            "term" : "poales",
            "count" : 1,
            "rank" : {
                "synonym" : 1
            }
        }
    ]
}

What the name of this kinf of facet and how can i do this please ?

thanks by advance


Solution

  • I think that you are looking for aggregations.

    Aggregations are built for composing multi level aggregations.

    So you can have a first level for name and then another level per rank.

    Something like:

    GET _search
    {
      "aggs": {
        "by_name": {
          "terms": {
            "field": "name"
          },
          "aggs": {
            "by_rank": {
              "terms": {
                "field": "rank"
              }
            }
          }
        }
      }
    }