Skip to content

Instantly share code, notes, and snippets.

@karmi
Last active February 13, 2017 12:27
Show Gist options
  • Save karmi/4951834 to your computer and use it in GitHub Desktop.
Save karmi/4951834 to your computer and use it in GitHub Desktop.
Script fields in Elasticsearch

This example demostrates how to manipulate search results with the script_fields support in Elasticsearch.

# (Re)create the index
curl -X DELETE 'http://localhost:9200/script-fields-test/'
curl -X PUT 'http://localhost:9200/script-fields-test/'
# Index documents
curl -X POST 'http://localhost:9200/script-fields-test/d/1' -d '{"title":"Title1", "count":1}'
curl -X POST 'http://localhost:9200/script-fields-test/d/2' -d '{"title":"Title1", "count":2}'
curl -X POST 'http://localhost:9200/script-fields-test/_refresh'
# Search
curl -X GET 'http://localhost:9200/script-fields-test/_search?pretty=true' -d '
{
"query" : { "match_all" : {} },
"fields" : ["_source"],
"script_fields" : {
"my_count" : {
"script" : "doc[\"count\"].value * factor",
"params" : {
"factor" : 2
}
}
}
}
'
@orenor
Copy link

orenor commented Jul 7, 2013

Hi,
Is there any way of adding a filter that has a condition based on the coming script_fields values?

@luizamboni
Copy link

I have trouble to use script_fields with filtered query
example return error:
I already try put "script_fields" block in multiple places to make work , nothing work

{
"fields": [
"_source"
],
"script_fields": [
{
"status": {
"script": "return 1;"
}
}
],
"query": {
"filtered": {
"query": {
"bool": {
"must": [
{
"term": {
"seller_id": 1
}
}
],
"must_not": []
}
},
"filter": {
"script": {
"script": "if(_source.concurrents.findAll{ it.new_price < _source.new_price && concurrent_ids.contains(it.seller_id) }.size == 0 && _source.concurrents.findAll{ it.new_price > _source.new_price && concurrent_ids.contains(it.seller_id) }.size > 0 ){ return true; }",
"params": {
"concurrent_ids": [
2,
3
]
}
}
}
}
},
"size": 500,
"from": 0
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment