Lucene温故知新

全文检索技术–Lucene


1)结构化数据和非结构化数据

  像数据库中存储的数据,格式、长度、数据类型固定,这些叫结构化数据。像word、PDF文档这些格式、长度、数据类型都不固定,这些称为非结构化数据。

2)全文检索

  对于这些非结构化数据,比如我们想从文本文件中找出包含“star”单词的文件,需要把非结构化数据变为结构化数据。先跟根据空格进行字符串拆分,得到一个单词列表,基于单词列表创建一个索引。然后查询索引,根据单词和文档的对应关系找到文档列表。这个过程叫做全文检索

Lucene实现全文检索的流程

在这里插入图片描述

1】创建索引
  1)获得文档

    比如要基于哪些数据进行搜索,这些数据就是原始文档。

  2)构建文档对象

    对应每个原始文档创建一个Document文档对象,每个文档都有一个编号,就是文档id。
    :每个document对象中包含多个域(field),域中保存就是原始文档数据。包含域的名称和值。比如filename、path、content、size等。

  2)分析文档

    1、根据空格进行字符串拆分,得到一个单词列表
    2、把单词统一转换成小写。
    3、去除标点符号
    4、去除无意义的词,比如“and”、“or”等。
    5、每个关键词都封装成一个Term对象中。Term中包含两部分内容:关键词所在的域和关键词本身。不同的域中拆分出来的相同的关键词是不同的Term。

  2)创建索引

    基于关键词列表创建一个索引。保存到索引库中。索引库中有索引、 document对象、关键词和文档的对应关系。就是通过词语找文档。

2】查询索引
  1)把关键词封装成一个查询对象

    包括要查询的域、要搜索的关键词

  2)执行查询

    根据要查询的关键词到对应的域上进行搜索。找到关键词,根据关键词找到 对应的文档

  2)展示结果

    根据文档的id找到文档对象

Lucene简单实例

注意:最低要求jdk8及以上。
添加jar包:
  lucene-analyzers-common-7.4.0.jar
  lucene-core-7.4.0.jar
  commons-io.jar

1)创建索引库
步骤:
		1、创建一个Director对象,指定索引库保存的位置。
		2、基于Directory对象创建一个IndexWriter对象
		3、读取磁盘上的文件,对应每个文件创建一个文档对象。
		4、向文档对象中添加域
		5、把文档对象写入索引库
		6、关闭indexwriter对象
@Test
    public void createIndex() throws Exception{
        //1.创建一个Director对象,制定索引库保存的位置
        //索引库保存在磁盘上
        Directory directory = FSDirectory.open(new File("D:\\temp").toPath());
        //2.基于director对象创建一个indexWriter对象,indexwriterconfig默认使用标准分析器
        IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig());
        //3.读取硬盘上的文件,对应每个文件创建一个文档对象
        File dir = new File("C:\\Users\\16421\\Desktop\\12_lucene\\02.参考资料\\searchsource");
        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);//文件的大小
            //4创建filed域,参数1:域名  参数二:域的内容  参数三:是否存储在磁盘
            Field fieldName = new TextField("name",filename,Field.Store.YES);
            Field fieldPath = new TextField("path",filepath,Field.Store.YES);
            Field fieldContent = new TextField("content",fileContent,Field.Store.YES);
            Field fieldSize = new TextField("size",fileSize+"",Field.Store.YES);
            //5创建文档对象
            Document document = new Document();
            //6向文档对象中添加域
            document.add(fieldName);
            document.add(fieldContent);
            document.add(fieldPath);
            document.add(fieldSize);
            //把文档对象写入索引库
            indexWriter.addDocument(document);
        }
        //关闭indexWriter
        indexWriter.close();
    }
