LuceneIndexManager.java
上传用户:cctqzzy
上传日期:2022-03-14
资源大小:12198k
文件大小:2k
源码类别:

搜索引擎

开发平台:

Java

  1. package chapter5;
  2. import java.util.Date;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.File;
  6. import java.io.FileReader;
  7. import org.apache.lucene.search.Hits;
  8. import org.apache.lucene.search.IndexSearcher;
  9. import org.apache.lucene.search.Query;
  10. import org.apache.lucene.search.TermQuery;
  11. import org.apache.lucene.store.Directory; 
  12. import org.apache.lucene.store.FSDirectory;
  13. import org.apache.lucene.document.Field;
  14. import org.apache.lucene.document.Document;
  15. import org.apache.lucene.index.IndexWriter;
  16. import org.apache.lucene.index.IndexReader;
  17. import org.apache.lucene.index.Term;
  18. import org.apache.lucene.analysis.Analyzer;
  19. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  20. import org.apache.lucene.analysis.SimpleAnalyzer;
  21. public class LuceneIndexManager {
  22. private static String Dest_Index_Path = "D:\workshop\TextIndex1";
  23. private static String Text_File_Path = "D:\workshop\ch2\aximofu.txt";
  24. private static String Text_update_Path = "D:\workshop\ch2\introduction.txt";
  25. public static void main(String[] args) {
  26.       
  27. try {
  28. Date start = new Date();
  29. File file = new File(Text_File_Path);
  30.         FileReader fpReader = new FileReader(file);
  31.         Directory dir = FSDirectory.getDirectory(Dest_Index_Path,false);
  32.         Analyzer TextAnalyzer = new SimpleAnalyzer();
  33.         IndexWriter TextIndex = new IndexWriter(dir,TextAnalyzer,false);
  34.         TextIndex.setUseCompoundFile(true);
  35. Document document = new Document();
  36. Field field_name = new Field("path", file.getName(), 
  37. Field.Store.YES,Field.Index.UN_TOKENIZED);
  38. document.add(field_name);
  39. FileInputStream inputfile=new FileInputStream(file); 
  40. int len=inputfile.available();
  41. byte[] buffer = new byte[len]; 
  42. inputfile.read(buffer);
  43. inputfile.close();
  44. String contentext = new String(buffer);
  45. Field field_content = new Field("content", contentext,
  46.  Field.Store.YES,Field.Index.TOKENIZED);
  47. document.add(field_content);
  48. TextIndex.addDocument(document);
  49. TextIndex.optimize();
  50. TextIndex.close();
  51. Date end = new Date();
  52. long tm_index = end.getTime() - start.getTime(); 
  53. System.out.println("Total Time:(ms)");
  54. System.out.println(tm_index);
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. System.out.println("Index success");
  59. }
  60. }