`

lucene学习笔记

    博客分类:
  • java
阅读更多
Lucene 其实很简单的,它最主要就是做两件事:建立索引和进行搜索。利用Lucene搜索前先要建立词库,也是所说的“建立索引”。这样Lucene才会“认识”这些词。
Lucene 建立索引需要用到如下几个类:

IndexWriter:lucene中最重要的的类之一,它主要是用来将文档加入索引,同时控制索引过程中的一些参数使用。

Analyzer:分析器,主要用于分析搜索引擎遇到的各种文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

Directory:索引存放的位置;lucene提供了两种索引存放的位置,一种是磁盘,一种是内存。一般情况将索引放在磁盘上;相应地lucene提供了FSDirectory和RAMDirectory两个类。

Document:文档;Document相当于一个要进行索引的单元,任何可以想要被索引的文件都必须转化为Document对象才能进行索引。


Field:字段。

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;

public class TextFileIndexer {

	/**利用现有文件中的文章创建词库(建立索引)
	 * @param args
	 */
	public static void main(String[] args) throws Exception{

	/* 指明要索引文件夹的位置,这里是C盘的S文件夹下 */  
       File fileDir = new File("c:\\s");  
 
       /* 这里放索引文件的位置 */  
       File indexDir = new File("c:\\index");  
       Analyzer luceneAnalyzer = new StandardAnalyzer();  
       IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,true);
       File[] textFiles = fileDir.listFiles();  
       long startTime = new Date().getTime();  
         
       //增加document到索引去  
       for (int i = 0; i < textFiles.length; i++) {  
           if (textFiles[i].isFile()&& textFiles[i].getName().endsWith(".txt")) {
                   
               System.out.println("File " + textFiles[i].getCanonicalPath()+ "正在被索引....");  
               String fileData = readFile(textFiles[i].getCanonicalPath(),"UTF-8");
               System.out.println(fileData);  
               Document document = new Document();  
               Field fieldPath = new Field("path", textFiles[i].getPath(),Field.Store.YES, Field.Index.NO);
               Field fieldBody = new Field("body", fileData, Field.Store.YES, Field.Index.TOKENIZED,Field.TermVector.WITH_POSITIONS_OFFSETS);  
               document.add(fieldPath);  
               document.add(fieldBody);  
               indexWriter.addDocument(document);  
           }  
       }  
       //optimize()方法是对索引进行优化  
       indexWriter.optimize();  
       indexWriter.close();  
         
       //测试一下索引的时间  
       long endTime = new Date().getTime();  
       System.out.println("这花费了"+ (endTime - startTime)+ " 毫秒来把文档增加到索引里面去!"+ indexDir.getPath());
	}
	
	public static String readFile(String FileName, String charset) throws IOException {
	           
        BufferedReader br = new BufferedReader(new InputStreamReader(  
                new FileInputStream(FileName), charset));  
        String line = null;  
        StringBuffer temp = new StringBuffer();  
          
        while ((line = br.readLine()) != null) {  
            temp.append(line);
        }  
        br.close();  
        return temp.toString();  
    }  

}


有了词库我们就可以开始搜索了,搜索要用到下面几个类:

IndexSearcher:是lucene中最基本的检索工具,所有的检索都会用到IndexSearcher工具;

Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。

QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。

Hits:在搜索完成之后,需要把搜索结果返回并显示给用户,只有这样才算是完成搜索的目的。在lucene中,搜索的结果的集合是用Hits类的实例来表示的。
Hits对象是搜索结果的集合 主要有下面几个方法:
1.length() ,   记录有多少条结果返回
2.doc(n)       返回第n个记录
3.id(in)         返回第n个记录的Document ID
4.score(n)       第n个记录的相关度(积分)


import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

public class TestQuery {

	/**进行搜索 
	 * @param args
	 */
	public static void main(String[] args) throws IOException, ParseException{
		// TODO Auto-generated method stub

		Hits hits = null;  
        String keywords = "中华";  
        Query query = null;  
        IndexSearcher searcher = new IndexSearcher("c:\\index");  
  
        Analyzer analyzer = new StandardAnalyzer();  
        try {  
            QueryParser qp = new QueryParser("body", analyzer);  
            query = qp.parse(keywords);  
        } catch (ParseException e) {  
        }  
        if (searcher != null) {
            hits = searcher.search(query);
            if (hits.length() > 0) {  
                System.out.println("找到:" + hits.length() + " 个结果!");  
            }  
        }  
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics