Skip to content

Instantly share code, notes, and snippets.

@drewr
Created October 23, 2013 22:50
Show Gist options
  • Save drewr/7128240 to your computer and use it in GitHub Desktop.
Save drewr/7128240 to your computer and use it in GitHub Desktop.
Example of function_score using the script_score function. This achieves a result similar to creating a script field and then sorting descending by that dynamic value.
#!/bin/sh
curl -XDELETE localhost:9200/foo >/dev/null
curl -XPOST localhost:9200/foo/t -d'
{
"clicks": 10,
"impressions": 1000,
"when": "2013-10-01"
}
'; echo
curl -XPOST localhost:9200/foo/t -d'
{
"clicks": 27,
"impressions": 1488,
"when": "2013-10-22"
}
'; echo
curl -XPOST localhost:9200/foo/t -d'
{
"clicks": 4,
"impressions": 500,
"when": "2013-10-23"
}
'; echo
curl -XPOST localhost:9200/foo/t -d'
{
"clicks": 1282,
"impressions": 100000,
"when": "2013-11-01"
}
'; echo
curl -XPOST localhost:9200/foo/_refresh; echo
curl localhost:9200/foo/_search -d@- <<EOF
{
"query": {
"filtered": {
"filter": {
"range": {
"when": {
"gte": "2013-10-20",
"lte": "2013-10-25"
}
}
},
"query": {
"function_score": {
"boost_mode": "replace",
"functions": [
{
"script_score": {
"script": "doc['clicks'].value / doc['impressions'].value"
}
}
],
"query": {
"match_all": {}
}
}
}
}
}
}
EOF
echo
## Note that _score is the result of the script (automatically sorted
## greatest->least)
##
## {
## "_shards": {
## "failed": 0,
## "successful": 5,
## "total": 5
## },
## "hits": {
## "hits": [
## {
## "_id": "AU7EdQF0RfqGh1ceKRfCnA",
## "_index": "foo",
## "_score": 0.01814516,
## "_source": {
## "clicks": 27,
## "impressions": 1488,
## "when": "2013-10-22"
## },
## "_type": "t"
## },
## {
## "_id": "eN66w46CSfeYLf_mZ8le0Q",
## "_index": "foo",
## "_score": 0.008,
## "_source": {
## "clicks": 4,
## "impressions": 500,
## "when": "2013-10-23"
## },
## "_type": "t"
## }
## ],
## "max_score": 0.01814516,
## "total": 2
## },
## "timed_out": false,
## "took": 3
## }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment