简体   繁体   中英

ElasticSearch Aggregator with sorting by text/keyword

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM