Search templates with nested query

Hi everyone.

I'm trying to make a search template with bool query. This bool query uses 'should' operator, which searches data throgh 4 fields of index. These results than must be filtered by two fields, so I try to use 'must' operator outside the 'should' operator. As a result, I have docs that suites both conditions of 'should' and 'must', but after a sum of these conditions I have other docs which suites only the 'must' operator conditions. I use the following script:

PUT _scripts/search_template
{
"script": {
"lang": "mustache",
"source": {
"query": {
"bool": {
"must": [
{"match": {"field_1": "true"}},
{"match": {"field_2": "true"}}
],
"should": [
{
"match": {
"field_3": {
"query": "{{query_string}}",
"fuzziness": "1",
"boost": 1
}
}
},
{
"match": {
"field_4": {
"query": "{{query_string}}",
"fuzziness": "1",
"boost": 2
}
}
},
{
"match": {
"field_5": {
"query": "{{query_string}}",
"fuzziness": "1",
"boost": 3
}
}
},
{
"match": {
"field_6": {
"query": "{{query_string}}",
"fuzziness": "1",
"boost": 1
}
}
}
]
}
},
"from": "{{from}}{{^from}}0{{/from}}",
"size": "{{size}}{{^size}}10{{/size}}"
},
"params": {
"query_string": "Query string"
}
}
}
PUT _scripts/search_template
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "field_1": "true"
              }
            },
            {
              "match": {
				"field_2": "true"
              }
            },
			{
				"bool": {
					"should": [
					{
					  "match": {
						"field_3": {
						  "query": "{{query_string}}",
						  "fuzziness": "1",
						  "boost": 1
						}
					  }
					},
					{
					  "match": {
						"field_4": {
						  "query": "{{query_string}}",
						  "fuzziness": "1",
						  "boost": 2
						}
					  }
					},
					{
					  "match": {
						"field_5": {
						  "query": "{{query_string}}",
						  "fuzziness": "1",
						  "boost": 3
						}
					  }
					},
					{
					  "match": {
						"field_6": {
						  "query": "{{query_string}}",
						  "fuzziness": "1",
						  "boost": 1
						}
					  }
					}
				  ]
				}				
			}
          ]          
        }
      },
      "from": "{{from}}{{^from}}0{{/from}}",
      "size": "{{size}}{{^size}}10{{/size}}"
    },
    "params": {
      "query_string": "Query string"
    }
  }
}
1 Like

Great thanks to you, @canelia! Now it works correctly

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.