最近需要对公司的产品搜索功能做一步改动,搜索到的结果首先按照是否有库存进行排序,然后再按照销量。由于库存量也是一个整数,如果直接按照库存量进行倒序排序的话,是不符合要求的,Lucene也没有支持我们这种特殊的业务需求,但是可以通过扩展的方式进行改写。
 
 
public class EmptyStockComparatorSource extends FieldComparatorSource {
@Override
public FieldComparator<?> newComparator(String fieldname, int numHits, int sortPos, boolean reversed)
throws IOException {
return new LongComparator(numHits, fieldname, 0L);
} public static class LongComparator extends FieldComparator.NumericComparator<Long> {
private final long[] values;
private long bottom;
private long topValue; /**
* Creates a new comparator based on {@link Long#compare} for {@code numHits}.
* When a document has no value for the field, {@code missingValue} is substituted.
*/
public LongComparator(int numHits, String field, Long missingValue) {
super(field, missingValue);
values = new long[numHits];
} @Override
protected void doSetNextReader(LeafReaderContext context) throws IOException {
currentReaderValues = getNumericDocValues(context, field);
if (missingValue != null) {
docsWithField = getDocsWithValue(context, field);
// optimization to remove unneeded checks on the bit interface:
if (docsWithField instanceof Bits.MatchAllBits) {
docsWithField = null;
}
} else {
docsWithField = null;
}
} @Override
public int compare(int slot1, int slot2) {
return Long.compare(values[slot1], values[slot2]);
} @Override
public int compareBottom(int doc) {
// TODO: there are sneaky non-branch ways to compute
// -1/+1/0 sign
long v2 = currentReaderValues.get(doc);
// Test for v2 == 0 to save Bits.get method call for
// the common case (doc has value and value is non-zero):
if (docsWithField != null && v2 == 0 && !docsWithField.get(doc)) {
v2 = missingValue;
} return Long.compare(bottom, v2);
} @Override
public void copy(int slot, int doc) {
long v2 = currentReaderValues.get(doc);
// Test for v2 == 0 to save Bits.get method call for
// the common case (doc has value and value is non-zero):
if (docsWithField != null && v2 == 0 && !docsWithField.get(doc)) {
v2 = missingValue;
} values[slot] = v2 > 0L ? 1L : 0L;
} @Override
public void setBottom(final int bottom) {
this.bottom = values[bottom];
} @Override
public void setTopValue(Long value) {
topValue = value;
} @Override
public Long value(int slot) {
return Long.valueOf(values[slot]) ;
} @Override
public int compareTop(int doc) {
long docValue = currentReaderValues.get(doc);
// Test for docValue == 0 to save Bits.get method call for
// the common case (doc has value and value is non-zero):
if (docsWithField != null && docValue == 0 && !docsWithField.get(doc)) {
docValue = missingValue;
}
return Long.compare(topValue, docValue);
}
}
}
 
其中LongComparator直接从lucene源码中copy出来,只需要做些许修改即可,最主要的修改就是copy(int slot, int doc)方法,在复制比较值得过程中,将所有存在库存的值都视为1,否则视为0,这样排序的结果就是我们所期待的。
 
我们用到的测试用例:
 
Directory directory1 = FSDirectory.open(Paths.get(
"/Users/xxx/develop/tools/solr-5.5.0/server/solr/product/data/index"));
DirectoryReader directoryReader1 = DirectoryReader.open(directory1);
IndexSearcher searcher1 = new IndexSearcher(directoryReader1);
Sort sort1 = new Sort(new SortField("psfixstock", new EmptyStockComparatorSource(), true),
new SortField("salesVolume", SortField.Type.INT, true)); TopFieldDocs topDocs1 = searcher1.search(new TermQuery(new Term("gender_text", "女士")), 10, sort1);
for (ScoreDoc scoreDoc : topDocs1.scoreDocs) {
int doc = scoreDoc.doc;
Document document = searcher1.doc(doc);
System.out.println(String.format("docId=%s, psfixstock=%s, salesVolumn=%s", doc, document.get("psfixstock"), document.get("salesVolume")));
}
 
在排序时,需要将其加入至Sort对象中,但执行的时候出现错误,显示docvalues的类型不正确:
 
