ElasticSearch多層nested查詢、nested過濾排除非結果內容

CodingAnHour發表於2020-11-29

示例mappings 下 fragment 是nested型別,fragment.tagTree也是巢狀型別

"mappings" : {
    "properties" : {
      "content" : {
        "type" : "text",
        "analyzer" : "ik_max_custom",
        "search_analyzer" : "ik_smart"
      },
      "id" : {
        "type" : "keyword"
      },
      "fragment" : {
        "type" : "nested",
        "properties" : {
          "content" : {
            "type" : "text",
            "analyzer" : "ik_max_custom",
            "search_analyzer" : "ik_smart"
          },
          "id" : {
            "type" : "integer"
          },
          "tagTree" : {
            "type" : "nested",
            "properties" : {
              "tag_id" : {
                "type" : "integer"
              },
              "tag_name" : {
                "type" : "keyword"
              },
              "tag_path" : {
                "type" : "keyword"
              }
            }
          },
          "title" : {
            "type" : "text",
            "analyzer" : "ik_max_word",
            "search_analyzer" : "ik_smart"
          }
        }
      }
    }
  }

查詢多層巢狀

  • 示例
    是否計算得分需自行考慮
    {
    	"constant_score": {
    		"filter": {
    			"nested": {
    				"path": "fragment",
    				"query": {
    					"nested": {
    						"path": "fragment.tagTree",
    						"query": {
    							"terms": {
    								"fragment.tagTree.tag_id": [927597]
    							}
    						}
    					}
    				}
    			}
    		},
    		"boost": 0
    	}
    }
    

巢狀過濾結果值

  • 例如一個文件,根據fragment.tagTree.tag_id=930365查詢,預期結果是隻有fragment.id=111,不想要fragment.id=222,因為都在一個文件中,如果不過濾那麼結果中會包含id =1這個文件的所有內容

    {
      "fragment" : [
        {
          "tagTree" : [
            {
              "tag_name" : "北京",
              "tag_id" : 930365,
              "tag_path" : "930364"
            }
          ],
          "id" : 111,
          "content" : "1111",
        },
        {
          "tagTree" : [ ],
          "id" : 222,
          "content" : "2222"
        }
      ],
      "id" : 1,
      "title" : "示例結果"
    }
    
  • 操作

    • “inner_hits”:可以實現如上結果
    • ““inner_hits”: {“size”:0}”:可以實現分類
    • 一個查詢中同一個欄位只能有一個inner_hits
    {
    	"constant_score": {
    		"filter": {
    			"nested": {
    				"path": "fragment",
    				"query": {
    					"nested": {
    						"path": "fragment.tagTree",
    						"query": {
    							"terms": {
    								"fragment.tagTree.tag_id": [111]
    							}
    						}
    					}
    				},
                 "inner_hits": {}
    			}
    		},
    		"boost": 0
    	}
    }
    

在這裡插入圖片描述

相關文章