Lucene使用之构建索引、查询

package cn.zhf.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class TextFileIndexer {
    public static void main(String[] args) throws IOException {
        // 被索引的文件
        File dirFile = new File("c:/users/zhf/desktop/toindex");
        // 索引结果文件
        File indexFile = new File("c:/users/zhf/desktop/indexed");
        //索引文件的存放位置,由子类获取真实路径
        Directory directory = FSDirectory.open(indexFile);
        // 标准分析器
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,
                analyzer);
        iwc.setOpenMode(OpenMode.CREATE);
        //写索引:是索引过程的核心组件,这个类负责创建新索引或打开已有的索引。提供索引文件的写入操作
        IndexWriter iw = new IndexWriter(directory, iwc);
        File[] files = dirFile.listFiles();//要索引的文件列表
        long startTime = new Date().getTime();

        //将索引文件添加到结果目录中(indexFile)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile() && files[i].getName().endsWith(".txt")) {
                System.out.println(files[i].getCanonicalPath() + "正在被索引");
                String temp = readFile(files[i].getCanonicalPath(), "GBK");
                System.out.println(temp);
                //域的集合
                Document document = new Document();
                //创建路径域
                Field fieldPath = new Field("path", files[i].getPath(),
                        Field.Store.YES, Field.Index.NO);
                //创建文本域
                Field fieldBody = new Field("body", temp, Field.Store.YES,
                        Field.Index.ANALYZED,
                        Field.TermVector.WITH_POSITIONS_OFFSETS);
                document.add(fieldPath);
                document.add(fieldBody);
                iw.addDocument(document);
            }
        }
        iw.close();
        long endTime = new Date().getTime();
        System.out.println("索引时间是: " + (startTime - endTime)
                + dirFile.getPath());

    }

    // 读取文件内容,将文件内容拼成一个字符串返回
    public static String readFile(String fileName, String charset)
            throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(new File(fileName))));
        String str = "";
        String ret = "";
        while ((str = br.readLine()) != null)
            ret += str;
        br.close();
        return ret;
    }

}
package cn.zhf.lucene;


import java.io.File;
import java.io.IOException;


import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;


public class TestQuery {


  public static void main(String[] args) throws CorruptIndexException, IOException, ParseException {
    String indexed = "c:/users/zhf/desktop/indexed";
    //用于搜索IndexWriter创建的索引
    IndexReader ir = IndexReader.open(FSDirectory.open(new File(indexed)));
    IndexSearcher is = new IndexSearcher(ir);
    ScoreDoc[] hits = null;
//    String keyword = "lucene";
//    Query query = null;
//    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
//    QueryParser qp = new QueryParser(Version.LUCENE_36,"body",analyzer);
//    query = qp.parse(keyword);
    //Term是搜索对象的基本单元,与Field类似
    Query q = new TermQuery(new Term("body","lucene"));
    if(is != null){
      //一个指针容器,指向前N个排名的搜索结果
      TopDocs top = is.search(q, 10);//返回最多10条记录
      hits = top.scoreDocs;
      if(hits.length>0)
        System.out.println("找到了 "+hits.length+" 条记录。");
      for(ScoreDoc d : hits){
        Document d1 = is.doc(d.doc);
        System.out.println(d1.get("path"));
        Explanation explanation = is.explain(q, d.doc);
        System.out.println("------------");
        System.out.println(explanation.toString());
      }
      is.close();
    }
  }


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值