创建:
public static void createLuceneCode(List<String> cars,String index) throws IOException {
// 1. 创建分词器,分析文档,对文档进行分词
Analyzer analyzer = new IKAnalyzer();
// 2. 创建Directory对象,声明索引库的位置
File file;
if (index.equals("a")){
file=new File(afile);
}else {
file=new File(bfile);
}
Directory directory = FSDirectory.open(Paths.get(String.valueOf(file)));
// 3. 创建IndexWriteConfig对象,写入索引需要的配置
IndexWriterConfig config = new IndexWriterConfig(analyzer);
// 4.创建IndexWriter写入对象
IndexWriter indexWriter = new IndexWriter(directory, config);
// 5.写入到索引库,通过IndexWriter添加文档对象document
//文档集合
List<Document> docList = new ArrayList<>();
for (String car: cars) {
Document doc = new Document();
doc.add(new TextField("cars",car,Field.Store.YES));//由于数据是字符串集合,只需要一个
docList.add(doc);
indexWriter.addDocument(doc);
}
// 6.释放资源
indexWriter.close();
}
查询:
public static synchronized String Search(String que,String index) throws IOException, ParseException {
//1. 创建分词器
log.info("创建分词器");
Analyzer analyzer = new IKAnalyzer();
//2. 创建查询对象,
log.info("创建查询对象");
QueryParser queryParser = new QueryParser("cars", analyzer);
//3. 设置搜索关键词
log.info("设置搜索关键词");
Query query = queryParser.parse(QueryParser.escape(que));
//4. 创建Directory目录对象, 指定索引库的位置
log.info("创建Directory目录对象, 指定索引库的位置");
File file;
if (index.equals("a")){
file=new File(afile);
}else {
file=new File(bfile);
}
//打开文件目录
Directory dir = FSDirectory.open(Paths.get(String.valueOf(file)));
//5. 创建输入流对象
IndexReader indexReader = DirectoryReader.open(dir);
//6. 创建搜索对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//7. 搜索, 并返回结果
TopDocs topDocs = indexSearcher.search(query,3);
//8. 获取结果集
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//9. 遍历结果集
log.info("获取第一个数据");
if (scoreDocs != null) {
for (ScoreDoc scoreDoc : scoreDocs) {
int docId=scoreDoc.doc;
Document doc = indexSearcher.doc(docId);
indexReader.close();
return String.valueOf(doc.get("cars"));
}
}
return "未找到匹配对象";
}