Reza Shadman
Reza Shadman

Reputation: 617

Elasticsearch: Sort by calculated date value

Is it possible to compare the datefield to current time and then make a sort by the result of that comparison (something like switch cases in SQL order by)?

The goal is to make documents having an specific datetime field which its value is bigger than current time, move to top of the list but all documents having an specific datetime field less than current time are equal in terms of priority and should not be sorted by this datetime field.

Upvotes: 1

Views: 999

Answers (1)

hkulekci
hkulekci

Reputation: 1942

Firstly, you can use microtime to easy usage. And there is script sort feature in Elasticsearch. You can also use if statements in this scripts.

{
    "query" : {
        ....
    },
    "sort" : {
        "_script" : {
            "type" : "number",
            "script" : {
                "inline": "if (doc['time'].value > current_time) return doc['field_name'].value; else return current_time",
                "params" : {
                    "current_time" : 1476354035
                }
            },
            "order" : "asc"
        }
    }
}

You should send a current time when you run your query with your script.

Upvotes: 1

Related Questions