首页 > 解决方案 > 如何在 ElasticSearch 中对价格字符串进行排序?

问题描述

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

标签: node.jssortingelasticsearchelasticsearch-5

解决方案


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

新映射:

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

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

通过查询更新:

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到您的索引中。


推荐阅读