2)查询索引库
步骤:
		1、创建一个Director对象,指定索引库的位置
		2、创建一个IndexReader对象
		3、创建一个IndexSearcher对象,构造方法中的参数indexReader对象。
		4、创建一个Query对象,TermQuery
		5、执行查询,得到一个TopDocs对象
		6、取查询结果的总记录数
		7、取文档列表
		8、打印文档中的内容
		9、关闭IndexReader对象
		
		//此处用的是默认分析器,只能分析英文,下文有中文分析器
		@Test
    public void searchIndex() throws Exception{
        //创建Director对象,制定文件位置
        Directory directory = FSDirectory.open(new File("D:\\temp").toPath());
        //创建indexReader对象
        IndexReader indexReader = DirectoryReader.open(directory);
        //创建一个indexSearch对象,构造方法中的参数是indexReader对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //创建一个query对象,termQuery
        Query query = new TermQuery(new Term("name", "spring"));
        //执行查询得到一个Topdoc对象
        //参数1:查询对象   参数2:查询结果返回的最大记录数
        TopDocs topDocs = indexSearcher.search(query, 10);
        //取查询结果的总记录数
        System.out.println("查询总记录数:"+topDocs.totalHits);
        //取文档列表
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        //打印文档中的内容
        for (ScoreDoc scoreDoc : scoreDocs) {
            int docId = scoreDoc.doc;//得到文档id
            //根据id取文档对象
            Document document = indexSearcher.doc(docId);
            System.out.println(document.get("name"));
            System.out.println(document.get("path"));
            System.out.println(document.get("size"));
            System.out.println(document.get("content"));
            System.out.println("-----------------------");
        }
        indexReader.close();
    }

使用luke查看索引库中的内容

luke是一个查看索引库的工具,直接点luck.bat运行即可
在这里插入图片描述

分析器

  分析器起到分词的作用,比如刚才用到的是默认的分析器,它只能把英文文本分词,中文文本则需要另外的分析器。

IKAnalyzer中文分析器

IKAnalyze的使用方法
  1)把IKAnalyzer的jar包添加到工程中
  2)把配置文件和扩展词典添加到工程的classpath下,也就是src下
注意:
  扩展词典严禁使用windows记事本编辑保证扩展词典的编码格式是utf-8

扩展词典:添加一些新词
停用词词典:无意义的词或者是敏感词汇
//使用Ikanalyzer分析器创建索引
    @Test
    public void createIkIndex() throws Exception{
        //1.创建一个Director对象,制定索引库保存的位置
        //把索引库保存在内存中
        //Directory directory = new RAMDirectory();
        //索引库保存在磁盘上
        Directory directory = FSDirectory.open(new File("D:\\temp").toPath());
        //2.基于director对象创建一个indexWriter对象,使用Ikanalyzer分析器

        IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        IndexWriter indexWriter = new IndexWriter(directory,config);

        //3.读取硬盘上的文件,对应每个文件创建一个文档对象
        File dir = new File("C:\\Users\\16421\\Desktop\\12_lucene\\02.参考资料\\searchsource");
        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);//文件的大小
            //4创建filed域,参数1:域名  参数二:域的内容  参数三:是否存储在磁盘
            Field fieldName = new TextField("name",filename,Field.Store.YES);
            Field fieldPath = new TextField("path",filepath,Field.Store.YES);
            Field fieldContent = new TextField("content",fileContent,Field.Store.YES);
            Field fieldSize = new TextField("size",fileSize+"",Field.Store.YES);
            //5创建文档对象
            Document document = new Document();
            //6向文档对象中添加域
            document.add(fieldName);
            document.add(fieldContent);
            document.add(fieldPath);
            document.add(fieldSize);
            //把文档对象写入索引库
            indexWriter.addDocument(document);
        }
        //关闭indexWriter
        indexWriter.close();
    }
