I found a solution, I hope it will help to those who might face the same kind of issue.
The solution is to split the large list into multiple smaller lists and put each of them in separate "terms" queries.
For example, let's say that the max_terms_count is 4 and we have 12 items which we need to exclude from the search result.
$iMaxTermsCount = 4;
$arItems = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
];
if (count($arItems) <= $iMaxTermsCount) {
// Add all items to the terms query. It will produce:
// "terms": {
// "item_id": [
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
// ]
// }
} else {
$arChunks = array_chunk($arItems, $iMaxTermsCount);
foreach ($arChunks as $ar) {
// Add some (4) items to the terms query.
}
// The loop above will produce:
// {
// "terms": {
// "item_id": [
// 1, 2, 3, 4
// ]
// }
// },
// {
// "terms": {
// "item_id": [
// 5, 6, 7, 8
// ]
// }
// },
// {
// "terms": {
// "item_id": [
// 9, 10, 11, 12
// ]
// }
// }
}
The final JSON object will be like this:
{
"query": {
"bool": {
"must_not": [
{
"bool": {
"should": [
{
"terms": {
"item_id": [
1, 2, 3, 4
]
}
},
{
"terms": {
"item_id": [
5, 6, 7, 8
]
}
},
{
"terms": {
"item_id": [
9, 10, 11, 12
]
}
}
]
}
}
]
}
}
}
The query above will exclude all items without throwing any errors.