Exception in thread "main" java.lang.IllegalStateException: unexpected docvalues type NONE for field 'psfixstock' (expected=NUMERIC). Use UninvertingReader or index with docvalues.
at org.apache.lucene.index.DocValues.checkField(DocValues.java:208)
at org.apache.lucene.index.DocValues.getNumeric(DocValues.java:227)
at org.apache.lucene.search.FieldComparator$NumericComparator.getNumericDocValues(FieldComparator.java:167)
at com.zp.solr.handler.component.EmptyStockComparatorSource$LongComparator.doSetNextReader(EmptyStockComparatorSource.java:36)
at org.apache.lucene.search.SimpleFieldComparator.getLeafComparator(SimpleFieldComparator.java:36)
at org.apache.lucene.search.FieldValueHitQueue.getComparators(FieldValueHitQueue.java:183)
at org.apache.lucene.search.TopFieldCollector$SimpleFieldCollector.getLeafCollector(TopFieldCollector.java:164)
at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:812)
at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:535)
at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:744)
at org.apache.lucene.search.IndexSearcher.searchAfter(IndexSearcher.java:729)
at org.apache.lucene.search.IndexSearcher.searchAfter(IndexSearcher.java:671)
at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:577)
at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:627)
at com.zp.solr.handler.component.EmptyStockSortingTest.main(EmptyStockSortingTest.java:57)
经过一番查找,找到原因,参考文档:http://qindongliang.iteye.com/blog/2297280,我们搜索所使用到的字段没有设置对应的docType。如果在solr中,需要进行手动排序的字段,设置docValues=“true”,并进行重新索引(使用full-import方式):
 

<field name="psfixstock" type="tint" indexed="true" stored="true" multiValued="false" docValues="true" />
 
必须要重新建立索引才可以正常运行。注意,此时Solr与Elastic Search采取的方案有所不同,Solr默认docValues=false,而ES则相反,使用Doc索引方式会对性能产生一定的影响,要谨慎使用。
 
对于lucene中,需要将添加document中增加数字类型Field:NumericDocValuesField,否则出现上面的错误,
 
document.add(new NumericDocValuesField("stock", stock));
 
最终的排序结果已经按照我们的需要进行了:
 
docId=2629, psfixstock=98391, salesVolumn=4685
docId=305, psfixstock=991, salesVolumn=14
docId=16762, psfixstock=3, salesVolumn=12
docId=22350, psfixstock=993, salesVolumn=10
docId=29021, psfixstock=11076, salesVolumn=10
docId=3635, psfixstock=61, salesVolumn=6
docId=4111, psfixstock=1104, salesVolumn=5
docId=10608, psfixstock=4395, salesVolumn=5
docId=4874, psfixstock=4975, salesVolumn=4
docId=4911, psfixstock=6, salesVolumn=4
docId=15071, psfixstock=998, salesVolumn=4
docId=4837, psfixstock=9, salesVolumn=3
docId=4860, psfixstock=1002, salesVolumn=3
docId=3749, psfixstock=2240, salesVolumn=2
docId=4109, psfixstock=1493, salesVolumn=2
docId=15068, psfixstock=1000, salesVolumn=2
docId=25901, psfixstock=11110, salesVolumn=2
docId=3688, psfixstock=21, salesVolumn=1
docId=4912, psfixstock=17, salesVolumn=1
docId=5035, psfixstock=2, salesVolumn=1
docId=11835, psfixstock=8, salesVolumn=1
docId=12044, psfixstock=1, salesVolumn=1
docId=13508, psfixstock=2, salesVolumn=1
docId=20019, psfixstock=1, salesVolumn=1
docId=20884, psfixstock=100000, salesVolumn=1
docId=22620, psfixstock=1, salesVolumn=1
docId=24128, psfixstock=1, salesVolumn=1
docId=0, psfixstock=2, salesVolumn=0
docId=9, psfixstock=1, salesVolumn=0
docId=11, psfixstock=4, salesVolumn=0
docId=15, psfixstock=3, salesVolumn=0
docId=20, psfixstock=4, salesVolumn=0
docId=23, psfixstock=2, salesVolumn=0
docId=24, psfixstock=5, salesVolumn=0
docId=25, psfixstock=7, salesVolumn=0
docId=35, psfixstock=2, salesVolumn=0
docId=53, psfixstock=2, salesVolumn=0
 
 
 

