I have documents with a boolean field Say
{
"field1" : true
}
Now I want to check, whether the "field1" is true or not, and run a query if it is true. How can I do that using scripts in Elasticsearch?
Daniel's approach is superior to literally using scripts because it will be significantly faster, but if you had a need to do it within a script, then you need to check if the value indexed is 'T' or 'F' in Elasticsearch 1.x. In Elasticsearch 2.x and above, Lucene changed to using the more traditional 1 and 0.
ES 2.x (and above):
{
"query" : {
"bool" : {
"filter" : [ {
"script" : {
"inline" : "doc['field1'].value == 1"
}
} ]
}
}
}
ES 1.x:
{
"query" : {
"filtered" : {
"filter" : {
"script" : {
"script" : "doc['field1'].value == 'T'"
}
}
}
}
}
It's a bad idea to ever use a script unless you are required to do something that cannot be done without one, such as compare to fields simultaneously to ensure that they have the same value.
T and F don't seem working with ES2.X. You should use 1 or 00 / 1 in Lucene 5.x.It sounds like you wish to use a filtered query, to query only on documents where field1 is true.
If you create a filtered query, you apply a filter before you run a query, so you will be querying only those documents that pass your filter, you can setup a filtered query as below.
{
"query":{
"filtered":{
"query":{
//Your query
},
"filter":{
"term":{"field1":true}
}
}
}
}
You should use a bool query to match a boolean condition as you want. Look at my example.
{
"query" : {
"bool" : {
"must" :
{
"term" : {
"field1" : true
}
}
}
}
}
Hope it helps!
should queries to add to the score.