Given the document:
{
"id": 1,
"school_cd": 18713,
"assignments": [
{
"doc_id": 1,
"doc_type_id": 11,
"doc_status": "ASSIGNED"
},
{
"doc_id": 2,
"doc_type_id": 11,
"doc_status": "PROCESSED"
},
{
"doc_id": 3,
"doc_type_id": 19,
"doc_status": "PROCESSED"
},
{
"doc_id": 4,
"doc_type_id": 19,
"doc_status": "ASSIGNED"
},
{
"doc_id": 5,
"doc_type_id": 19,
"doc_status": "ASSIGNED"
}
]
}
I have a query where I want to return a document if the count of the nested assignments
elements meets a certain threshold. There are two conditions:
- The
assignments.doc_type_id
== 19, and - The
assignments.doc_status
== ‘PROCESSED’
I’ve tried the following script, with no luck:
{
"query": {
"script": {
"script": {
"source": "def count = 0; for (item in doc['assignments']) {if (item.doc_type_id == 11 && item.doc_status.keyword == 'PROCESSED') {count +=1;}} return count <= 2;",
"lang": "painless"
},
"boost": 1.0
}
}
}
Which returns an error:
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"org.opensearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:104)",
"org.opensearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:53)",
"for (item in doc['assignments']) {",
" ^---- HERE"
],
"script": "def count = 0; for (item in doc['assignments']) {if (item.doc_type_id == 11 && item.doc_status.keyword == 'PROCESSED') {count +=1;}} return count <= 2;",
"lang": "painless",
"position": {
"offset": 32,
"start": 15,
"end": 49
},
"caused_by": {
"type": "illegal_argument_exception",
"reason": "No field found for [assignments] in mapping with types []"
}
Is there another approach to this?