J.Done
J.Done

Reputation: 3033

Get resultSearch with _score from sorted data in elasticsearch

I would like to get sample data of filtered and sorted data. I tried this with 'random_score' and this is how i did.

{
   "query": {
      "function_score": {
      "query": {
        "function_score": {
          "functions": [
            {
              "random_score": {
                "seed": 1
              }
            }
          ]
        }
      },
      "functions": [
        {
          "script_score": {
            "script": "if (_score.doubleValue() > 0.2) {return 1;} else {return 0;}"
          }
        }
      ],
      "boost_mode": "replace"
    }
   }
}

It will make only 1/5 data's _score 1. BUT when I added sort() query,

{
   "query": {
      "function_score": {
      "query": {
        "function_score": {
          "functions": [
            {
              "random_score": {
                "seed": 1
              }
            }
          ]
        }
      },
      "functions": [
        {
          "script_score": {
            "script": "if (_score.doubleValue() > 0.2) {return 1;} else {return 0;}"
          }
        }
      ],
      "boost_mode": "replace"
    }
   },
   "sort": 
      {
         "eventcnt": {
            "order": "desc"
         }
      }

}

_score became null. Is It unable to get _random_score with sort?

And how should I get data whose _score has 1? Should I filter score as 1 data on client side?

Upvotes: 0

Views: 82

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

You need to use track_scores in case of sorting by a field value. More details here.

For completeness sake:

{
  "track_scores": true,
  "query": {
    "function_score": {
      "query": {
        "function_score": {
          "functions": [
            {
              "random_score": {
                "seed": 1
              }
            }
          ]
        }
      },
      "functions": [
        {
          "script_score": {
            "script": "if (_score.doubleValue() > 0.2) {return 1;} else {return 0;}"
          }
        }
      ],
      "boost_mode": "replace"
    }
  },
  "sort": {
    "eventcnt": {
      "order": "desc"
    }
  }
}

Upvotes: 1

Related Questions