Stutract Two values

Hi,

I want to get difference between two values.

suppose I have data in following format.
"_source" : {
"students" : [
{
"name" : "A",
"total_fee" : 12345,
"paid_fee" : 12344.8
},
{
"name" : "B",
"total_fee" : 23456,
"paid_fee" : 23455.6
}
]
}

Now I want to get the difference between "total_fee" and "paid_fee" for each student.
I have already tried
{
"query": {
"bool": {
"filter": {
"script": {
"script": "doc['students.total_fee'].value - doc['students.paid_fee'].value"
}
}
}
}
}
but it is returning empty "hits".

I have also tried

{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "students",
"query": {
"script": {
"script": {
"inline": "doc['students.total_fee'].value - doc['students.paid_fee'].value",
"lang": "expression"
}
}
}
}
}
]
}
}

also the "script_fields" did not worked.

Please suggest how can I achieve the desired output.

Thanks in advance :smiley: .

You should use script field:

{
   "script_fields" : {
        "difference" : {
            "script" : "doc['total_fee'].value - doc['paid_fee'].value"
        }
    }
}

Hi @wangqinghuan,

I tried "script_fields" but it is resulting to "0" not the correct difference.
Is there anything to do with nested data?

Thanks for quick response.

I have tried

but it is giving 0 as difference.

Is it because difference is very less?

If I'm not using "students." it is giving "no field found [total_fee]" error.

Is it because difference is very less?

No.

If I'm not using "students." it is giving "no field found [total_fee]" error.

students.total_fee is a nested structure. Why do you use nested document?

The data I have is in nested format. The student data was just for example.

Hi,

Thanks for your replies.

I found the solution on stackOverflow.

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