如何在elasticsearch中计算数据

3okqufwl  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(487)

我试图计算数据和分配在同一领域后,搜索结果。

{
  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,
    }
  }
]

在这里,我想修改最大\u基准在搜索过程中。所以像这样发送查询。

{
  "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";
        }

有人能帮我吗

ndh0cuux

ndh0cuux1#

你的建议接近好的解决方案。答案是使用脚本字段。你可以在这里找到医生
[https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-fields.html#script-字段]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
        }
      }
    }
  }
}

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

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

相关问题