yiisoft / yii2-elasticsearch

Yii 2 Elasticsearch extension
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
428 stars 253 forks source link

Add notes on script sorting to the docs #145

Open nagyt234 opened 6 years ago

nagyt234 commented 6 years ago

It would be good to have the possibility to use script sorting of ElasticSearch. E.g.:

{
  "sort": {
    "_script": {
      "type": "number",
      "script": "return rdoc['nutrient_220_rda_rate'].value + doc['nutrient_221_rda_rate'].value",
      "lang": "groovy",
      "order": "asc"
    }
  }
}

It is possible to use script field:

$query->fields = array_merge($allFields, [
    'rda_sum' => "doc['nutrient_220_rda_rate'].value + doc['nutrient_221_rda_rate'].value",
]);

It would be the best if we could use such a script field in the orderBy method.

j2443070 commented 2 years ago

Any chance for this feature?

bizley commented 2 years ago

All PRs are welcome.

beowulfenator commented 1 year ago

This has actually been implemented. One caveat: you can not sort on a script field by providing its name. You actually need to provide the script. Here's the example from the official docs:

{
  "query": {
    "term": {
      "sold": "true"
    }
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "doc['theatre'].value.length() * params.factor",
        "params": {
          "factor": 1.1
        }
      },
      "order": "asc"
    }
  }
}

Let's rewrite this using yii2-elasticsearch.

$query->where(['sold' => 'true'])->orderBy(['_script' => [
    'lang' => 'painless'
    'source' => "doc['theatre'].value.length() * params.factor",
    'params' => [
        'factor' => 1.1
    ]
]]);

Note how the value for the _script key is an array, not a string.

This needs to be put into the docs.