ElasticSearch query to search parent docs and consider that at least has one child

时间:2016-05-11 11:34:58

标签: php laravel elasticsearch

I have implemented parent child relation ship in elasticsearch, parent type name is participant_tests and its child type name is participant_test_question_answers, I have some search conditions for parent type as bellow:

query": {
  "bool":{
    "should":[
      {
        "range":{
          "created_at":{
             "gte":"2016-01-01",
             "lte":"2016-05-11",
             "format":"YYYY-MM-dd"
           }
         }
       },
       {
         "terms":{
            "created_by.id":["1000001"]
         }
       },
       {
         "multi_match":{
            "query":"test human time",
             "fields":[
                "course_tests.course_id.course_no",
                 "participant_test_questions.answer_text",
                 "participants.first_name",
                 "participants.last_name",
                 "participants.promote_unique_user_id","result"
              ],
              "operator":"OR"
            }
          }
        ]
     }
  }

Above query return result but if I want to check has_child no result returned. I have added this lines after bool class.

"has_child": {
  "type": "participant_test_question_answers",
  "min_children": 1,
  "query": {
    "match_all": {}
  }
}

1 个答案:

答案 0 :(得分:1)

尝试此查询:

{
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "created_at": {
              "gte": "2016-01-01",
              "lte": "2016-05-11",
              "format": "YYYY-MM-dd"
            }
          }
        },
        {
          "terms": {
            "created_by.id": [
              "1000001"
            ]
          }
        },
        {
          "multi_match": {
            "query": "test human time",
            "fields": [
              "course_tests.course_id.course_no",
              "participant_test_questions.answer_text",
              "participants.first_name",
              "participants.last_name",
              "participants.promote_unique_user_id",
              "result"
            ],
            "operator": "OR"
          }
        }
      ],
      "must": [
        {
          "has_child": {
            "type": "participant_test_question_answers",
            "min_children": 1,
            "query": {
              "match_all": {}
            }
          }
        }
      ]
    }
  }
}