`

lucene3.0学习笔记(二)index

阅读更多
1。IndexWriter的学习

Java代码 复制代码 收藏代码
  1. IndexWriter writer = new IndexWriter(FSDirectory.open("E:\\test\\index"),   
  2.                 new StandardAnalyzer(Version.LUCENE_CURRENT), true,   
  3.                 IndexWriter.MaxFieldLength.LIMITED);  
IndexWriter writer = new IndexWriter(FSDirectory.open("E:\\test\\index"),
				new StandardAnalyzer(Version.LUCENE_CURRENT), true,
				IndexWriter.MaxFieldLength.LIMITED);


IndexWriter类的构造函数共四个参数:
(1).Directory dir:FSDirectory:表示对文件系统目录的操作;RAMDirectory:内存中的目录操作,一般FSDirectory用的较多。
(2).Analyzer a: 用来对文档进行词法分析和语言处理(StandardAnalyzer对中文分词的支持不是很好)
(3).boolean b :如果没有该索引就创建,否则覆盖原有索引
(4).

2.document的学习

    Document是lucene自己定义的一种文件格式,lucene使用docement来代替对应的物理文件或者保存在数据库中的数据。因此Document只能作为数据源在Lucene中的数据存贮的一种文件形式。
  Document只是负责收集数据源,因为不同的文件可以构建同一个Document。只要用户将不同的文件创建成Document类型的文件,Lucene就能快速找到查找并且使用他们。
  对于一个Document文件,可以同时增加多个Field。Lucene中对于每个数据源是使用Field类来表示的。多个Field组成一个Document,多个Document组成一个索引文件。

Java代码 复制代码 收藏代码
  1. Document doc = new Document();   
  2.         doc.add(new Field("contents"new FileReader(f)));   
  3.         doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,   
  4.                 Field.Index.ANALYZED));   
  5.         writer.addDocument(doc);  
Document doc = new Document();
		doc.add(new Field("contents", new FileReader(f)));
		doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,
				Field.Index.ANALYZED));
		writer.addDocument(doc);




3。
Java代码 复制代码 收藏代码
  1. int numIndexed = writer.numDocs();//当前索引中文档的个数   
  2.         writer.optimize();   
  3.         writer.close();  
int numIndexed = writer.numDocs();//当前索引中文档的个数
		writer.optimize();
		writer.close();



4。搜索

搜索过程如下:

创建IndexSearcher准备进行搜索
创建Analyer用来对查询语句进行词法分析和语言处理
创建QueryParser用来对查询语句进行语法分析
QueryParser调用parser进行语法分析,形成查询语法树,放到Query中
IndexSearcher调用search对查询语法树Query进行搜索,得到结果TopScoreDocCollector


Java代码 复制代码 收藏代码
  1. IndexSearcher is = new IndexSearcher(FSDirectory.open(indexDir), true);// read-only   
  2.         String field = "contents";   
  3.         QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,   
  4.                 new StandardAnalyzer(Version.LUCENE_CURRENT));   
  5.         Query query = parser.parse(q);   
  6.         TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM,   
  7.                 false);   
  8.         long start = new Date().getTime();// start time   
  9.         is.search(query, collector);  
IndexSearcher is = new IndexSearcher(FSDirectory.open(indexDir), true);// read-only
		String field = "contents";
		QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,
				new StandardAnalyzer(Version.LUCENE_CURRENT));
		Query query = parser.parse(q);
		TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM,
				false);
		long start = new Date().getTime();// start time
		is.search(query, collector);







附上例子:
(1)创建索引
Java代码 复制代码 收藏代码
  1. import java.io.File;   
  2. import java.io.FileReader;   
  3. import java.io.IOException;   
  4. import java.util.Date;   
  5.   
  6. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  7. import org.apache.lucene.document.Document;   
  8. import org.apache.lucene.document.Field;   
  9. import org.apache.lucene.index.IndexWriter;   
  10. import org.apache.lucene.store.FSDirectory;   
  11. import org.apache.lucene.util.Version;   
  12.   
  13. public class Indexer {   
  14.     private static String INDEX_DIR = "E:\\test\\index";// 索引存放目录   
  15.     private static String DATA_DIR = "E:\\test\\file\\";// 文件存放的目录   
  16.   
  17.     public static void main(String[] args) throws Exception {   
  18.         long start = new Date().getTime();   
  19.         int numIndexed = index(new File(INDEX_DIR), new File(DATA_DIR));// 调用index方法   
  20.         long end = new Date().getTime();   
  21.         System.out.println("Indexing " + numIndexed + " files took "  
  22.                 + (end - start) + " milliseconds");   
  23.     }   
  24.   
  25.     /**  
  26.      * 索引dataDir下的.txt文件,并储存在indexDir下,返回索引的文件数量  
  27.      * @param indexDir  
  28.      * @param dataDir  
  29.      * @return int  
  30.      * @throws IOException  
  31.      */  
  32.     public static int index(File indexDir, File dataDir) throws IOException {   
  33.         if (!dataDir.exists() || !dataDir.isDirectory()) {   
  34.             throw new IOException(dataDir   
  35.                     + " does not exist or is not a directory");   
  36.         }   
  37.         IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir),   
  38.                 new StandardAnalyzer(Version.LUCENE_CURRENT), true,   
  39.                 IndexWriter.MaxFieldLength.LIMITED);   
  40.         indexDirectory(writer, dataDir);// 调用indexDirectory方法   
  41.         int numIndexed = writer.numDocs();//当前索引中文档的个数   
  42.         writer.optimize();   
  43.         writer.close();   
  44.         return numIndexed;   
  45.     }   
  46.   
  47.     /**  
  48.      * 循环遍历目录下的所有.txt文件并进行索引  
  49.      * @param writer  
  50.      * @param dir  
  51.      * @throws IOException  
  52.      */  
  53.     private static void indexDirectory(IndexWriter writer, File dir)   
  54.             throws IOException {   
  55.         File[] files = dir.listFiles();   
  56.         for (int i = 0; i < files.length; i++) {   
  57.             File f = files[i];   
  58.             if (f.isDirectory()) {   
  59.                 indexDirectory(writer, f); // recurse   
  60.             } else if (f.getName().endsWith(".txt")) {   
  61.                 indexFile(writer, f);   
  62.             }   
  63.         }   
  64.     }   
  65.   
  66.     /**  
  67.      * 对单个txt文件进行索引  
  68.      * @param writer  
  69.      * @param f  
  70.      * @throws IOException  
  71.      */  
  72.     private static void indexFile(IndexWriter writer, File f)   
  73.             throws IOException {   
  74.         if (f.isHidden() || !f.exists() || !f.canRead()) {   
  75.             return;   
  76.         }   
  77.         System.out.println("Indexing " + f.getCanonicalPath());   
  78.         Document doc = new Document();//针对参数文件建立索引文档   
  79.         doc.add(new Field("contents"new FileReader(f)));   
  80.         doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,   
  81.                 Field.Index.ANALYZED));   
  82.         writer.addDocument(doc);//在writer中加入此文档   
  83.     }   
  84.   
  85. }  
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;

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.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Indexer {
	private static String INDEX_DIR = "E:\\test\\index";// 索引存放目录
	private static String DATA_DIR = "E:\\test\\file\\";// 文件存放的目录

	public static void main(String[] args) throws Exception {
		long start = new Date().getTime();
		int numIndexed = index(new File(INDEX_DIR), new File(DATA_DIR));// 调用index方法
		long end = new Date().getTime();
		System.out.println("Indexing " + numIndexed + " files took "
				+ (end - start) + " milliseconds");
	}

	/**
	 * 索引dataDir下的.txt文件,并储存在indexDir下,返回索引的文件数量
	 * @param indexDir
	 * @param dataDir
	 * @return int
	 * @throws IOException
	 */
	public static int index(File indexDir, File dataDir) throws IOException {
		if (!dataDir.exists() || !dataDir.isDirectory()) {
			throw new IOException(dataDir
					+ " does not exist or is not a directory");
		}
		IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir),
				new StandardAnalyzer(Version.LUCENE_CURRENT), true,
				IndexWriter.MaxFieldLength.LIMITED);
		indexDirectory(writer, dataDir);// 调用indexDirectory方法
		int numIndexed = writer.numDocs();//当前索引中文档的个数
		writer.optimize();
		writer.close();
		return numIndexed;
	}

	/**
	 * 循环遍历目录下的所有.txt文件并进行索引
	 * @param writer
	 * @param dir
	 * @throws IOException
	 */
	private static void indexDirectory(IndexWriter writer, File dir)
			throws IOException {
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory()) {
				indexDirectory(writer, f); // recurse
			} else if (f.getName().endsWith(".txt")) {
				indexFile(writer, f);
			}
		}
	}

	/**
	 * 对单个txt文件进行索引
	 * @param writer
	 * @param f
	 * @throws IOException
	 */
	private static void indexFile(IndexWriter writer, File f)
			throws IOException {
		if (f.isHidden() || !f.exists() || !f.canRead()) {
			return;
		}
		System.out.println("Indexing " + f.getCanonicalPath());
		Document doc = new Document();//针对参数文件建立索引文档
		doc.add(new Field("contents", new FileReader(f)));
		doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,
				Field.Index.ANALYZED));
		writer.addDocument(doc);//在writer中加入此文档
	}

}



2。搜索

Java代码 复制代码 收藏代码
  1. import java.io.File;   
  2. import java.util.Date;   
  3. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  4. import org.apache.lucene.document.Document;   
  5. import org.apache.lucene.queryParser.QueryParser;   
  6. import org.apache.lucene.search.IndexSearcher;   
  7. import org.apache.lucene.search.Query;   
  8. import org.apache.lucene.search.ScoreDoc;   
  9. import org.apache.lucene.search.TopScoreDocCollector;   
  10. import org.apache.lucene.store.FSDirectory;   
  11. import org.apache.lucene.util.Version;   
  12.   
  13. public class Searcher {   
  14.     private static String INDEX_DIR = "E:\\test\\index\\";// 索引所在的路径   
  15.     private static String KEYWORD = "接受";// 关键词   
  16.     private static int TOP_NUM = 100;// 显示前100条结果   
  17.   
  18.     public static void main(String[] args) throws Exception {   
  19.         File indexDir = new File(INDEX_DIR);   
  20.         if (!indexDir.exists() || !indexDir.isDirectory()) {   
  21.             throw new Exception(indexDir   
  22.                     + " does not exist or is not a directory.");   
  23.         }   
  24.         search(indexDir, KEYWORD);// 调用search方法进行查询   
  25.     }   
  26.   
  27.     /**  
  28.      * 查询  
  29.      *   
  30.      * @param indexDir  
  31.      * @param q  
  32.      * @throws Exception  
  33.      */  
  34.     public static void search(File indexDir, String q) throws Exception {   
  35.         IndexSearcher is = new IndexSearcher(FSDirectory.open(indexDir), true);// read-only   
  36.         String field = "contents";   
  37.         QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,   
  38.                 new StandardAnalyzer(Version.LUCENE_CURRENT));   
  39.         Query query = parser.parse(q);   
  40.         TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM,   
  41.                 false);   
  42.         long start = new Date().getTime();// start time   
  43.         is.search(query, collector);   
  44.         ScoreDoc[] hits = collector.topDocs().scoreDocs;   
  45.         System.out.println(hits.length);   
  46.         for (int i = 0; i < hits.length; i++) {   
  47.             Document doc = is.doc(hits[i].doc);// new method is.doc()   
  48.             System.out.println(doc.getField("filename") + "   "  
  49.                     + hits[i].toString() + " ");   
  50.         }   
  51.         long end = new Date().getTime();// end time   
  52.         System.out.println("Found " + collector.getTotalHits()   
  53.                 + " document(s) (in " + (end - start)   
  54.                 + " milliseconds) that matched query '" + q + "':");   
  55.     }   
  56. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics