如何通过在文档字段上进行计算来查询和排序elasticsearch?

时间:2019-07-10 08:16:41

标签: elasticsearch

我有一个ElasticSearch,每个文档都有3个字段-
1. id
2.货币
3.价格

我想按价格对数据进行排序,
我可以使用排序查询来做到这一点。

但是我的数据使用不同的货币,例如美元和印度卢比,
假设1 USD = 70 INR

包含1美元价格的文档,
降序排序时应首先显示。

创建-

PUT /price/_doc/1?pretty
{
    "id":1,
    "currency": "USD",
    "price": 1
}
PUT /price/_doc/2?pretty
{
    "id":2,
    "currency": "INR",
    "price": 50
}

排序查询-

GET /price/_search/
{
    "sort": [
      {
        "price": {
          "order": "desc"
        }
      }
    ], 
    "query": {
      "match_all": {}
    }
}

数据如下所示-

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": null,
    "hits": [
      {
        "_index": "price",
        "_type": "_doc",
        "_id": "2",
        "_score": null,
        "_source": {
          "id": 2,
          "currency": "INR",
          "price": 50
        },
        "sort": [
          50
        ]
      },
      {
        "_index": "price",
        "_type": "_doc",
        "_id": "1",
        "_score": null,
        "_source": {
          "id": 1,
          "currency": "USD",
          "price": 1
        },
        "sort": [
          1
        ]
      }
    ]
  }
}

预期-

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": null,
    "hits": [
      {
        "_index": "price",
        "_type": "_doc",
        "_id": "1",
        "_score": null,
        "_source": {
          "id": 1,
          "currency": "USD",
          "price": 1
        },
        "sort": [
          1
        ]
      },
      {
        "_index": "price",
        "_type": "_doc",
        "_id": "2",
        "_score": null,
        "_source": {
          "id": 2,
          "currency": "INR",
          "price": 50
        },
        "sort": [
          50
        ]
      }
    ]
  }
}

我知道可以一次在多个索引上进行查询,
如果我维护另一个索引以了解价格明细,对您有帮助吗?
在ElasticSearch中可以进行这种排序和计算吗? 如果是这样,我如何在查询elasticsearch时实现此计算?

0 个答案:

没有答案