Lucene包括很多種不同的搜索方式,首先生成一個檢索器IndexSearcher searcher = new
IndexSearcher("Index_Path", new StandardAnalyzer(),
true),然后再調用searcher.search(query),其中典型的query查詢方式有以下幾種:
1)按詞條搜索:TermQuery,即搜索某一詞條。
方法如下:Query query = new TermQuery(new Term("field", "keyword"));
其中參數field指欲查找的字段,keyword指欲檢索的關鍵字。
2)在某一范圍類搜索:RangeQuery
方法如下:RangeQuery query = new RangeQuery(begin, end, include);
其中參數begin和end均是一個Term對象,分別指在索引中相應Term的起始位置和結束位置。include是一個boolean值,true表是包含起始和結束位置,false表示不包含邊界值。
3)多關鍵字的搜索:PhraseQuery
方法如下:
PhraseQuery query = new PhraseQuery();
query.add(new Term("content","keyword1"));
query.add(new Term("content","keyword2"));
要
注意的是PhraseQuery類中有一個setSlop方法,該方法用于設定一個稱之為"坡度"的變量,來確定關鍵字之間是否允許、允許多少個無關詞匯
存在。默認值為0,即兩個關鍵字之間無任何詞匯存在,才能被搜索到。設置該值以后,只有當兩個關鍵字之間無關詞的數目小于等于坡度值是,才能被搜索
到。(文章末尾給出了具體例子)
4)使用通配符搜索:WildcardQuery
使用方法類似于1),只不過字段的關鍵字允許使用?(代表一個字符)、*(代表多個字符)
另外,還有以下不同的搜索方法:
“與或”搜索BooleanQuery、使用前綴搜索PerfixQuery、使用短語綴搜索PhrasePrefixQuery、模糊查詢搜索FuzzyQuery等。
/*
* 多關鍵字搜索的例子*/
package testlucene;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
public class PhraseQueryTest {
public static void main(String[] args)throws Exception{
Document doc1 = new Document();
doc1.add(new Field("content","david mary smith robert",Field.Store.YES,Field.Index.TOKENIZED));
doc1.add(new Field("title","doc1",Field.Store.YES,Field.Index.TOKENIZED));
Document doc2 = new Document();
doc2.add(new Field("content","david smith mary robert",Field.Store.YES,Field.Index.TOKENIZED));
doc2.add(new Field("title","doc2",Field.Store.YES,Field.Index.TOKENIZED));
Document doc3 = new Document();
doc3.add(new Field("content","david smith robert mary",Field.Store.YES,Field.Index.TOKENIZED));
doc3.add(new Field("title","doc3",Field.Store.YES,Field.Index.TOKENIZED));
IndexWriter writer = new IndexWriter("c:\\index",new StandardAnalyzer(),true);
//writer.setUseCompoundFile(true); //設置為混合索引格式
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
writer.close();
IndexSearcher searcher = new IndexSearcher("c:\\index");
Term word1 = new Term("content","david");
Term word2 = new Term("content","mary");
Term word3 = new Term("content","smith");
Term word4 = new Term("content","robert");
PhraseQuery query = new PhraseQuery();
query.add(word1);
query.add(word2);
query.add(word3);
query.setSlop(Integer.MAX_VALUE);
Hits hits = searcher.search(query);
Print.printResult(hits,"david and mary");
}
}
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程