Lucene入门

2019-09-20  本文已影响0人  iDevOps
什么是Lucene

可以使用Lucene实现全文检索。Lucene是apache下的一个开放源代码的全文检索引擎工具包。提供了完整的查询引擎和索引引擎,部分文本分析引擎,Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能。

全文检索的应用场景

对于数据量大、数据结构不固定的数据可采用全文检索方式搜索,比如百度、Google等搜索引擎、论坛站内搜索、电商网站站内搜索等。

先说说数据分类
Lucene实现全文检索的流程
创建索引和查询索引流程图
  1. 创建索引库,对要进行检索的内容进行索引构建一个索引库,具体包括原始文档->采集文档->创建文档->分析文档->索引文档
  2. 查询索引,从索引库搜索内容,具体包括创建查询->从索引库搜索->渲染搜索结果
搭建测试环境
public static void main(String[] args) throws Exception {

        //1. 创建一个Director对象,指定索引保存的位置
        Directory directory = FSDirectory.open(new File("D:\\temp\\index").toPath());//FSDirectory是保存到磁盘, RAMDirectory保存到内存

        //2. 创建一个IndexWriter对象
        IndexWriterConfig config = new IndexWriterConfig(); //默认StandardAnalyzer分词器
        IndexWriter indexWriter = new IndexWriter(directory, config);

        //3. 读取磁盘文件,每个文件都创建一个文档对象
        File dir = new File("D:\\temp\\resources");
        File[] files = dir.listFiles();
        for(File f : files){
            //文件信息
            String fileName = f.getName();
            String filePath = f.getPath();
            String fileContent = FileUtils.readFileToString(f, "utf-8");
            long fileSize = FileUtils.sizeOf(f);

            //创建Field, 参数依次: 域的名称、域的内容、是否存储
            Field fieldName = new TextField("name", fileName, Field.Store.YES);
            Field fieldPath = new StoredField("path", filePath);
            Field fieldContent = new TextField("content", fileContent, Field.Store.YES);
            Field fieldSizeValue = new LongPoint("size", fileSize);
            Field fieldSizeStore = new StoredField("size", fileSize);

            //创建Document
            Document document = new Document();
            document.add(fieldName);
            document.add(fieldPath);
            document.add(fieldContent);
            document.add(fieldSizeValue);
            document.add(fieldSizeStore);

            //把文档写入索引库
            indexWriter.addDocument(document);
        }
        //关闭indexWriter对象
        indexWriter.close();;
    }
    public static void main(String[] args) throws Exception {

        //1. 指定索引库路径
        Directory directory = FSDirectory.open(new File("D:\\temp\\index").toPath());

        //2. 创建IndexReader
        IndexReader indexReader = DirectoryReader.open(directory);

        //3. 创建IndexSearcher
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        //4. 创建查询
        Query query = new TermQuery(new Term("name", "apache"));
        TopDocs topDocs = indexSearcher.search(query, 10);//最多查询10条
        System.out.println(topDocs.totalHits);//查询的总条数
        for(ScoreDoc scoreDoc : topDocs.scoreDocs){
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println(document.get("name"));
        }

        //5. 关闭IndexReader
        indexReader.close();
    }
使用Luke工具查看索引文件
luke索引查看工具
luke主界面
分析器

对中文支持不友好

public static void main(String[] args) throws Exception{
    //1. 创建一个标准分析器
    Analyzer analyzer = new StandardAnalyzer();

    //2. 获取tokenStream对象,参数: 域名(可以随便给一个)、要分析的文本内容
    TokenStream tokenStream = analyzer.tokenStream("test", "The Spring Framework provides a comprehensive programming and configuration model.");

    //3. 添加引用
    //3.1 添加一个引用, 用于获取每个关键词
    CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
    //3.2 添加一个引用, 记录了关键词的开始位置以及结束位置
    OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);

    //4. 遍历关键词, 通过incrementToken判断列表是否结束, reset将指针调整到列表的头部
    tokenStream.reset();
    while (tokenStream.incrementToken()){
        System.out.print(offsetAttribute.startOffset() + "  ");//关键字起始位置
        System.out.print(charTermAttribute + "  ");
        System.out.println(offsetAttribute.endOffset());//关键字结束位置
    }
}
输出:
4  spring  10
11  framework  20
21  provides  29
32  comprehensive  45
46  programming  57
62  configuration  75
76  model  81
public static void main(String[] args) throws Exception{
    //1. 创建一个中文分析器
    Analyzer analyzer = new IKAnalyzer();

    //2. 获取tokenStream对象,参数: 域名(可以随便给一个)、要分析的文本内容
    TokenStream tokenStream = analyzer.tokenStream("test", "中华人民共和国");

    //3. 添加引用
    //3.1 添加一个引用, 用于获取每个关键词
    CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
    //3.2 添加一个引用, 记录了关键词的开始位置以及结束位置
    OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);

    //4. 遍历关键词, 通过incrementToken判断列表是否结束, reset将指针调整到列表的头部
    tokenStream.reset();
    while (tokenStream.incrementToken()){
        System.out.print(offsetAttribute.startOffset() + "  ");//关键字起始位置
        System.out.print(charTermAttribute + "  ");
        System.out.println(offsetAttribute.endOffset());//关键字结束位置
    }
}
索引库的维护

Field域的属性
是否分析,是否对域的内容进行分词处理
是否索引,是否将Field分析后的词或整个Field值进行索引,只有索引了才能可以搜索到。
是否存储,将Field的值存储到文档中,存储在文档中的Field才可以从Document中获取到。

Field类 数据类型 是否分析 是否索引 是否存储 描述
StringField(FieldName, FieldValue,Store.YES)) 字符串 N Y Y或N 这个Field用来构建一个字符串Field,但是不会进行分析,会将整个串存储在索引中,比如(订单号,姓名等)是否存储在文档中用Store.YES或Store.NO决定
LongPoint(String name, long... point) Long型 Y Y N 可以使用LongPoint、IntPoint等类型存储数值类型的数据。让数值类型可以进行索引。但是不能存储数据,如果想存储数据还需要使用StoredField
StoredField(FieldName, FieldValue) 重载方法,支持多种类型 N N Y 这个Field用来构建不同类Field,不分析,不索引,但要Field存储在文档中
TextField(FieldName, FieldValue, Store.NO)或TextField(FieldName, reader) 字符串或流 Y Y Y或N 如果是一个Reader, lucene猜测内容比较多,会采用Unstored的策略.
# 删除全部索引
indexWriter.deleteAll();
# 按指定查询条件删除
//创建一个查询条件
Query query = new TermQuery(new Term("filename", "apache"));
//根据查询条件删除
indexWriter.deleteDocuments(query);
indexWriter.updateDocument(new Term("content", "java"), document);
  1. 通过Lucene提供的Query子类进行查询(参考上面的代码)
  2. 通过QueryParse解析查询表达式

依赖包: lucene-queryparser-7.4.0.jar

QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
Query query = queryParser.parse("Lucene是java开发的");
上一篇 下一篇

猜你喜欢

热点阅读