弹性搜索> Groovy脚本>具有多个结果的嵌套字段导致symfony

时间:2016-11-22 12:16:03

标签: php symfony elasticsearch groovy foselasticabundle

如何在totalRate中添加条件并获取 FeeAmount 嵌套字段的值? 我在symfony中使用了Fos-elastica包

弹性搜索映射

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

我希望条件按照我在Groovy脚本的下面代码中编写的。 这里,_source.rates()返回多个结果,因此我需要为每个费率服务添加单独的条件

    $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;

1 个答案:

答案 0 :(得分:0)

我找到了谷歌的解决方案..

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

将上述代码替换为此代码,并且可以正常使用

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