分享

Lucene3.3、Lucene3.4中文分词——庖丁解牛分词实例

 梧桐话 2013-02-17

Lucene3.3、Lucene3.4中文分词——庖丁解牛分词实例

分类: Java 搜索 小代码 374人阅读 评论(0) 收藏 举报
如果是Lucene3.0以上版本首先我们需要下载庖丁解牛最新源码并生成jar文件,我已经将最新源码和jar文件上传了:http://download.csdn.net/detail/a_2cai/3671164 ,可以下载,或者下载一个SVN客户端从http://code.google.com/p/paoding/检出最新的trunk源码,本地编译下。

当我们有了最新的庖丁解牛分词包和lucene3.3或Lucene3.4即可以运行以下示例:(我已将源码和使用到的文件以及生成的索引文件上传了:http://download.csdn.net/detail/a_2cai/3671272

为了简单起见我建了一个txt文件:内容如下(就如一个数据库的不同条目)

172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::移动侦测::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVU::移动::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVUC::移动侦测::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::Lucene测试::2011/9/1172.7.14.198::172.7.19.71::遮挡一下::遮挡报警::2011/9/1172.7.14.198::172.7.19.71::遮经挡报警::遮挡报警::2011/9/1172.7.14.198::172.7.19.71::多域测试::移动侦测::2011/9/1172.7.14.198::172.7.19.71::多域测试::移动侦测::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::移动侦测::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVU::磁盘已满::2011/8/31172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::移动侦测::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::移动侦测::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVU::移动::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVUC::移动侦测::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::Lucene测试::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::遮挡报警::2011/9/1172.7.14.198::172.7.19.71::DS-2DF1-4010020090611AACH290005648WC::移动侦测指的是将一个汉字序列切分成一个一个单独的词::2011/9/1172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVU::查询方式总体来讲分两类:查询API查询和语法查询::2011/8/31172.7.14.198::172.7.24.51::DS-9016HF-S1620100809BBRR401273372WCVU::对于查询时的Field名一定要大小写对应,默认情况下要查询的关键字要转成小写,这在lucene建索引的时候做过特殊处理::2011/8/31

建索引:

   

  1. public static void testIndex() throws Exception{  
  2.         String itemFilePath = "TestDocs/luceneDemoTest.txt";  
  3.         boolean isCreate = false;  
  4.         Date start = new Date();  
  5.         try {  
  6.             System.out.println("Indexing to directory '" + indexFilePath + "'...");  
  7.   
  8.             Directory dir = FSDirectory.open(new File(indexFilePath));  
  9.             //Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);  
  10.             //Analyzer analyzer = new PaodingAnalyzer("etc/paoding-analysis-default.properties");  
  11.             //Analyzer analyzer = new PaodingAnalyzer("F:/paodingetc/paoding-analysis-default.properties");  
  12.             //Analyzer analyzer = new PaodingAnalyzer("ifexists:paoding-dic-home.properties");  
  13.             Analyzer analyzer = new PaodingAnalyzer();  
  14.             IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_33,  
  15.                     analyzer);  
  16.   
  17.             if (isCreate) {  
  18.                 //创建新索引删除旧索引  
  19.                 iwc.setOpenMode(OpenMode.CREATE);  
  20.             } else {  
  21.                 // 向索引中添加新的Document  
  22.                 iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);  
  23.             }  
  24.             // iwc.setRAMBufferSizeMB(256.0);  
  25.   
  26.             IndexWriter writer = new IndexWriter(dir, iwc);  
  27.             FileInputStream fis;  
  28.             try {  
  29.                 fis = new FileInputStream(itemFilePath);  
  30.             } catch (FileNotFoundException fnfe) {  
  31.                 return;  
  32.             }  
  33.             try {  
  34.                 //new BufferedReader();  
  35.   
  36.                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));  
  37.                 String item = "";  
  38.                 String[] fields;  
  39.                 item = bufferedReader.readLine();  
  40.                 Integer id = 0;  
  41.                 while(!"".equals(item) && item != null) {  
  42.                     id++;  
  43.                     fields = item.split("::");  
  44.   
  45.                     // 创建空文档  
  46.                     Document doc = new Document();  
  47. //                  NumericField idField = new NumericField("ID", Field.Store.YES, true);  
  48. //                  idField.setIntValue(id);  
  49. //                  doc.add(idField);  
  50.                     doc.add(new Field("ID", id.toString(),Field.Store.YES, Field.Index.NO));  
  51.                     doc.add(new Field("IDSTR", id.toString(),Field.Store.YES, Field.Index.NOT_ANALYZED));//不分词索引,其实没必要索引为了测试所以索引  
  52.   
  53.                     NumericField idField = new NumericField("IDNUM", Field.Store.YES, true);  
  54.                     idField.setIntValue(id);  
  55.                     doc.add(idField);//用于测试数字  
  56.   
  57.                     doc.add(new Field("PCIP", fields[0],Field.Store.YES, Field.Index.ANALYZED));  
  58.   
  59.                     doc.add(new Field("DeviceIP", fields[1],Field.Store.YES, Field.Index.ANALYZED));  
  60.   
  61.                     doc.add(new Field("DeviceSerialNum", fields[2],Field.Store.YES, Field.Index.ANALYZED));  
  62.   
  63.                     doc.add(new Field("AlarmType", fields[3],Field.Store.YES, Field.Index.ANALYZED));  
  64.   
  65.                     //一个域可以有子集  
  66.                     doc.add(new Field("MultiFields", fields[2],Field.Store.YES, Field.Index.ANALYZED));  
  67.                     doc.add(new Field("MultiFields", fields[3],Field.Store.YES, Field.Index.ANALYZED));  
  68.   
  69.                     NumericField alarmDatetime = new NumericField("alarmDatetime", Field.Store.YES, true);  
  70.                     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");  
  71.                     alarmDatetime.setLongValue(simpleDateFormat.parse(fields[4]).getTime());  
  72.                     doc.add(alarmDatetime);  
  73.   
  74.                     if (id == 5) {  
  75.                         doc.setBoost(1.2f);  
  76.                     }  
  77.   
  78.                     if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {  
  79.                         writer.addDocument(doc);  
  80.                     } else {  
  81.                         writer.updateDocument(new Term("ID" , id.toString()),  
  82.                                 doc);  
  83.                     }  
  84.                     item = bufferedReader.readLine();  
  85.                 }  
  86.   
  87.             } finally {  
  88.                 fis.close();  
  89.             }  
  90.   
  91.             //writer.optimize();//优化索引  
  92.   
  93.             writer.close();  
  94.   
  95.             Date end = new Date();  
  96.             System.out.println(end.getTime() - start.getTime()  
  97.                     + " total milliseconds");  
  98.   
  99.         } catch (IOException e) {  
  100.             System.out.println(" caught a " + e.getClass()  
  101.                     + "\n with message: " + e.getMessage());  
  102.         }  
  103.     }  
  104.       


