sorting - Elasticsearch分组和按嵌套字段最小值的顺序

标签 sorting elasticsearch nested aggregation

我有一个产品结构,这些产品可以在不同的商店以不同的价格购买:

[{
  "name": "SomeProduct",
  "store_prices": [
    {
      "store": "FooStore1",
      "price": 123.45
    },
    {
      "store": "FooStore2",
      "price": 345.67
    }
  ]
},{
  "name": "OtherProduct",
  "store_prices": [
    {
      "store": "FooStore1",
      "price": 456.78
    },
    {
      "store": "FooStore2",
      "price": 234.56
    }
  ]
}]

我想显示以最低价格升序排列的产品列表,以这种方式限制在10个结果中:
  • SomeProduct:123.45 USD
  • 其他产品:234.56 USD

  • 这该怎么做?我尝试了https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html中描述的嵌套聚合方法,但它仅返回所有产品的最低价格,而不返回每种产品的最低价格:
    {
      "_source": [
        "name",
        "store_prices.price"
      ],
      "query": {
        "match_all": {}
      },
      "sort": {
        "store_prices.price": "asc"
      },
      "aggs": {
        "stores": {
          "nested": {
            "path": "store_prices"
          },
          "aggs": {
            "min_price": {"min": {"field": "store_prices.price"}}
          }
        }
      },
      "from": 0,
      "size": 10
    }
    

    在SQL中,可以使用以下查询描述我要执行的操作。恐怕我在“sql中”考虑的太多了:
    SELECT
      p.name,
      MIN(s.price) AS price
    FROM
      products p
    INNER JOIN
      store_prices s ON s.product_id = p.id
    GROUP BY
      p.id
    ORDER BY
      price ASC
    LIMIT 10
    

    最佳答案

    您需要一个nested sorting:

    {
       "query": // HERE YOUR QUERY,
       "sort": {
         "store_prices.price": {
           "order" : "asc",
           "nested_path" : "store_prices",
           "nested_filter": {
              // HERE THE FILTERS WHICH ARE EVENTUALLY 
              // FILTERING OUT SOME OF YOUR STORES
           }
         }
       }
    }
    

    请注意,您必须在嵌套过滤器字段内重复最终的嵌套查询。然后,您可以在响应的score字段中找到价格。

    关于sorting - Elasticsearch分组和按嵌套字段最小值的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040088/

    相关文章:

    Ruby 就地对子数组进行排序

    c# - 如何使用NEST获得包含给定子词的搜索结果?

    ruby-on-rails - 运行测试时 ElasticSearch Rails resource_already_exists_exception

    ruby-on-rails - Elasticsearch::Transport::Transport::Errors::Forbidden: [403] 发送超过 1200 个字符的文本字段时出错

    python - 如何在Python中生成嵌套循环

    arrays - Mongodb 使用聚合框架过滤深度嵌套数组

    java - 数组排序问题: 2 different sorting results

    javascript - 动态修改或生成Javascript代码

    java - Java 中数组列表出现越界异常错误

    css 背景颜色 child 不显示