ITeye博客

lucene3.0学习笔记(二)index

a52071453 · 2012-08-28 11:07 · compass · lucene · Web前端 · Lucene · 搜索引擎 · Markdown

luceneApacheF#

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. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  6. import org.apache.lucene.document.Document;
  7. import org.apache.lucene.document.Field;
  8. import org.apache.lucene.index.IndexWriter;
  9. import org.apache.lucene.store.FSDirectory;
  10. import org.apache.lucene.util.Version;
  11. public class Indexer {
  12. private static String INDEX_DIR = "E:\\test\\index";// 索引存放目录
  13. private static String DATA_DIR = "E:\\test\\file\\";// 文件存放的目录
  14. public static void main(String[] args) throws Exception {
  15. long start = new Date().getTime();
  16. int numIndexed = index(new File(INDEX_DIR), new File(DATA_DIR));// 调用index方法
  17. long end = new Date().getTime();
  18. System.out.println("Indexing " + numIndexed + " files took "
  19. + (end - start) + " milliseconds");
  20. }
  21. /**
  22. * 索引dataDir下的.txt文件,并储存在indexDir下,返回索引的文件数量
  23. * @param indexDir
  24. * @param dataDir
  25. * @return int
  26. * @throws IOException
  27. */
  28. public static int index(File indexDir, File dataDir) throws IOException {
  29. if (!dataDir.exists() || !dataDir.isDirectory()) {
  30. throw new IOException(dataDir
  31. + " does not exist or is not a directory");
  32. }
  33. IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir),
  34. new StandardAnalyzer(Version.LUCENE_CURRENT), true,
  35. IndexWriter.MaxFieldLength.LIMITED);
  36. indexDirectory(writer, dataDir);// 调用indexDirectory方法
  37. int numIndexed = writer.numDocs();//当前索引中文档的个数
  38. writer.optimize();
  39. writer.close();
  40. return numIndexed;
  41. }
  42. /**
  43. * 循环遍历目录下的所有.txt文件并进行索引
  44. * @param writer
  45. * @param dir
  46. * @throws IOException
  47. */
  48. private static void indexDirectory(IndexWriter writer, File dir)
  49. throws IOException {
  50. File[] files = dir.listFiles();
  51. for (int i = 0; i < files.length; i++) {
  52. File f = files[i];
  53. if (f.isDirectory()) {
  54. indexDirectory(writer, f); // recurse
  55. } else if (f.getName().endsWith(".txt")) {
  56. indexFile(writer, f);
  57. }
  58. }
  59. }
  60. /**
  61. * 对单个txt文件进行索引
  62. * @param writer
  63. * @param f
  64. * @throws IOException
  65. */
  66. private static void indexFile(IndexWriter writer, File f)
  67. throws IOException {
  68. if (f.isHidden() || !f.exists() || !f.canRead()) {
  69. return;
  70. }
  71. System.out.println("Indexing " + f.getCanonicalPath());
  72. Document doc = new Document();//针对参数文件建立索引文档
  73. doc.add(new Field("contents", new FileReader(f)));
  74. doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,
  75. Field.Index.ANALYZED));
  76. writer.addDocument(doc);//在writer中加入此文档
  77. }
  78. }
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. public class Searcher {
  13. private static String INDEX_DIR = "E:\\test\\index\\";// 索引所在的路径
  14. private static String KEYWORD = "接受";// 关键词
  15. private static int TOP_NUM = 100;// 显示前100条结果
  16. public static void main(String[] args) throws Exception {
  17. File indexDir = new File(INDEX_DIR);
  18. if (!indexDir.exists() || !indexDir.isDirectory()) {
  19. throw new Exception(indexDir
  20. + " does not exist or is not a directory.");
  21. }
  22. search(indexDir, KEYWORD);// 调用search方法进行查询
  23. }
  24. /**
  25. * 查询
  26. *
  27. * @param indexDir
  28. * @param q
  29. * @throws Exception
  30. */
  31. public static void search(File indexDir, String q) throws Exception {
  32. IndexSearcher is = new IndexSearcher(FSDirectory.open(indexDir), true);// read-only
  33. String field = "contents";
  34. QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,
  35. new StandardAnalyzer(Version.LUCENE_CURRENT));
  36. Query query = parser.parse(q);
  37. TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM,
  38. false);
  39. long start = new Date().getTime();// start time
  40. is.search(query, collector);
  41. ScoreDoc[] hits = collector.topDocs().scoreDocs;
  42. System.out.println(hits.length);
  43. for (int i = 0; i < hits.length; i++) {
  44. Document doc = is.doc(hits[i].doc);// new method is.doc()
  45. System.out.println(doc.getField("filename") + "   "
  46. + hits[i].toString() + " ");
  47. }
  48. long end = new Date().getTime();// end time
  49. System.out.println("Found " + collector.getTotalHits()
  50. + " document(s) (in " + (end - start)
  51. + " milliseconds) that matched query '" + q + "':");
  52. }
  53. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。