创建Lucene搜索引擎和使用

创建:

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 "未找到匹配对象";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值