代码如下:
运行结果:
共有1条索引,命中1条
0:the quick brown fox jumped over the lazy dog
- package demo;
- import java.io.IOException;
- import org.apache.lucene.analysis.WhitespaceAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.Field;
- import org.apache.lucene.index.CorruptIndexException;
- import org.apache.lucene.index.IndexWriter;
- import org.apache.lucene.index.Term;
- import org.apache.lucene.search.IndexSearcher;
- import org.apache.lucene.search.PhraseQuery;
- import org.apache.lucene.search.ScoreDoc;
- import org.apache.lucene.search.TopDocs;
- import org.apache.lucene.store.LockObtainFailedException;
- import org.apache.lucene.store.RAMDirectory;
- public class TestLucene {
- public static void main(String[] args) throws CorruptIndexException, LockObtainFailedException, IOException {
- String content = "the quick brown fox jumped over the lazy dog";
- RAMDirectory directory = new RAMDirectory();
- IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, new IndexWriter.MaxFieldLength(1000));
- Document doc = new Document();
- doc.add(new Field("field", content, Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- writer.close();
- IndexSearcher searcher = new IndexSearcher(directory);
- PhraseQuery query = new PhraseQuery();
- query.setSlop(3);
- String[] phrase = new String[]{"fox", "quick"};
- for (int i = 0; i < phrase.length; i++) {
- query.add(new Term("field", phrase[i]));
- }
- TopDocs topDocs = searcher.search(query, 100);
- ScoreDoc[] hits = topDocs.scoreDocs;
- System.out.println("共有" + searcher.maxDoc() + "条索引,命中" + hits.length + "条");
- for (int i = 0; i < hits.length; i++) {
- int DocId = hits[i].doc;
- Document document = searcher.doc(DocId);
- System.out.println(DocId + ":" + document.get("field"));
- }
- searcher.close();
- }
- }
共有1条索引,命中1条
0:the quick brown fox jumped over the lazy dog