查看分析器分析效果
@Test
    public void testIkAnalyzer() throws Exception{
        //创建一个标准分析器对象
        Analyzer analyzer = new IKAnalyzer();
        //2)使用分析器对象的tokenStream方法获得一个TokenStream对象
        TokenStream tokenStream = analyzer.tokenStream("", "用户发起request请求至控制器Spring(Controller)\n" +
                "控制接收用户请求的数据,委托给模型进行处理");
        //3)向TokenStream对象中设置一个引用,相当于数一个指针
        CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
        //4)调用TokenStream对象的rest方法。如果不调用抛异常
        tokenStream.reset();
        //5)使用while循环遍历TokenStream对象
        while(tokenStream.incrementToken()){
            System.out.println(charTermAttribute.toString());
        }
        //6)关闭TokenStream对象
        tokenStream.close();
    }

索引库维护

field域的属性

在这里插入图片描述

1)添加文档
@Test
    //索引库维护--添加文档
    public void addDocument() throws Exception{
        //1.创建一个indexWriter对象,需要使用IkAnalyzer作为分析器
        IndexWriter indexWriter = new IndexWriter(FSDirectory.open(new File("D:\\temp").toPath()),new IndexWriterConfig(new IKAnalyzer()));
        //2.创建一个document对象
        Document document = new Document();
        //3.向document对象中添加域
        document.add(new TextField("name","新添加的文件", Field.Store.YES));
        document.add(new TextField("content","新添加的文件内容", Field.Store.NO));
        document.add(new StoredField("path","c:/temp/hello"));
        //4.把文档存入索引库
        indexWriter.addDocument(document);
        indexWriter.close();
    }

2)删除文档
@Test
    public void deleteDocument() throws Exception{
        IndexWriter indexWriter = new IndexWriter(FSDirectory.open(new File("D:\\temp").toPath()),new IndexWriterConfig(new IKAnalyzer()));
        //indexWriter.deleteAll();//删除所有
        indexWriter.deleteDocuments(new Term("name","spring"));//删除name为spring的索引
        indexWriter.close();
    }
}
3)修改文档
//索引库维护,更新文档,原理:先删除,后添加
    @Test
    public void updateDocument() throws Exception{
        IndexWriter indexWriter = new IndexWriter(FSDirectory.open(new File("D:\\temp").toPath()),new IndexWriterConfig(new IKAnalyzer()));
        //1.创建一个新的文档对象
        Document document = new Document();
        //2.向文档对象中添加域
        document.add(new TextField("name","spring",Field.Store.YES));
        document.add(new TextField("name1","更新之后的文档1",Field.Store.YES));
        document.add(new TextField("name2","更新之后的文档2",Field.Store.YES));
        //更新操作
        //先把name中包含spring的索引(name列的一行)删掉,再添加
        indexWriter.updateDocument(new Term("name","spring"),document);
        //关闭索引库
        indexWriter.close();
    }

索引库查询

1、使用Query的子类
  1)TermQuery(简单示例中)
    根据关键词进行查询。
    需要指定要查询的域及要查询的关键词
  2)RangeQuery
    范围查询

//数值范围查询
    @Test
    public void testRangeQuery() throws Exception{
    	IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("D:\\temp").toPath()));
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //创建一个query对象
        Query size = LongPoint.newRangeQuery("size", 01, 1001);
        //执行查询
        TopDocs topDocs = indexSearcher.search(size, 10);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            //取文档id
            int id = scoreDoc.doc;
            //根据id取对象
            Document document = new Document();
            document.get("name");
        }
    }

2、使用QueryPaser进行查询
  可以对要查询的内容先分词,然后基于分词的结果进行查询。比如一句话,使用这种查询方法就会先给这句话分词。
  添加一个jar包
  lucene-queryparser-7.4.0.jar

//对于句子,先分词,然后进行全文检索
    @Test
    public void testQueryParser() throws Exception{
        //创建一个queryParse对象,参数1:默认搜索域,参数2:分析器对象

        QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
        //使用QueryParser对象创建一个Query对象
        Query query = queryParser.parse("spring");
        //执行查询
        TopDocs topDocs = indexSearcher.search(query, 10);
        //取查询结果的总记录数
        System.out.println("查询总记录数:"+topDocs.totalHits);

    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值