Check value exists in params array using ElasticSearch painless script


(Charbel) #1

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)",
                            ],
                        ],
                    ]],
                ],

(Abdon Pijpelink) #2

If I understand the logic of your query, what you're trying to do is multiply the score by 27 if one of the IDs occurs in the id field. You can achieve that without a script, by using a terms query inside a filter function, instead of a script_score function. I think this will be easier, as it will allow you to avoid having to do any scripting:

{
  "query": {
    "function_score": {
      "query": {
        YOUR_$QUERY
      },
      "functions": [
        {
          "filter": {
            "terms": {
              "id": [
                "123",
                "456"
              ]
            }
          },
          "weight": 27
        }
      ]
    }
  }
}

(Charbel) #3

The thing is that I have to stick with scripting, as there are other scripts running


(Abdon Pijpelink) #4

Alright. Why not simply pass in an array of values, rather than a map with key-value pairs? The following should work:

      "functions": [
        {
          "script_score": {
            "script": {
              "source": "(params.listing.contains(doc['id'].value) ? Math.pow(3, 3) : 0)",
              "params": {
                "listing": [
                  123,
                  456
                ]
              }
            }
          }
        }
      ]