Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch - Script Filter over a list of nested objects

I am trying to figure out how to solve these two problems that I have with my ES 5.6 index.

"mappings": {
    "my_test": {
        "properties": {
            "Employee": {
                "type": "nested",
                "properties": {
                    "Name": {
                        "type": "keyword",
                        "normalizer": "lowercase_normalizer"
                    },
                    "Surname": {
                        "type": "keyword",
                        "normalizer": "lowercase_normalizer"
                    }
                }
            }
        }
    }
}

I need to create two separate scripted filters:

1 - Filter documents where size of employee array is == 3

2 - Filter documents where the first element of the array has "Name" == "John"

I was trying to make some first steps, but I am unable to iterate over the list. I always have a null pointer exception error.

{
  "bool": {
    "must": {
      "nested": {
        "path": "Employee",
        "query": {
          "bool": {
            "filter": [
              {
                "script": {
                  "script" :     """

                   int array_length = 0; 
                   for(int i = 0; i < params._source['Employee'].length; i++) 
                   {                              
                    array_length +=1; 
                   } 
                   if(array_length == 3)
                   {
                     return true
                   } else 
                   {
                     return false
                   }

                     """
                }
              }
            ]
          }
        }
      }
    }
  }
}
like image 682
betto86 Avatar asked Jul 05 '19 14:07

betto86


2 Answers

As Val noticed, you cant access _source of documents in script queries in recent versions of Elasticsearch. But elasticsearch allow you to access this _source in the "score context".

So a possible workaround ( but you need to be careful about the performance ) is to use a scripted score combined with a min_score in your query.

You can find an example of this behavior in this stack overflow post Query documents by sum of nested field values in elasticsearch .

In your case a query like this can do the job :

POST <your_index>/_search
{
  "min_score": 0.1,
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": """
              if (params["_source"]["Employee"].length === params.nbEmployee) {
                def firstEmployee = params._source["Employee"].get(0);
                if (firstEmployee.Name == params.name) {
                  return 1;
                } else {
                  return 0;
                }
              } else {
                return 0;
              }
""",
              "params": {
                "nbEmployee": 3,
                "name": "John"
              }
            }
          }
        }
      ]
    }
  }
}

The number of Employee and first name should be set in the params to avoid script recompilation for every use case of this script.

But remember it can be very heavy on your cluster as Val already mentioned. You should narrow the set a document on which your will apply the script by adding filters in the function_score query ( match_all in my example ). And in any case, it is not the way Elasticsearch should be used and you cant expect bright performances with such a hacked query.

like image 61
Pierre Mallet Avatar answered Nov 10 '22 03:11

Pierre Mallet


1 - Filter documents where size of employee array is == 3

For the first problem, the best thing to do is to add another root-level field (e.g. NbEmployees) that contains the number of items in the Employee array so that you can use a range query and not a costly script query.

Then, whenever you modify the Employee array, you also update that NbEmployees field accordingly. Much more efficient!

2 - Filter documents where the first element of the array has "Name" == "John"

Regarding this one, you need to know that nested fields are separate (hidden) documents in Lucene, so there is no way to get access to all the nested docs at once in the same query.

If you know you need to check the first employee's name in your queries, just add another root-level field FirstEmployeeName and run your query on that one.

like image 1
Val Avatar answered Nov 10 '22 04:11

Val