Skip to content

Instantly share code, notes, and snippets.

@radu-gheorghe
Created November 7, 2012 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radu-gheorghe/4031013 to your computer and use it in GitHub Desktop.
Save radu-gheorghe/4031013 to your computer and use it in GitHub Desktop.
Elasticsearch - sort by the sum of elements within an array
#!/bin/bash
#delete the test type
curl -XDELETE localhost:9200/test/test2/
#insert some docs######
curl -XPOST localhost:9200/test/test2/ -d '{
"id": 123,
"a": 10,
"b": 12,
"c": [
{
"x": "A",
"y": 102,
"z": 92
},
{
"x": "B",
"y": 110,
"z": 96
}
]
}'
curl -XPOST localhost:9200/test/test2/ -d '{
"id": 123,
"a": 10,
"b": 12,
"c": [
{
"x": "A",
"y": 10,
"z": 92
},
{
"x": "B",
"y": 110,
"z": 96
}
]
}'
curl -XPOST localhost:9200/test/test2/ -d '{
"id": 123,
"a": 10,
"b": 12,
"c": [
{
"x": "A",
"y": 1,
"z": 92
},
{
"x": "B",
"y": 110,
"z": 96
}
]
}'
#done inserting######
#verify the mapping
curl localhost:9200/test/test2/_mapping
#refresh
curl localhost:9200/test/_refresh
#custom score query
curl localhost:9200/test/test2/_search?pretty=true -d '{
"query": {
"custom_score": {
"query": {"match_all": {}},
"script": "result=0; for (element : _source.c) { result = result + element.y; result = result + element.z*3 }; result"
}
}
}'
#script sort
curl localhost:9200/test/test2/_search?pretty=true -d '{
"sort": {
"_script": {
"type": "number",
"script": "result=0; for (element : _source.c) { result = result + element.y; result = result + element.z*3 }; result"
}
}
}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment