使用ElasticSearch无痛脚本在params数组中检查值是否存在 [英] Check value exists in params array using ElasticSearch painless script

查看:633
本文介绍了使用ElasticSearch无痛脚本在params数组中检查值是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ElasticSearch的新手.我正在一个项目中,我必须搜索与输入http://foo.bar/search?listing=123,456相匹配的列表.我建立了一个数组,其键和值相同,并表示列表ID.我尝试运行以下示例,但在包含附近失败.该脚本是为轻松编写语言而构建的.但是,我总是会遇到运行时错误.

I am new to ElasticSearch. I am working on a project where I have to search listings which matches the input http://foo.bar/search?listing=123,456. I have built an array which key and value are the same and representing the listing ids. I have tried to run the following example but it failed near contains. The script is built for painless language. However, I always get the runtime error.

我无法使它正常工作,我可能做错了什么?

I cannot get this to work, what could I be doing wrong?

 'function_score' => [
       'query' => $query,
           'score_mode' => 'sum',
              'functions' => [[
                'script_score' => [
                 'script' => [
                   'params' => ['listing' => [123 => 123, 456 => 456]],
    'source' => "(params.listing.contains(doc['id'].value) ? Math.pow(3, 3) : 0)",
                            ],
                        ],
                    ]],
                ],

推荐答案

您可以使用以下查询.您可以检查script部分,了解所需的实现方式.

You can make use of the below query. You can check the script part as how what you need has been implemented.

POST <your_index_name>/_search
{
  "query": {
    "function_score": {
      "score_mode": "sum", 
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": """
                  boolean allValues = false;
                  for(int i=0; i<params.value.size(); i++){
                    if(doc['id'].value.contains(params.value.get(i))){
                      allValues = true;
                    }else{
                      allValues = false;
                      break;
                    }
                  } 
                  if(allValues){
                    return Math.pow(3,3)
                  } else {
                    return 0;
                  }
                """,
              "params":{
                "value": ["123","456"]
              }
            }
          }
        }
      ]
    }
  }
}

查询的作用是,它检查是否存在于参数中的所有值,即123 & 456是否存在于id字段中,如果存在,它将继续进行并相应地计算得分.

What the query does is, it checks to see if all the values present in params i.e 123 & 456 is present in the id field, if it does, it would go ahead and calculate score accordingly.

在我最后测试查询时,不是id字段是keyword.

Not that id field is a keyword when I tested the query at my end.

您可以在php脚本中相应地使用查询.让我知道是否有帮助!

You can use the query accordingly in your php script. Let me know if this helps!

这篇关于使用ElasticSearch无痛脚本在params数组中检查值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