I would like to learn how to fetch documents with the first value of the calendarItems.minNights field greater than 2 using Elasticsearch DSL. The data structure looks like this:
In the above data structure, I want to retrieve documents where the first value of calendarItems.minNights is greater than 2. What should be the Elasticsearch DSL query for this?
Thank you.
Data
{
"_index": "list",
"_id": "5150",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"id": 5150,
"title": "test title",
"calendarItems": [
{
"actualDate": "2023-07-10T00:00:00+03:00",
"price": 458,
"minNights": 4,
"status": "booked",
"reason": null,
"isBlock": null
},
{
"actualDate": "2023-07-11T00:00:00+03:00",
"price": 458,
"minNights": 2,
"status": "available",
"reason": null,
"isBlock": null
},
{
"actualDate": "2023-07-12T00:00:00+03:00",
"price": 458,
"minNights": 2,
"status": "available",
"reason": null,
"isBlock": null
},
{
"actualDate": "2023-07-12T00:00:00+03:00",
"price": 458,
"minNights": 2,
"status": "booked",
"reason": null,
"isBlock": null
}
]
}
}
Query
"query": {
"bool": {
"must": [
{
"nested": {
"path": "calendarItems",
"query": {
"bool": {
"must": [
{
"range": {
"calendarItems.actualDate": {
"gte": "2023-07-07T00:00:00+03:00",
"lte": "2023-07-12T23:59:59+03:00"
}
}
},
{
"term": {
"calendarItems.status": "available"
}
},
{
"script": {
"script": {
"source": "2 >= doc['calendarItems.minNights'].value",
"lang": "painless"
}
}
}
]
}
}
}
}
],
"must_not": [
{
"nested": {
"path": "calendarItems",
"query": {
"bool": {
"must": [
{
"term": {
"calendarItems.status": "booked"
}
},
{
"range": {
"calendarItems.actualDate": {
"gte": "2023-07-07T00:00:00+03:00",
"lte": "2023-07-12T23:59:59+03:00"
}
}
}
]
}
}
}
}
]
}
}
I solved this
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "calendarItems",
"query": {
"bool": {
"must": [
{
"range": {
"calendarItems.actualDate": {
"gte": "2023-07-07T00:00:00+03:00",
"lte": "2023-07-15T23:59:59+03:00"
}
}
},
{
"term": {
"calendarItems.status": "available"
}
}
]
}
}
}
},
{
"nested": {
"path": "calendarItems",
"query": {
"bool": {
"must": [
{
"range": {
"calendarItems.actualDate": {
"gte": "2023-07-07T00:00:00+03:00",
"lte": "2023-07-07T23:59:59+03:00"
}
}
},
{
"term": {
"calendarItems.status": "available"
}
},
{
"script": {
"script": {
"source": "8 >= doc['calendarItems.minNights'].value",
"lang": "painless"
}
}
}
]
}
}
}
}
],
"must_not": [
{
"nested": {
"path": "calendarItems",
"query": {
"bool": {
"must": [
{
"term": {
"calendarItems.status": "booked"
}
},
{
"range": {
"calendarItems.actualDate": {
"gte": "2023-07-07T00:00:00+03:00",
"lte": "2023-07-15T23:59:59+03:00"
}
}
}
]
}
}
}
}
]
}
}
}