Solr查询时设置字段的boost值,改变默认打分排序

实现方法有3个:

  1. 在建索引的时候设置boost,这个值会写入文件,建索引时有额外的性能开销;
  2. 在查询的时候指定boost,这个值不会写入文件,查询时指定任意字段的boost值,适用与一个索引库的多种查询场景,但查询时有额外性能开销;
  3. (推想)前两者结合使用,如绝大多数都需要标题优先,那么建索引时可指定标题boost为2,其他场景可在查询时指定标题boost为0.5,中和建索引时的设置。

这里仅演示第二种方法:

idtitlecontent默认得分指定标题boost值为2后得分
108test开发笔记 开发笔记 开发笔记 开发笔记 开发笔记1.60938081.0178617
107开发笔记 1.4394741.8208065

指定方法:
Solr查询指定字段boost值

这时doc 107已经排在上边了:
Solr查询指定字段boost值后的排序

debug query效果:
Solr查询指定字段boost值,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使用场景及与之对应的改变搜索排序的方法

如过此内容对您有帮助,欢迎以点击广告的形式来支持我们,但请每天不要多于一次,否则可能被识别恶意点击,导致封号。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值