Lucene是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎。
1,所需的基础jar包
lucene-analyzers-common-6.4.2.jar
lucene-core-6.4.2.jar
lucene-memory-6.4.2.jar
lucene-queryparser-6.4.2.jar
lucene-core-6.4.2.jar
lucene-memory-6.4.2.jar
lucene-queryparser-6.4.2.jar
官方下载地址:http://www.apache.org/dyn/closer.lua/lucene/java/6.4.2
2,lucene倒排索引原理
3,一些基础代码实现
package com.zhuyun.demo;
import java.nio.file.Paths;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
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.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
public class LuceneDemo {
@Test
public void createIndex() throws Exception {
IndexWriter indexWriter = new IndexWriter(FSDirectory.open(Paths.get("index/")), new IndexWriterConfig(new StandardAnalyzer()));
Document document = new Document();
document.add(new StringField("age", "17", Store.YES));
document.add(new StringField("name", "cai", Store.YES));
document.add(new StringField("content", "aaaa", Store.YES));
indexWriter.addDocument(document);
indexWriter.close();
}
@Test
public void searchIndex() throws Exception {
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(Paths.get("index/"))));
Query query = new TermQuery(new Term("age", "17")); //查询age=15的文档
// Query query = new QueryParser("content", analyzer).parse("张三是个教师!");
TopDocs topDocs = indexSearcher.search(query, 10); //返回符合条件的前10条
System.out.println("count:" + topDocs.totalHits); //查询出来的结果总数
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
Document document = null;
for (ScoreDoc scoreDoc : scoreDocs) {
int docId = scoreDoc.doc;
document = indexSearcher.doc(docId);
String age = document.get("age");
String name = document.get("name");
String content = document.get("content");
System.out.println("age:" + age + ",name:" + name + ",content:"
+ content);
}
}
}
第二个方法,根据条件查询结果:
count:1
age:17,name:cai,content:aaaa