Elasticsearch如何用条件排序

时间:2016-09-01 15:00:56

标签: sorting elasticsearch nested

在我的ElasticSearch(2.x)上,我有这样的文件:

{
    "title": "A good title",
    "formats": [{
        "name": "pdf",
        "prices": [{
            "price": 11.99,
            "currency": "EUR"
        }, {
            "price": 18.99,
            "currency": "AUD"
        }]
    }]
}

我希望按formats.prices.price对文档进行排序,但仅限formats.prices.currency === 'EUR'

我尝试在formats.prices上执行嵌套字段,然后运行此查询:

{
  "query": {
    "filtered": {
      "query": {
        "and": [
          {
            "match_all": {}
          }
        ]
      }
    }
  },
  "sort": {
    "formats.prices.price": {
      "order": "desc",
      "nested_path": "formats.prices",
      "nested_filter": {
        "term": {
          "currency": "EUR"
        }
      }
    }
  }
}

但遗憾的是我无法获得正确的订单。

更新: 映射的相关部分:

   "formats": {
        "properties": {
          "name": {
            "type": "string"
          },
          "prices": {
            "type": "nested",
            "include_in_parent": true,
            "properties": {
              "currency": {
                "type": "string"
              },
              "price": {
                "type": "double"
              }
            }
          }
        }
      },

1 个答案:

答案 0 :(得分:1)

我希望这能解决你的问题

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "formats.prices",
            "filter": {
              "match": {
                "formats.prices.currency": "EUR"
              }
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 50,
  "sort": [
    {
      "formats.prices.price": {
        "order": "asc",
        "nested_path": "formats.prices",
        "nested_filter": {
          "match": {
            "formats.prices.currency": "EUR"
          }
        }
      }
    }
  ]
}