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
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章