实现方法有3个:
- 在建索引的时候设置boost,这个值会写入文件,建索引时有额外的性能开销;
- 在查询的时候指定boost,这个值不会写入文件,查询时指定任意字段的boost值,适用与一个索引库的多种查询场景,但查询时有额外性能开销;
- (推想)前两者结合使用,如绝大多数都需要标题优先,那么建索引时可指定标题boost为2,其他场景可在查询时指定标题boost为0.5,中和建索引时的设置。
这里仅演示第二种方法:
id | title | content | 默认得分 | 指定标题boost值为2后得分 |
108 | test | 开发笔记 开发笔记 开发笔记 开发笔记 开发笔记 | 1.6093808 | 1.0178617 |
107 | 开发笔记 | 1.439474 | 1.8208065 |
指定方法:
这时doc 107已经排在上边了:
debug query效果:
找到了方法,我们不难获得在solrj中的实现:
package demo.service; import java.util.Iterator; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import base.util.ConfigUtil; public class SolrService { private static Logger log = Logger.getLogger(SolrService.class); private static HttpSolrServer solrServer; static { solrServer = new HttpSolrServer(ConfigUtil.getValue("solr.url")); solrServer.setConnectionTimeout(5000); } public static void main(String[] args) { SolrQuery query = new SolrQuery(); query.setQuery("title: 开发笔记^2 OR content:开发笔记"); QueryResponse rsp = null; try { rsp = solrServer.query(query); } catch (SolrServerException e) { log.error("Boost查询时遇到错误:", e); } SolrDocumentList docs = rsp.getResults(); Iterator<SolrDocument> iter = docs.iterator(); while (iter.hasNext()) { SolrDocument doc = iter.next(); String idStr = doc.getFieldValue("id").toString(); int id = Integer.parseInt(idStr); String title = doc.getFieldValue("title").toString(); String content = doc.getFieldValue("content").toString(); System.out.println("id:"+id+" title:"+title+" content:"+content); } } }
注:因为我们想设置的boost针对某字段,那么在查询在时候就不能再用拷贝字段了。
其实还有一个使用拷贝字段也能排序的方法,供大家参考:
Solr copyField使用场景及与之对应的改变搜索排序的方法
如过此内容对您有帮助,欢迎以点击广告的形式来支持我们,但请每天不要多于一次,否则可能被识别恶意点击,导致封号。