从lucene看世界(二) 初步搜索

时间关系,直接上代码,后续再完善

package com.nsu.edu.cn.lemon.task;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.xml.QueryBuilder;
import org.apache.lucene.queryparser.xml.builders.TermQueryBuilder;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * @author :zhangpengyu
 * @date :Created in 2019/7/22 21:22
 * @description:第一节 初始lucene
 * @modified By:
 * @version: 1.0.0$
 */
public class SearchLucene {
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchLucene.class);
    public static void main(String[] args) throws IOException {
        IndexReader indexReader = null;
        try {
            LOGGER.info("lucene index start .");
            //TODO 创建Directory
            //创建在内存中
            Directory directory = new RAMDirectory();
            //创建在文件中
            Directory directory1 = FSDirectory.open(Paths.get("D:/Demo/firstIndex"));
            //TODO 创建IndexReader
            indexReader = DirectoryReader.open(directory1);
            //TODO 根据indexReader创建indexSearch
            IndexSearcher indexSearcher = new IndexSearcher(indexReader);
            //TODO 创建搜索的query
            Analyzer analyzer = new StandardAnalyzer();
            QueryBuilder queryBuilder = new TermQueryBuilder();
            QueryParser queryParser = new QueryParser("content", analyzer);
            Query query = queryParser.parse( "时光机");
            //TODO 根据searcher搜索并返回topDoc
            TopDocs tds = indexSearcher.search(query, 10);
            //TODO 根据topDoc搜索并返回scoreDoc
            ScoreDoc[] sds = tds.scoreDocs;
            System.out.println(sds.length);
            for(ScoreDoc sd:sds){
                //TODO 根据searcher和scoreDoc获取Document对象
                Document d = indexSearcher.doc(sd.doc);
                //TODO 根据Document对象获取需要的值
                System.out.println(d.get("name"));
            }
            LOGGER.info("lucene index end .");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            if (indexReader != null) {
                indexReader.close();
            }
        }
    }
}

你可能感兴趣的:(日积月累)