AlexD
AlexD

Reputation: 4290

Elasticsearch sort by several field names

I have a few fields I want to sort by together so they get the same priority.

Currently my sorting looks like:

"sort": [
  {
    "stats.favoriteCount": {
      "order": "desc",
      "missing": 0
    },
    "stats.likeCount": {
      "order": "desc",
      "missing": 0
    }
  }
]

My issue with this is that favoriteCount will always be treated first, even though likeCount has higher values.

So for 2 documents that have:

1: {"stats.favoriteCount": 50, "likeCount": 0}
2: {"stats.favoriteCount": 0, "likeCount": 70}

The first document would be ranked higher since Elasticsearch translates the sorting to: [50,0] and [0,70].

Can I somehow treat those 2 fields as equals in means of sorting?

Upvotes: 0

Views: 97

Answers (2)

AlexD
AlexD

Reputation: 4290

I've amended Andrei Stefan's answer (thanks!) to this:

{
  "sort": {
    "_script": {
      "type": "number",
      "script": "return max(doc['stats.favoriteCount'].value,doc['stats.likeCount'].value)",
      "lang": "groovy",
      "order": "desc"
    }
  }
}

Upvotes: 0

Andrei Stefan
Andrei Stefan

Reputation: 52368

I think you need script sorting. Something like this:

{
  "sort": {
    "_script": {
      "type": "number",
      "script": "if (doc['stats.favoriteCount'].value>doc['stats.likeCount'].value) return doc['stats.favoriteCount'].value; return doc['stats.likeCount'].value;",
      "lang": "groovy",
      "order": "desc"
    }
  }
}

Upvotes: 1

Related Questions