I'm using elasticsearch in my laravel-app and I'm trying to use the range-query. I have an array of companies, which in different periods have different amounts of employees, but I'm only interested in the newest period, which in this case means the last item of the employees array.
so, basically the array looks like this:
"company" => [
"name" => "some company",
"company_number" => "1234567",
"status" => "normal",
"employees" => [
"period_1" => [
"amount" => 10
],
"period_2" => [
"amount" => 15
],
"period_3" => [
"amount" => 24
],
etc etc...
]
]
so, in the frontend, you can enter a minimum and a maximum value to search for companies with certain amounts of employees. In my Controller, I then do this:
"query":{
"bool": {
"should" : [
{ "match" : { "company.status" : "normal" },
{
"range": {
"company.employees": { // I WANT THE LAST ITEM FROM THIS ARRAY
"gte": "'. $min . '",
"lt" : "'.$max .'"
}
}
}
]
}
}
This basically works, but of course, doesn't give me the last record of the employees array.
How can I solve this? Please help...
UPDATE
ok so now I added the code which was suggested:
"query": {
"bool": {
"should" : [
{ "match" : { "company.status" : "normal" },
{
"range": {
"company.employees": { // I WANT THE LAST ITEM FROM THIS ARRAY
"gte": "'. $min . '",
"lt" : "'.$max .'"
}
}
}
]
},
"script": {
"source": """
def period_keys = new ArrayList(ctx._source.company.employees.keySet());
Collections.sort(period_keys);
Collections.reverse(period_keys);
def latest_period = period_keys[0];
def latest_amount = ctx._source.company.employees[latest_period].amount;
ctx._source.company.current_employees = ["period": latest_period, "amount": latest_amount];
"""
}
}
}
But I get the error: Unexpected character ('{' (code 123)): was expecting comma to separate Object entries...
Since I'm still learning I must say, I have no clue what is going on and error messaging from Elasticsearch is horrible.
Anyway, does anyone have a clue? Thanks in advance