How to excute size function in script Plainess when I want access my field with type nested?

Example, I have index following:

PUT candidates
{
 "mappings": {
  "language": {
      type: "nested"
   }
 }
}
POST candidates/_doc
{
  "firstname": "Mike", 
  "age": 31, 
  "city": "New York",
  "language":[
    {
      "name": "English",
      "level": "native"
    },
    {
      "name": "French",
      "level": "basic"
    },
    {
      "name": "German",
      "level": "advanced"
    },
    {
      "name": "Spanish",
      "level": "low"
    }
  ]   
}
POST candidates/_doc
{
  "firstname": "Andre", 
  "age": 28, 
  "city": "Texas",
  "language":[
    {
      "name": "Portuguese",
      "level": "native"
    }
  ]   
}
POST candidates/_doc
{
  "firstname": "Andre", 
  "age": 28, 
  "city": "Texas",
  "language":[]   
}

I want check language.length > 0 == true then return true.

I try script query for plainess following:

if (doc['language'].size() > 0) { 
   return true;
}
return false;

But, I received error:

"caused_by": {
            "type": "illegal_argument_exception",
            "reason": "No field found for [language] in mapping"
 }

Hi @duyhunter1001

You can try using script_fields.

GET candidates/_search
{
  "_source": "*", 
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "exists_languages": {
      "script": {
        "lang": "painless",
        "source": """
        if (params['_source']['language'].length > 0) { 
            return true;
        }
        return false;
        """
      }
    }
  }
}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.