Lucene教程

来源:互联网 发布:mac浏览器兼容模式 编辑:程序博客网 时间:2024/06/02 04:23

Lucene大大简化了在应用中集成全文搜索的功能。但实际上Lucene十分简单,我可以在五分钟之内向你展示如何使用Lucene。

1. 建立索引

为了简单起见,我们下面为一些字符串创建内存索引:

[java] view plain copy
  1. StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);  
  2. Directory index = new RAMDirectory();  
  3.    
  4. IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);  
  5.    
  6. IndexWriter w = new IndexWriter(index, config);  
  7. addDoc(w, "Lucene in Action""193398817");  
  8. addDoc(w, "Lucene for Dummies""55320055Z");  
  9. addDoc(w, "Managing Gigabytes""55063554A");  
  10. addDoc(w, "The Art of Computer Science""9900333X");  
  11. w.close();  


addDoc()方法把文档(译者注:这里的文档是Lucene中的Document类的实例)添加到索引中。

[java] view plain copy
  1. private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {  
  2.   Document doc = new Document();  
  3.   doc.add(new TextField("title", title, Field.Store.YES));  
  4.   doc.add(new StringField("isbn", isbn, Field.Store.YES));  
  5.   w.addDocument(doc);  
  6. }  


注意,对于需要分词的内容我们使用TextField,对于像id这样不需要分词的内容我们使用StringField。

2.搜索请求

我们从标准输入(stdin)中读入搜索请求,然后对它进行解析,最后创建一个Lucene中的Query对象。

[java] view plain copy
  1. String querystr = args.length > 0 ? args[0] : "lucene";  
  2. Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);  


3.搜索

我们创建一个Searcher对象并且使用上面创建的Query对象来进行搜索,匹配到的前10个结果封装在TopScoreDocCollector对象里返回。

[java] view plain copy
  1. int hitsPerPage = 10;  
  2. IndexReader reader = IndexReader.open(index);  
  3. IndexSearcher searcher = new IndexSearcher(reader);  
  4. TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);  
  5. searcher.search(q, collector);  
  6. ScoreDoc[] hits = collector.topDocs().scoreDocs;  


4.展示

现在我们得到了搜索结果,我们需要想用户展示它。

[java] view plain copy
  1. System.out.println("Found " + hits.length + " hits.");  
  2. for(int i=0;i<hits.length;++i) {  
  3.     int docId = hits[i].doc;  
  4.     Document d = searcher.doc(docId);  
  5.     System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));  
  6. }  



这里是这个小应用的完整代码。下载HelloLucene.java。

[java] view plain copy
  1. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  2. import org.apache.lucene.document.Document;  
  3. import org.apache.lucene.document.Field;  
  4. import org.apache.lucene.document.StringField;  
  5. import org.apache.lucene.document.TextField;  
  6. import org.apache.lucene.index.DirectoryReader;  
  7. import org.apache.lucene.index.IndexReader;  
  8. import org.apache.lucene.index.IndexWriter;  
  9. import org.apache.lucene.index.IndexWriterConfig;  
  10. import org.apache.lucene.queryparser.classic.ParseException;  
  11. import org.apache.lucene.queryparser.classic.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.TopScoreDocCollector;  
  16. import org.apache.lucene.store.Directory;  
  17. import org.apache.lucene.store.RAMDirectory;  
  18. import org.apache.lucene.util.Version;  
  19.    
  20. import java.io.IOException;  
  21.    
  22. public class HelloLucene {  
  23.   public static void main(String[] args) throws IOException, ParseException {  
  24.     // 0. Specify the analyzer for tokenizing text.  
  25.     //    The same analyzer should be used for indexing and searching  
  26.     StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);  
  27.    
  28.     // 1. create the index  
  29.     Directory index = new RAMDirectory();  
  30.    
  31.     IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);  
  32.    
  33.     IndexWriter w = new IndexWriter(index, config);  
  34.     addDoc(w, "Lucene in Action""193398817");  
  35.     addDoc(w, "Lucene for Dummies""55320055Z");  
  36.     addDoc(w, "Managing Gigabytes""55063554A");  
  37.     addDoc(w, "The Art of Computer Science""9900333X");  
  38.     w.close();  
  39.    
  40.     // 2. query  
  41.     String querystr = args.length > 0 ? args[0] : "lucene";  
  42.    
  43.     // the "title" arg specifies the default field to use  
  44.     // when no field is explicitly specified in the query.  
  45.     Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);  
  46.    
  47.     // 3. search  
  48.     int hitsPerPage = 10;  
  49.     IndexReader reader = DirectoryReader.open(index);  
  50.     IndexSearcher searcher = new IndexSearcher(reader);  
  51.     TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);  
  52.     searcher.search(q, collector);  
  53.     ScoreDoc[] hits = collector.topDocs().scoreDocs;  
  54.        
  55.     // 4. display results  
  56.     System.out.println("Found " + hits.length + " hits.");  
  57.     for(int i=0;i<hits.length;++i) {  
  58.       int docId = hits[i].doc;  
  59.       Document d = searcher.doc(docId);  
  60.       System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));  
  61.     }  
  62.    
  63.     // reader can only be closed when there  
  64.     // is no need to access the documents any more.  
  65.     reader.close();  
  66.   }  
  67.    
  68.   private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {  
  69.     Document doc = new Document();  
  70.     doc.add(new TextField("title", title, Field.Store.YES));  
  71.    
  72.     // use a string field for isbn because we don't want it tokenized  
  73.     doc.add(new StringField("isbn", isbn, Field.Store.YES));  
  74.     w.addDocument(doc);  
  75.   }  
  76. }  


