1、創建Directory
2、根據directory創建indexReader
3、根據indexReader創建indexSearcher
4、創建搜索的Query
5、根據searcher搜索並且返回TopDocs
6、根據TopDocs獲取ScordDoc對象獲取具體的Document對象
7、根據searcher和ScordDoc對象獲取具體的Document對象
8、根據Document對象獲取需要的值
9、關閉reader
- /**
- * @see 1、關鍵詞查詢
- * @see 2、查詢所有的文檔 重點
- * @see 3、範圍查詢
- * @see 4、通配符查詢 重點
- * @see 5、短語查詢
- * @see 6、Boolean查詢 重點
- */
- public class QueryTest {
- /**
- * 關鍵詞查詢 * 因爲在創建Term對象的時候,沒有分詞器,所以這裏的字母是區分大小寫的 * Term構造函數的第二個參數指的是關鍵詞,必須存在
- */
- @Test
- public void testTermQuery() throws Exception {
- Term term = new Term("title", "總冠軍");
- Query query = new TermQuery(term);
- this.testSearchIndex(query);
- }
- /**
- * 查詢所有的文檔
- */
- @Test
- public void testAllQuery() throws Exception {
- Query query = new MatchAllDocsQuery();
- this.testSearchIndex(query);
- }
- /**
- * 通配符查詢 說明: * 代表任意多個任意字符 ? 代表一個任意字符
- */
- @Test
- public void testWildCardQuery() throws Exception {
- Term term = new Term("title", "*總?軍");
- Query query = new WildcardQuery(term);
- this.testSearchIndex(query);
- }
- /**
- * boolean查詢 可以根據Occur的常量把好幾個查詢結合在一起
- */
- @Test
- public void testBooleanQuery() throws Exception {
- Term term = new Term("title", "總冠軍");
- TermQuery termQuery = new TermQuery(term);
- Term term2 = new Term("content", "2?13");
- Query wildCardQuery = new WildcardQuery(term2);
- BooleanQuery query = new BooleanQuery();
- query.add(termQuery, Occur.SHOULD);// Occur.MUST必須有、Occur.MUST_NOT必須沒有、Occur.SHOULD可以有
- query.add(wildCardQuery, Occur.SHOULD);
- this.testSearchIndex(query);
- }
- /**
- * 範圍查詢 查詢id範圍在5~15間的數據
- */
- @Test
- public void testRangeQuery() throws Exception {
- Query query = NumericRangeQuery.newLongRange("id", 5L, 15L, true, true);
- this.testSearchIndex(query);
- }
- /**
- * 所有的Term對象只能在同一個field中進行 如果兩個以上大的關鍵詞進行組合查詢,得知道其中的位置(分詞後的位置)
- */
- @Test
- public void testPharseQuery() throws Exception {
- Term term = new Term("title", "NBA總冠軍");
- Term term2 = new Term("title", "NBA總冠軍");
- PhraseQuery phraseQuery = new PhraseQuery();
- phraseQuery.add(term);
- phraseQuery.add(term2);
- this.testSearchIndex(phraseQuery);
- }
- // 公共輸出方法
- private void testSearchIndex(Query query) throws Exception {
- IndexSearcher indexSearcher = new IndexSearcher(LuceneUtils.directory);
- TopDocs topDocs = indexSearcher.search(query, 50);
- int count = topDocs.totalHits;// 總的記錄數
- ScoreDoc[] scoreDocs = topDocs.scoreDocs;
- List<Article> articleList = new ArrayList<Article>();
- for (int i = 0; i < scoreDocs.length; i++) {
- int index = scoreDocs[i].doc;
- Document document = indexSearcher.doc(index);
- Article article = DocumentUtils.document2Article(document);
- articleList.add(article);
- }
- // 輸入搜索出來的內容
- for (Article article : articleList) {
- System.out.println(article.getId());
- System.out.println(article.getTitle());
- System.out.println(article.getContent());
- }
- }
- }