Skip to main content
 首页 » 编程设计

c#之ElasticSearch 按具有默认值的子字段对父文档进行评分

2024年02月13日21shangdawei

假设我有一些父文档名为“room”,还有一些子文档名为“person”并带有“age”字段。现在我想在 ES 中使用 age 字段使用 custom_score 查询对一些房间进行评分。

我已经使查询几乎按预期工作,唯一的问题是:没有对空房间(没有子文档)进行评分。我怎样才能给他们一个默认分数什么的。在本例中,我想对 room_id 为 1~5 的五个房间进行评分。如果 4 号房间没有子文档,则不会对其进行评分。查询只会命中 4 条具有预期分数的记录。我想要的是给空房间一个默认分数。也许函数分数查询适合这种情况,但我使用 NEST 作为目前不支持函数分数查询的 .NET 客户端。

顺便说一句:SO 的 CSS 在这里不起作用,我不知道为什么。如果帖子格式不正确,请帮助编辑,谢谢。

{ 
  "query": { 
    "custom_score": { 
      "script": "_score", 
      "query": { 
        "filtered": { 
          "query": { 
            "has_child": { 
              "type": "person", 
              "score_type": "sum", 
              "query": { 
                "custom_score": { 
                  "script": "doc['person.age'].value - 50d", 
                  "query": { 
                    "match_all": {} 
                  } 
                } 
              } 
            } 
          }, 
          "filter": { 
            "bool": { 
              "should": [ 
                { 
                  "terms": { 
                    "room_id": [ "1", "2", "3", "4", "5" ] 
                  } 
                } 
              ] 
            } 
          } 
        } 
      } 
    } 
  } 
} 

请您参考如下方法:

您的 has_child 过滤器使其仅包含具有子项的父记录,但您需要所有父记录。您可以使用带有两个 should 子句的 bool should 查询:

  • 有 child 的记录(必须用has_child和custom_score计算)
  • 没有 child 的记录(must_not with has_child 和默认分数)
{ 
  "query": { 
    "custom_score": { 
      "script": "_score", 
      "query": { 
        "filtered": { 
          "query": { 
            "bool" : { 
              "should" : [ 
                { 
                  "bool" : { 
                    "must" : { 
                      "has_child": { 
                        "type": "person", 
                        "score_type": "sum", 
                        "query": { 
                          "custom_score": { 
                            "script": "doc['person.age'].value - 50d", 
                            "query": { 
                              "match_all": {} 
                            } 
                          } 
                        } 
                      } 
                    } 
                  } 
                }, 
                { 
                  "bool" : {  
                    "must_not" : { 
                      "has_child": { 
                        "type": "person", 
                        "query": { 
                          "match_all": {} 
                        } 
                      } 
                    } 
                  } 
                } 
              ] 
            } 
          }, 
          "filter": { 
            "bool": { 
              "should": [ 
                { 
                  "terms": { 
                    "room_id": ["1","2","3","4","5"] 
                  } 
                } 
              ] 
            } 
          } 
        } 
      } 
    } 
  } 
}