狠狠撸

狠狠撸Share a Scribd company logo
lucene2.4 gong on

我把 lucene2.4 发行包的一个例子改的更简单些,仅供参考,其中在 eclipse
中运行遇到中文乱码问题,这些在代码中会有体现。




完成这个例子后,我顺便试了一下 qieqie 的庖丁解牛中文分词器,很好用,
而且分发包中有个简单的说明文档。




Java 代码

  1. package tutorial;
  2.
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8.
  9. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  10.import org.apache.lucene.document.Document;
  11.import org.apache.lucene.document.Field;
  12.import org.apache.lucene.index.IndexWriter;
  13.
  14.public class IndexFiles {
  15.
  16.     public static void main(String[] args) {
  17.         long start = System.currentTimeMillis();
  18.         try {
  19.             IndexWriter writer = new IndexWriter("index",
  20.                     new StandardAnalyzer(), true,
  21.                     IndexWriter.MaxFieldLength.LIMITED);
  22.             indexDocs(writer, new File("data"));
  23.             writer.optimize();
  24.             writer.close();
  25.             System.out.println("用时:" + (System.currentTimeMi
      llis() - start)
  26.                     + " 毫秒");
  27.         } catch (IOException e) {
  28.             e.printStackTrace();
29.        }
30.    }
31.
32.     static void indexDocs(IndexWriter writer, File file) throws
    IOException {
33.         if (file.canRead()) {
34.             if (file.isDirectory()) {
35.                 String[] files = file.list();
36.                 if (files != null) {
37.                      for (int i = 0; i < files.length; i++) {
38.                          indexDocs(writer, new File(file, files[
    i]));
39.                      }
40.                 }
41.             } else {
42.                 System.out.println("添加 " + file);
43.                 try {
44.                      //针对参数文件建立索引文档
45.                      Document doc = new Document();
46.                      //Field.Index.NOT_ANALYZED 文件名称 建立索
    引,但不分词
47.                      doc.add(new Field("filename", file.getCanon
    icalPath(),
48.                              Field.Store.YES, Field.Index.NOT_AN
    ALYZED));
49.                      doc.add(new Field("contents",
50.                              new InputStreamReader(new FileInput
    Stream(file.getCanonicalPath()), "utf-8")));
51.                      //在 writer 中加入此文档
52.                      writer.addDocument(doc);
53.                      //抛弃了原来 demo 中的如下做法,因为这样不能
    设定字符编码,当出现因为编码为题查不到
54.                      //中文字符时,便束手无策。
55.                      //writer.addDocument(FileDocument.Document(
    file));
56.                 } catch (FileNotFoundException fnfe) {
57.                      ;
58.                 }
59.             }
60.         }
61.     }
62.
63.}
Java 代码

  1. package tutorial;
  2.
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6.
  7. import org.apache.lucene.analysis.Analyzer;
  8. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  9. import org.apache.lucene.document.Document;
  10.import org.apache.lucene.index.IndexReader;
  11.import org.apache.lucene.queryParser.QueryParser;
  12.import org.apache.lucene.search.IndexSearcher;
  13.import org.apache.lucene.search.Query;
  14.import org.apache.lucene.search.ScoreDoc;
  15.import org.apache.lucene.search.Searcher;
  16.import org.apache.lucene.search.TopDocCollector;
  17.
  18.public class SearchFiles {
  19.
  20.    public static void main(String[] args) throws Exception {

  21.
  22.           IndexReader reader = IndexReader.open("index");
  23.
  24.           Searcher searcher = new IndexSearcher(reader);
  25.           Analyzer analyzer = new StandardAnalyzer();
  26.
  27.           BufferedReader in = new BufferedReader(new InputStreamR
        eader(System.in));
  28.
  29.           String field = "contents";
  30.           QueryParser parser = new QueryParser(field, analyzer);

  31.
  32.           String queries = null;
  33.           Query query = null;
  34.           while (true) {
  35.               if (queries == null) {
  36.                   System.out.print("输入查询词(quit or exit 退出):
         ");
37.            }
38.
39.            String line = in.readLine();
40.            if (line == null || line.length() == -1) {
41.                continue;
42.            } else if (line.equals("quit") || line.equals("exit
      ")) {
43.                break;
44.            }
45.            line = line.trim();
46.
47.            query = parser.parse(line);
48.            System.out.println("查询: " + query.toString(field)
      );
49.
50.             long start = System.currentTimeMillis();
51.             doPagingSearch(searcher, query, 5);
52.             System.out.println("用时:" + (System.currentTimeMi
    llis() - start)
53.                     + " 毫秒");
54.         }
55.
56.         reader.close();
57.     }
58.
59.     public static void doPagingSearch(Searcher searcher, Query
    query,
60.             int hitsPerPage) throws IOException {
61.
62.         TopDocCollector collector = new TopDocCollector(5 * hit
    sPerPage);
63.         searcher.search(query, collector);
64.         ScoreDoc[] hits = collector.topDocs().scoreDocs;
65.
66.         int numTotalHits = collector.getTotalHits();
67.         System.out.println("符合查询词的文件数:" + numTotalHit
    s);
68.
69.         int start = 0;
70.         int end = Math.min(numTotalHits, hitsPerPage);
71.
72.         for (int i = start; i < end; i++) {
73.             Document doc = searcher.doc(hits[i].doc);
74.             String path = doc.get("filename");
75.       if (path != null) {
   76.           System.out.println((i + 1) + ". " + path);
   77.       } else {
   78.           System.out.println((i + 1) + ". " + "沒有这个目
       录指定的文件");
   79.       }
   80.     }
   81.   }
   82.
   83.}




也许我的进度有点缓慢,因为这两天有点事,且总是心神不宁的。今天去火车站
买票了,给我的感觉是跟我平常买票没什么区别,我很容易就买到票了,而且
还有座位。也许是因为家近的原因吧。或者是我买的日期不是一个高峰点。




2009-01-12

下面是从庖丁文档里粘出来的,并为了适应版本 2.4 做了部分修改的代码:

Java 代码

   1. package tutorial;
   2.
   3. import net.paoding.analysis.analyzer.PaodingAnalyzer;
   4.
   5. import org.apache.lucene.analysis.Analyzer;
   6. import org.apache.lucene.analysis.TokenStream;
   7. import org.apache.lucene.document.Document;
   8. import org.apache.lucene.document.Field;
   9. import org.apache.lucene.index.IndexReader;
   10.import org.apache.lucene.index.IndexWriter;
   11.import org.apache.lucene.index.TermPositionVector;
   12.import org.apache.lucene.queryParser.QueryParser;
   13.import org.apache.lucene.search.IndexSearcher;
   14.import org.apache.lucene.search.Query;
   15.import org.apache.lucene.search.ScoreDoc;
   16.import org.apache.lucene.search.Searcher;
   17.import org.apache.lucene.search.TopDocCollector;
   18.import org.apache.lucene.search.highlight.Formatter;
   19.import org.apache.lucene.search.highlight.Highlighter;
20.import org.apache.lucene.search.highlight.QueryScorer;
21. import org.apache.lucene.search.highlight.TokenGroup;
22.import org.apache.lucene.search.highlight.TokenSources;
23.
24.public class PaodingExample {
25.
26.     public static void main(String[] args) throws Exception {

27.        String IDNEX_PATH = "index";
28.
29.        // 获取 Paoding 中文分词器
30.        Analyzer analyzer = new PaodingAnalyzer();
31.
32.         // 建立索引
33.         IndexWriter writer = new IndexWriter(IDNEX_PATH, analyz
    er, true, IndexWriter.MaxFieldLength.LIMITED);
34.         Document doc = new Document();
35.         Field field = new Field("content", "你好,世界!", Field
    .Store.YES,
36.                  Field.Index.ANALYZED, Field.TermVector.WITH_POS
    ITIONS_OFFSETS);
37.         doc.add(field);
38.         writer.addDocument(doc);
39.         writer.close();
40.
41.         System.out.println("Indexed success!");
42.
43.         // 检索
44.         IndexReader reader = IndexReader.open(IDNEX_PATH);
45.         QueryParser parser = new QueryParser("content", analyze
    r);
46.         Query query = parser.parse("你好");
47.         Searcher searcher = new IndexSearcher(reader);
48.         TopDocCollector collector = new TopDocCollector(5);
49.         searcher.search(query, collector);
50.         ScoreDoc[] hits = collector.topDocs().scoreDocs;
51.
52.         if (collector.getTotalHits() == 0) {
53.             System.out.println("hits.length=0");
54.             System.exit(0);
55.         }
56.
57.         Document doc2 = searcher.doc(hits[0].doc);
58.         // 高亮处理
59.          String text = doc2.get("content");
 60.          TermPositionVector tpv = (TermPositionVector) reader.ge
     tTermFreqVector(
 61.                  0, "content");
 62.          TokenStream ts = TokenSources.getTokenStream(tpv);
 63.          Formatter formatter = new Formatter() {
 64.              public String highlightTerm(String srcText, TokenGr
     oup g) {
 65.                  if (g.getTotalScore() <= 0) {
 66.                      return srcText;
 67.                  }
 68.                  return "<b>" + srcText + "</b>";
 69.              }
 70.          };
 71.
 72.          Highlighter highlighter = new Highlighter(formatter, ne
     w QueryScorer(
 73.                  query));
 74.          String result = highlighter.getBestFragments(ts, text,
     5, "…");
 75.          System.out.println("result:nt" + result);
 76.          reader.close();
 77.
 78.     }
 79.
 80.}




 ?   02:44
 ?   浏览 (931)
 ?   评论 (5)
 ?   分类: 检索/P2P/分布式
 ?   收藏
 ?   相关推荐

评论
5 楼 每天看看 2009-04-29        引用
//Field.Index.NOT_ANALYZED 文件名称 建立索引,但不分词
                    doc.add(new Field("filename",
file.getCanonicalPath(),Field.Store.YES, Field.Index.NOT_ANALYZED));


这样建立索引,是不是我在搜索时可以

String field = "filename";
QueryParser parser = new QueryParser(field, analyzer);
query = parser.parse(filePath);

这样搜索,结果应该有一条记录。
4 楼 zhyt710 2009-02-07    引用
当然不是,你完全可以逐个遍历 int numTotalHits =
collector.getTotalHits(); 个符合条件的结果。但是对于大数据量的系统,一
般出现的结果数量非常的巨大,所以采取分页显示的方式。             就是说把打印结果放
在一个 while 循环里,每次循环都让 start 加一页数量的大小,只要 start 的
值小于 numTotalHits。   从而实现分页显示。   我在这里是为了尽可能的简化程序,
使读者更容易入门
xuganggogo 写道

Deprecated. Hits will be removed in Lucene 3.0.Instead e. g.
TopDocCollector and TopDocs can be used:&nbsp;&nbsp; TopDocCollector
collector = new TopDocCollector(hitsPerPage);&nbsp;&nbsp;
searcher.search(query, collector);&nbsp;&nbsp; ScoreDoc[] hits =
collector.topDocs().scoreDocs;&nbsp;&nbsp; for (int i = 0; i &lt;
hits.length; i++) {&nbsp;&nbsp;&nbsp;&nbsp; int docId =
hits[i].doc;&nbsp;&nbsp;&nbsp;&nbsp; Document d =
searcher.doc(docId);&nbsp;&nbsp;&nbsp;&nbsp; // do something with
current hit 这里代替 hits 的方法,只能对 hitsPerPage 个结果进行操作。                难道
hitsPerPage 是写死的吗?如果要遍历所有结果集,该如何做?

3 楼 xuganggogo 2009-02-05    引用
Deprecated. Hits will be removed in Lucene 3.0.

Instead e. g. TopDocCollector and TopDocs can be used:

   TopDocCollector collector = new TopDocCollector(hitsPerPage);
   searcher.search(query, collector);
   ScoreDoc[] hits = collector.topDocs().scoreDocs;
   for (int i = 0; i < hits.length; i++) {
     int docId = hits[i].doc;
     Document d = searcher.doc(docId);
// do something with current hit
这里代替 hits 的方法,只能对 hitsPerPage 个结果进行操作。
难道 hitsPerPage 是写死的吗?
如果要遍历所有结果集,该如何做?
2 楼 zhyt710 2009-02-04    引用
并为了适应版
xuganggogo 写道

这个能用作索引 HTML 吗?


当然可以,只要是文本文件都可以。           对于不是纯文本文件的如 pdf,excel 等,只
要进行相应的解析成文本后,便可建立索引
1 楼 xuganggogo 2009-02-04 引用
这个能用作索引 HTML 吗?

More Related Content

What's hot (11)

闯补惫补物件导向
闯补惫补物件导向闯补惫补物件导向
闯补惫补物件导向
艾鍗科技
?
PHPUnit 入門介紹
PHPUnit 入門介紹PHPUnit 入門介紹
PHPUnit 入門介紹
Jace Ju
?
Row Set初步学习V1.1
Row Set初步学习V1.1Row Set初步学习V1.1
Row Set初步学习V1.1
Zianed Hou
?
OpenEJB - 另一個選擇
OpenEJB - 另一個選擇OpenEJB - 另一個選擇
OpenEJB - 另一個選擇
Justin Lin
?
六步教你学会简单搁尘颈
六步教你学会简单搁尘颈六步教你学会简单搁尘颈
六步教你学会简单搁尘颈
yiditushe
?
深入淺出 Web 容器 - Tomcat 原始碼分析
深入淺出 Web 容器  - Tomcat 原始碼分析深入淺出 Web 容器  - Tomcat 原始碼分析
深入淺出 Web 容器 - Tomcat 原始碼分析
Justin Lin
?
Java 操作 Excel (读)
Java 操作 Excel (读)Java 操作 Excel (读)
Java 操作 Excel (读)
wensheng wei
?
闯补惫补程序员面试之葵花宝典
闯补惫补程序员面试之葵花宝典闯补惫补程序员面试之葵花宝典
闯补惫补程序员面试之葵花宝典
yiditushe
?
Android 源码分析 -- (一) Android启动过程
Android 源码分析 -- (一) Android启动过程Android 源码分析 -- (一) Android启动过程
Android 源码分析 -- (一) Android启动过程
manateew
?
础颈蝉补苍耻虫安装光盘分析
础颈蝉补苍耻虫安装光盘分析础颈蝉补苍耻虫安装光盘分析
础颈蝉补苍耻虫安装光盘分析
Guangyao Cheng
?
闯补惫补物件导向
闯补惫补物件导向闯补惫补物件导向
闯补惫补物件导向
艾鍗科技
?
PHPUnit 入門介紹
PHPUnit 入門介紹PHPUnit 入門介紹
PHPUnit 入門介紹
Jace Ju
?
Row Set初步学习V1.1
Row Set初步学习V1.1Row Set初步学习V1.1
Row Set初步学习V1.1
Zianed Hou
?
OpenEJB - 另一個選擇
OpenEJB - 另一個選擇OpenEJB - 另一個選擇
OpenEJB - 另一個選擇
Justin Lin
?
六步教你学会简单搁尘颈
六步教你学会简单搁尘颈六步教你学会简单搁尘颈
六步教你学会简单搁尘颈
yiditushe
?
深入淺出 Web 容器 - Tomcat 原始碼分析
深入淺出 Web 容器  - Tomcat 原始碼分析深入淺出 Web 容器  - Tomcat 原始碼分析
深入淺出 Web 容器 - Tomcat 原始碼分析
Justin Lin
?
Java 操作 Excel (读)
Java 操作 Excel (读)Java 操作 Excel (读)
Java 操作 Excel (读)
wensheng wei
?
闯补惫补程序员面试之葵花宝典
闯补惫补程序员面试之葵花宝典闯补惫补程序员面试之葵花宝典
闯补惫补程序员面试之葵花宝典
yiditushe
?
Android 源码分析 -- (一) Android启动过程
Android 源码分析 -- (一) Android启动过程Android 源码分析 -- (一) Android启动过程
Android 源码分析 -- (一) Android启动过程
manateew
?
础颈蝉补苍耻虫安装光盘分析
础颈蝉补苍耻虫安装光盘分析础颈蝉补苍耻虫安装光盘分析
础颈蝉补苍耻虫安装光盘分析
Guangyao Cheng
?

Viewers also liked (6)

15 3 Powerpoint
15 3 Powerpoint15 3 Powerpoint
15 3 Powerpoint
Tamara
?
Cloud-based IT Services - The Future
Cloud-based IT Services - The FutureCloud-based IT Services - The Future
Cloud-based IT Services - The Future
InTechnology Managed Services (part of Redcentric)
?
CC Company Profile
CC Company ProfileCC Company Profile
CC Company Profile
Brittany Snell
?
4 软件架构导论
4  软件架构导论4  软件架构导论
4 软件架构导论
yiditushe
?
Sea Anemones P Pt Presentation
Sea Anemones P Pt PresentationSea Anemones P Pt Presentation
Sea Anemones P Pt Presentation
Tamara
?
Disaster Planning Backup, Backup, Backup
Disaster Planning Backup, Backup, BackupDisaster Planning Backup, Backup, Backup
Disaster Planning Backup, Backup, Backup
TechSoup
?

Similar to Lucene2 4 Demo (20)

107个常用javascript语句 oss 计算技术 - ossez info of tech
107个常用javascript语句   oss 计算技术 - ossez info of tech107个常用javascript语句   oss 计算技术 - ossez info of tech
107个常用javascript语句 oss 计算技术 - ossez info of tech
YUCHENG HU
?
基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索
fulin tang
?
基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索
fulin tang
?
厂辫谤颈苍驳框架,技术详解及使用指导
厂辫谤颈苍驳框架,技术详解及使用指导厂辫谤颈苍驳框架,技术详解及使用指导
厂辫谤颈苍驳框架,技术详解及使用指导
yiditushe
?
The Journey of Source Generator
The Journey of Source GeneratorThe Journey of Source Generator
The Journey of Source Generator
Roberson Liou
?
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
Guo Albert
?
HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享
Chong-Kuan Chen
?
Introduction to MVC of CodeIgniter 2.1.x
Introduction to MVC of CodeIgniter 2.1.xIntroduction to MVC of CodeIgniter 2.1.x
Introduction to MVC of CodeIgniter 2.1.x
Bo-Yi Wu
?
Javascript autoload
Javascript autoloadJavascript autoload
Javascript autoload
jay li
?
Spark 巨量資料處理基礎教學
Spark 巨量資料處理基礎教學Spark 巨量資料處理基礎教學
Spark 巨量資料處理基礎教學
NUTC, imac
?
《Java程序设计》期末考试试题 (六)
《Java程序设计》期末考试试题 (六)《Java程序设计》期末考试试题 (六)
《Java程序设计》期末考试试题 (六)
jane2006
?
Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序
HO-HSUN LIN
?
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
Tao He
?
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
Jian-Kai Wang
?
Spring4.x + hibernate4.x_配置详解
Spring4.x + hibernate4.x_配置详解Spring4.x + hibernate4.x_配置详解
Spring4.x + hibernate4.x_配置详解
zany_hui
?
惭测厂蚕尝源码分析.01.代码结构与基本流程
惭测厂蚕尝源码分析.01.代码结构与基本流程惭测厂蚕尝源码分析.01.代码结构与基本流程
惭测厂蚕尝源码分析.01.代码结构与基本流程
Lixun Peng
?
Mongo db技术分享
Mongo db技术分享Mongo db技术分享
Mongo db技术分享
晓锋 陈
?
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC
?
107个常用javascript语句 oss 计算技术 - ossez info of tech
107个常用javascript语句   oss 计算技术 - ossez info of tech107个常用javascript语句   oss 计算技术 - ossez info of tech
107个常用javascript语句 oss 计算技术 - ossez info of tech
YUCHENG HU
?
基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索
fulin tang
?
基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索基于尝耻肠别苍别的站内搜索
基于尝耻肠别苍别的站内搜索
fulin tang
?
厂辫谤颈苍驳框架,技术详解及使用指导
厂辫谤颈苍驳框架,技术详解及使用指导厂辫谤颈苍驳框架,技术详解及使用指导
厂辫谤颈苍驳框架,技术详解及使用指导
yiditushe
?
The Journey of Source Generator
The Journey of Source GeneratorThe Journey of Source Generator
The Journey of Source Generator
Roberson Liou
?
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
Guo Albert
?
HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享
Chong-Kuan Chen
?
Introduction to MVC of CodeIgniter 2.1.x
Introduction to MVC of CodeIgniter 2.1.xIntroduction to MVC of CodeIgniter 2.1.x
Introduction to MVC of CodeIgniter 2.1.x
Bo-Yi Wu
?
Javascript autoload
Javascript autoloadJavascript autoload
Javascript autoload
jay li
?
Spark 巨量資料處理基礎教學
Spark 巨量資料處理基礎教學Spark 巨量資料處理基礎教學
Spark 巨量資料處理基礎教學
NUTC, imac
?
《Java程序设计》期末考试试题 (六)
《Java程序设计》期末考试试题 (六)《Java程序设计》期末考试试题 (六)
《Java程序设计》期末考试试题 (六)
jane2006
?
Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序Net Parallel Programming .NET平行處理與執行序
Net Parallel Programming .NET平行處理與執行序
HO-HSUN LIN
?
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
颁语言产别苍肠丑尘补谤办覆盖信息收集总结4
Tao He
?
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
Jian-Kai Wang
?
Spring4.x + hibernate4.x_配置详解
Spring4.x + hibernate4.x_配置详解Spring4.x + hibernate4.x_配置详解
Spring4.x + hibernate4.x_配置详解
zany_hui
?
惭测厂蚕尝源码分析.01.代码结构与基本流程
惭测厂蚕尝源码分析.01.代码结构与基本流程惭测厂蚕尝源码分析.01.代码结构与基本流程
惭测厂蚕尝源码分析.01.代码结构与基本流程
Lixun Peng
?
Mongo db技术分享
Mongo db技术分享Mongo db技术分享
Mongo db技术分享
晓锋 陈
?
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC
?

More from yiditushe (20)

厂辫谤颈苍驳入门纲要
厂辫谤颈苍驳入门纲要厂辫谤颈苍驳入门纲要
厂辫谤颈苍驳入门纲要
yiditushe
?
J Bpm4 1中文用户手册
J Bpm4 1中文用户手册J Bpm4 1中文用户手册
J Bpm4 1中文用户手册
yiditushe
?
性能测试实践2
性能测试实践2性能测试实践2
性能测试实践2
yiditushe
?
性能测试实践1
性能测试实践1性能测试实践1
性能测试实践1
yiditushe
?
性能测试技术
性能测试技术性能测试技术
性能测试技术
yiditushe
?
Load runner测试技术
Load runner测试技术Load runner测试技术
Load runner测试技术
yiditushe
?
J2 ee性能测试
J2 ee性能测试J2 ee性能测试
J2 ee性能测试
yiditushe
?
面向对象的闯蝉培训
面向对象的闯蝉培训面向对象的闯蝉培训
面向对象的闯蝉培训
yiditushe
?
贵濒别虫3中文教程
贵濒别虫3中文教程贵濒别虫3中文教程
贵濒别虫3中文教程
yiditushe
?
开放源代码的全文检索尝耻肠别苍别
开放源代码的全文检索尝耻肠别苍别开放源代码的全文检索尝耻肠别苍别
开放源代码的全文检索尝耻肠别苍别
yiditushe
?
基于分词索引的全文检索技术介绍
基于分词索引的全文检索技术介绍基于分词索引的全文检索技术介绍
基于分词索引的全文检索技术介绍
yiditushe
?
Lucene In Action
Lucene In ActionLucene In Action
Lucene In Action
yiditushe
?
Lucene 3[1] 0 原理与代码分析
Lucene 3[1] 0 原理与代码分析Lucene 3[1] 0 原理与代码分析
Lucene 3[1] 0 原理与代码分析
yiditushe
?
7 面向对象设计原则
7 面向对象设计原则7 面向对象设计原则
7 面向对象设计原则
yiditushe
?
10 团队开发
10  团队开发10  团队开发
10 团队开发
yiditushe
?
9 对象持久化与数据建模
9  对象持久化与数据建模9  对象持久化与数据建模
9 对象持久化与数据建模
yiditushe
?
8 Uml构架建模
8  Uml构架建模8  Uml构架建模
8 Uml构架建模
yiditushe
?
3 Uml行为建模与Ooa
3  Uml行为建模与Ooa3  Uml行为建模与Ooa
3 Uml行为建模与Ooa
yiditushe
?
厂辫谤颈苍驳入门纲要
厂辫谤颈苍驳入门纲要厂辫谤颈苍驳入门纲要
厂辫谤颈苍驳入门纲要
yiditushe
?
J Bpm4 1中文用户手册
J Bpm4 1中文用户手册J Bpm4 1中文用户手册
J Bpm4 1中文用户手册
yiditushe
?
性能测试实践2
性能测试实践2性能测试实践2
性能测试实践2
yiditushe
?
性能测试实践1
性能测试实践1性能测试实践1
性能测试实践1
yiditushe
?
性能测试技术
性能测试技术性能测试技术
性能测试技术
yiditushe
?
Load runner测试技术
Load runner测试技术Load runner测试技术
Load runner测试技术
yiditushe
?
J2 ee性能测试
J2 ee性能测试J2 ee性能测试
J2 ee性能测试
yiditushe
?
面向对象的闯蝉培训
面向对象的闯蝉培训面向对象的闯蝉培训
面向对象的闯蝉培训
yiditushe
?
贵濒别虫3中文教程
贵濒别虫3中文教程贵濒别虫3中文教程
贵濒别虫3中文教程
yiditushe
?
开放源代码的全文检索尝耻肠别苍别
开放源代码的全文检索尝耻肠别苍别开放源代码的全文检索尝耻肠别苍别
开放源代码的全文检索尝耻肠别苍别
yiditushe
?
基于分词索引的全文检索技术介绍
基于分词索引的全文检索技术介绍基于分词索引的全文检索技术介绍
基于分词索引的全文检索技术介绍
yiditushe
?
Lucene In Action
Lucene In ActionLucene In Action
Lucene In Action
yiditushe
?
Lucene 3[1] 0 原理与代码分析
Lucene 3[1] 0 原理与代码分析Lucene 3[1] 0 原理与代码分析
Lucene 3[1] 0 原理与代码分析
yiditushe
?
7 面向对象设计原则
7 面向对象设计原则7 面向对象设计原则
7 面向对象设计原则
yiditushe
?
10 团队开发
10  团队开发10  团队开发
10 团队开发
yiditushe
?
9 对象持久化与数据建模
9  对象持久化与数据建模9  对象持久化与数据建模
9 对象持久化与数据建模
yiditushe
?
8 Uml构架建模
8  Uml构架建模8  Uml构架建模
8 Uml构架建模
yiditushe
?
3 Uml行为建模与Ooa
3  Uml行为建模与Ooa3  Uml行为建模与Ooa
3 Uml行为建模与Ooa
yiditushe
?

Lucene2 4 Demo

  • 1. lucene2.4 gong on 我把 lucene2.4 发行包的一个例子改的更简单些,仅供参考,其中在 eclipse 中运行遇到中文乱码问题,这些在代码中会有体现。 完成这个例子后,我顺便试了一下 qieqie 的庖丁解牛中文分词器,很好用, 而且分发包中有个简单的说明文档。 Java 代码 1. package tutorial; 2. 3. import java.io.File; 4. import java.io.FileInputStream; 5. import java.io.FileNotFoundException; 6. import java.io.IOException; 7. import java.io.InputStreamReader; 8. 9. import org.apache.lucene.analysis.standard.StandardAnalyzer; 10.import org.apache.lucene.document.Document; 11.import org.apache.lucene.document.Field; 12.import org.apache.lucene.index.IndexWriter; 13. 14.public class IndexFiles { 15. 16. public static void main(String[] args) { 17. long start = System.currentTimeMillis(); 18. try { 19. IndexWriter writer = new IndexWriter("index", 20. new StandardAnalyzer(), true, 21. IndexWriter.MaxFieldLength.LIMITED); 22. indexDocs(writer, new File("data")); 23. writer.optimize(); 24. writer.close(); 25. System.out.println("用时:" + (System.currentTimeMi llis() - start) 26. + " 毫秒"); 27. } catch (IOException e) { 28. e.printStackTrace();
  • 2. 29. } 30. } 31. 32. static void indexDocs(IndexWriter writer, File file) throws IOException { 33. if (file.canRead()) { 34. if (file.isDirectory()) { 35. String[] files = file.list(); 36. if (files != null) { 37. for (int i = 0; i < files.length; i++) { 38. indexDocs(writer, new File(file, files[ i])); 39. } 40. } 41. } else { 42. System.out.println("添加 " + file); 43. try { 44. //针对参数文件建立索引文档 45. Document doc = new Document(); 46. //Field.Index.NOT_ANALYZED 文件名称 建立索 引,但不分词 47. doc.add(new Field("filename", file.getCanon icalPath(), 48. Field.Store.YES, Field.Index.NOT_AN ALYZED)); 49. doc.add(new Field("contents", 50. new InputStreamReader(new FileInput Stream(file.getCanonicalPath()), "utf-8"))); 51. //在 writer 中加入此文档 52. writer.addDocument(doc); 53. //抛弃了原来 demo 中的如下做法,因为这样不能 设定字符编码,当出现因为编码为题查不到 54. //中文字符时,便束手无策。 55. //writer.addDocument(FileDocument.Document( file)); 56. } catch (FileNotFoundException fnfe) { 57. ; 58. } 59. } 60. } 61. } 62. 63.}
  • 3. Java 代码 1. package tutorial; 2. 3. import java.io.BufferedReader; 4. import java.io.IOException; 5. import java.io.InputStreamReader; 6. 7. import org.apache.lucene.analysis.Analyzer; 8. import org.apache.lucene.analysis.standard.StandardAnalyzer; 9. import org.apache.lucene.document.Document; 10.import org.apache.lucene.index.IndexReader; 11.import org.apache.lucene.queryParser.QueryParser; 12.import org.apache.lucene.search.IndexSearcher; 13.import org.apache.lucene.search.Query; 14.import org.apache.lucene.search.ScoreDoc; 15.import org.apache.lucene.search.Searcher; 16.import org.apache.lucene.search.TopDocCollector; 17. 18.public class SearchFiles { 19. 20. public static void main(String[] args) throws Exception { 21. 22. IndexReader reader = IndexReader.open("index"); 23. 24. Searcher searcher = new IndexSearcher(reader); 25. Analyzer analyzer = new StandardAnalyzer(); 26. 27. BufferedReader in = new BufferedReader(new InputStreamR eader(System.in)); 28. 29. String field = "contents"; 30. QueryParser parser = new QueryParser(field, analyzer); 31. 32. String queries = null; 33. Query query = null; 34. while (true) { 35. if (queries == null) { 36. System.out.print("输入查询词(quit or exit 退出): ");
  • 4. 37. } 38. 39. String line = in.readLine(); 40. if (line == null || line.length() == -1) { 41. continue; 42. } else if (line.equals("quit") || line.equals("exit ")) { 43. break; 44. } 45. line = line.trim(); 46. 47. query = parser.parse(line); 48. System.out.println("查询: " + query.toString(field) ); 49. 50. long start = System.currentTimeMillis(); 51. doPagingSearch(searcher, query, 5); 52. System.out.println("用时:" + (System.currentTimeMi llis() - start) 53. + " 毫秒"); 54. } 55. 56. reader.close(); 57. } 58. 59. public static void doPagingSearch(Searcher searcher, Query query, 60. int hitsPerPage) throws IOException { 61. 62. TopDocCollector collector = new TopDocCollector(5 * hit sPerPage); 63. searcher.search(query, collector); 64. ScoreDoc[] hits = collector.topDocs().scoreDocs; 65. 66. int numTotalHits = collector.getTotalHits(); 67. System.out.println("符合查询词的文件数:" + numTotalHit s); 68. 69. int start = 0; 70. int end = Math.min(numTotalHits, hitsPerPage); 71. 72. for (int i = start; i < end; i++) { 73. Document doc = searcher.doc(hits[i].doc); 74. String path = doc.get("filename");
  • 5. 75. if (path != null) { 76. System.out.println((i + 1) + ". " + path); 77. } else { 78. System.out.println((i + 1) + ". " + "沒有这个目 录指定的文件"); 79. } 80. } 81. } 82. 83.} 也许我的进度有点缓慢,因为这两天有点事,且总是心神不宁的。今天去火车站 买票了,给我的感觉是跟我平常买票没什么区别,我很容易就买到票了,而且 还有座位。也许是因为家近的原因吧。或者是我买的日期不是一个高峰点。 2009-01-12 下面是从庖丁文档里粘出来的,并为了适应版本 2.4 做了部分修改的代码: Java 代码 1. package tutorial; 2. 3. import net.paoding.analysis.analyzer.PaodingAnalyzer; 4. 5. import org.apache.lucene.analysis.Analyzer; 6. import org.apache.lucene.analysis.TokenStream; 7. import org.apache.lucene.document.Document; 8. import org.apache.lucene.document.Field; 9. import org.apache.lucene.index.IndexReader; 10.import org.apache.lucene.index.IndexWriter; 11.import org.apache.lucene.index.TermPositionVector; 12.import org.apache.lucene.queryParser.QueryParser; 13.import org.apache.lucene.search.IndexSearcher; 14.import org.apache.lucene.search.Query; 15.import org.apache.lucene.search.ScoreDoc; 16.import org.apache.lucene.search.Searcher; 17.import org.apache.lucene.search.TopDocCollector; 18.import org.apache.lucene.search.highlight.Formatter; 19.import org.apache.lucene.search.highlight.Highlighter;
  • 6. 20.import org.apache.lucene.search.highlight.QueryScorer; 21. import org.apache.lucene.search.highlight.TokenGroup; 22.import org.apache.lucene.search.highlight.TokenSources; 23. 24.public class PaodingExample { 25. 26. public static void main(String[] args) throws Exception { 27. String IDNEX_PATH = "index"; 28. 29. // 获取 Paoding 中文分词器 30. Analyzer analyzer = new PaodingAnalyzer(); 31. 32. // 建立索引 33. IndexWriter writer = new IndexWriter(IDNEX_PATH, analyz er, true, IndexWriter.MaxFieldLength.LIMITED); 34. Document doc = new Document(); 35. Field field = new Field("content", "你好,世界!", Field .Store.YES, 36. Field.Index.ANALYZED, Field.TermVector.WITH_POS ITIONS_OFFSETS); 37. doc.add(field); 38. writer.addDocument(doc); 39. writer.close(); 40. 41. System.out.println("Indexed success!"); 42. 43. // 检索 44. IndexReader reader = IndexReader.open(IDNEX_PATH); 45. QueryParser parser = new QueryParser("content", analyze r); 46. Query query = parser.parse("你好"); 47. Searcher searcher = new IndexSearcher(reader); 48. TopDocCollector collector = new TopDocCollector(5); 49. searcher.search(query, collector); 50. ScoreDoc[] hits = collector.topDocs().scoreDocs; 51. 52. if (collector.getTotalHits() == 0) { 53. System.out.println("hits.length=0"); 54. System.exit(0); 55. } 56. 57. Document doc2 = searcher.doc(hits[0].doc); 58. // 高亮处理
  • 7. 59. String text = doc2.get("content"); 60. TermPositionVector tpv = (TermPositionVector) reader.ge tTermFreqVector( 61. 0, "content"); 62. TokenStream ts = TokenSources.getTokenStream(tpv); 63. Formatter formatter = new Formatter() { 64. public String highlightTerm(String srcText, TokenGr oup g) { 65. if (g.getTotalScore() <= 0) { 66. return srcText; 67. } 68. return "<b>" + srcText + "</b>"; 69. } 70. }; 71. 72. Highlighter highlighter = new Highlighter(formatter, ne w QueryScorer( 73. query)); 74. String result = highlighter.getBestFragments(ts, text, 5, "…"); 75. System.out.println("result:nt" + result); 76. reader.close(); 77. 78. } 79. 80.} ? 02:44 ? 浏览 (931) ? 评论 (5) ? 分类: 检索/P2P/分布式 ? 收藏 ? 相关推荐 评论
  • 8. 5 楼 每天看看 2009-04-29 引用 //Field.Index.NOT_ANALYZED 文件名称 建立索引,但不分词 doc.add(new Field("filename", file.getCanonicalPath(),Field.Store.YES, Field.Index.NOT_ANALYZED)); 这样建立索引,是不是我在搜索时可以 String field = "filename"; QueryParser parser = new QueryParser(field, analyzer); query = parser.parse(filePath); 这样搜索,结果应该有一条记录。 4 楼 zhyt710 2009-02-07 引用 当然不是,你完全可以逐个遍历 int numTotalHits = collector.getTotalHits(); 个符合条件的结果。但是对于大数据量的系统,一 般出现的结果数量非常的巨大,所以采取分页显示的方式。 就是说把打印结果放 在一个 while 循环里,每次循环都让 start 加一页数量的大小,只要 start 的 值小于 numTotalHits。 从而实现分页显示。 我在这里是为了尽可能的简化程序, 使读者更容易入门 xuganggogo 写道 Deprecated. Hits will be removed in Lucene 3.0.Instead e. g. TopDocCollector and TopDocs can be used:&nbsp;&nbsp; TopDocCollector collector = new TopDocCollector(hitsPerPage);&nbsp;&nbsp; searcher.search(query, collector);&nbsp;&nbsp; ScoreDoc[] hits = collector.topDocs().scoreDocs;&nbsp;&nbsp; for (int i = 0; i &lt; hits.length; i++) {&nbsp;&nbsp;&nbsp;&nbsp; int docId = hits[i].doc;&nbsp;&nbsp;&nbsp;&nbsp; Document d = searcher.doc(docId);&nbsp;&nbsp;&nbsp;&nbsp; // do something with current hit 这里代替 hits 的方法,只能对 hitsPerPage 个结果进行操作。 难道 hitsPerPage 是写死的吗?如果要遍历所有结果集,该如何做? 3 楼 xuganggogo 2009-02-05 引用 Deprecated. Hits will be removed in Lucene 3.0. Instead e. g. TopDocCollector and TopDocs can be used: TopDocCollector collector = new TopDocCollector(hitsPerPage); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; for (int i = 0; i < hits.length; i++) { int docId = hits[i].doc; Document d = searcher.doc(docId);
  • 9. // do something with current hit 这里代替 hits 的方法,只能对 hitsPerPage 个结果进行操作。 难道 hitsPerPage 是写死的吗? 如果要遍历所有结果集,该如何做? 2 楼 zhyt710 2009-02-04 引用 并为了适应版 xuganggogo 写道 这个能用作索引 HTML 吗? 当然可以,只要是文本文件都可以。 对于不是纯文本文件的如 pdf,excel 等,只 要进行相应的解析成文本后,便可建立索引 1 楼 xuganggogo 2009-02-04 引用 这个能用作索引 HTML 吗?