Uttam Panara Uttam Panara - 4 days ago 5
Groovy Question

Elastic search > Groovy script > Nested Fields with multiple result in symfony

How to add condition and get value of FeeAmount nested field in totalRate?
I have used Fos-elastica bundle in symfony

Elastic search mapping

profile:
mappings:
id: ~
title: ~
name: ~
rates:
type: "nested"
properties:
id: ~
serviceName: ~
FeeAmount:
type: "float"


I want condition as per i have written in below code for Groovy script.
Here, _source.rates() returns multiple results so i need to add separate condition for each rates service

$elasticaClient = new \Elastica\Client();
$search = new \Elastica\Search($elasticaClient);
$search->addIndex('COC');
$search->addType('Profile');

$mainQuery = new \Elastica\Query(); // main query

// Start Groovy Script

$scriptString = "total = 0;
for (pos in _source.rates()) {
if(pos.id == 1){
total = total + pos.FeeAmount;
}
}
return total;";

$script = new \Elastica\Script($scriptString);
$script->setLang('groovy');

$mainQuery->setFields(['_source']);
$mainQuery->setScriptFields([ 'totalRate' => $script]);

$search->setQuery($mainQuery);

$results = $search->search()->getResults();

return $results;

Answer

I have find solution by google..

 $scriptString = "total = 0;
    for (pos in _source.rates()) {
        if(pos.id == 1){
            total = total + pos.FeeAmount;
        }
    }
    return total;";

Replace above code with this one, and it's works

$scriptString = "
    def total = 0;
    for (rate in _source.rates) {
        total = total + rate.FeeAmount;
    }
    return total;";    
Comments