依赖
<lunece.version>8.5.0</lunece.version>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>${lunece.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>${lunece.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>${lunece.version}</version>
</dependency>
<dependency>
<groupId>com.jianggujin</groupId>
<artifactId>IKAnalyzer-lucene</artifactId>
<version>8.0.0</version>
</dependency>
创建写索引
public void indexCreate(){
try {
FSDirectory directory = FSDirectory.open(Paths.get("F:\\lucene\\index\\example03"));
StandardAnalyzer analyzer = new StandardAnalyzer();
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer));
Document doc1 = new Document();
doc1.add(new IntField("id",1,Field.Store.YES));
doc1.add(new StringField("name", "zhangsan", Field.Store.YES));
doc1.add(new StringField("age", "15", Field.Store.YES));
doc1.add(new StringField("test", "a", Field.Store.YES));
doc1.add(new TextField("content", "百知教育 I love baizhi", Field.Store.YES));
doc1.add(new Field("date", DateTools.dateToString(new Date(), Resolution.SECOND), StringField.TYPE_STORED));
Document doc2 = new Document();
doc2.add(new IntField("id",2,Field.Store.YES));
doc2.add(new StringField("test", "e", Field.Store.YES));
doc2.add(new StringField("age", "18", Field.Store.YES));
doc2.add(new StringField("name", "lisi", Field.Store.YES));
doc2.add(new TextField("content", "lucene实战开发 I love Lucene", Field.Store.YES));
doc2.add(new Field("date", DateTools.dateToString(new Date(), Resolution.SECOND), StringField.TYPE_STORED));indexWriter.addDocument(doc1);
indexWriter.addDocument(doc2);
indexWriter.close();
directory.close();
} catch (Exception e) {
e.printStackTrace();
}
}
创建读索引
FSDirectory directory = FSDirectory.open(Paths.get("F:\\lucene\\index\\example04"));
IndexReader indexReader = DirectoryReader.open(directory);
DirectoryReader directoryReader = DirectoryReader.openIfChanged((DirectoryReader) indexReader);
if(directoryReader != null){
indexReader.close();
indexReader = directoryReader;
}
IndexSearcher searcher = new IndexSearcher(indexReader);
查询
常用Query查询
1. TermQuery
Query query = new TermQuery(new Term("content","百" ));
2. TermRangeQuery
Query query = new TermRangeQuery("name", new BytesRef("zh"),new BytesRef("an"), true, true);
3. NumericRangeQuery
Query query = NumericRangeQuery.newIntRange("id", 2, 3, true,false);
4. PrefixQuery
Query query = new PrefixQuery(new Term("name","lis"));
5. WildcardQuery
Query query = new WildcardQuery(new Term("content","育*"));
6. FuzzyQuery
Query query = new FuzzyQuery(new Term("content","baiahi"));
7. BooleanQuery
BooleanQuery.Builder builder=new BooleanQuery.Builder();
TermQuery query1 = new TermQuery(new Term("content","百"));
TermQuery query2 = new TermQuery(new Term("name","zhangsan"));
query.add(query1,Occur.MUST_NOT);
query.add(query2,Occur.MUST);
8. PhraseQuery
PhraseQuery query = new PhraseQuery();
query.setSlop(1);
query.add(new Term("content","i"));
query.add(new Term("content","baizhi"));
Sort sort = new Sort(new SortField(“id”, SortField.Type.LONG, true));
TopDocs topDocs = searcher.search(query, 10,sort);
基于QueryParser的高级搜索
public void indexSearchByQueryParser(){
try {
FSDirectory directory = FSDirectory.open(Paths.get("F:\\lucene\\index\\example03"));
IndexReader indexReader = DirectoryReader.open(directory);
DirectoryReader directoryReader = DirectoryReader.openIfChanged((DirectoryReader) indexReader);
if(directoryReader != null) indexReader = directoryReader;
IndexSearcher searcher = new IndexSearcher(indexReader);
QueryParser queryParser = new QueryParser("content", new StandardAnalyzer());
Query query = null;
query = queryParser.parse("百知");
query = queryParser.parse("test:[a TO e]");
query = queryParser.parse("age:{10 TO 20}");
query = queryParser.parse("百*");
query = queryParser.parse("lo?e");
query = queryParser.parse("baiz?i");
query = queryParser.parse("baizha~");
query = queryParser.parse("lovi~");
query = queryParser.parse("name:zhangsan OR lucene");
query = queryParser.parse("name:zhangsan AND baizhi");
query = queryParser.parse("name:zhangsan NOT lucene");
query = queryParser.parse("content:\"love lucene\"");
query = queryParser.parse("content:\"i lucene\"~1");
query = queryParser.parse("百知^0.1");
query = queryParser.parse("+love -name:zhangsan");
query = queryParser.parse("love -baizhi");
TopDocs topDocs = searcher.search(query, 10);
System.out.println("查询结果:"+topDocs.totalHits+"条");
System.out.println("最大文档数:"+indexReader.maxDoc());
System.out.println("最大索引文档数:"+indexReader.numDocs());
for(ScoreDoc sd : topDocs.scoreDocs){
System.out.print(searcher.doc(sd.doc).get("id")+" | ");;
System.out.print(searcher.doc(sd.doc).get("name")+" | ");;
System.out.print(searcher.doc(sd.doc).get("content")+" | ");;
System.out.print(DateTools.stringToDate(searcher.doc(sd.doc).get("date")));
System.out.println();
}
indexReader.close();
directory.close();
} catch (Exception e) {
e.printStackTrace();
}
}
分页
@Test
public void indexSearchByPage() {
try {
FSDirectory directory = FSDirectory.open(Paths.get("F:\\lucene\\index\\example04"));
IndexReader indexReader = DirectoryReader.open(directory);
DirectoryReader directoryReader = DirectoryReader.openIfChanged((DirectoryReader) indexReader);
if(directoryReader != null){
indexReader.close();
indexReader = directoryReader;
}
IndexSearcher searcher = new IndexSearcher(indexReader);
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse("name:张三*");
int nowPage = 8;
int pageSize = 10;
int start = (nowPage-1)*pageSize;
TopDocs td1 = searcher.search(query, start);
ScoreDoc scoreDoc = null;
if (start > 1){
scoreDoc = td1.scoreDocs[start-1];
}
TopDocs topDocs = searcher.searchAfter(scoreDoc, query, pageSize);
System.out.println("总条数:"+topDocs.totalHits);
for (ScoreDoc sd : topDocs.scoreDocs) {
Document doc = searcher.doc(sd.doc);
System.out.print(doc.get("id")+" | ");
System.out.print(doc.get("name")+" | ");
System.out.print(doc.get("content"));
System.out.println();
}
indexReader.close();
directory.close();
} catch (Exception e) {
e.printStackTrace();
}
}
高亮查询
@Test
public void testHighlighter() throws Exception {
IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("C:\\Users\\JackChen\\Desktop\\index").toPath()));
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
Query query = queryParser.parse("lucene.txt");
Formatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>");
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(formatter, scorer);
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("总记录数:" + topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc doc:scoreDocs){
System.out.println("----------开始------------");
int docId = doc.doc;
Document document = indexSearcher.doc(docId);
String highlighterContent = highlighter.getBestFragment(new StandardAnalyzer(),"name",document.get("name"));
System.out.println(highlighterContent);
document.getField("content");
System.out.println(document.get("name"));
System.out.println(document.get("content"));
System.out.println(document.get("path"));
System.out.println(document.get("size"));
System.out.println("----------结束------------");
}
indexReader.close();
}