Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch query - sort by @timestamp and another field?

Can I search elasticsearch (version 2.3) and in the search query sort by more than 1 field? Right now i'm sorting by @timestamp and I would like to sort by hostname as well.

Thanks,

like image 757
deez Avatar asked Oct 01 '17 12:10

deez


People also ask

How do I sort data in an Elasticsearch document?

Elasticsearch supports sorting by array or multi-valued fields. The mode option controls what array value is picked for sorting the document it belongs to.

Can I Index a document with a timestamp in Elasticsearch?

Back in the earliest days of Elasticsearch, a _timestamp mapping field was available for an index. While this functionality has been deprecated since version 2.0, this certainly doesn’t mean that you can no longer index a document with a timestamp.

How many results can I get from an Elasticsearch query?

Keep in mind that the default number of results to return is 10, which is why not all results show up in the output; you can add the "size" parameter to your query to specify how many results you’d like to get back. Analyzed fields in Elasticsearch allow for broader searching on partial matches, but they can make sorting a tricky task.

Why are my array values not in order in Elasticsearch?

This is because Elasticsearch has no dedicated array type, and any field could contain multiple values. The fields parameter also does not guarantee that array values are returned in a specific order. See the mapping documentation on arrays for more background.


2 Answers

As the doc says, you can add one or more sort on specific fields like this:

"sort" : [{ "@timestamp" : "desc" },
        { "hostname " : "desc" }]
like image 105
Taras Kohut Avatar answered Oct 23 '22 10:10

Taras Kohut


{
    "query": {
        "range": {
            "@timestamp": {
                "gte": "@timestamp",
                "lte": "@timestamp"
            }
        }
    },
    "from": 0,
    "size": 1000,
    "_source": [
        "@timestamp",
    ],
    "sort": [{
            "@timestamp": {
                "order": "desc"
            }
        },
        {
            "age": "desc"
        }
    ]
}
like image 27
Anush Akshantal Avatar answered Oct 23 '22 09:10

Anush Akshantal