lucene near-real-time search代码示例

package player.kent.chen.temp.lucene.nrts;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class MyNearRealTimeSearch {

    public static void main(String[] args) throws Exception {

        //创建index writer对象
        Directory indexDir = new RAMDirectory();
        IndexWriter indexWriter = new IndexWriter(indexDir,
                new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED);

        //为第一个文档建索引,但不commit()
        String text1 = "I have a dream";
        Document doc1 = new Document();
        doc1.add(new Field("content", text1, Field.Store.YES, Field.Index.ANALYZED));
        indexWriter.addDocument(doc1);

        //搜一下
        IndexSearcher indexSearcher = new IndexSearcher(indexWriter.getReader()); //关键语句,searcher的reader来自上面的writer
        TopDocs result1 = indexSearcher.search(new TermQuery(new Term("content", "dream")), 1);
        System.out.println(result1.totalHits); //1

        //把第二个doc加入索引
        String text2 = " the sons of former slaves and the sons of former slave owners";
        Document doc2 = new Document();
        doc2.add(new Field("content", text2, Field.Store.YES, Field.Index.ANALYZED));
        indexWriter.addDocument(doc2);

        //再搜一下。 这时要更新一下search对象
        IndexReader newReader = indexSearcher.getIndexReader().reopen(); //reader重开,并返回新实例
        indexSearcher.getIndexReader().close(); //关闭原来的reader
        indexSearcher = new IndexSearcher(newReader);

        //搜
        TopDocs result2 = indexSearcher.search(new TermQuery(new Term("content", "slaves")), 1);
        System.out.println(result2.totalHits); //1

        indexWriter.close();
    }
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.