当前位置: 首页 > news >正文

Lucene5学习之FunctionQuery功能查询

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 我猜,大家最大的疑问就是:不是已经有那么多Query实现类吗,为什么又设计一个FunctionQuery,它的设计初衷是什么,或者说它是用来解决什么问题的?我们还是来看看源码里是怎么解释FunctionQuery的:

意思就是基于ValueSource来返回每个文档的评分即valueSourceScore,那ValueSource又是怎么东东?接着看看ValueSource源码里的注释说明:

 ValueSource是用来根据指定的IndexReader来实例化FunctionValues的,那FunctionValues又是啥?

 从接口中定义的函数可以了解到,FunctionValues提供了根据文档ID获取各种类型的DocValuesField域的值的方法,那这些接口返回的域值用来干嘛的,翻看FunctionQuery源码,你会发现:

从上面几张图,我们会发现,FunctionQuery构造的时候需要提供一个ValueSource,然后在FunctionQuery的内部类AllScorer中通过valueSource实例化了FunctionValues,然后在计算FunctionQuery评分的时候通过FunctionValues获取DocValuesField的域值,域值和FunctionQuery的权重值相乘得到FunctionQuery的评分。

float score = qWeight * vals.floatVal(doc);

 那这里ValueSource又起什么作用呢,为什么不直接让FunctionQuery来构建FunctionValues,而是要引入一个中间角色ValueSource呢?

因为FunctionQuery应该线程安全的,即允许多次查询共用同一个FunctionQuery实例,如果让FunctionValues直接依赖FunctionQuery,那可能会导致某个线程通过FunctionValues得到的docValuesField域值被另一个线程修改了,所以引入了一个ValuesSource,让每个FunctionQuery对应一个ValueSource,再让ValueSource去生成FunctionValues,因为docValuesField域值的正确性会影响到最后的评分。另外出于缓存原因,因为每次通过FunctionValues去加载docValuesField的域值,其实还是通过IndexReader去读取的,这就意味着有磁盘IO行为,磁盘IO次数可是程序性能杀手哦,所以设计CachingDoubleValueSource来包装ValueSource.不过CachingDoubleValueSource貌似还处在捐献模块,不知道下个版本是否会考虑为ValueSource添加Cache功能。

ValueSource构造很简单:

public DoubleFieldSource(String field) {  
    super(field);  
  } 

你只需要提供一个域的名称即可,不过要注意,这里的域必须是DocValuesField,不能是普通的StringField,TextField,IntField,FloatField,LongField。

那FunctionQuery可以用来解决什么问题?举个例子:比如你索引了N件商品,你希望通过某个关键字搜索时,出来的结果优先按最近上架的商品显示,再按商品和搜索关键字匹配度高低降序显示,即你希望最近上架的优先靠前显示,评分高的靠前显示。

下面是一个FunctionQuery使用示例,模拟类似这样的场景:

书籍的出版日期越久远,其权重因子会按天数一天天衰减,从而实现让新书自动靠前显示

import java.io.IOException;  
import java.util.Map;  
  
import org.apache.lucene.index.DocValues;  
import org.apache.lucene.index.LeafReaderContext;  
import org.apache.lucene.index.NumericDocValues;  
import org.apache.lucene.queries.function.FunctionValues;  
import org.apache.lucene.queries.function.valuesource.FieldCacheSource;  
  
import com.yida.framework.lucene5.util.score.ScoreUtils;  
  
/** 
 * 自定义ValueSource[计算日期递减时的权重因子,日期越近权重值越高] 
 * @author Lanxiaowei 
 * 
 */  
public class DateDampingValueSouce extends FieldCacheSource {  
    //当前时间  
    private static long now;  
    public DateDampingValueSouce(String field) {  
        super(field);  
        //初始化当前时间  
        now = System.currentTimeMillis();  
    }  
    /** 
     * 这里Map里存的是IndexSeacher,context.get("searcher");获取 
     */  
    @Override  
    public FunctionValues getValues(Map context, LeafReaderContext leafReaderContext)  
            throws IOException {  
        final NumericDocValues numericDocValues = DocValues.getNumeric(leafReaderContext.reader(), field);    
        return new FunctionValues() {  
            @Override  
            public float floatVal(int doc) {  
                return ScoreUtils.getNewsScoreFactor(now, numericDocValues,doc);  
            }  
            @Override  
            public int intVal(int doc) {  
                return (int) ScoreUtils.getNewsScoreFactor(now, numericDocValues,doc);  
            }  
            @Override  
            public String toString(int doc) {  
                return description() + '=' + intVal(doc);  
            }  
        };  
    }  
      
}  
import org.apache.lucene.index.NumericDocValues;  
  
import com.yida.framework.lucene5.util.Constans;  
  
/** 
 * 计算衰减因子[按天为单位] 
 * @author Lanxiaowei 
 * 
 */  
public class ScoreUtils {  
    /**存储衰减因子-按天为单位*/  
    private static float[] daysDampingFactor = new float[120];  
    /**降级阀值*/  
    private static float demoteboost = 0.9f;  
    static {  
        daysDampingFactor[0] = 1;  
        //第一周时权重降级处理  
        for (int i = 1; i < 7; i++) {  
            daysDampingFactor[i] = daysDampingFactor[i - 1] * demoteboost;  
        }  
        //第二周  
        for (int i = 7; i < 31; i++) {             
            daysDampingFactor[i] = daysDampingFactor[i / 7 * 7 - 1]  
                    * demoteboost;  
        }  
        //第三周以后  
        for (int i = 31; i < daysDampingFactor.length; i++) {  
            daysDampingFactor[i] = daysDampingFactor[i / 31 * 31 - 1]  
                    * demoteboost;  
        }  
    }  
      
    //根据相差天数获取当前的权重衰减因子  
    private static float dayDamping(int delta) {  
        float factor = delta < daysDampingFactor.length ? daysDampingFactor[delta]  
                : daysDampingFactor[daysDampingFactor.length - 1];  
        System.out.println("delta:" + delta + "-->" + "factor:" + factor);  
        return factor;  
    }  
      
    public static float getNewsScoreFactor(long now, NumericDocValues numericDocValues, int docId) {  
        long time = numericDocValues.get(docId);  
        float factor = 1;  
        int day = (int) (time / Constans.DAY_MILLIS);  
        int nowDay = (int) (now / Constans.DAY_MILLIS);  
        System.out.println(day + ":" + nowDay + ":" + (nowDay - day));  
        // 如果提供的日期比当前日期小,则计算相差天数,传入dayDamping计算日期衰减因子  
        if (day < nowDay) {  
            factor = dayDamping(nowDay - day);  
        } else if (day > nowDay) {  
            //如果提供的日期比当前日期还大即提供的是未来的日期  
            factor = Float.MIN_VALUE;  
        } else if (now - time <= Constans.HALF_HOUR_MILLIS && now >= time) {  
            //如果两者是同一天且提供的日期是过去半小时之内的,则权重因子乘以2  
            factor = 2;  
        }  
        return factor;  
    }  
      
    public static float getNewsScoreFactor(long now, long time) {  
        float factor = 1;  
        int day = (int) (time / Constans.DAY_MILLIS);  
        int nowDay = (int) (now / Constans.DAY_MILLIS);  
        // 如果提供的日期比当前日期小,则计算相差天数,传入dayDamping计算日期衰减因子  
        if (day < nowDay) {  
            factor = dayDamping(nowDay - day);  
        } else if (day > nowDay) {  
            //如果提供的日期比当前日期还大即提供的是未来的日期  
            factor = Float.MIN_VALUE;  
        } else if (now - time <= Constans.HALF_HOUR_MILLIS && now >= time) {  
            //如果两者是同一天且提供的日期是过去半小时之内的,则权重因子乘以2  
            factor = 2;  
        }  
        return factor;  
    }  
    public static float getNewsScoreFactor(long time) {  
        long now = System.currentTimeMillis();  
        return getNewsScoreFactor(now, time);  
    }  
}  
import java.io.IOException;  
import java.nio.file.Paths;  
import java.text.DateFormat;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
import org.apache.lucene.analysis.Analyzer;  
import org.apache.lucene.analysis.standard.StandardAnalyzer;  
import org.apache.lucene.document.Document;  
import org.apache.lucene.document.Field;  
import org.apache.lucene.document.Field.Store;  
import org.apache.lucene.document.LongField;  
import org.apache.lucene.document.NumericDocValuesField;  
import org.apache.lucene.document.TextField;  
import org.apache.lucene.index.DirectoryReader;  
import org.apache.lucene.index.IndexReader;  
import org.apache.lucene.index.IndexWriter;  
import org.apache.lucene.index.IndexWriterConfig;  
import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
import org.apache.lucene.index.Term;  
import org.apache.lucene.queries.CustomScoreQuery;  
import org.apache.lucene.queries.function.FunctionQuery;  
import org.apache.lucene.search.IndexSearcher;  
import org.apache.lucene.search.ScoreDoc;  
import org.apache.lucene.search.Sort;  
import org.apache.lucene.search.SortField;  
import org.apache.lucene.search.TermQuery;  
import org.apache.lucene.search.TopDocs;  
import org.apache.lucene.store.Directory;  
import org.apache.lucene.store.FSDirectory;  
/** 
 * FunctionQuery测试 
 * @author Lanxiaowei 
 * 
 */  
