在查询Elasticsearch v6.0.1时使用无痛脚本将新字段添加到_source对象中

时间:2019-08-01 09:22:13

标签: elasticsearch

我有一个索引,其中字段映射具有一个属性(id:整数)。 当我查询该索引时,我能够得到正确的响应。现在,我想使用无痛脚本在查询时向_source对象添加一个额外的字段。 elasticsearch版本是6.0.1。

我已经尝试将脚本添加为查询块中的字段。但这会引发错误:

{
  "error": {
    "root_cause": [
      {
        "type": "parsing_exception",
        "reason": "[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
        "line": 7,
        "col": 7
      }
    ],
    "type": "parsing_exception",
    "reason": "[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
    "line": 7,
    "col": 7
  },
  "status": 400
}
GET 20190719_candidate/candidate/_search
{
    "min_score": 0.001,
    "query": {
      "term": {
        "id": 1234
      }, 
      "script": {
        "script": {
          "inline": "doc['field_1'] = 'field_1_value'"
        }
      }
    }, 
    "from": 0,
    "size": 20
}

_source对象的预期结果是:

{
  "id": "1234567",
  "field_1": "field_1_value"
}

2 个答案:

答案 0 :(得分:1)

您缺少以下结构:

GET 20190719_candidate/candidate/_search
{
    "min_score": 0.001,
    "query": {
      "term": {
        "id": 1234
      }, 
      "script_fields": {
           "test1":{
                 "script": {
                      "lang": "painless",                       
                      "source": "'field_1_value'"
                 }
            }
      }
    }, 
    "from": 0,
    "size": 20
}

在此示例中看看:

GET /_search
{
    "query" : {
        "match_all": {}
    },
    "script_fields" : {
        "test1" : {
            "script" : {
                "lang": "painless",
                "source": "doc['price'].value * 2"
            }
        },
        "test2" : {
            "script" : {
                "lang": "painless",
                "source": "doc['price'].value * params.factor",
                "params" : {
                    "factor"  : 2.0
                }
            }
        }
    }
}

来源:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-script-fields

答案 1 :(得分:0)

  

“ root_cause”:[         {           “ type”:“ parsing_exception”,           “ reason”:“ [字词]格式错误的查询,预期[END_OBJECT],但找到了[FIELD_NAME]”,           “行”:7           “ col”:7         }       ]

该错误表明您的查询格式错误,您错过了第7行的右括号以关闭“ query”属性。

您的查询应类似于:

GET 20190719_candidate/candidate/_search
{
    "min_score": 0.001,
    "query": {
      "term": {
        "id": 1234
      }}, 
      "script": {
          "lang": "painless",
          "inline": "doc['field_1'] = 'field_1_value'"
      }, 
    "from": 0,
    "size": 20
}