1、应业务需求,需要按照用户输入的关键字匹配位置(从左至右)显示排序结果,
由于是solr小白,从网上搜索相关知识,解决方案如下:
1、创建自定义查询分析器类 public class DynamicQParser extends QParser(可换成Solr已实现Parser)
2、创建自定义查询分析器插件,构建查询分析器
public class DynamicQParserPlugin extends QParserPlugin{
@Override
public QParser createParser(String qstr, SolrParams localParams,
SolrParams params, SolrQueryRequest req) {
// TODO Auto-generated method stub
return new DynamicQParser(qstr, localParams, params, req);
}
}
3、创建自定义Query
public class DynamicQuery extends CustomScoreQuery {
/**
*
*/
private static final long serialVersionUID = 1L;
public DynamicQuery(Query subQuery) {
super(subQuery);
// TODO Auto-generated constructor stub
}
private String queryStr;
@Override
protected DynamicScoreProvider getCustomScoreProvider(IndexReader reader)
throws IOException {
/**
* 自定评分的步骤 创建一个类继承于CustomScoreProvider 覆盖customScore方法
*/
DynamicScoreProvider dScoreProvider=new DynamicScoreProvider(reader);
dScoreProvider.setQueryStr(this.getQueryStr());
return dScoreProvider;
}
public String getQueryStr() {
return queryStr;
}
public void setQueryStr(String queryStr) {
this.queryStr = queryStr;
}
4、创建自定义QueryProvider
public class DynamicScoreProvider extends CustomScoreProvider {
private static final Log log = LogFactory.getLog(DynamicScoreProvider.class);
String[] names=null;
String[] favCounts=null;
public DynamicScoreProvider(IndexReader reader) {
super(reader);
try {
names = FieldCache.DEFAULT.getStrings(reader, "name");
favCounts= FieldCache.DEFAULT.getStrings(reader, "favCount");
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("get filecache error!", e);
}
// TODO Auto-generated constructor stub
}
private String queryStr;
@Override
public float customScore(int doc, float subQueryScore, float valSrcScore)
throws IOException {
// return super.customScore(doc, subQueryScore, valSrcScore);
String name = names[doc];
String favCount = favCounts[doc];
if (name == null || queryStr == null || name.length() == 0
|| queryStr.length() == 0) {
return super.customScore(doc, subQueryScore, valSrcScore);
}
int position = name.indexOf(queryStr);
if (position >= 0) {
if(queryStr.length()==name.length()){
float favCountScore=StringUtil.nullToFloat(favCount) / 1000f;
float dynicScore = 90000.0f
+ (favCountScore>=1000.0f?1000.0f:favCountScore);
return dynicScore;
}else{
float favCountScore=StringUtil.nullToFloat(favCount) / 1000f;
float dynicScore = 10000f * (1 / (position + 1f))
+ (favCountScore>=1000.0f?1000.0f:favCountScore);
return dynicScore;
}
} else {
return super.customScore(doc, subQueryScore, valSrcScore);
}
}
public String getQueryStr() {
return queryStr;
}
public void setQueryStr(String queryStr) {
this.queryStr = queryStr;
}
5.在solrconfig.xml引入QParserPlugin
<queryParser name="dynamic" class="***.***.***.DynamicQParserPlugin"/>
并在requestHandler配置中<defType>dynamic</defType>