Search code examples
elasticsearchmvel

Scripting - How to create a filter based on array length / size?


I'm very new to ES but I'm trying to create a script that can query for an array to contain some matches but also filter based on the total array size.

Example data:

"_source": {
  "id": 5,
  "title": "Chicken & vegetable broth, soda farls & chicken liver toasts ",
  "ingredients": [
    "1 organic or free-range chicken",
    "5 large onions",
    "100g butter, for frying"
  ]
}

The following query would match the record above but would not return it because it has less than 5 ingredients.

{
"query": {
    "function_score": {
        "query": {
            "terms": {
                "ingredients": ["beef", "bacon"]
            }
        },
        "functions": [{
            "script_score": {
                "script": "ingredients-amount",
                "params": {
                    "my_modifier": 5
                }
            }
        }]
    }
  }
}

I thought ingredients-amount.mvel would simple be along the lines of:

doc['ingredients'].values.length > my_modifier

Thanks for the help


Solution

  • Index the length of the array, so you can do a simple range-filter.

    If you use a script for this, you will be loading the entire field into memory, which you probably don't want to do.