3、对日期和数字添加索引(lucene笔记)

这里我们拷贝之前的工程(lucene_index01)为工程lucene_index02。然后在创建索引和搜索方法上进行改进测试。
相关代码:
IndexUtil.java

package cn.lucene.index;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.StaleReaderException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class IndexUtil {
    private String[] ids = {"1", "2", "3", "4", "5", "6"};
    //下面是邮件
    private String[] emails = {"aa@qq.com", "bb@sina.edu", "cc@yahu.org", "ss@sina.com", "dd@gmail.com", "ee@163.com"};
    //下面是邮件内容
    private String[] content = {
            "welcom to visited the space,I like football", 
            "hello boy, i like someone", 
            "come on baby", 
            "first blood", 
            "I like football,I like football", 
            "my girlfriend is so beatiful, every body like game"
    };
    private int[] attaches = {2,5,6,5,8,4};//附件数量
    //发件人名字
    private String[] names = {"Tom", "Jack", "goudan", "alibaba", "jerry", "kitty"};
    //邮件的日期
    private Date[] dates = null;
    
    private Directory directory = null;
    private Map<String, Float> scores = new HashMap<String, Float>();//新建一个Map,用来存储权值
    
    public IndexUtil() {
        try {
            setDates();//设置日期
            scores.put("qq.com", 2.0f);//如果是"qq.com"结尾的索引则让其权值为2.0,注意:默认是1.0
            scores.put("sina.edu", 1.5f);
            directory = FSDirectory.open(new File("E:/myeclipse/Lucene/index"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //创建索引
    public void index(){
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));
            //此方法可将索引全部清空
            writer.deleteAll();
            Document document = null;
            for(int i = 0; i < ids.length; i++){
                document = new Document();
                //id需要存储,不需要加权、分词,email也需要存储,但不需要分词,有时候也需要加权
                //对于内容,我们不需要存储和加权,但需要分词。而名字需要存储,不需要分词和加权
                //这里我们先不对整型数据进行索引,后面再说
                document.add(new Field("id", ids[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                document.add(new Field("email", emails[i], Field.Store.YES, Field.Index.NOT_ANALYZED));
                document.add(new Field("content", content[i], Field.Store.NO, Field.Index.ANALYZED));
                document.add(new Field("name", names[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                
                //为数字添加索引,第三个参数设置为true表示默认索引
                document.add(new NumericField("attach", Field.Store.YES, true).setIntValue(attaches[i]));
                //为日期添加索引
                document.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));
                
                
                String et = emails[i].substring(emails[i].lastIndexOf("@") + 1);
                System.out.println(et);
                //加入权值
                if(scores.containsKey(et)){
                    document.setBoost(scores.get(et));
                }else{
                    document.setBoost(0.5f);
                }
                writer.addDocument(document);
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(writer != null){
                try {
                    writer.close();
                } catch (CorruptIndexException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //设置日期
    private void setDates(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dates = new Date[ids.length];
            dates[0] = sdf.parse("2015-02-15");
            dates[1] = sdf.parse("2015-03-01");
            dates[2] = sdf.parse("2015-05-18");
            dates[3] = sdf.parse("2015-09-05");
            dates[4] = sdf.parse("2015-12-15");
            dates[5] = sdf.parse("2015-08-29");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    public void search(){
        IndexReader reader;
        try {
            reader = IndexReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            TermQuery query = new TermQuery(new Term("content", "like"));//搜索内容中含有like的
            TopDocs tds = searcher.search(query, 10);
            for(ScoreDoc sd : tds.scoreDocs){
                Document doc = searcher.doc(sd.doc);
                //这里我们获取权值getBoost()的时候发现都是1.0,这是因为这里是获取的一个document,和原来的没有关系。
                //要想看其权值信息,可以使用luke工具
                //而这里的日期需要我们转换成日期格式
                System.out.println("(" + sd.doc + "权值:"+ doc.getBoost() + ")" + doc.get("name") + "[" + doc.get("email") + "]-->" 
                            + doc.get("id") + "-->" + doc.get("attach") + "-->" + doc.get("date"));
                reader.close();
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

说明:

  • 这里我们首先加入日期,同时使用
//为数字添加索引,第三个参数设置为true表示默认索引
document.add(new NumericField("attach", Field.Store.YES, true).setIntValue(attaches[i]));
//为日期添加索引
document.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));

为数字和日期加入索引。

  • 这里要注意的是我们要想查看索引的权值不能使用getBoost方法,不然查出来的权值都是1.0,可以使用luke工具查看。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 构建索引过程 文档是Lucene索引和被搜索的最小单位,一个文档包含一个或者多个域,而域则包含了真正 被搜索 的内...
    RagPanda阅读 3,502评论 0 2
  • 目录结构:1.全文检索 2.Lucene入门3.Lucene进阶 全文检索 一, 生活中的搜索:1.Win...
    CoderZS阅读 1,729评论 0 12
  • 也是项目需要用的框架之一,为了不让自己轻易忘记它,在此记录一系列的lucene学习笔记(基于lucene4.4,I...
    JackFrost_fuzhu阅读 2,025评论 4 27
  • 火车倒着走 思念的有效期限 快到了 风来了,我努力挥动着手 你好吗 是从家乡跑过来的吧 穿梭,停歇 我长着双臂却不...
    李大侠_阅读 161评论 7 5
  • 小时候, 吮着一颗糖果, 连空气都是甜的, 那时的天空那么蓝, 太阳那么暖, 长大后, 即使深吮糖果, 也未必融化...
    洛熙_阅读 269评论 0 0