只看原创   查看文章

封装Lucene日常操作

使用包装类对象,进行操作,请注意!!!

import com.neal.myblog.entity.TArticleVO;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

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

/*
   1.写一段传统的JDBC程序,将每条的用户信息从数据库读取出来
   2.针对每条用户记录,建立一个lucene document
        Document doc = new Document();
   3.并根据你的需要,将用户信息的各个字段对应luncene document中的field 进行添加,如:
        doc.add(new Field(“NAME”,”USERNAME”,Field.Store.YES,Field.Index.UN_TOKENIZED));
   4.然后将该条doc加入到索引中, 如: luceneWriter.addDocument(doc);
        这样就建立了lucene的索引库
   5.编写对索引库的搜索程序(看lucene文档),通过对lucene的索引库的查找,你可以快速找到对应记录的ID
   6.通过ID到数据库中查找相关记录
*/

/**
 * Lucene数据装填
 *
 * @author Neal
 */
public class DataBaseIndexUtil {

    /**
     * 设置默认索引位置
     */
    private static final String INDEX_PATH = "D://indexFile//dbIndex";
    private static Directory dir;
    private static Analyzer analyzer;
    private static IndexWriter writer;

    private DataBaseIndexUtil() {
        throw new AssertionError();
    }

    /**
     * 将Document对象更新索引(默认根据文章ID更新),用于文章更新时,对应的索引也应该更新
     *
     * @param tArticleVO TArticleVO
     * @throws IOException IOException
     */
    public static void updateIndex(TArticleVO tArticleVO) throws IOException {
        dir = FSDirectory.open(Paths.get(INDEX_PATH));
        analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
        writer = new IndexWriter(dir, iwc);
        writer.updateDocument(new Term("article_id", tArticleVO.gettArticleEX().getArticleId() + ""), getDoc(tArticleVO));
        writer.commit();
        writer.close();
    }

    /**
     * 增加索引,用于文章发布时,添加对应索引
     *
     * @param tArticleVO TArticleVO
     * @throws IOException IOException
     */
    public static void addIndex(TArticleVO tArticleVO) throws IOException {
        dir = FSDirectory.open(Paths.get(INDEX_PATH));
        analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
        writer = new IndexWriter(dir, iwc);
        writer.addDocument(getDoc(tArticleVO));
        writer.commit();
        writer.close();
    }

    /**
     * 删除指定索引,用于文章删除时,对应索引也应该删除
     *
     * @throws IOException IOException
     */
    public static void deleteIndex(long articleId) throws IOException {
        dir = FSDirectory.open(Paths.get(INDEX_PATH));
        analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        writer = new IndexWriter(dir, iwc);
        writer.deleteDocuments(new Term("article_id", articleId + ""));
        writer.commit();
        writer.close();
    }

    /**
     * 返回一个更新后的Document对象,用于更新,添加索引
     *
     * @param tArticleVO TArticleVO,包装类
     * @return Document
     */
    private static Document getDoc(TArticleVO tArticleVO) {
        Document doc = new Document();
        doc.add(new TextField("article_id", tArticleVO.gettArticleEX().getArticleId() + "", Field.Store.YES));
        doc.add(new TextField("article_title", tArticleVO.gettArticleEX().getArticleTitle() + "", Field.Store.YES));
        doc.add(new TextField("article_time", tArticleVO.gettArticleEX().getArticleTime() + "", Field.Store.YES));
        doc.add(new TextField("article_content", tArticleVO.gettArticleEX().getArticleContent() + "", Field.Store.YES));
        doc.add(new TextField("article_tag", tArticleVO.gettArticleEX().getArticleTag() + "", Field.Store.YES));
        doc.add(new TextField("category_name", tArticleVO.gettCategory().getCategoryName() + "", Field.Store.YES));
        return doc;
    }
}

当然,还有测试查询

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.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 java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


/**
 * Lucene数据查找
 *
 * @author dell
 */
public class DataBaseSearcherUtil {

    /**
     * 默认索引位置
     */
    private static final String INDEX_PATH = "D://indexFile//dbIndex";

    private DataBaseSearcherUtil() {
        throw new AssertionError();
    }

