Elasticsearch得分与子文档计数

时间:2015-10-16 19:28:50

标签: elasticsearch

我有这三个对象(3个用户有照片,每张照片都有一个类别ID)

{
    "id": 1,
    "name": "User1",
    "photos":[
        {
            "id": 1,
            "cat": 1
        },
        {
            "id": 2,
            "cat": 1
        },
        {
            "id": 3,
            "cat": 2
        }
    ]
}
{
    "id": 2,
    "name": "User2",
    "photos":[
        {
            "id": 4,
            "cat": 1
        },
        {
            "id": 5,
            "cat": 2
        },
        {
            "id": 6,
            "cat": 2
        }
    ]
}
{
    "id": 3,
    "name": "User3",
    "photos":[
        {
            "id": 7,
            "cat": 2
        },
        {
            "id": 8,
            "cat": 3
        },
        {
            "id": 9,
            "cat": 3
        }
    ]
}

我想给这些文件一个分数(最高分数:10),具体取决于他们用cat = 1的照片数量

Object1 : 2 objects with cat = 1
Object2 : 1 objects with cat = 1
Object3 : 0 objects with cat = 1

因此得分将为Object1 = 10,Object2 = 5,Object3 = 0

1 个答案:

答案 0 :(得分:2)

无论@eemp说什么,或者如果你不能修改文档索引的方式和/或如果你不能修改映射,那么一个解决方案就是利用function_score queryscript_score组件我们访问photos数组并将cat == 1元素的数量乘以5。

{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "script_score": {
            "script": "_source.photos.findAll{return it.cat == 1}.size() * 5"
          }
        }
      ]
    }
  }
}

你会得到你期望的分数,即

  • 10 for object 1
  • 5 for object 2
  • 对象3
  • 0