1. 程式人生 > >elasticsearch中的精準文字位置匹配

elasticsearch中的精準文字位置匹配

在elasticsearch中,將長篇幅的文件劃分為樹形結構的段落後,有助於文字的精準位置匹配,

例如:原來的content是這樣的:

content = "一、大標題 \n 1. 一級標題 \n 1> 二級標題"

段落劃分後,是如下這樣:

content = {
    paras: [
        {
            "text": "大標題",
             "sub_paras": [
                     {
                         "text": "一級標題",
                         "sub_paras": [
                              {
                                  "text": "二級標題"
                                }
                          ]
                      }
              ]
        }
    ]
}


如果在查詢時,只想定位到文字所在的段落,可以這樣查詢:

            "query": {
                "bool": {
                    "should": [
                        {"nested": {
                            "path": "content.paras",
                            "query": {
                                "term": {
                                    "content.paras.text": "哈哈"
                                }
                            },
                            "inner_hits": {
                                "name": "inner_hit_p"
                            }
                        }},
                        {"nested": {
                            "path": "content.paras.sub_paras",
                            "query": {
                                "term": {
                                    "content.paras.sub_paras.text": "哈哈"
                                }
                            },
                            "inner_hits": {
                                "name": "inner_hit_sub_p"
                            }
                        }},
                        {"nested": {
                            "path": "content.paras.sub_paras.sub_paras",
                            "query": {
                                "term": {
                                    "content.paras.sub_paras.sub_paras.text": "哈哈"
                                }
                            },
                            "inner_hits": {
                                "name": "inner_hit_sub_sub_p"
                            }
                        }},
                    ]
                }
            }