返回顶部

收藏

Lucene 生成索引以及搜索的完整例子

更多

简单,但足以说明问题。适用于 Lucene 3.0.x 版本。

package net.oschina.tester;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;

/**
 * 搜索测试
 * @author Winter Lau
 * @date 2010-10-18 下午09:20:18
 */
public class SearchTester {

    private static RAMDirectory dir;
    private static SimpleAnalyzer a;
    private static IndexSearcher searcher;

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        buildIndex();
        testSearch();
    }

    static void testSearch() throws Exception {
        Query q = new TermQuery(new Term("tags","TkRoot".toLowerCase()));
        TopDocs docs = searcher.search(q, null, 100000);
        System.out.println("HITS:"+docs.totalHits);
        for(int i = 0; i< docs.totalHits;i++){
            ScoreDoc s_doc = docs.scoreDocs[i];
            Document doc = searcher.doc(s_doc.doc);
            System.out.println(doc);
        }
    }

    static void buildIndex() throws Exception {
        dir = new RAMDirectory();
        a = new SimpleAnalyzer();
        IndexWriter writer = new IndexWriter(dir, a, IndexWriter.MaxFieldLength.UNLIMITED);
        Document doc = new Document();
        doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NOT_ANALYZED));
        doc.add(new Field("tags", "Java,数组,TkRoot", Field.Store.NO, Field.Index.ANALYZED));
        System.out.println(doc);
        writer.addDocument(doc);
        writer.close();
        searcher = new IndexSearcher(dir);
    }
}
//该片段来自于http://outofmemory.cn

标签:java,基础

收藏

0人收藏

支持

0

反对

0

发表评论