2015-09-28 37 views
0

我有這樣的文件:通過濾波陣列的最匹配的彈性排序

{ 
    id : 1, 
    title : One, 
    tags : { 
    {id : 1, title : One}, 
    {id : 2, title : Two}, 
    {id : 3, title : Three}, 
    } 
}, 
{ 
    id : 2, 
    title : Two, 
    tags : { 
    {id : 1, title : One}, 
    {id : 4, title : Four}, 
    {id : 5, title : Five}, 
    } 
}, 
{ 
    id : 3, 
    title : Three, 
    tags : { 
    {id : 1, title : One}, 
    {id : 2, title : Two}, 
    {id : 4, title : Four}, 
    } 
} 

我的第一個項目的tags.id過濾:

{ 
    "query": { 
    "filtered": { 
     "filter": { 
     "bool": { 
      "must_not": { 
      "ids": { 
       "values": [1] 
      } 
      }, 
      "should": [ 
      { 
       "term": { 
       "tags.id": "1" 
       } 
      }, 
      { 
       "term": { 
       "tags.id": "2" 
       } 
      }, 
      { 
       "term": { 
       "tags.id": "3" 
       } 
      } 
      ] 
     } 
     } 
    } 
    }, 
    "track_scores": true, 
    "size": 20, 
    "sort": { 
    "_score": "desc" 
    } 
} 

有沒有什麼辦法讓結果通過最匹配排序標籤?在這種情況下,項目三個(2個符合項)應該是第一個,然後是項目兩個(1符合)。
看來,如果我沒有查詢使用過濾器,那麼所有項目的得分是1。

回答

0

這個什麼:

{ 
    "query" : { 
     "bool": { 
      "must_not": { 
       "ids": { 
        "values": [1] 
       } 
      }, 
      "should": [ 
       { 
        "constant_score" : { 
         "filter" : { 
          "term": { 
           "tags.id": "1" 
          } 
         } 
        } 
       }, 
       { 
        "constant_score" : { 
         "filter" : { 
          "term": { 
           "tags.id": "2" 
          } 
         } 
        } 
       }, 
       { 
        "constant_score" : { 
         "filter" : { 
          "term": { 
           "tags.id": "3" 
          } 
         } 
        } 
       } 
      ] 
     } 
    } 
} 

此查詢將確保與ID的記錄= 1是不是對結果和對結果進行排序,從而更加匹配的標籤,結果的結果來之前具有較少的匹配標籤。

根據您在目前爲止提供的描述中查找的內容,我不認爲filtered查詢是必要的。 must_not子句將過濾掉不希望的結果。使用其默認值的bool查詢將處理您想要的排序。

0

很可能@eemp的回答也可以,但我寧願在可能的情況下留下過濾器,所以不會考慮分數計數。所以我移動了tgas過濾器進行查詢。

{ 
    "query": { 
    "filtered": { 
     "filter": { 
     "bool": { 
      "must_not": { 
      "ids": { 
       "values": [1] 
      } 
      } 
     } 
     }, 
     "query": { 
     "bool": { 
      "should": [ 
      { 
       "term": { 
       "tags.id": "1" 
       } 
      }, 
      { 
       "term": { 
       "tags.id": "2" 
       } 
      }, 
      { 
       "term": { 
       "tags.id": "3" 
       } 
      } 
      ] 
     } 
     } 
    } 
    }, 
    "size": 20 
} 
+0

這個id過濾器不會影響早先答案中的分數。我在標籤項查詢周圍添加了constant_score,以便典型的tf-idf評分不會對分數產生影響。因此,您擁有的內容並不總能保證標記匹配更多的結果出現在標記匹配較少的結果之前(可能很少,但取決於數據)。您可以通過在查詢中傳遞「explain」:true來查看此分數,以查看分數的解釋 - 查看詞彙頻率,逆文檔頻率,解釋中的字段標準。 – eemp

+0

好吧:)所以我檢查了你的解決方案,它的工作原理。我不完全理解,但我相信它會更好;)謝謝 – CRONUS