您的位置:首页 > 其它

lucene初级入门

2017-04-11 13:39 302 查看
1、Lucene的核心jar包

lucene-core-4.3.1.jar

lucene-analyzers-common-4.3.1.jar

lucene-queryparser-4.3.1.jar

2、主要开发包说明

org.apache.lucene.analysis:语言分析器,主要用于分词

org.apache.lucene.document:索引文档的管理

org.apache.lucene.index:索引管理,如增、删、改

org.apache.lucene.queryparser:查询分析

org.apache.lucene.search:检索管理

org.apache.lucene.store:数据存储管理

org.apache.lucene.util:工具包

3、写入索引操作的核心类

Directory:代表索引文档的存储位置,这是一个抽象类有FSDirectory和RAMDirectory两个主要子类。前者将索引写入文件系统,后者将索引文档写入内存。

Analyzer:建立索引时使用的分析器,主要子类有StandardAnalyzer(一个汉字一个词),还可以由第三方提供如开源社区提供一些中文分词器。

IndexWriterConfig:操作索引库的配置信息

IndexWriter:建立索引的核心类,用来操作索引(增、删、改)

Document:代表一个索引文档

Field:代表索引文档中存储的数据,新版本的Lucene进行了细化给出了多个子类:IntField、LongField、FloatField、DoubleField、TextField、StringField等。

4、写入索引

public class IndexFile {
public static void main(String[] args) throws IOException {
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
Directory directory = FSDirectory.open(new File("D:/index"));
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_42,
analyzer);
IndexWriter it = new IndexWriter(directory, iwc);
Document doc = new Document();
doc.add(new org.apache.lucene.document.TextField("info",
"this is my firdt lucene test", Field.Store.YES));
it.addDocument(doc);
it.close();
directory.close();
}
}

5、查询索引操作的核心类

IndexReader:读取索引的工具类,常用子类有DirectoryReader

IndexSearch:查询索引的核心类

QueryParser:查询分析器,表示从哪里查用哪个分析器

Query:代表一次查询

TopDocs:封装了匹配情况,比如匹配多少个

ScoreDoc:匹配的数据,里面封装了索引文档的得分和索引ID

6、查询索引


public class SearcheFile {
public static void main(String[] args) throws Exception {
Analyzer a = new StandardAnalyzer(Version.LUCENE_42);
Directory dir =FSDirectory.open(new File("D:/index"));
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher is = new IndexSearcher(reader);
QueryParser parse = new QueryParser(Version.LUCENE_42, "info", a);
Query query = parse.parse("lucene");
TopDocs topDocs = is.search(query, 1000);
System.out.println("总共匹配多少个:"+topDocs.totalHits);
ScoreDoc[] hits = topDocs.scoreDocs;
System.out.println("多少条数据:"+hits.length);
for (ScoreDoc scoreDoc : hits) {
System.out.println("匹配得分:"+scoreDoc.score);
System.out.println("文档索引ID:"+scoreDoc.doc);
Document doc = is.doc(scoreDoc.doc);
System.out.println(doc.get("info"));
}
reader.close();
dir.close();
}

}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: