Lucene基本使用-2(读取数据库,未封装)-SpringBoot

**

依赖:续前篇 https://blog.csdn.net/mtm001/article/details/106360908

**
数据库文件:在项目的resources文件夹里。还在审核
在这里插入图片描述
实体

package com.hr.lucene.entity;


import java.util.Date;

public class Products {

  private Integer pid;
  private String name;
  private Integer catalog;
  private String catalogName;
  private double price;
  private Integer number;
  private String description;
  private String picture;
  private Date releaseTime;


  public Integer getPid() {
    return pid;
  }

  public void setPid(Integer pid) {
    this.pid = pid;
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }


  public Integer getCatalog() {
    return catalog;
  }

  public void setCatalog(Integer catalog) {
    this.catalog = catalog;
  }


  public String getCatalogName() {
    return catalogName;
  }

  public void setCatalogName(String catalogName) {
    this.catalogName = catalogName;
  }


  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }


  public Integer getNumber() {
    return number;
  }

  public void setNumber(Integer number) {
    this.number = number;
  }


  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }


  public String getPicture() {
    return picture;
  }

  public void setPicture(String picture) {
    this.picture = picture;
  }


  public Date getReleaseTime() {
    return releaseTime;
  }

  public void setReleaseTime(Date releaseTime) {
    this.releaseTime = releaseTime;
  }

}

Mapper

package com.hr.lucene.mapper;

import com.hr.lucene.entity.Products;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface ProductsMapper {
    @Results(id = "findAll",value = {
            @Result(property = "id",column = "id",id = true),
            @Result(property = "releaseTime",column = "release_time")
    })
    @Select("select * from products")
    List<Products> findAll();
}

Dao

package com.hr.lucene.dao;

import com.hr.lucene.entity.Products;
import com.hr.lucene.mapper.ProductsMapper;
import org.apache.lucene.analysis.Analyzer;
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.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Repository;
import org.wltea.analyzer.lucene.IKAnalyzer;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName LuceneDao
 * @Description: TODO
 * @Author 汤永红
 * @Date 2020/5/26 0026
 * @Version V1.0
 **/
@Repository
public class ProductsDao {
    @Resource
    private ProductsMapper mapper;
    //创建索引
    public void createIndex() throws Exception{

        //2.索引库 D:\lucene\indexdb
        //3.FSD(打开哪个索引库)
        File target = new File("D:\\lucene\\products");
        FSDirectory directory = FSDirectory.open(target);
        //分词器(切词) 标准,中文
        //StandardAnalyzer analyzer = new StandardAnalyzer();
        Analyzer analyzer = new IKAnalyzer();//中文分词器
        //版本号
        Version version =Version.LUCENE_4_10_3;
        //配置文件
        IndexWriterConfig iwc = new IndexWriterConfig(version, analyzer);
        //写
        IndexWriter iw = new IndexWriter(directory, iwc);
        List<Products> lists = mapper.findAll();
        if(lists!=null && lists.size()>0){
            for (Products product : lists) {


        // 对以上的内容进行字段构建

                Document doc = new Document();
                doc.add(new TextField("pid", product.getPid()+"", Field.Store.YES));
                doc.add(new TextField("name", product.getName(), Field.Store.YES));
                doc.add(new TextField("catalog", product.getCatalog()+"", Field.Store.YES));
                doc.add(new TextField("catalog_name", product.getCatalogName()+"", Field.Store.YES));
                doc.add(new TextField("price", product.getPid()+"", Field.Store.YES));
                doc.add(new TextField("number", product.getNumber()+"", Field.Store.YES));
                doc.add(new TextField("description", product.getDescription()+"", Field.Store.YES));
                doc.add(new TextField("picture", product.getPicture(), Field.Store.YES));
                System.out.println(product.getReleaseTime());
                String mydate= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(product.getReleaseTime());
                doc.add(new TextField("release_time", mydate, Field.Store.YES));
//                写入
                iw.addDocument(doc);
            }
            iw.close();
        }

    }

    //搜索索引
    public List<Products> searchIndex(String field,String keyWords,int size) throws Exception{
        //1.FSD(打开哪个索引库)
        File target = new File("D:\\lucene\\products");
        FSDirectory directory = FSDirectory.open(target);
        //2.打开索引库
        DirectoryReader reader = DirectoryReader.open(directory);
        //3.创建搜索
        IndexSearcher searcher = new IndexSearcher(reader);
        //4.要搜索的字段和内容
        Term term = new Term(field,keyWords);
        //5.创建查询,返加几条
        TermQuery termQuery = new TermQuery(term);
        //6.搜索
        TopDocs docs = searcher.search(termQuery, size);//条数
        //7.获取document
        ScoreDoc[] mydoc=docs.scoreDocs;
        List<Products> lists = null;
        if(mydoc!=null && mydoc.length>0){
            lists = new ArrayList<>();
            for (ScoreDoc scoreDoc : mydoc) {
                int index = scoreDoc.doc;//下标
                Document doc = searcher.doc(index);
                Products info = new Products();
                //pid
                info.setPid(Integer.parseInt(doc.get("pid")));
                //name
                info.setName(doc.get("name"));
                //catalog
                info.setCatalog(Integer.parseInt(doc.get("catalog")));
                //catalog_name
                info.setCatalogName(doc.get("catalog_name"));
                //price
                info.setPid(Integer.parseInt(doc.get("price")));
                //number
                info.setNumber(Integer.parseInt(doc.get("number")));
                //description
                info.setDescription(doc.get("description"));
                //picture
                info.setPicture(doc.get("picture"));
                //release_time
                String release_time = doc.get("release_time");
                Date parse = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(release_time);
                info.setReleaseTime(parse);
                lists.add(info);
                info = null;
            }
        }
        return  lists;
    }

}




application.properties

server.port=8888
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=52Java

web

package com.hr.lucene.web;

import com.hr.lucene.dao.ProductsDao;
import com.hr.lucene.entity.Products;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName LuceneController
 * @Description: TODO
 * @Author 汤永红
 * @Date 2020/5/26 0026
 * @Version V1.0
 **/
@RestController
@RequestMapping("/api/products")
public class ProductsController {
    @Resource
    private ProductsDao dao;
    @RequestMapping("/createIndex")
    public String createIndex(){
        //调工具包的代码
        try {
            dao.createIndex();
            return "成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "失败";
    }
//        /api/lucene/useIndex
    @RequestMapping("/useIndex/{key}")
    public List<Products> useIndex(@PathVariable("key") String key){
        //调工具包的代码
        try {
            List<Products> products = dao.searchIndex("name",key,10);
            return products;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }
}

测试:
创建索引
http://localhost:8888//api/products/createIndex
在这里插入图片描述
搜索索引
http://localhost:8888//api/products/useIndex/%E5%AE%B6%E5%A4%A9%E4%B8%8B
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤永红

一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值