    /**
     * 返回文章ID list
     *
     * @param file     确认搜索的域
     * @param keywords 关键字
     * @param num      搜素深度
     * @return List
     * @throws IOException    IOException
     * @throws ParseException ParseException
     */
    public static List<String> searchData(String file, String keywords, int num) throws IOException, ParseException {
        Directory dir;
        dir = FSDirectory.open(Paths.get(INDEX_PATH));
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);
        Analyzer analyzer = new StandardAnalyzer();
        QueryParser parser = new QueryParser(file, analyzer);
        parser.setDefaultOperator(QueryParser.AND_OPERATOR);
        Query query = parser.parse(keywords);
        TopDocs hits = searcher.search(query, num);
        List<String> list = new ArrayList<>();
        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            list.add(doc.get("article_id"));
        }
        System.out.println("有效的索引文档:" + reader.numDocs());
        System.out.println("删掉的索引文档:" + reader.numDeletedDocs());
        return list;
    }

    public static void main(String[] args) {
        try {
            List<String> list = searchData("article_content", "nothing", 100);
            System.out.println(list.size());
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

当然,你需要这样使用

/**
     * 客户端关键字搜索
     *
     * @param keywords 关键字
     * @param modelMap ModelMap
     * @return 视图
     * @throws IOException    IOException
     * @throws ParseException ParseException
     */
    @RequestMapping(value = "/searchArticleToRead", method = RequestMethod.POST)
    public String searchArticleToRead(String keywords, ModelMap modelMap) throws IOException, ParseException {
        List<String> list = DataBaseSearcherUtil.searchData("article_content", keywords, 10);
        // 如果在文章内容没搜索到,则转到搜索标题,标题没搜索到,就搜索文章属性
        if (list.size() == 0) {
            list = DataBaseSearcherUtil.searchData("article_title", keywords, 10);
            if (list.size() == 0) {
                list = DataBaseSearcherUtil.searchData("category_name", keywords, 10);
            }
        }
        List<TArticleVO> articleVOS = new ArrayList<>();
        if (list.size() > 0) {
            for (String articleId : list) {
                //将查询的ID索引,进行数据库查询,返回文章list
                articleVOS.add(articleByVisitorService.getArticleById(Long.parseLong(articleId)));
            }
        }
        modelMap.addAttribute("articleVOS", articleVOS);
        // 调用数据库的侧边栏查询
        asideContent(modelMap);
        return "page/index";
    }


原创 Feb 8, 2018 9:35:55 PM 71 0

使用Zxing处理二维码

去maven仓库下载Google家的zxing的jar包,或者直接maven引入依赖,具体使用到了两个jar包,zxing javase.jar 还有zxing core核心jar包,下面是代码

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

/**
 * 二维码测试类
 *
 * @author 10614
 */
public class Test {
    public static void main(String[] args) throws IOException, WriterException {
//        testEncode();
        testDecode();
    }

    /**
     * 生成二维码
     *
     * @throws WriterException WriterException
     * @throws IOException     IOException
     */
    private static void testEncode() throws WriterException, IOException {
        String filePath = "D://";
        String fileName = "zxing.png";
        String content = "测试zxing生成二维码";
        // 图像宽度
        int width = 300;
        // 图像高度
        int height = 300;
        // 图像类型
        String format = "png";
        Map<EncodeHintType, Object> hints = new HashMap<>(16);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 生成矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        Path path = FileSystems.getDefault().getPath(filePath, fileName);
        // 输出图像
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);
        System.out.println("输出成功.");
    }

    /**
     * 解析二维码
     */
    private static void testDecode() {
        String filePath = "D:\\loginqrcode.jpg";
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<>(16);
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            // 对图像进行解码
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            System.out.println("图片中内容:  ");
            System.out.println("author: " + result.getText());
            System.out.println("图片中格式:  ");
            System.out.println("encode: " + result.getBarcodeFormat());
        } catch (IOException | NotFoundException e) {
            e.printStackTrace();
        }
    }
}


原创 Feb 27, 2018 10:34:37 AM 81 1

我的头像

黑天白夜

你懂的越多,懂你的就越少!

  • 来访数:4,422
  • 总文章:28
  • 原创数:27
  • 点赞数:8