Trouble with has_parent query containing scripted function_score

后端 未结 2 1548
时光取名叫无心
时光取名叫无心 2020-12-19 19:17

I have two document types, in a parent-child relationship:

\"myParent\" : {
  \"properties\" : {
    \"weight\" : {
      \"type\" : \"double\"
    }
  }
}

         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 20:02

    I think the problem is that you are trying to score child documents based on a field in the parent document and that the function score should really be the other way round.

    To solve the problem my idea would be to store the parent/child relation and the score with the child documents. Then you would filter for child documents and score them according to the weight in the child document.

    An example:

    "myParent" : {
        "properties" : {
            "name" : {
                "type" : "string"
            }
        }
    }
    
    "myChild" : {
        "_parent" : {
            "type" : "myParent"
        },
        "_routing" : {
            "required" : true
        },
        "properties": {
            "weight" : {
                "type" : "double"
            }
        }
    }
    

    Now you could use a has_parent filter to select all child documents that have a certain parent and then score them using the function score:

    {
        "query": {
            "filtered": {
                "query": {
                    "function_score" : {
                        "script_score" : {
                            "script" : "_score * doc['weight'].value"
                        }
                    }
                },
                "filter": {
                    "has_parent": {
                        "parent_type": "myParent",
                        "query": {
                            "term": {
                                "name": "something"
                            }
                        }
                    }
                }
            }
        }
    }
    

    So if parent documents were blog posts and child comments, then you could filter all posts and score the comments based on weight. I doubt that scoring childs based on parents is possible though I might be wrong :)

    Disclaimer: 1st post to stack overflow...

提交回复
热议问题