This solution seems to be doing the trick. I have combined `exists` and `terms` so that the term is applied only if it exists in the document.
This way, despite having multiple indices, it automatically applies terms only to documents where fields exist.
Here is the query:
{
"query": {
"bool": {
"must": [
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"multi_match": {
"boost": 1,
"fields": [
"media_values.title",
"title",
"vehicle_brand_name"
],
"query": "<query_text>",
"type": "bool_prefix"
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"bool": {
"must_not": {
"exists": {
"field": "media_data.type.keyword"
}
}
}
},
{
"bool": {
"must": [
{
"exists": {
"field": "media_data.type.keyword"
}
},
{
"terms": {
"media_data.type.keyword": [
"Video"
]
}
}
]
}
}
]
}
},
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"bool": {
"must_not": {
"exists": {
"field": "media_values.orientation"
}
}
}
},
{
"bool": {
"must": [
{
"exists": {
"field": "media_values.orientation"
}
},
{
"terms": {
"media_values.orientation": [
"landscape"
]
}
}
]
}
}
]
}
},
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"bool": {
"must_not": {
"exists": {
"field": "workflow.status.keyword"
}
}
}
},
{
"bool": {
"must": [
{
"exists": {
"field": "workflow.status.keyword"
}
},
{
"terms": {
"workflow.status.keyword": [
"APPROVED"
]
}
}
]
}
}
]
}
}
]
}
}
]
}
}
}
Ok after a day of fiddling with `bool` I got it working:
{
"query": {
"bool" : {
"must" : [
{
"multi_match": {
"query": "keyword",
"fields": [
"name^3",
"body"
]
}
},
{
"bool": {
"should": [
{
"bool": {
"must": [
{
"range": {
"publish_at": {
"lte" : "now"
}
}
},
{
"range": {
"publish_until": {
"gt" : "now"
}
}
}
]
}
},
{
"bool": {
"must_not": [
{
"exists": {
"field": "publish_at"
}
},
{
"exists": {
"field": "publish_until"
}
}
]
}
}
]
}
}
]
}
}
}