elasticsearch中如何计算数据

How to calculate data in elastic search

我正在尝试计算数据并在搜索结果后分配到同一字段中。

{
  query: {
    "query_string": {
      "query": req.body.query
    }
  }
}

我正在获取搜索结果。

"results": [
  {
    "_index": "test_index",
    "_type": "_doc",
    "_id": "34",
    "_score": 1.8216469,
    "_source": {
      "pre_function_area": "100",
      "property_id": 46,
      "max_benchmark": 0,
    }
  }
]

这里我想在搜索时修改max_benchmark。所以像 as.

这样发送查询
{
  "query": {
      "bool" : {
        "must" : {
          "query_string": {
            "query": "test"
          }
        },
          "filter" : {
              "script" : {
                  "script" : { //Math.round((pow *  doc['max_benchmark'].value) * 10) / 10
                      "lang": "expression",
                    //  "lang": "painless",
                      "source": "doc['max_benchmark'].value * 5",
                   }
              }
          }
      }
  }

}

但它不会更新到字段 我不想更新 elasticsearch 中的实际字段值。我只想在搜索后逻辑上更改值,以便它显示给用户。基本上我正在尝试计算以下公式并想要更新字段。

        let months = 0;
          if(event_date != "") {
            let ai_date = moment(); 
            ai_date.month(obj._source.month);
            ai_date.year(obj._source.year);
            months = ai_date.diff(event_date, 'months');
          }
          console.log("months "+months);
          let pow = Math.pow(1.009,months);
          obj._source.max_benchmark_cal = Math.round((pow *  obj._source.max_benchmark) * 10) / 10;
          obj._source.min_benchmark_cal = Math.round((pow *  obj._source.min_benchmark) * 10) / 10;
        } else {
          obj._source.max_benchmark_cal = "NA";
          obj._source.min_benchmark_cal = "NA";
        }

谁能帮帮我

您已接近最佳解决方案。 答案是使用脚本字段。 您可以在此处找到文档

[https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-fields.html#script-fields]1

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
        }
      }
    }
  }
}

编辑:回复您的评论。 您不能向 _source 添加字段,但您可以通过在源中指定所需的字段来获取 _source 和脚本化字段。 (* 被接受)。

举个例子:

GET test/_search
{
  "query": {
    "match_all": {}
  },
  "_source": "*", 
  "script_fields": {
    "test1": {
      "script": {
        "lang": "painless",
        "source": "if(doc['title.keyword'].size()>0 ){doc['title.keyword'].value}"
      }
    }
  }
}