I’m currently facing an issue with constructing a proper Elasticsearch query. The goal is to implement a filtering mechanism with the following requirements
In SQL, this would be straightforward using an OR condition, like this:
SELECT *
FROM posts
WHERE userId = 'my_user_id'
OR (userId != 'my_user_id' AND hiddenUntil <= CURRENT_TIMESTAMP);
How can I wrote elastic search query that run same with the sql?
{
"query": {
"bool": {
"filter": [
{
"term": { "userId": "my_user_id" }
},
{
"bool": {
"must": [
{ "range": { "hiddenUntil": { "lte": 1728291700750 } } }
],
"must_not": [
{ "term": { "userId": "my_user_id" } }
]
}
}
]
}
}
}
You can use should query with must/must_not inside it and specify minimum_should_match to satisfy your criteria.
{
"query": {
"bool": {
"must": [],
"filter": [],
"should": [
{
"bool": {
"must": [
{
"term": {
"userId": "my_user_id"
}
}
]
}
},
{
"bool": {
"must_not": [
{
"term": {
"userId": "my_user_id"
}
}
],
"must": [
{
"range": {
"hiddenUntil": {
"lte": 1728291700750
}
}
}
]
}
}
],
"minimum_should_match": 1,
"must_not": []
}
}
}