<pre name="code" class="java">package com.lucene.demo1;
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;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
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.store.Directory;
import org.apache.lucene.store.RAMDirectory;
public class SimpleDemo {
public static void main(String[] args) throws Exception {
// 定义分析器
Analyzer analyzer = new StandardAnalyzer();
// Store the index in memory:
Directory directory = new RAMDirectory();
// 把索引存储在内存里,FSDirectory.open(new File("index"))把索引存在磁盘里
IndexWriterConfig config = new IndexWriterConfig(analyzer);
// 把文件添加到索引
IndexWriter iwriter = new IndexWriter(directory, config);
// 创建Document对象
Document doc = new Document();
String text = "hello world";
String text2 = "hello world2";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
doc.add(new Field("fieldname2", text2, TextField.TYPE_NOT_STORED));
iwriter.addDocument(doc);
iwriter.close();
System.out.println(doc.getFields());
// 从索引读取数据
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// 查询fieldname对应的值包含text的值
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("hello");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
System.out.println(hits.length);
// 输出查询结果
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println(hitDoc.get("fieldname"));
System.out.println(hitDoc.getField("fieldname"));
System.out.println(hitDoc.get("fieldname2"));
System.out.println(hitDoc.getField("fieldname2"));
}
ireader.close();
directory.close();
}
}
Lucene--简单的写与读
最新推荐文章于 2021-02-17 17:30:50 发布