public class FunctionQueryTest {  
    private static final DateFormat formate = new SimpleDateFormat("yyyy-MM-dd");  
    public static void main(String[] args) throws Exception {  
        String indexDir = "C:/lucenedir-functionquery";  
        Directory directory = FSDirectory.open(Paths.get(indexDir));  
          
        //System.out.println(0.001953125f * 100000000 * 0.001953125f / 100000000);  
        //创建测试索引[注意:只用创建一次,第二次运行前请注释掉这行代码]  
        //createIndex(directory);  
          
          
        IndexReader reader = DirectoryReader.open(directory);  
        IndexSearcher searcher = new IndexSearcher(reader);  
        //创建一个普通的TermQuery  
        TermQuery termQuery = new TermQuery(new Term("title", "solr"));  
        //根据可以计算日期衰减因子的自定义ValueSource来创建FunctionQuery  
        FunctionQuery functionQuery = new FunctionQuery(new DateDampingValueSouce("publishDate"));   
        //自定义评分查询[CustomScoreQuery将普通Query和FunctionQuery组合在一起,至于两者的Query评分按什么算法计算得到最后得分,由用户自己去重写来干预评分]  
        //默认实现是把普通查询评分和FunctionQuery高级查询评分相乘求积得到最终得分,你可以自己重写默认的实现  
        CustomScoreQuery customScoreQuery = new CustomScoreQuery(termQuery, functionQuery);  
        //创建排序器[按评分降序排序]  
        Sort sort = new Sort(new SortField[] {SortField.FIELD_SCORE});  
        TopDocs topDocs = searcher.search(customScoreQuery, null, Integer.MAX_VALUE, sort,true,false);  
        ScoreDoc[] docs = topDocs.scoreDocs;  
          
        for (ScoreDoc scoreDoc : docs) {  
            int docID = scoreDoc.doc;  
            Document document = searcher.doc(docID);  
            String title = document.get("title");  
            String publishDateString = document.get("publishDate");  
            System.out.println(publishDateString);  
            long publishMills = Long.valueOf(publishDateString);  
            Date date = new Date(publishMills);  
            publishDateString = formate.format(date);  
            float score = scoreDoc.score;  
            System.out.println(docID + "  " + title + "                    " +   
                publishDateString + "            " + score);  
        }  
          
        reader.close();  
        directory.close();  
    }  
      
    /** 
     * 创建Document对象 
     * @param title              书名 
     * @param publishDateString  书籍出版日期 
     * @return 
     * @throws ParseException 
     */  
    public static Document createDocument(String title,String publishDateString) throws ParseException {  
        Date publishDate = formate.parse(publishDateString);  
        Document doc = new Document();  
        doc.add(new TextField("title",title,Field.Store.YES));  
        doc.add(new LongField("publishDate", publishDate.getTime(),Store.YES));  
        doc.add(new NumericDocValuesField("publishDate", publishDate.getTime()));  
        return doc;  
    }  
      