Lucene根据字段进行自定义搜索扩展的更多相关文章

  1. 搜索引擎系列 ---lucene简介 创建索引和搜索初步

    一.什么是Lucene? Lucene最初是由Doug Cutting开发的,2000年3月,发布第一个版本,是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎 :Lucene得名于Doug妻子 ...

  2. 自定义和扩展 SharePoint 2010 Server 功能区

    了解构成 SharePoint 2010 服务器功能区的组件以及如何通过演练两个功能区自定义项方案来自定义功能区. 适用范围: Microsoft SharePoint Foundation 2010 ...

  3. lucene简介 创建索引和搜索初步

    lucene简介 创建索引和搜索初步 一.什么是Lucene? Lucene最初是由Doug Cutting开发的,2000年3月,发布第一个版本,是一个全文检索引擎的架构,提供了完整的查询引擎和索引 ...

  4. Angular4.x 自定义搜索组件

    Angular4 随笔(三)  ——自定义搜索组件 1.简介 本组件主要是实现了搜索功能,主要是通过父子组件传值实现. 基本逻辑: 1.创建一个搜索组件,如:ng g component  searc ...

  5. Elasticsearch7.X 入门学习第七课笔记-----Mapping多字段与自定义Analyzer

    原文:Elasticsearch7.X 入门学习第七课笔记-----Mapping多字段与自定义Analyzer 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处 ...

  6. paip.lucene 4.3 中文语义搜索最佳实践

    paip.lucene 4.3 中文语义搜索最佳实践 首先一个问题是要不要使用lucene 自带的分词器...我觉得最好不使用哪自带的分词器.效果还凑火,就是不好控制... 先使用ik,ict,mms ...

  7. Qt之自定义搜索框

    简述 关于搜索框,大家都经常接触.例如:浏览器搜索.Windows资源管理器搜索等. 当然,这些对于Qt实现来说毫无压力,只要思路清晰,分分钟搞定. 方案一:调用QLineEdit现有接口 void ...

  8. 【Qt】Qt之自定义搜索框【转】

    简述 关于搜索框,大家都经常接触.例如:浏览器搜索.Windows资源管理器搜索等. 当然,这些对于Qt实现来说毫无压力,只要思路清晰,分分钟搞定. 简述 效果 细节分析 Coding 源码下载 效果 ...

  9. Android自定义View——自定义搜索框(SearchView)

    Android自定义View——自定义搜索框(SearchView) http://www.apkbus.com/android-142064-1-1.html

随机推荐

  1. codeforces 11 B.Jumping Jack 想法题

    B. Jumping Jack Jack is working on his jumping skills recently. Currently he's located at point zero ...

  2. python 十进制数转二进制数

    def convertToBinary(n): """Function to print binary number for the input decimal usin ...

  3. thinkphp5中的配置如何使用

    thinkphp5中的配置如何使用 一.总结 一句话总结:先加载配置,然后读取配置即可 加载配置 读取配置 Config::load(APP_PATH.'fry_config.php');\\加载配置 ...

  4. tcpdump 实现原理【整理】

    参考:http://blog.sina.com.cn/s/blog_523491650101au7f.html 一.tcpdump 对于本机中进程的系统行为调用跟踪,strace是一个很好的工具,而在 ...

  5. 伸展树的基本操作——以【NOI2004】郁闷的出纳员为例

    前两天老师讲了伸展树……虽然一个月以前自己就一直在看平衡树这一部分的书籍,也仔细地研读过伸展树地操作代码,但是就是没写过程序……(大概也是在平衡树的复杂操作和长代码面前望而生畏了)但是今天借着老师布置 ...

  6. WebLogic发布S2SH应用时提示ClassNotFoundException: org.hibernate.hql.ast.HqlToken异常

    使用Spring+hibernate如下 <properties> <!--定义方言.fetch深度.是否显示sql--> <property name="hi ...

  7. Django 之 分页

    1. urs.py # coding:utf-8 from django.conf.urls import url import views urlpatterns = [ # 分页练习 url(r' ...

  8. CUDA Samples: dot product(使用零拷贝内存)

    以下CUDA sample是分别用C++和CUDA实现的点积运算code,CUDA包括普通实现和采用零拷贝内存实现两种,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程C ...

  9. 如何从MTK机器的NVRAM中获取WIFI mac地址

    在MTK的机器中,如果不用特定的工具烧写MAC地址,在开机后打开WIFI后会显示: "NVRAM WARNING: Err=0x10" 这就是没有烧写mac地址的原因,所以每次打开 ...

  10. Android系统服务(一)解析ActivityManagerService(AMS)

    相关文章 Android系统启动流程系列 Android应用进程系列 Android深入四大组件系列 前言 此前在Android系统启动流程.应用进程以及深入四大组件这三个系列文章中,都提及到了AMS ...