【问题标题】:Elasticsearch scripted fields. Dynamic param selectionElasticsearch 脚本字段。动态参数选择
【发布时间】:2019-06-27 23:57:01
【问题描述】:

我正在尝试根据文档中的值创建一个动态参数。

到目前为止,我在这里尝试过

 body: {
            "script_fields": {
                "potentialIncome": {
                    "script": {
                        "lang": "painless",
                        "source": "doc.rentPrice.value - params['doc.buyingPrice.value']",
                        "params": {
                            120000: 1200,
                            150000: 1500
                        }
                    }
                }

            }
        }

这会引发以下错误:

type: 'script_exception',
    reason: 'runtime error',
    script_stack: 
     [ 'doc.rentPrice.value - params[\'doc.buyingPrice.value\']',
       '                            ^---- HERE' ],
    script: 'doc.rentPrice.value - params[\'doc.buyingPrice.value\']',
    lang: 'painless' 

我想让参数动态化,让文档值buyingPrice 决定扣除哪个值。

使用 ElasticSearch 7.2


一个复杂而糟糕的方法是使用以下脚本

if(doc['buyingPrice'].value==120000){return doc['rentPrice'].value-params['120000']}

else if(doc['buyingPrice'].value==150000){return doc['rentPrice'].value-params['150000']}


Es 对象:

{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [{
            "_index": "immo",
            "_type": "objects",
            "_id": "1",
            "_score": 1.0,
            "_source": {
                "buyingPrice": 120000,
                "rentPrice": 500
            }
        }, {
            "_index": "immo",
            "_type": "objects",
            "_id": "2",
            "_score": 1.0,
            "_source": {
                "buyingPrice": 150000,
                "rentPrice": 500
            }
        }]
    }
}

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    您需要尝试不使用单引号。

    "source": "return (params[String.valueOf(doc.buyingPrice.value)] != null) ? doc.rentPrice.value - params[String.valueOf(doc.buyingPrice.value)] :  0",
                             ^                     ^
                             |                     |
    

    【讨论】:

    • 这在某种意义上有效,它不再中断 - 但潜在收入现在始终为 0。我编辑并添加了对象
    • 好了,我修复了查询。
    • 太棒了,很高兴它有帮助!
    • 嘿 - 你能帮我一个忙吗? ;) 我有同样的问题 - 现在它是一个文本字段。文本字段是doc.region.value,我有参数,其中键是字符串。我该怎么做?
    • 欢迎提出新问题。
    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2020-12-20
    相关资源
    最近更新 更多