Lucene学习笔记

Lucene 版本:Lucene 7.3.1
luke工具:https://github.com/DmitryKey/luke/releases

索引操作

  索引操作的核心类是IndexWriter,IndexWriter需要指定索引的生成位置directory和生成索引要用的分词器analyzer。分词器以及其他的配置信息通过IndexWriterConfig类来指定.

//构造函数
new IndexWriter(direcroty,config)

lucene创建索引

  创建索引需要Document对象,Document对象有Field对象组成。这是一个通用的模型概念,具有很强的扩展性。一个Document可以是数据库中的一条记录,则Field就是具体字段值;一个Document也可以是一个文件对象,则Filed可以代表是fileName,fileContent,fileSize等信息。

Field域的属性(4.10.3)

是否分析:是否对域的内容进行分词处理。前提是我们要对域的内容进行查询。
是否索引:将Field分析后的词或整个Field值进行索引,只有索引方可搜索到。
比如:商品名称、商品简介分析后进行索引,订单号、身份证号不用分析但也要索引,这些将来都要作为查询条件。
是否存储:将Field值存储在文档中,存储在文档中的Field才可以从Document中获取
比如:商品名称、订单号,凡是将来要从Document中获取的Field都要存储。

Field类数据类型Analyzed是否分析Index是否索引Stored是否存储说明
StringField(FieldName, FieldValue,Store.YES))字符串NYY 或 N这个Field用来构建一个字符串Field,但是不会进行分析,会将整个串存储在索引中,比如(订单号,姓名等);是否存储在文档中用Store.YES或Store.NO决定
LongField(FieldName, FieldValue,Store.YES)Long型YYY 或 N这个Field用来构建一个Long数字型Field,进行分析和索引,比如(价格);是否存储在文档中用Store.YES或Store.NO决定
StoredField(FieldName, FieldValue)重载方法,支持多种类型NYY这个Field用来构建不同类型Field,不分析,不索引,但要Field存储在文档中(如图片,因为要存放图片地址)
TextField(FieldName, FieldValue, Store.NO) 或 TextField(FieldName, reader)字符串或流YYY 或N如果是一个Reader, lucene猜测内容比较多,会采用Unstored的策略.

实现步骤

  • 第一步:创建一个java工程,并导入jar包。
  • 第二步:创建一个indexwriter对象。
      1)指定索引库的存放位置Directory对象
      2)指定一个分析器,对文档内容进行分析。
  • 第二步:创建document对象。
  • 第三步:创建field对象,将field添加到document对象中。
  • 第四步:使用indexwriter对象将document对象写入索引库,此过程进行索引创建。并将索引和document对象写入索引库。
  • 第五步:关闭IndexWriter对象。
    @Test
    public void testIndexCreate() throws Exception {
        //创建Lucene索引的步骤

        //**:核心:创建索引index和文档document写对象(需要指定目录和配置信息(分词器))
        //  a:创建索引存储位置
        Directory directory = FSDirectory.open(Paths.get("dic"));
        //  b:创建分词器
//        IKAnalyzer analyzer = new IKAnalyzer(); //lucene 7 已经不兼容IKAnalyzer分词器
        StandardAnalyzer analyzer = new StandardAnalyzer();
        //  c:创建索引文档写对象的配置文件(指定分词器)
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        // d:创建索引文档写对象
        IndexWriter indexWriter = new IndexWriter(directory, conf);

        //创建文档document
        File dataDir = new File("data");
        for (File file : dataDir.listFiles()) {
            String fileName = file.getName();
            Long fileSize = FileUtils.sizeOf(file);
            String fileContent = FileUtils.readFileToString(file, "utf-8");
            Document doc = new Document();
            TextField nameField = new TextField("fileName", fileName, Field.Store.YES);
            TextField sizeField = new TextField("fileSize", fileSize.toString(), Field.Store.YES);
            TextField contentField = new TextField("fileContent", fileContent, Field.Store.YES);
            doc.add(nameField);
            doc.add(sizeField);
            doc.add(contentField);
            indexWriter.addDocument(doc);
        }


        //提交
        indexWriter.commit();
        //关闭流
        indexWriter.close();

    }

索引库的添加

向索引库中添加document对象。
第一步:先创建一个indexwriter对象
第二步:创建一个document对象
第三步:把document对象写入索引库
第四步:关闭indexwriter。

   //添加索引(4.10.3)
    @Test
    public void addDocument() throws Exception {
        //索引库存放路径
        Directory directory = FSDirectory.open(new File("dic"));

        IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new IKAnalyzer());
        //创建一个indexwriter对象
        IndexWriter indexWriter = new IndexWriter(directory, config);
        //创建一个Document对象
        Document document = new Document();
        //向document对象中添加域。
        //不同的document可以有不同的域,同一个document可以有相同的域。
        document.add(new TextField("filename", "新添加的文档", Store.YES));
        document.add(new TextField("content", "新添加的文档的内容", Store.NO));
        document.add(new TextField("content", "新添加的文档的内容第二个content", Store.YES));
        document.add(new TextField("content1", "新添加的文档的内容要能看到", Store.YES));
        //添加文档到索引库
        indexWriter.addDocument(document);
        //关闭indexwriter
        indexWriter.close();

    }

