Lucene的搜索結(jié)果默認(rèn)按相關(guān)度排序,這個相關(guān)度排序是基于內(nèi)部的Score和DocID,Score又基于關(guān)鍵詞的內(nèi)部評分和做索引時的boost。默認(rèn)Score高的排前面,如果Score一樣,再按索引順序,先索引的排前面。那么有人問了,如果我要先索引的排后面怎么辦呢?隱士研究了源碼后發(fā)現(xiàn)這是相當(dāng)簡單的事情。以下代碼基于Lucene 2.0。
看Sort的默認(rèn)構(gòu)造函數(shù),相關(guān)度就是SortField.FIELD_SCORE和SortField.FIELD_DOC的組合。
java 代碼
/**
* Sorts by computed relevance. This is the same sort criteria as calling
* {@link Searcher#search(Query) Searcher#search()}without a sort criteria,
* only with slightly more overhead.
*/
public Sort() {
this(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC });
}
那么該如何構(gòu)造我們需要的SortField呢?請看SortField的一個構(gòu)造函數(shù),有一個參數(shù)reverse可供我們調(diào)整結(jié)果集的順序。
java 代碼
/** Creates a sort, possibly in reverse, by terms in the given field with the
* type of term values explicitly given.
* @param field Name of field to sort by. Can be
*
* @param type Type of values in the terms.
* @param reverse True if natural order should be reversed.
*/
public SortField (String field, int type, boolean reverse) {
this.field = (field != null) ? field.intern() : field;
this.type = type;
this.reverse = reverse;
}
由此可見,只要構(gòu)造一個SortField[]就可以實現(xiàn)我們要的功能,請看:
java 代碼
// 評分降序,評分一樣時后索引的排前面
new SortField[] { SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true) }
// 評分升序,評分一樣時后索引的排前面,呵呵,此為最不相關(guān)的排前面,挺有趣的
new SortField[] { new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true) }
只要將此SortField[]作為參數(shù)傳入Sort的構(gòu)造函數(shù)得到Sort的一個instance,將此instance傳入searcher.search(query, sort)即可得到了期望的結(jié)果。
看Sort的默認(rèn)構(gòu)造函數(shù),相關(guān)度就是SortField.FIELD_SCORE和SortField.FIELD_DOC的組合。
java 代碼
/**
* Sorts by computed relevance. This is the same sort criteria as calling
* {@link Searcher#search(Query) Searcher#search()}without a sort criteria,
* only with slightly more overhead.
*/
public Sort() {
this(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC });
}
那么該如何構(gòu)造我們需要的SortField呢?請看SortField的一個構(gòu)造函數(shù),有一個參數(shù)reverse可供我們調(diào)整結(jié)果集的順序。
java 代碼
/** Creates a sort, possibly in reverse, by terms in the given field with the
* type of term values explicitly given.
* @param field Name of field to sort by. Can be
null
if*
type
is SCORE or DOC.* @param type Type of values in the terms.
* @param reverse True if natural order should be reversed.
*/
public SortField (String field, int type, boolean reverse) {
this.field = (field != null) ? field.intern() : field;
this.type = type;
this.reverse = reverse;
}
由此可見,只要構(gòu)造一個SortField[]就可以實現(xiàn)我們要的功能,請看:
java 代碼
// 評分降序,評分一樣時后索引的排前面
new SortField[] { SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true) }
// 評分升序,評分一樣時后索引的排前面,呵呵,此為最不相關(guān)的排前面,挺有趣的
new SortField[] { new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true) }
只要將此SortField[]作為參數(shù)傳入Sort的構(gòu)造函數(shù)得到Sort的一個instance,將此instance傳入searcher.search(query, sort)即可得到了期望的結(jié)果。