您的位置:首页 > 其它

lucene入门

2017-12-25 12:55 246 查看

lucene基础入门的一些细节

## 核心类 ##

1. Directory

这个类可以选择索引的存放位置信息。

Path path = Paths.get(String path);
/*
*这里最烦的就是,Directory的参数必须是Path对象,而Path和Paths只有在Java 7以后才出现。androidsdk是1.6的,所以这个东西目前无法在android上使用。
*/
Directory index_path = FSDirectory.open(Path path);


2. Analyzer

是lucene的分词器,精准的分词才是更智能搜索的核心。lucene自带标准的分词 StandardAnalyzer,要使用中文分词的话,可以用中文分词工具包IKAnalyzer。

Analyzer analyzer = new StandardAnalyzer();
Analyzer analyzer = new IKAnalyzer();


3. IndexWriterConfig

索引创建的配置参数,用于生成IndexWriter

IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);


4. IndexWriter

IndexWriter是创建索引的类,他可以对索引进行田间删除和更新操作。一般会把创建的索引文件存放到一个固定的文件夹下面,这就是上边介绍的Directory类的作用。

5. IdexReader

是一个用来读取IndexWriter创建好的索引文档的类,读取之后交给IndexSearcher来完成查找。

Directory directory = FSDirectory.open(Paths.get(indexPath));
IndexReader ireader = new Directory.open(directory)
IndexSearcher isearcher = new IndexSearcher(ireader);


现在查询类isearcher已经建立好了,就需要给他传入一个查询对象是想查询了,而IndexSearcher接受的参数对象是一个Query对象。

6. Query

生成Query对象有很多方式

luncene 查询字符串的解析

感谢这位大佬的分享

在这里还可以使用QueryParser类来生成Query对象,QUeryParser实际上是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象,使用QueryParser必须要设定一个分析器。含有中文字符的话就用IKAnalyzer。

//fieldname指的是doc中加入的属性名,比如body对应的是所有文件的内容,names指定以后的fieldnames=body,就算是在所有文件的内容中去查找keyword,返回内容符合keyword的所有文件。
//method 1
Query query = null;
query = QueryParser.parse(keyword,fieldname,analyzer)
//method 2
QueryParser parser = new QueryParser("fieldname",analyzer);
Query query = Parser.parse(keyword);


7. 获取查询结果

将查询query对象传给Isearcher就能得到一个文档数组。这个文档数组的数据是每个文档生成的document。

ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;


8. 处理查询到的结果

Document hitDoc = isearcher.doc(hits[i].doc);
String content = hitdoc.get("body");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lucene