lucene删除全部索引

indexWriter.deleteAll();
 @Test
    public void testIndexDeleAll() throws Exception {
        //核心:常见索引文档写对象
        Directory directory = FSDirectory.open(Paths.get("dic"));
        StandardAnalyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, config);

        indexWriter.deleteAll();
        indexWriter.commit();
        indexWriter.close();
    }

lucene删除指定索引

indexWriter.deleteDocuments(Term ... terms);

    或者

indexWriter.deleteDocuments(Query ... querys);
    @Test
    // 指定Term删除document,删除索引
    public void testIndexDeleByDocuments1() throws Exception {
        //核心:创年索引文档写对象
        Directory dir = FSDirectory.open(Paths.get("dic"));
        IndexWriterConfig conf = new IndexWriterConfig(new StandardAnalyzer());
        IndexWriter indexWriter = new IndexWriter(dir, conf);

        // 指定Term删除document,删除索引
        indexWriter.deleteDocuments(new Term("fileName", "apache"));
        // 指定查询条件删除document,删除索引
        QueryParser parser = new QueryParser("fileName", new StandardAnalyzer());
        Query query = parser.Query("apache");
        indexWriter.deleteDocuments(query);
        indexWriter.commit();
        indexWriter.close();
    }

索引库的修改

原理就是先删除后添加。

    //修改索引库(4.10.3)
    @Test
    public void updateIndex() throws Exception {
        IndexWriter indexWriter = getIndexWriter();
        //创建一个Document对象
        Document document = new Document();
        //向document对象中添加域。
        //不同的document可以有不同的域,同一个document可以有相同的域。
        document.add(new TextField("filename", "要更新的文档", Store.YES));
        document.add(new TextField("content", "2013年11月18日 - Lucene 简介 Lucene 是一个基于 Java 的全文信息检索工具包,它不是一个完整的搜索应用程序,而是为你的应用程序提供索引和搜索功能。", Store.YES));
        indexWriter.updateDocument(new Term("content", "java"), document);
        //关闭indexWriter
        indexWriter.close();
    }

查询索引

对要搜索的信息创建Query查询对象,Lucene会根据Query查询对象生成最终的查询语法,类似关系数据库Sql语法一样Lucene也有自己的查询语法,比如:“name:lucene”表示查询Field的name为“lucene”的文档信息。

可通过两种方法创建查询对象:
1)使用Lucene提供Query子类
  Query是一个抽象类,lucene提供了很多查询对象,比如TermQuery项精确查询,NumericRangeQuery数字范围查询等。
如下代码:

Query query = new TermQuery(new Term("name", "lucene"));

2)使用QueryParse解析查询表达式
  QueryParse会将用户输入的查询表达式解析成Query对象实例。
如下代码:

QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
Query query = queryParser.parse("name:lucene");

查询步骤

  • 第一步:创建一个Directory对象,也就是索引库存放的位置。
  • 第二步:创建一个indexReader对象,需要指定Directory对象。
  • 第三步:创建一个indexsearcher对象,需要指定IndexReader对象
  • 第四步:创建一个TermQuery对象,指定查询的域和查询的关键词。
  • 第五步:执行查询。
  • 第六步:返回查询结果。遍历查询结果并输出。
  • 第七步:关闭IndexReader对象

IndexSearcher搜索方法

方法说明
indexSearcher.search(query, n)根据Query搜索,返回评分最高的n条记录
indexSearcher.search(query, filter, n)根据Query搜索,添加过滤策略,返回评分最高的n条记录
indexSearcher.search(query, n, sort)根据Query搜索,添加排序策略,返回评分最高的n条记录
indexSearcher.search(booleanQuery, filter, n, sort)根据Query搜索,添加过滤策略,添加排序策略,返回评分最高的n条记录

TopDocs

Lucene搜索结果可通过TopDocs遍历,TopDocs类提供了少量的属性,如下:

方法说明
totalHits匹配搜索条件的总记录数
scoreDocs顶部匹配记录

注意:
Search方法需要指定匹配记录数量n:indexSearcher.search(query, n)
TopDocs.totalHits:是匹配索引库中所有记录的数量
TopDocs.scoreDocs:匹配相关度高的前边记录数组,scoreDocs的长度小于等于search方法指定的参数n

使用queryparser查询

  通过QueryParser也可以创建Query,QueryParser提供一个Parse方法,此方法可以直接根据查询语法来查询。Query对象执行的查询语法可通过System.out.println(query);查询。
需要使用到分析器。建议创建索引时使用的分析器和查询索引时使用的分析器要一致。

查询语法
1、基础的查询语法,关键词查询:
  域名+“:”+搜索的关键字
  例如:content:java
2、范围查询
  域名+“:”+[最小值 TO 最大值]
  例如:size:[1 TO 1000]
  范围查询在lucene中不支持数值类型,支持字符串类型。在solr中支持数值类型。
3、组合条件查询
  1)+条件1 +条件2:两个条件之间是并且的关系and
  例如:+filename:apache +content:apache
  2)+条件1 条件2:必须满足第一个条件,应该满足第二个条件
  例如:+filename:apache content:apache
  3)条件1 条件2:两个条件满足其一即可。
  例如:filename:apache content:apache
  4)-条件1 条件2:必须不满足条件1,要满足条件2
  例如:-filename:apache content:apache

TablesAre
Occur.MUST 查询条件必须满足,相当于and+(加号)
Occur.SHOULD 查询条件可选,相当于or空(不用符号)
Occur.MUST_NOT 查询条件不能满足,相当于not非-(减号)

第二种写法:
条件1 AND 条件2
条件1 OR 条件2
条件1 NOT 条件2

    @Test
    public void testIndexSearch() throws Exception {
        //核心类:IndexSearch IndexReader 
        Directory directory = FSDirectory.open(Paths.get("dic"));
        IndexReader indexReader = StandardDirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        StandardAnalyzer analyzer = new StandardAnalyzer();
        //查询解析器,指定分词器(同索引创年分词器一致),指定默认的查询字段
        QueryParser queryParser = new QueryParser("fileContent", analyzer);
        //查询语法=域名:搜索的关键字,若没有指定域名,则按照默认的查询域查询
        Query query = queryParser.parse("fileName:apache");

        //按照查询条件查询,并指定最多显示几条结果
        //第一个参数是查询对象,第二个参数是查询结果返回的最大值
        TopDocs topDocs = indexSearcher.search(query, 5);
        //满足查询条件的全部记录条数
        long totalHits = topDocs.totalHits;
        System.out.println("总的记录数:" + totalHits);
        //结果集
        //topDocs.scoreDocs存储了document对象的id
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        for (ScoreDoc scoreDoc : scoreDocs) {
            //索引ID值 scoreDoc.doc属性就是document对象的id
            int docID = scoreDoc.doc;
            Document document = indexReader.document(docID);
            //document.getField("fileName") 返回 IndexableField
            System.out.println(document.getField("fileName").stringValue()+" : "+document.getField("fileSize").stringValue());
            System.out.println("=============================================================================");
        }
    }

MulitFieldQueryParser

可以指定多个默认搜索域

@Test
    public void testMultiFiledQueryParser() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //可以指定默认搜索的域是多个
        String[] fields = {"filename", "content"};
        //创建一个MulitFiledQueryParser对象
        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields, new IKAnalyzer());
        Query query = queryParser.parse("java and apache");
        System.out.println(query);
        //执行查询
        printResult(query, indexSearcher);

    }

使用query的子类查询

TermQuery

TermQuery,通过项查询,TermQuery不使用分析器,所以建议匹配不分词的Field域查询,比如订单号、分类ID号等。
指定要查询的域和要查询的关键词。

//使用Termquery查询(4.10.3)
    @Test
    public void testTermQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //创建查询对象
        Query query = new TermQuery(new Term("content", "lucene"));
        //执行查询
        TopDocs topDocs = indexSearcher.search(query, 10);
        //共查询到的document个数
        System.out.println("查询结果总数量:" + topDocs.totalHits);
        //遍历查询结果
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println(document.get("filename"));
            //System.out.println(document.get("content"));
            System.out.println(document.get("path"));
            System.out.println(document.get("size"));
        }
        //关闭indexreader
        indexSearcher.getIndexReader().close();
    }

NumericRangeQuery

可以根据数值范围查询。

//数值范围查询
    @Test
    public void testNumericRangeQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //创建查询
        //参数:
        //1.域名
        //2.最小值
        //3.最大值
        //4.是否包含最小值
        //5.是否包含最大值
        Query query = NumericRangeQuery.newLongRange("size", 1l, 1000l, true, true);
        //执行查询
        printResult(query, indexSearcher);
    }

BooleanQuery

可以组合查询条件。

//组合条件查询(4.10.3)
    @Test
    public void testBooleanQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //创建一个布尔查询对象
        BooleanQuery query = new BooleanQuery();
        //创建第一个查询条件
        Query query1 = new TermQuery(new Term("filename", "apache"));
        Query query2 = new TermQuery(new Term("content", "apache"));
        //组合查询条件
        query.add(query1, Occur.MUST);
        query.add(query2, Occur.MUST);
        //执行查询
        printResult(query, indexSearcher);
    }

Occur.MUST:必须满足此条件,相当于and
Occur.SHOULD:应该满足,但是不满足也可以,相当于or
Occur.MUST_NOT:必须不满足。相当于not

MatchAllDocsQuery

使用MatchAllDocsQuery查询索引目录中的所有文档

@Test(4.10.3)
    public void testMatchAllDocsQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //创建查询条件
        Query query = new MatchAllDocsQuery();
        //执行查询
        printResult(query, indexSearcher);
    }

从Lucene 4.10.3到Lucene 7.1.0:带你了解版本之间的些许差异

https://blog.csdn.net/cslucifer/article/details/78548980?locationNum=10&fps=1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值