Rasmus
Rasmus

Reputation: 2943

ElasticSearch aggregations - sorting values

In this sample I have some cars with an unknown number of facets on them.

When doing aggregations I would like the values in the aggregations to be sorted alphabetically. However, some of the facets are integers, and that will produce these aggregations

Color
 blue (2)
 red (1)

Top speed
 100 (1)
 120 (1)
 90 (1)

Year
 2015 (1)

As you can see the topspeed facet is sorted wrong - 90 should be first.

Sample data

PUT /my_index
{
  "mappings": {
    "product": {
      "properties": {
        "displayname" :{"type": "string"}, 
        "facets": {
          "type": "nested", 
          "properties": {
            "name":     { "type": "string"  },
            "value":    { "type": "string"  },
            "datatype": { "type": "string"  }
          }
        }
      }
    }
  }
}



PUT /my_index/product/1
{
  "displayname": "HONDA",
  "facets": [
    {
      "name": "topspeed",
      "value": "100",
      "datatype": "integer"
    },
    {
      "name": "color",
      "value": "Blue",
      "datatype": "string"
    }
  ]
}

PUT /my_index/product/2
{
  "displayname": "WV",
  "facets": [
    {
      "name": "topspeed",
      "value": "90",
      "datatype": "integer"
    },
    {
      "name": "color",
      "value": "Red",
      "datatype": "string"
    }
  ]
}

PUT /my_index/product/3
{
  "displayname": "FORD",
  "facets": [
    {
      "name": "topspeed",
      "value": "120",
      "datatype": "integer"
    },
    {
      "name": "color",
      "value": "Blue",
      "datatype": "string"
    },
    {
      "name": "year",
      "value": "2015",
      "datatype": "integer"
    }
  ]
}

GET my_index/product/1

GET /my_index/product/_search
{
  "size": 0, 
   "aggs": {
    "facets": {
      "nested": {
        "path": "facets"
      },
      "aggs": {
        "nested_facets": {
          "terms": {
            "field": "facets.name"
          },
          "aggs": {
            "facet_value": {
              "terms": {
                "field": "facets.value",
                "size": 0,
                "order": {
                  "_term": "asc"
                }
              }
            }
          }
        }
      }
    }
  }
}

As you can see each facet has a datatype (integer or string).

Any ideas how I can get the sorting of values to be like this:

Color
 blue (2)
 red (1)

Top speed
 90(1)     
 100 (1)
 120 (1)

Year
 2015 (1)

I've played around with adding a new field to the facet "sortable_value" where i pad the integer values like this "00000000090" at index time. But could not get the aggregations to work.

Any help is appreciated

Upvotes: 1

Views: 143

Answers (1)

lingxiao
lingxiao

Reputation: 1224

That's an uncommon way of representing your data.

I'd suggest changing your data structure to the following { "displayname": "FORD", "facets": { "topspeed": 120, "color": "Blue", "year": 2015 } }

Upvotes: 1

Related Questions