0

I have elasticsearch set up for searching across a products catalog's variants. Basically where:

Product has_many variants Variant belongs_to product

And the variant index json / mapping contains the product name.

I am trying to search variants, grouped by product id, bucket size of 1. I am able to do it and sort by min price, max price, etc.

This works:

POST /variants/_search?size=0
{
    "aggs" : {
        "min_price" : { "min" : { "field" : "price" } }
    }
}

This is (sort of) what I need next:

POST /variants/_search?size=0
{
    "aggs" : {
        "product_name" : { "sort by product_name asc / desc" }
    }
}

My last task is about sorting them alphabetically, but I dont seem to be able to sort by a keyword field (asc/desc) using an aggregator.

Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27

1 Answers1

1

In ES 6.0, you could do this. Note that size limits how many are returned, and the more you request the more expensive the query will be to execute. So if you really need many thousands you will probably want to try a different approach. Probably something where you created a separate rolled up index for products that you could search/sort instead of trying to do it through aggregations.

GET /variants/_search
{
    "size": 0,
    "aggs" : {
        "product_name" : {
            "terms" : {
                "field" : "product_name",
                "size": 1000,
                "order" : { "_key" : "asc" }
            }
        }
    }
}

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order

Ryan Widmaier
  • 7,948
  • 2
  • 30
  • 32
  • This did not seem to work. I am getting a weird error: Invalid aggregation order path [product_name]. Buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end – Marcelo Ribeiro Jun 06 '18 at 00:02
  • 1
    It seems this is not allowed for child aggregators but works at the root level. Thanks. – Marcelo Ribeiro Jun 06 '18 at 14:33