    //创建测试索引  
    public static void createIndex(Directory directory) throws ParseException, IOException {  
        Analyzer analyzer = new StandardAnalyzer();  
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);  
        indexWriterConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);  
        IndexWriter writer = new IndexWriter(directory, indexWriterConfig);  
          
        //创建测试索引  
        Document doc1 = createDocument("Lucene in action 2th edition", "2010-05-05");  
        Document doc2 = createDocument("Lucene Progamming", "2008-07-11");  
        Document doc3 = createDocument("Lucene User Guide", "2014-11-24");  
        Document doc4 = createDocument("Lucene5 Cookbook", "2015-01-09");  
        Document doc5 = createDocument("Apache Lucene API 5.0.0", "2015-02-25");  
        Document doc6 = createDocument("Apache Solr 4 Cookbook", "2013-10-22");  
        Document doc7 = createDocument("Administrating Solr", "2015-01-20");  
        Document doc8 = createDocument("Apache Solr Essentials", "2013-08-16");  
        Document doc9 = createDocument("Apache Solr High Performance", "2014-06-28");  
        Document doc10 = createDocument("Apache Solr API 5.0.0", "2015-03-02");  
          
        writer.addDocument(doc1);  
        writer.addDocument(doc2);  
        writer.addDocument(doc3);  
        writer.addDocument(doc4);  
        writer.addDocument(doc5);  
        writer.addDocument(doc6);  
        writer.addDocument(doc7);  
        writer.addDocument(doc8);  
        writer.addDocument(doc9);  
        writer.addDocument(doc10);  
        writer.close();  
    }  
}  

 运行测试结果如图:

转载于:https://my.oschina.net/liuyuantao/blog/1477873

相关文章:

  • linux 系统函数之 (dirname, basename)【转】
  • [转] Java关键字final、static使用总结
  • thrift-TFileTransport
  • linux配置nfs步骤及心得
  • idea工具使用 修改resource无法立即生效 需要重启
  • 并查集专题: HDU1232畅通工程
  • 深入理解7816(3)-----关于T=0 【转】
  • 安装aix 6.1系统的完整教程,初学者都可以学会
  • iOS 颜色设置看我就够了
  • [webpack] devtool里的7种SourceMap[转]
  • 【Unity笔记】用代码动态修改Animator状态机的状态
  • ES6解构赋值
  • 给Lisp程序员的Python简介
  • 《thinking in Java》--第二章一切都是对象
  • C# 添加、修改和删除PDF书签
  • python3.6+scrapy+mysql 爬虫实战
  • bearychat的java client
  • docker-consul
  • iOS 颜色设置看我就够了
  • log4j2输出到kafka
  • Python 基础起步 (十) 什么叫函数?
  • Redis 懒删除(lazy free)简史
  • Transformer-XL: Unleashing the Potential of Attention Models
  • 第13期 DApp 榜单 :来,吃我这波安利
  • 基于组件的设计工作流与界面抽象
  • 猫头鹰的深夜翻译:JDK9 NotNullOrElse方法
  • 删除表内多余的重复数据
  • 微信开放平台全网发布【失败】的几点排查方法
  • 用Visual Studio开发以太坊智能合约
  • 在electron中实现跨域请求,无需更改服务器端设置
  • mysql 慢查询分析工具:pt-query-digest 在mac 上的安装使用 ...
  • RDS-Mysql 物理备份恢复到本地数据库上
  • Salesforce和SAP Netweaver里数据库表的元数据设计
  • ​queue --- 一个同步的队列类​
  • (06)Hive——正则表达式
  • (13)Hive调优——动态分区导致的小文件问题
  • (LeetCode) T14. Longest Common Prefix
  • (MATLAB)第五章-矩阵运算
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (免费领源码)python#django#mysql校园校园宿舍管理系统84831-计算机毕业设计项目选题推荐
  • (七)Java对象在Hibernate持久化层的状态
  • (一)80c52学习之旅-起始篇
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • (转)Android学习系列(31)--App自动化之使用Ant编译项目多渠道打包
  • (转)C#调用WebService 基础
  • (轉貼)《OOD启思录》:61条面向对象设计的经验原则 (OO)
  • .NET 线程 Thread 进程 Process、线程池 pool、Invoke、begininvoke、异步回调
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .NET国产化改造探索(一)、VMware安装银河麒麟
  • .Net接口调试与案例
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .Net通用分页类(存储过程分页版,可以选择页码的显示样式,且有中英选择)
  • ;号自动换行
  • @data注解_SpringBoot 使用WebSocket打造在线聊天室(基于注解)