检索:

 

  1. public static void testSearch() throws Exception{  
  2.        String field = "AlarmType";  
  3.        boolean raw = false;  
  4.        String queryString = "移动";  
  5.        int hitsPerPage = 10;  
  6.   
  7.        IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File(indexFilePath)));  
  8.        //Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);  
  9.        //Analyzer analyzer = new PaodingAnalyzer();  
  10.   
  11.        BufferedReader in = null;  
  12.        //QueryParser parser = new QueryParser(Version.LUCENE_33, field, analyzer);  
  13.   
  14.        //Query query = parser.parse(queryString.trim());  
  15.        Query query = new TermQuery(new Term(field,"查询"));  
  16.        System.out.println("Searching for: " + query.toString(field));  
  17.     // Collect enough docs to show 5 pages  
  18.        TopDocs results = searcher.search(query, 5 * hitsPerPage, Sort.RELEVANCE);  
  19.        ScoreDoc[] hits = results.scoreDocs;  
  20.        int numTotalHits = results.totalHits;  
  21.        System.out.println(numTotalHits + " total matching documents");  
  22.        for (int i = 0; i < hits.length; i++) {  
  23.            Document doc = searcher.doc(hits[i].doc);  
  24.            System.out.println("ID:" + doc.get("ID") + "\tPCIP:" + doc.get("PCIP") + "\tDeviceIP:" + doc.get("DeviceIP")  
  25.                    + "\tDeviceSerialNum:" + doc.get("DeviceSerialNum") + "\tAlarmType:" + doc.get("AlarmType")  
  26.                    + "\tAlarmDatetime:" + new Date(Long.parseLong(doc.get("alarmDatetime"))).toString());  
  27.        }  
  28.    }  


以上为建索引和检索的简单实例,大家可以下载源码运行调试下,对于初接触的人使用会有帮助的。Demo源码以及相关配置信息见eclipse工程:http://download.csdn.net/detail/a_2cai/3671272

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多