Home > front end >  How to get the last element of an array field in Elasticsearch
How to get the last element of an array field in Elasticsearch

Time:10-23

I've this document indexed (index: customer-v1, type: customer, _id: 123):

GET customers-v1/customer/123

which result in:

{
  "_index" : "customers-v1",
  "_type" : "customer",
  "_id" : "123",
  ...
  "_source" : {
    "name": ...
    "age": ...
    "payments": [
      {"month": "2021-01", "amount": 10},
      {"month": "2021-02", "amount": 100},
      {"month": "2021-03", "amount": 30},
      {"month": "2021-04", "amount": 56},
    ]
  } 
}

Now I need to return a computed field(along with original data), via script, it must return the last item on field payments

CodePudding user response:

You can use scripted_fields in search query to find the last element of an array.

POST customers-v1/_search
{
    "stored_fields": [
        "_source"
    ],
    "script_fields": {
        "lastPayment": {
            "script": {
                "source": "def payments = params['_source']['payments']; return payments[payments.length - 1];",
                "lang": "painless"
            }
        }
    }
}

The above query will fetch the source along with the last element of the array:

{
    "took": 4,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "customers-v1",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "name": "...",
                    "age": "...",
                    "payments": [
                        {
                            "month": "2021-01",
                            "amount": 10
                        },
                        {
                            "month": "2021-02",
                            "amount": 100
                        },
                        {
                            "month": "2021-03",
                            "amount": 30
                        },
                        {
                            "month": "2021-04",
                            "amount": 56
                        }
                    ]
                },
                "fields": {
                    "lastPayment": [
                        {
                            "amount": 56,
                            "month": "2021-04"
                        }
                    ]
                }
            }
        ]
    }
}
  • Related