金色坐标

关注互联网应用和搜索引擎技术

« Lucene使用代码实例之建立索引网上开店同样竞争激烈 »

Lucene使用代码实例之搜索文档

利用Lucene为文本文档建立索引之后,就可以基于这个索引进行文档的内容搜索,从而找到包含某个关键词或短语的文档。Lucene在搜索文档时主要会用到IndexSearcher, Term, Query, TermQuery, Hits等五个基础类:

1,Query类:这是一个抽象类,用于将用户输入的查询字符串封装成Lucene能够识别的Query,它具有TermQuery, BooleanQuery, PrefixQuery等多种实现。

2,Term类:用于描述搜索的基本单位,其构造函数是Term(“fieldName”,”queryWord”),其中第一个参数代表要在文档的哪一个Field上进行搜索,第二个参数代表要搜索的关键词。

3,TermQuery类:TermQuery是抽象类Query的一个具体实现,也是Lucene支持的最为基本的一个查询类。TermQuery的构造函数是TermQuery(new Term(“fieldName”,”queryWord”)),唯一的参数是一个Term对象。

4,IndexSearcher类:用于在建立好的索引上进行搜索的句柄类,其打开索引方式被设置为只读,因此允许多个IndexSearcher实例操作同一个索引。

5,Hits类:搜索结果类。

代码:利用索引搜索文档

package TestLucene;
import java.io.File;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.FSDirectory;
/**
 * This class is used to demonstrate the
 * process of searching on an existing
 * Lucene index
 *
 */
public class TxtFileSearcher {
    public static void main(String[] args) throws Exception{
        String queryStr = "lucene";
        //This is the directory that hosts the Lucene index
        File indexDir = new File("D:\\luceneIndex");
        FSDirectory directory = FSDirectory.getDirectory(indexDir,false);
        IndexSearcher searcher = new IndexSearcher(directory);
        if(!indexDir.exists()){
            System.out.println("The Lucene index is not exist");
            return;
        }
        Term term = new Term("contents",queryStr.toLowerCase());
        TermQuery luceneQuery = new TermQuery(term);
        Hits hits = searcher.search(luceneQuery);
        for(int i = 0; i < hits.length(); i++){
            Document document = hits.doc(i);
            System.out.println("File: " + document.get("path"));
        }
    }
}
 
在代码中,类IndexSearcher的构造函数接受一个类型为Directory的对象,传入的FSDirctory对象代表索引存储在磁盘上的位置,IndexSearcher实例化后,其以只读方式打开了这个索引。

然后程序构造了一个Term对象,指定要在文档内容中搜索包含关键词“lucene”的文档,程序利用这个Term对象构造出TermQuery对象,并把其传入到IndexSearcher的search方法中进行查询,返回的结果保存在Hits对象中。

最后程序利用循环代码将搜索到的文档路径全部打印出来。




原创文章,如转载请注明:转载自金色坐标 [ http://www.kingxy.com/ ]

本文链接地址:http://www.kingxy.com/archives/88.html
  • 相关文章:
  • Lucene使用代码实例之建立索引  (2009-2-13 13:42:28)

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

  • 订阅我的博客:订阅我的博客
  • 通过Google订阅本站
  • 通过bloglines订阅本站
  • 通过抓虾订阅本站
  • 通过yahoo订阅本站

Search

Google

最新评论及回复

最近发表

金色坐标博客——京ICP备09009094号

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载本站内容必须也遵循“署名-非商业用途-保持一致”的创作共用协议.
KingXY Blog - This site is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.