您的位置:首页 > 其它

Lucene6入门教程(三)搜索和查询

2017-08-21 16:43 447 查看
要想实现搜索,就需要构建索引和搜索引擎这两个方面,上节已经实现目录的构建,那么,在(三)中,我们需要实现的便是搜索引擎的构建了。

**(一)搜索构建的步骤如下:**
(1)创建Directory和IndexReader;(即空间支持和读取文件)
(2)根据IndexReader创建IndexSearch;(对IndexReader的查询实现)
(3)创建搜索的Query、parser和Query ;(表示查询方法/范围/对象)
(4)searcher开始搜索并且返回TopDocs;(开始搜索,记录topDocs)
(5)根据TopDocs获取对象,结束。
**(二)IndexSearch()介绍**
IndexSearch()是索引查询器,用以完成Lucene6搜索引擎(索引内容和查询索引)中,索引查询器的构建过程。 IndexSearch()的特点:
(1)它实现了对单个IndexReader查询;
(2)之后调用search(Query,n)方法实现对索引的查询;
(3)可共享,多线程和实时查询等;
**(三)Query(查询)的介绍**
Query类是是一个抽象类,包含各种各样的实用方法,它的所有类型查询的子类都是在Lucene6的搜索过程中使用的,常与Term类(查询搜索中的最低单位,类似于Field)使用。
搜索过程中,需要用创建parser确定要搜索的内容,需要query1创建搜索的对象。


//java代码,搜索查询“content”
package com.Licene6;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Paths;

/***Created by Mo
*On 2017/8/18  ***14:18.
* *  Lucene6.4.1搜索
******/
public class Searcher {
//这个方法是搜索索引的方法,传入索引路径和查询表达式
public static void search(String indexDir,String query) throws IOException, ParseException {
//打开索引目录
Directory dir= FSDirectory.open(Paths.get(indexDir));
// 1234、创建搜索的Query
IndexSearcher searcher=new IndexSearcher(DirectoryReader.open(dir));
// 使用标准的分词器
Analyzer analyzer = new StandardAnalyzer();
// 在content中搜索,创建parser确定要搜索的内容,其中,第2个参数为搜索的域
QueryParser parser=new QueryParser("contents",analyzer);
// 创建Query表示搜索域为content中,包含搜索内容为query1的文档
Query query1=parser.parse(query);
long start=System.currentTimeMillis();
// 开始搜索
TopDocs hits=searcher.search(query1,11);
long end=System.currentTimeMillis();
System.out.println(hits.totalHits);
System.out.println(end-start);//计算搜搜时间等
//获取搜索的地址等
for(ScoreDoc scoreDoc:hits.scoreDocs){
Document doc=searcher.doc(scoreDoc.doc);
System.out.println(doc.get("fullpath"));//地址,完整的
}
}

public static void main(String[] args) throws IOException, ParseException {
String indexDir="D:\\workspace\\lucene6.4.1\\learing2017.8\\0818\\index";//索引,index时建立的
String query="content";//搜索的word
search(indexDir, query);
}
}


参考文献:

1.索引查询器:http://blog.csdn.net/wuyinggui10000/article/details/45698667

2.搜索初步:http://blog.csdn.net/zpf336/article/details/45079319
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: