lucene9 给个demo
时间: 2023-11-21 12:03:56 浏览: 245
好的,下面是一个简单的 Lucene9 的示例代码,包括创建索引和搜索:
```java
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
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.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import java.nio.file.Paths;
public class LuceneDemo {
public static void main(String[] args) throws IOException, ParseException {
// 创建索引
Directory directory = FSDirectory.open(Paths.get("index"));
IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());
IndexWriter writer = new IndexWriter(directory, config);
Document doc1 = new Document();
doc1.add(new TextField("content", "Lucene is a full-text search engine library in Java", Field.Store.YES));
writer.addDocument(doc1);
Document doc2 = new Document();
doc2.add(new TextField("content", "Lucene is used to build search applications", Field.Store.YES));
writer.addDocument(doc2);
writer.close();
// 搜索
Directory directory2 = FSDirectory.open(Paths.get("index"));
IndexSearcher searcher = new IndexSearcher(directory2);
// TermQuery
Query termQuery = new TermQuery(new Term("content", "search"));
TopDocs topDocs = searcher.search(termQuery, 10);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document doc = searcher.doc(scoreDoc.doc);
System.out.println(doc.get("content") + " score: " + scoreDoc.score);
}
// QueryParser
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse("Lucene search");
TopDocs topDocs2 = searcher.search(query, 10);
for (ScoreDoc scoreDoc : topDocs2.scoreDocs) {
Document doc = searcher.doc(scoreDoc.doc);
System.out.println(doc.get("content") + " score: " + scoreDoc.score);
}
searcher.getIndexReader().close();
directory2.close();
}
}
```
以上代码创建了一个包含两条文档的索引,然后使用 TermQuery 和 QueryParser 分别进行了搜索,并打印出了搜索结果。
阅读全文