如何在 ElasticSearch 中对价格字符串进行排序?

时间:2021-07-25 20:23:35

标签: node.js sorting elasticsearch elasticsearch-5

在我的示例中,我尝试排序,但没有成功。我的问题是因为我的价格是字符串,价格就是这样 => 1.300,00。当我对字符串价格进行排序时,我以它为例。 0,00 | 1,00 | 1.000,00 | 2,00。 我想以 double 格式进行排序或类似的格式。 我怎样才能做到这一点 ? output

1 个答案:

答案 0 :(得分:0)

在弹性搜索中保留 Price 作为关键字不是一个好主意,最好的方法是在弹性搜索中将 price 映射为 scaled float,如下所示:

新映射:

PUT [index_name]/_mapping
{
  "properties": {
    "price2": {
      "type": "scaled_float",
        "scaling_factor": 100
    }
  }
}

要解决您的问题,您可以添加新映射并将您的值从 string 转换为 numeric 值:

按查询更新:

POST [index_name]/_update_by_query
{
    "query": {
        "match_all": {}
    }, 
    "script": {
       "source": "ctx._source['price2'] = ctx._source['price'].replace(',','')"
    }
}

此查询会将您的 keyword 值转换为 string 并将其映射到名为 price2 的另一个字段中,然后您需要有一个 ingest pipeline 来执行此过程新条目:

摄取管道:

POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "script": {
          "description": "Extract 'tags' from 'env' field",
          "lang": "painless",
          "source": "ctx['price2'] = ctx['price'].replace(',','')"
        }
      }
    ]
  },
  "docs": [
    {
      "_source": {
        "price": "5,000.00"
      }
    }
  ]
}

您需要删除 _simulate 并将此 ingest pipeline 添加到您的索引中。

相关问题