Sort an elasicsearch resultset based on a filter term Sort an elasicsearch resultset based on a filter term elasticsearch elasticsearch

Sort an elasicsearch resultset based on a filter term


To achieve this, you will have to store your categories as nested documents. If not, Elasticsearch will not know what sort is associated with what category ID.

Then, you will have to sort on the nested documents, by also filtering to choose the right one.

Here's a runnable example you can play with: https://www.found.no/play/gist/47282a07414e1432de6d

curl -XPUT "$ELASTICSEARCH_ENDPOINT/play" -d '{    "mappings": {        "type": {            "properties": {                "categories": {                    "type": "nested"                }            }        }    }}'curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '{"index":{"_index":"play","_type":"type"}}{"id":1,"title":"foobar","categories":[{"id":"28554568","sort":102},{"id":"28554577","sort":482},{"id":"28554578","sort":2}]}{"index":{"_index":"play","_type":"type"}}{"id":2,"title":"barbaz","categories":[{"id":"28554577","sort":0}]}'curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '{    "query": {        "nested": {            "path": "categories",            "query": {                "term": {                    "categories.id": {                        "value": 28554577                    }                }            }        }    },    "sort": {        "categories.sort": {            "order": "asc",            "nested_filter": {                "term": {                    "categories.id": 28554577                }            }        }    }}'