Elasticsearch使用if语句进行高级排序

时间:2019-01-17 18:40:16

标签: elasticsearch

在我的ES中,我有对象“ person”,看起来像这样:

{
 name: "a",
 type: "single"
}


{
 name: "b",
 type: "family",
 children: {
   {
     name: "ba",
     active: 1
   },
   {
     name: "bb",
     active: 0
   }
 }
}

{
 name: "c",
 type: "family",
 children: {
   {
     name: "ba",
     active: 0
   },
   {
     name: "bb",
     active: 0
   }
 }
}

现在我想得到所有的“人”,但是... if type = family and all children active = 0然后,该对象应该在列表的底部(_score = 0)

如何获得这种类型的排序?

1 个答案:

答案 0 :(得分:0)

您可以通过几种不同的方式来获得类似的结果:

我认为最好的方法是使用功能得分查询。其原因是因为提升(或降级)部分与查询本身保持分开。因此,例如,如果允许用户按名称搜索,则该部分与降级没有活跃孩子的家庭的部分分开。

您首先需要将“子项”字段的映射更新为nested,这将使您能够处理子项对象数组中包含的各个项目。之后,正确的function_score查询将使您可以降级符合您的条件的项目。我只是想吐出您需要的字段映射和查询,但是希望这可以帮助您入门。

名义字段映射

{
  "mappings": {
    "_doc" : {
      "properties" : {
        "name": {
          "type": "text"
        },
        "type": {
          "type": "keyword"
        },
        "children" : {
          "type" : "nested",
          "properties": {
            "name": {
              "type": "text",
            },
            "active": {
              // Unless you intend to do some math with the active
              // field, you should probably us a boolean for this flag
              "type": "boolean"
            }
          }
        }
      }
    }
  }
}

名义查询

{
  "query": {
    "function_score": {
      "query": { "match_all": {}},
      // Other options available for boost_mode, e.g. multiply--see docs
      "boost_mode": "sum",
      "functions": [
        {
          // You'll need to tweak this weighting, depending on your query
          "weight": 5,
          "filter": {
            "bool": {
              "must": [
                // Filters this boost to apply only to `type: family`
                { "term" : { "type" : "family" }}, 
                // Nested query to select items with active children.  
                // Using `score_mode: sum` means that more active children will
                // give more of a boost.  Other score modes available
                {
                  "nested": {  
                    "path" : "children",
                    "score_mode" : "sum",
                    "query" : {
                      "bool" : {
                        "must" : [
                          { "term" : { "children.active" : true }}
                        ]
                      }
                    }
                  }
                } 
              ]
            }
          }
        }
      ]
    }
  }
}

这将对具有活动子项的记录进行增强,将其余子项留在底部。另外,您可以编写一个查询,使其仅与没有活动子级的记录匹配,并施加负权重。

如果您对如何使这两个部分中的任何一个有其他疑问,只需提交一个特定于您所遇到问题的问题。祝你好运!