Patrícia Villela
Patrícia Villela

Reputation: 839

Elasticsearch cardinality sorted wrong

When I make a request like this

curl -XGET "http://localhost:9200/log/travels/_search?pretty" -d '                                                                 
{
    "aggs":{
        "travelers":{
            "terms":{
                "field":"traveler",
                "shard_size":0,
                "size":5,
                "order":{
                    "cities":"desc"
                }
            },
            "aggs":{
                "cities":{
                    "nested":{
                        "path":"cities"
                    },
                    "aggs":{
                        "city_count":{
                            "cardinality":{
                                "field":"cities.name"
                            }
                        }
                    }
                }
            }
        }
    }
}'

I get a response that's ordered wrong, like this

"aggregations" : {
    "travelers" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 410,
      "buckets" : [ {
        "key" : "patrick",
        "doc_count" : 9,
        "cities" : {
          "doc_count" : 10,
          "city_count" : {
            "value" : 3
          }
        }
      }, {
        "key" : "jonathan",
        "doc_count" : 8,
        "cities" : {
          "doc_count" : 10,
          "city_count" : {
            "value" : 4
          }
        }
      }, {
        "key" : "yosef",
        "doc_count" : 8,
        "cities" : {
          "doc_count" : 10,
          "city_count" : {
            "value" : 4
          }
        }
      }, {
        "key" : "mark",
        "doc_count" : 8,
        "cities" : {
          "doc_count" : 9,
          "city_count" : {
            "value" : 2
          }
        }
      }, {
        "key" : "mike",
        "doc_count" : 7,
        "cities" : {
          "doc_count" : 9,
          "city_count" : {
            "value" : 5
          }
        }
      } ]
    }
  }

I wanted it ordered by the number of cities traveled to. If I change cardinality to value_count, it orders correctly, but I can't have it that way because it counts the duplicates.

If any more details help you, feel free to ask for.

Upvotes: 5

Views: 1936

Answers (1)

ThomasC
ThomasC

Reputation: 8165

If you are trying to sort by a 2-levels deep sub-aggregation, the order syntax is slightly different according to the documentation (look at the end of the paragraph).

It is also explained more clearly in this part of the ElasticSearch Definitive Guide.

In your case, something like this should do the trick :

"order":{ "cities>city_count.value":"desc" }

Hope this helps!

Upvotes: 9

Related Questions