2012-10-26 81 views
2

考慮到有一個標籤集合的帖子的流行示例,假設我們希望每個標籤不僅僅是一個字符串,而是一個字符串的元組,表示所述標籤的強度的雙倍值。彈性搜索 - 標記強度(嵌套/子文檔提升)

如何將一個查詢職位和得分這些基於標籤的強度之和(假設我們正在尋找標籤名稱具體條款)

回答

8

它可以通過索引標籤爲nested documents來完成,然後使用nested查詢與custom score查詢相結合。在下面的示例中,術語查詢查找匹配標籤,自定義分數查詢使用「標籤」文檔的「wight」字段的值作爲分數,嵌套查詢將這些分數的總和用作頂級文檔的最終分數。

curl -XDELETE 'http://localhost:9200/test-idx' 
echo 
curl -XPUT 'http://localhost:9200/test-idx' -d '{ 
    "mappings": { 
     "doc": { 
      "properties": { 
       "title": { "type": "string" }, 
       "tags": { 
        "type": "nested", 
        "properties": { 
         "tag": { "type": "string", "index": "not_analyzed" }, 
         "weight": { "type": "float" } 
        } 
       } 
      } 
     } 
    } 
}' 
echo 
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '{ 
    "title": "1", 
    "tags": [{ 
     "tag": "A", 
     "weight": 1 
    }, { 
     "tag": "B", 
     "weight": 2 
    }, { 
     "tag": "C", 
     "weight": 4 
    }] 
} 
' 
echo 
curl -XPUT 'http://localhost:9200/test-idx/doc/2' -d '{ 
    "title": "2", 
    "tags": [{ 
     "tag": "B", 
     "weight": 2 
    }, { 
     "tag": "C", 
     "weight": 3 
    }] 
} 
' 
echo 
curl -XPUT 'http://localhost:9200/test-idx/doc/3' -d '{ 
    "title": "3", 
    "tags": [{ 
     "tag": "B", 
     "weight": 2 
    }, { 
     "tag": "D", 
     "weight": 4 
    }] 
} 
' 
echo 
curl -XPOST 'http://localhost:9200/test-idx/_refresh' 
echo 
# Example with custom script (slower but more flexable) 
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true' -d '{ 
    "query" : { 
     "nested": { 
      "path": "tags", 
      "score_mode": "total", 
      "query": { 
       "custom_score": { 
        "query": { 
         "terms": { 
          "tag": ["A", "B", "D"], 
          "minimum_match" : 1 
         } 
        }, 
        "script" : "doc['\''weight'\''].value" 
       } 
      } 
     } 
    }, 
    "fields": [] 
}' 
echo