Elasticsearch按嵌套对象的数量排序

时间:2016-03-09 16:22:58

标签: elasticsearch

我有以下ES内容,基本上是包含来自网站的嵌套优惠的产品列表。

{
"product": {
  "ean": "abc",
  "features": {
     "product_type": "DVD player"
  },
  "color": "Black",
  "manufacturer": "Sony",
  "sitedetails": [
     {
        "name": "amazon.com",
        "sku": "zzz",
        "url": "http://www.amazon.com/dp/zzz"
     },
     {
        "name": "bestbuy.com",
        "sku": "aaa",
        "url": "http://www.bestbuy.com/aaa"
     }
  ],
  "category": "Portable DVD Players"
 },
 product: { etc etc},
 product: { etc etc},
}

如何按网站详细信息排序?

TNX!

3 个答案:

答案 0 :(得分:1)

您可以使用Script Based Sorting完成此操作,如下所示:

{
   "sort": {
      "_script": {
         "type": "number",
         "script": "_source.product.sitedetails.size()",
         "order": "desc"
      }
   }
}

答案 1 :(得分:1)

从问题中的示例来看,它看起来像是单个文档,但单个json文档不可能在同一级别具有相同名称的多个字段。

因此,继续假设每个product字段代表不同的顶级文档

{
  "size": 10,
  "from": 0,
  "query": {
    "match_all": {} 
  },
  "sort" : {
    "_script" : {
      "script": "doc['sitedetails'].values.size()",
      "order": "desc",
      "type" : "number"
    }
  }
}

答案 2 :(得分:0)

您可以使用Painless执行此操作,因此您无需启用动态脚本。

{
  "sort": [{
    "_script": {
       "type": "number",
       "script": "params._source?.product?.sitedetails?.length ?: 0",
       "order": "desc"
     }
   }]
}

我还包括处理空字段。看到 https://www.elastic.co/guide/en/elasticsearch/painless/master/_operators.html

https://github.com/elastic/elasticsearch/issues/20068