可以直接在命令行中使用这个小应用,键入java HelloLucene 

下面可以做什么?

  1. 阅读下面关于Lucene的书籍。
  2. 你需要应该使用Apache Solr代替Apache Lucene吗?
  3. 更多关于Lucene的基本概念

一些与Lucene和搜索相关的书籍

Github上的基于maven的库

Mac Luq在Github上的基于maven的库:

https://github.com/macluq/helloLucene

用下面这条命令下载它:

1
git clone https://github.com/macluq/helloLucene.git

PS:如果你是Java新手的话,试试下面的命令:

1
2
3
4
5
6
wget http://repo1.maven.org/maven2/org/apache/lucene/lucene-core/4.0.0/lucene-core-4.0.0.jar
wget http://repo1.maven.org/maven2/org/apache/lucene/lucene-analyzers-common/4.0.0/lucene-analyzers-common-4.0.0.jar
wget http://repo1.maven.org/maven2/org/apache/lucene/lucene-queryparser/4.0.0/lucene-queryparser-4.0.0.jar
wget http://www.lucenetutorial.com/code/HelloLucene.java
javac -classpath .:lucene-core-4.0.0.jar:lucene-analyzers-common-4.0.0.jar:lucene-queryparser-4.0.0.jar HelloLucene.java
java -classpath .:lucene-core-4.0.0.jar:lucene-analyzers-common-4.0.0.jar:lucene-queryparser-4.0.0.jar HelloLucene

你会得到下面的结果:

1
2
3
Found 2 hits.
1. Lucene in Action
2. Lucene for Dummies

Erik,一个可能对你有所帮助的读者抱怨到:

编译过程还算顺利,但是我不能正常运行这段代码。在网上搜索并且自己尝试了以后发现Lucene的jar文件必须在classpath中,否则运行不起来。这可能对很多像我这样的java初学者很多帮助。

安装Lucene

PS:我发现一些初学者在安装Lucene时有些困难。

你应该先下载Lucene,然后把它解压到一个你用于编程的目录。

如果你使用Netbeans,你也可以这么做:

  • 遵循这里的教程。
  • 按照下面的步骤:
  1. 通过以此点击Netbeans菜单栏上的“工具”,然后选择“库管理器”,把Lucene的jar文件作为外部类库加进来。
  2. 在Lucene项目上面右键,选择“属性”
  3. 在弹出来的对话框中,以此选择“类库”,”添加jar或文件夹”选项
  4. 定位到从lucene-[version].tar.gz解压出来的文件夹上,选择 lucene-core-[version].jar。
  5. 点击“确定”,现在jar文件就已经添加到你项目的classpath中去了



来源:http://blog.csdn.net/z69183787/article/details/47909463

原创粉丝点击