zoukankan      html  css  js  c++  java
  • Lucene教程具体解释


      欢迎关注微信账号:java那些事:csh624366188.每天一篇java相关的文章 

    注明:本文是由本人在开发有关基于lucene资源检索系统时的一点总结,当中一部分是自己依据开发过程自己总结的,也有部分是摘自网络,因无法获取当时摘文的地址,所以在此没有写源地址。

    转载请声明出处

    Lucene-3.0.0配置

    一、Lucene开发环境配置

    step1.Lucene开发包下载

    step2.Java开发环境配置

    step3.Tomcat安装

    step4.Lucene开发环境配置

    解压下载的lucene-3.0.0.zip,能够看到lucene-core-3.0.0.jar和lucene-demos-3.0.0.jar这两个文件,将其解压(建议放在安装jdklib目录内),并把路径加入到环境变量的classpath

    二、Lucene开发包中Demo调试

    控制台应用程序

    step1.建立索引

    >java org.apache.lucene.demo.IndexFiles [C:Java](已经存在的随意文件路径)

    将对C:Java下全部文件建立索引,同一时候,在当前命令行位置将生成index目录。

    step2.执行查询

    >java org.apache.lucene.demo.SearchFiles

    将会出现Query:提示符,在其后输入keyword,回车,就可以得到查询结果。

    Web应用程序

    step1.将lucene-core-3.0.0.jar和lucene-demos-3.0.0jar这两个文件拷贝到安装Tomcat commonlib

    step2.解压下载的lucene-3.0.0.zip,能够看到luceneweb.war文件。将该文件拷贝到安装Tomcatwebapps

    step3.重新启动Tomcatserver。

    step4.建立索引

    >java org.apache.lucene.demo.IndexHTML -create -index [索引数据存放路径] [被索引文件路径](如:D:lucene empindex D:lucene empdocs

    step5.打开安装Tomcatwebappslucenewebconfiguration.jsp文件,找到String indexLocation = "***",将"***"改为第四步中[索引数据存放路径]保存关闭。

    step6.执行查询

    http://localhost:8080/luceneweb

    在文本框中输入keyword,执行,就可以得到查询结果。

    说明:本文採用lucene-3.0.0版本号,执行step6 时查询报错,依据提示将安装Tomcatwebappsluceneweb esults.jsp 

    [    QueryParser qp = new QueryParser("contents", analyzer);     ]     改动为

    [    QueryParser qp = new QueryParser(Version.LUCENE_CURRENT,"contents", analyzer);    ]

    注:本文參考YM's house

    lucenedemo环境搭建 

    总结一下lucene的环境搭建,查看以及了解lucene的原理,对其有个大概的了解。

    1、下载lucene2.3.2

    地址:http://apache.mirror.phpchina.com/lucene/java/

    2、下载jdk1.6

    3、下载tomcat

    下载以上内容完毕后,開始安装。

    1、安装jdk

    一路确定下去,无需选择。

    2、安装tomcat

    一路确定下去,无需选择。

    3、解压文件就可以

    假设解压文件路径为d:lucene

    如今能够建立目录(此处的目录为我们要进行检索的信息的原始数据文件,我们放置在docs中,还有一个是lucene生成的检索信息,我们放置于index),即能够在d:lucene下建立一个tempdocs以及tempindex,此处两个目录目录能够随意,当然不一定非得放置于d:lucene

    然后将须要检索的原始数据文件放置于docs目录中。

    拷贝解压的lucene目录中的lucene-core-2.3.2.jar以及lucene-demos-2.3.2.jartemp目录中,解压。

    假设没有配置jdk环境,參考下方:

    打开我的电脑-属性-高级-环境变量:

    在系统变量中加入:

    JAVA_HOME C:Program FilesJavajdk1.6.0

    PATH %JAVA_HOME%in

    CLASSPATH .;%JAVA_HOME%lib ools.jar;%JAVA_HOME%jrelib t.jar;

    打开命令行:将目录定位到temp目录。

    输入命令:

    java org.apache.lucene.demo.IndexHTML -create -index D:lucene empindex D:lucene empdocs

    即建立索引与原始数据文件的关系。

    完毕后,会发现index目录中多处一部分数据,以后再研究。

    然后找到tomcat的安装目录,拷贝lucene中的luceneweb.war进入tomcatwebapps目录中,启动tomcat,会看见webapps下多出一个目录,找到configuration.jsp文件,将当中的String indexLocation = "/opt/lucene/index";改动为String indexLocation = "D:/lucene/temp/index";就是刚才生成的文件。

    打开浏览器,输入http://127.0.0.1:8080/luceneweb/

    输入须要查询的信息,看看结果怎样。

    简单地说:首先建立索引文件放置目录,cmd命令生成索引文件,部署project,改动project文件里目标为索引文件目录。

    搜索引擎的组成

     搜索引擎一般由搜索器、索引器、检索器和用户接口四个部分组成: 

    搜索器

      其功能是在互联网中漫游,发现和搜集信息; 

    索引器

      其功能是理解搜索器所搜索到的信息,从中抽取出索引项,用于表示文档以及生成文档库的索引表; 

    检索器

      其功能是依据用户的查询在索引库中高速检索文档,进行相关度评价,对将要输出的结果排序,并能按用户的查询需求合理反馈信息; 

    用户接口

      其作用是接纳用户查询、显示查询结果、提供个性化查询项。

    d:luceneindex是上一篇学习笔记([Lucene3.0学习笔记1(建立索引))中生成的索引文件的存放地址。详细步骤简单介绍例如以下:

    1、创建Directory对象,索引目录

    2、创建IndexSearch对象,建立查询(參数是Directory对象)

    3、创建QueryParser对象(lucene版本号,查询Field字段,所用分词器)

    4、生成Query对象,由QueryParser对象的parse函数生成(參数是所查的keyword)

    5、建立TopDocs对象(IndexSearchsearch函数,參数是Query查询对象,)

    6TopDocs对象数组里存放查询信息

    7、关闭IndexSearch

    索引创建和搜索过程所一个总结

    Lucene教程

    Lucene是apache组织的一个用java实现全文搜索引擎的开源项目。 其功能非常的强大,api也非常easy。总得来说用Lucene来进行建立 和搜索和操作数据库是差点儿相同的(有点像),Document能够看作是 数据库的一行记录,Field能够看作是数据库的字段。用lucene实 现搜索引擎就像用JDBC实现连接数据库一样简单。 

    Lucene2.0,它与曾经广泛应用和介绍的Lucene 1.4.3并不兼容。 Lucene2.0的下载地址是http://apache.justdn.org/lucene/java/ 


    样例一 :

    1、在windows系统下的的C盘,建一个名叫s的目录,在该目录里面随便建三个txt文件,随便起名啦,就叫"1.txt","2.txt"和"3.txt"啦 
    当中1.txt的内容例如以下: 

    中华人民共和国   
    全国人民   
    2006年   

    而"2.txt"和"3.txt"的内容也能够随便写几写,这里懒写,就复制一个和1.txt文件的内容一样吧

    2、下载lucene包,放在classpath路径中 
    建立索引:

    package  lighter.javaeye.com;   
      
    import  java.io.BufferedReader;   
    import  java.io.File;   
    import  java.io.FileInputStream;   
    import  java.io.IOException;   
    import  java.io.InputStreamReader;   
    import  java.util.Date;   
      
    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.index.IndexWriter;   
      
    /** */ /**   
     * author lighter date 2006-8-7  
      */   
    public   class  TextFileIndexer  {   
         public   static   void  main(String[] args)  throws  Exception  {   
             /**/ /*  指明要索引目录的位置,这里是C盘的S目录下  */   
            File fileDir  =   new  File( " c://s " );   
      
             /**/ /*  这里放索引文件的位置  */   
            File indexDir  =   new  File( " c://index " );   
            Analyzer luceneAnalyzer  =   new  StandardAnalyzer();  //建立一个标准分析器 
            IndexWriter indexWriter  =   new  IndexWriter(indexDir, luceneAnalyzer,   
                     true );   //创建一个索引器
            File[] textFiles  =  fileDir.listFiles();   
             long  startTime  =   new  Date().getTime();   
               
             //添加document到索引去    
             for  ( int  i  =   0 ; i  <  textFiles.length; i ++ )  {   
                 if  (textFiles[i].isFile()   
                         &&  textFiles[i].getName().endsWith( " .txt " ))  {   
                    System.out.println( " File  "   +  textFiles[i].getCanonicalPath()   
                             +   "正在被索引 . " );   
                    String temp  =  FileReaderAll(textFiles[i].getCanonicalPath(),   
                             " GBK " );   
                    System.out.println(temp);   
                    Document document  =   new  Document();  //Document是一个记录。用来表示一个条目。就是搜索建立的倒排索引的条目。比方说,你要搜索自己电脑上的文件。这个时候就能够创建field。然后用field组合成 document 。最后会变成若干文件。这个document和 文件系统document不是一个概念。 
                    Field FieldPath  =   new  Field( " path " , textFiles[i].getPath(),   
                            Field.Store.YES, Field.Index.NO);   //创建一个字段
                    Field FieldBody  =   new  Field( " body " , temp, Field.Store.YES,   
                            Field.Index.TOKENIZED,   
                            Field.TermVector.WITH_POSITIONS_OFFSETS);   
                    document.add(FieldPath);   
                    document.add(FieldBody);   
                    indexWriter.addDocument(document);   
                }    
            }    
             // optimize()方法是对索引进行优化    
            indexWriter.optimize();   
            indexWriter.close();   
               
             //測试一下索引的时间    
             long  endTime  =   new  Date().getTime();   
            System.out   
                    .println( "这花费了 "   
                             +  (endTime  -  startTime)   
                             +   "  毫秒来把文档添加到索引里面去! "   
                             +  fileDir.getPath());   
        }    
      
         public   static  String FileReaderAll(String FileName, String charset)   
                 throws  IOException  {   
            BufferedReader reader  =   new  BufferedReader( new  InputStreamReader(   
                     new  FileInputStream(FileName), charset));   
            String line  =   new  String();   
            String temp  =   new  String();   
               
             while  ((line  =  reader.readLine())  !=   null )  {   
                temp  +=  line;   
            }    
            reader.close();   
             return  temp;   
        }    
    }  

    索引的结果: 

    File C:/s/ 1 .txt正在被索引 .   
    中华人民共和国全国人民2006年   
    File C:/s/ 2 .txt正在被索引 .   
    中华人民共和国全国人民2006年   
    File C:/s/ 3 .txt正在被索引 .   
    中华人民共和国全国人民2006年   
    这花费了297 毫秒来把文档添加到索引里面去 ! c:/s  


    3、建立了索引之后,查询啦....

    package  lighter.javaeye.com;   
      
    import  java.io.IOException;   
      
    import  org.apache.lucene.analysis.Analyzer;   
    import  org.apache.lucene.analysis.standard.StandardAnalyzer;   
    import  org.apache.lucene.queryParser.ParseException;   
    import  org.apache.lucene.queryParser.QueryParser;   
    import  org.apache.lucene.search.Hits;   
    import  org.apache.lucene.search.IndexSearcher;   
    import  org.apache.lucene.search.Query;   
      
    public   class  TestQuery  {   
         public   static   void  main(String[] args)  throws  IOException, ParseException  {   
            Hits hits  =   null ;   
            String queryString  =   "中华 " ;   
            Query query  =   null ;   
            IndexSearcher searcher  =   new  IndexSearcher( " c://index " );   
      
            Analyzer analyzer  =   new  StandardAnalyzer();   
             try   {   
                QueryParser qp  =   new  QueryParser( " body " , analyzer);   
                query  =  qp.parse(queryString);   
            }   catch  (ParseException e)  {   
            }    
             if  (searcher  !=   null )  {   
                hits  =  searcher.search(query);   
                 if  (hits.length()  >   0 )  {   
                    System.out.println( "找到: "   +  hits.length()  +   "  个结果! " );   
                }    
            }    
        }  
      
    }   

    其执行结果:

    找到: 3  个结果 ! 

    Lucene事实上非常easy的,它最主要就是做两件事:建立索引和进行搜索 
    来看一些在lucene中使用的术语,这里并不打算作详细的介绍,仅仅是点一下而已----由于这一个世界有一种好东西,叫搜索。

    IndexWriter:lucene中最重要的的类之中的一个,它主要是用来将文档加入索引,同一时候控制索引过程中的一些參数使用。

    Analyzer:分析器,主要用于分析搜索引擎遇到的各种文本。经常使用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

    Directory:索引存放的位置;lucene提供了两种索引存放的位置,一种是磁盘,一种是内存。普通情况将索引放在磁盘上;对应地lucene提供了FSDirectory和RAMDirectory两个类。

    Document:文档;Document相当于一个要进行索引的单元,不论什么能够想要被索引的文件都必须转化为Document对象才干进行索引。

    Field:字段。

    IndexSearcher:是lucene中最主要的检索工具,全部的检索都会用到IndexSearcher工具;

    Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。

    QueryParser:是一个解析用户输入的工具,能够通过扫描用户输入的字符串,生成Query对象。

    Hits:在搜索完毕之后,须要把搜索结果返回并显示给用户,仅仅有这样才算是完毕搜索的目的。在lucene中,搜索的结果的集合是用Hits类的实例来表示的。

    上面作了一大堆名词解释,以下就看几个简单的实例吧:
     1、简单的的StandardAnalyzer測试样例 

    package  lighter.javaeye.com;   
      
    import  java.io.IOException;   
    import  java.io.StringReader;   
      
    import  org.apache.lucene.analysis.Analyzer;   
    import  org.apache.lucene.analysis.Token;   
    import  org.apache.lucene.analysis.TokenStream;   
    import  org.apache.lucene.analysis.standard.StandardAnalyzer;   
      
    public   class  StandardAnalyzerTest    
    {   
         //构造函数,    
         public  StandardAnalyzerTest()   
         {   
        }    
         public   static   void  main(String[] args)    
         {   
             //生成一个StandardAnalyzer对象    
            Analyzer aAnalyzer  =   new  StandardAnalyzer();   
             //測试字符串    
            StringReader sr  =   new  StringReader( " lighter javaeye com is the are on " );   
             //生成TokenStream对象    
            TokenStream ts  =  aAnalyzer.tokenStream( " name " , sr);    
             try   {   
                 int  i = 0 ;   
                Token t  =  ts.next();   
                 while (t != null )   
                 {   
                     //辅助输出时显示行号    
                    i ++ ;   
                     //输出处理后的字符    
                    System.out.println( "第 " + i + "行: " + t.termText());   
                     //取得下一个字符    
                    t = ts.next();   
                }    
            }   catch  (IOException e)  {   
                e.printStackTrace();   
            }    
        }    
    }    

    显示结果:

    第1行:lighter 
    第2行:javaeye 
    第3行:com 

    提示一下: 
    StandardAnalyzer是lucene中内置的"标准分析器",能够做例如以下功能:
     1、对原有句子依照空格进行了分词 
    2、全部的大写字母都能够能转换为小写的字母 
    3、能够去掉一些没实用处的单词,比如"is","the","are"等单词,也删除了全部的标点 
    查看一下结果与"new StringReader("lighter javaeye com is the are on")"作一个比較就清楚明了。 
    这里不正确其API进行解释了,详细见lucene的官方文档。须要注意一点,这里的代码使用的是lucene2的API,与1.43版有一些明显的区别。 

    2、看还有一个实例,简单地建立索引,进行搜索 

    package  lighter.javaeye.com;   
    import  org.apache.lucene.analysis.standard.StandardAnalyzer;   
    import  org.apache.lucene.document.Document;   
    import  org.apache.lucene.document.Field;   
    import  org.apache.lucene.index.IndexWriter;   
    import  org.apache.lucene.queryParser.QueryParser;   
    import  org.apache.lucene.search.Hits;   
    import  org.apache.lucene.search.IndexSearcher;   
    import  org.apache.lucene.search.Query;   
    import  org.apache.lucene.store.FSDirectory;   
      
    public   class  FSDirectoryTest  {   
      
         //建立索引的路径    
         public   static   final  String path  =   " c://index2 " ;   
      
         public   static   void  main(String[] args)  throws  Exception  {   
            Document doc1  =   new  Document();   
            doc1.add(  new  Field( " name " ,  " lighter javaeye com " ,Field.Store.YES,Field.Index.TOKENIZED));   
      
            Document doc2  =   new  Document();   
            doc2.add( new  Field( " name " ,  " lighter blog " ,Field.Store.YES,Field.Index.TOKENIZED));   
      
            IndexWriter writer  =   new  IndexWriter(FSDirectory.getDirectory(path,  true ),  new  StandardAnalyzer(),  true );   
            writer.setMaxFieldLength( 3 );   
            writer.addDocument(doc1);   
            writer.setMaxFieldLength( 3 );   
            writer.addDocument(doc2);   
            writer.close();   
      
            IndexSearcher searcher  =   new  IndexSearcher(path);   
            Hits hits  =   null ;   
            Query query  =   null ;   
            QueryParser qp  =   new  QueryParser( " name " , new  StandardAnalyzer());   
               
            query  =  qp.parse( " lighter " );   
            hits  =  searcher.search(query);   
            System.out.println( "查找/ " lighter/ "  共 "   +  hits.length()  +   "个结果 " );   
      
            query  =  qp.parse( " javaeye " );   
            hits  =  searcher.search(query);   
            System.out.println( "查找/ " javaeye/ "  共 "   +  hits.length()  +   "个结果 " );   
      
        }    
      
    }   

    执行结果:

    查找 " lighter "  共2个结果   
    查找 " javaeye "  共1个结果  


    到如今我们已经能够用lucene建立索引了
    以下介绍一下几个功能来完好一下:
    1.索引格式

    事实上索引目录有两种格式,

    一种是除配置文件外,每个Document独立成为一个文件(这种搜索起来会影响速度)。

    还有一种是全部的Document成一个文件,这样属于复合模式就快了。

    2.索引文件可放的位置:

    索引能够存放在两个地方1.硬盘,2.内存
    放在硬盘上能够用FSDirectory(),放在内存的用RAMDirectory()只是一关机就没了

    FSDirectory.getDirectory(File file,  boolean  create)
    FSDirectory.getDirectory(String path,  boolean  create)

    两个工厂方法返回目录
    New RAMDirectory()就直接能够
    再和

    IndexWriter(Directory d, Analyzer a,  boolean  create)

    一配合就可以了
    如:

    IndexWrtier indexWriter  =   new  IndexWriter(FSDirectory.getDirectory(c://index, true ), new  StandardAnlyazer(), true );
    IndexWrtier indexWriter  =   new  IndexWriter( new  RAMDirectory(), new  StandardAnlyazer(), true );

    3.索引的合并
    这个可用

    IndexWriter.addIndexes(Directory[] dirs)

    将目录加进去
    来看个样例:

    public   void  UniteIndex()  throws  IOException
         {
            IndexWriter writerDisk  =   new  IndexWriter(FSDirectory.getDirectory( " c://indexDisk " ,  true ), new  StandardAnalyzer(), true );
            Document docDisk  =   new  Document();
            docDisk.add( new  Field( " name " , "程序猿之家 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writerDisk.addDocument(docDisk);
            RAMDirectory ramDir  =   new  RAMDirectory();
            IndexWriter writerRam  =   new  IndexWriter(ramDir, new  StandardAnalyzer(), true );
            Document docRam  =   new  Document();
            docRam.add( new  Field( " name " , "程序猿杂志 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writerRam.addDocument(docRam);
            writerRam.close(); //这种方法非常重要,是必须调用的 
            writerDisk.addIndexes( new  Directory[] {ramDir} );
            writerDisk.close();
        } 
         public   void  UniteSearch()  throws  ParseException, IOException
         {
            QueryParser queryParser  =   new  QueryParser( " name " , new  StandardAnalyzer());
            Query query  =  queryParser.parse( "程序猿 " );
            IndexSearcher indexSearcher  = new  IndexSearcher( " c://indexDisk " );
            Hits hits  =  indexSearcher.search(query);
            System.out.println( "找到了 " + hits.length() + "结果 " );
             for ( int  i = 0 ;i
             {
                Document doc  =  hits.doc(i);
                System.out.println(doc.get( " name " ));
            } 
    }


    这个样例是将内存中的索引合并到硬盘上来.
    注意:合并的时候一定要将被合并的那一方的IndexWriter的close()方法调用。

    4.对索引的其它操作:
    IndexReader类是用来操作索引的,它有对Document,Field的删除等操作。
    以下一部分的内容是:全文的搜索
    全文的搜索主要是用:IndexSearcher,Query,Hits,Document(都是Query的子类),有的时候用QueryParser
    主要步骤:

    1 . new  QueryParser(Field字段, new  分析器)
    2 .Query query  =  QueryParser.parser(要查询的字串”);这个地方我们能够用反射api看一下query到底是什么类型
    3 . new  IndexSearcher(索引目录).search(query);返回Hits
    4 .用Hits.doc(n);能够遍历出Document
    5 .用Document可得到Field的详细信息了。 

    事实上1 ,2两步就是为了弄出个Query实例,到底是什么类型的看分析器了。

    拿曾经的样例来说吧

    QueryParser queryParser  =   new  QueryParser( " name " , new  StandardAnalyzer());
            Query query  =  queryParser.parse( "程序猿 " );
    /**/ /*这里返回的就是org.apache.lucene.search.PhraseQuery */ 
            IndexSearcher indexSearcher  = new  IndexSearcher( " c://indexDisk " );
            Hits hits  =  indexSearcher.search(query);


    无论是什么类型,无非返回的就是Query的子类,我们全然能够不用这两步直接new个Query的子类的实例就ok了,只是一般还是用这两步由于它返回的是PhraseQuery这个是非常强大的query子类它能够进行多字搜索用QueryParser能够设置各个keyword之间的关系这个是最经常使用的了。
    IndexSearcher:
    事实上IndexSearcher它内部自带了一个IndexReader用来读取索引的,IndexSearcher有个close()方法,这种方法不是用来关闭IndexSearche的是用来关闭自带的IndexReader。

    QueryParser呢能够用parser.setOperator()来设置各个keyword之间的关系(与还是或)它能够自己主动通过空格从字串里面将keyword分离出来。
    注意:用QueryParser搜索的时候分析器一定的和建立索引时候用的分析器是一样的。
    Query:
    能够看一个lucene2.0的帮助文档有非常多的子类:
    BooleanQuery, ConstantScoreQuery, ConstantScoreRangeQuery, DisjunctionMaxQuery, FilteredQuery, MatchAllDocsQuery, MultiPhraseQuery, MultiTermQuery, PhraseQuery, PrefixQuery, RangeQuery, SpanQuery, TermQuery
    各自实使用方法看一下文档就能知道它们的使用方法了
    以下一部分讲一下lucene的分析器:
    分析器是由分词器和过滤器组成的,拿英文来说吧分词器就是通过空格把单词分开,过滤器就是把the,to,of等词去掉不被搜索和索引。
    我们最经常使用的是StandardAnalyzer()它是lucene的标准分析器它集成了内部的很多的分析器。
    最后一部分了:lucene的高级搜索了
    1.排序
    Lucene有内置的排序用IndexSearcher.search(query,sort)可是功能并不理想。我们须要自己实现自定义的排序。
    这种话得实现两个接口: ScoreDocComparator, SortComparatorSource
    用IndexSearcher.search(query,new Sort(new SortField(String Field,SortComparatorSource)));
    就看个样例吧:
    这是一个建立索引的样例:

    public   void  IndexSort()  throws  IOException
    {
            IndexWriter writer  =   new  IndexWriter( " C://indexStore " , new  StandardAnalyzer(), true );
            Document doc  =   new  Document()
            doc.add( new  Field( " sort " , " 1 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 4 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 3 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 5 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 9 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 6 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            doc  =   new  Document();
            doc.add( new  Field( " sort " , " 7 " ,Field.Store.YES,Field.Index.TOKENIZED));
            writer.addDocument(doc);
            writer.close();


    以下是搜索的样例:
    [code]
    public void SearchSort1() throws IOException, ParseException
    {
            IndexSearcher indexSearcher = new IndexSearcher("C://indexStore");
            QueryParser queryParser = new QueryParser("sort",new StandardAnalyzer());
            Query query = queryParser.parse("4");
           
            Hits hits = indexSearcher.search(query);
            System.out.println("有"+hits.length()+"个结果");
            Document doc = hits.doc(0);
            System.out.println(doc.get("sort"));
    }
    public void SearchSort2() throws IOException, ParseException
    {
            IndexSearcher indexSearcher = new IndexSearcher("C://indexStore");
            Query query = new RangeQuery(new Term("sort","1"),new Term("sort","9"),true);//这个地方前面没有提到,它是用于范围的Query能够看一下帮助文档.
            Hits hits = indexSearcher.search(query,new Sort(new SortField("sort",new MySortComparatorSource())));
            System.out.println("有"+hits.length()+"个结果");
            for(int i=0;i
            {
                Document doc = hits.doc(i);
                System.out.println(doc.get("sort"));
            }
    }
    public class MyScoreDocComparator implements ScoreDocComparator
    {
        private Integer[]sort;
        public MyScoreDocComparator(String s,IndexReader reader, String fieldname) throws IOException
        {
            sort = new Integer[reader.maxDoc()];
            for(int i = 0;i
            {
                Document doc =reader.document(i);
                sort[i]=new Integer(doc.get("sort"));
            }
        }
        public int compare(ScoreDoc i, ScoreDoc j)
        {
            if(sort[i.doc]>sort[j.doc])
                return 1;
            if(sort[i.doc]
                return -1;
            return 0;
        }
        public int sortType()
        {
            return SortField.INT;
        }
        public Comparable sortValue(ScoreDoc i)
        {
            // TODO自己主动生成方法存根
            return new Integer(sort[i.doc]);
        }
    }
    public class MySortComparatorSource implements SortComparatorSource
    {
        private static final long serialVersionUID = -9189690812107968361L;
        public ScoreDocComparator newComparator(IndexReader reader, String fieldname)
                throws IOException
        {
            if(fieldname.equals("sort"))
                return new MyScoreDocComparator("sort",reader,fieldname);
            return null;
        }
    }[/code]
    SearchSort1()输出的结果没有排序,SearchSort2()就排序了。
    2.多域搜索MultiFieldQueryParser
    假设想输入keyword而不想关心是在哪个Field里的就能够用MultiFieldQueryParser了
    用它的构造函数就可以后面的和一个Field一样。
    MultiFieldQueryParser. parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer)                                          ~~~~~~~~~~~~~~~~~
    第三个參数比較特殊这里也是与曾经lucene1.4.3不一样的地方
    看一个样例就知道了
    String[] fields = {"filename", "contents", "description"};
     BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
                    BooleanClause.Occur.MUST,//在这个Field里必须出现的
                    BooleanClause.Occur.MUST_NOT};//在这个Field里不能出现
     MultiFieldQueryParser.parse("query", fields, flags, analyzer);

    1、lucene的索引不能太大,要不然效率会非常低。大于1G的时候就必须考虑分布索引的问题

    2、不建议用多线程来建索引,产生的互锁问题非常麻烦。经常发现索引被lock,无法又一次建立的情况

    3、中文分词是个大问题,眼下免费的分词效果都非常差。假设有能力还是自己实现一个分词模块,用最短路径的切分方法,网上有教材和demo源代码,能够參考。

    4、建增量索引的时候非常耗cpu,在訪问量大的时候会导致cpu的idle为0

    5、默认的评分机制不太合理,须要依据自己的业务定制

    总体来说lucene要用好不easy,必须在上述方面扩充他的功能,才干作为一个商用的搜索引擎

    编程点滴.LUCENEFILED选项

    争取每日记录一些

    Index选项

    Index.ANALYZED – 索引并分词(适用于body, title, abstract.).
    Index.NOT_ANALYZED – 索引但不分词,能够使用NORM方式.(能够人为干预提权)

    Index.ANALYZED_NO_NORMS – 索引并分词但不使用NORM方式(不可觉得提权)

    Index.NOT_ANALYZED_NO_NORMS – 索引但不分词也不使用NORM方式(经经常使用到,存储标志值最好的方式.)

    Index.NO – 不索引

    Store选项

    Store.YES – 存储

    Store.NO  – 不存储

    TermVector选项

    (TermVector.NO外其它必须要求Index选项为Index.ANALYZEDIndex.NOT_ANALYZED)

    TermVector.YES – 最主要的向量存储(特殊性,数量,在哪个文档)

    TermVector.WITH_POSITIONS – TermVector.YES+位置
    TermVector.WITH_OFFSETS – TermVector.YES+偏移

    TermVector.WITH_POSITIONS_OFFSETS – TermVector.YES+位置+偏移

    TermVector.NO – 不做向量存储

    各选项组合应用场景

    Index

    Store

    TermVector

    事例

    NOT_ANALYZ

    Technorati 标签LUCENE FIELD INDEX ANALYZED NOT_ANALYZED TermVector

    ED_NO_NORMS

    YES

    NO

    主键,电话,身份证号,URLs,日期和须要排序的字段

    ANALYZED

    YES

    WITH_POSITIONS_OFFSETS

    文档标题,摘要.

    ANALYZED

    NO

    WITH_POSITIONS_OFFSETS

    文档主体

    NO

    YES

    NO

    文档类型,数据库主键(假设不须要检索该字段的话)

    NOT_ANALYZED

    NO

    NO

    隐藏字段

    排序的注意事项

    假设须要排序的字段是数字就用NumericField,假设是文本,一定要记得使用FIELD.Index.NOT_ANALYZED.

    假设不须要提权则应该使用NOT_ANALYZED_NO_NORMS

    多值字段的保存

    在同一个Document下能够给同一个字段赋不同的值.比如

    Document doc = new Document();
    for (int i = 0; i < authors.length; i++) {
          doc.add(new Field("author", authors[i],
                                        Field.Store.YES,
                                        Field.Index.ANALYZED));
    }

    LUCENE.NET QQ交流群(81361051) 

    Lucene  API

    l  被索引的文档用Document对象表示。

    l  IndexWriter通过函数addDocument将文档加入到索引中,实现                  创建索引的过程。

    l  Lucene的索引是应用反向索引。

    l  当用户有请求时,Query代表用户的查询语句。

    l  IndexSearcher通过函数search搜索Lucene Index。

    l  IndexSearcher计算term weight和score而且将结果返回给用户。

    l  返回给用户的文档集合用TopDocsCollector表示。

    Lucene搜索的api的类主要有4个 IndexSearcher ,Query(包括子类),QueryParser,Hits

    :IndexSearcher是搜索的入口,他的search方法提供了搜索功能
    Query有非常多子类, 各种不同的子类代表了不同的查询条件,下文详述
    QueryParser是一个非常通用的帮助类,他的作用是把用户输入的文本转换为内置的Query对象(大多数web搜索引擎都提供一个查询输入框来让用户输入查询条件)。QueryParser内置提供了非常多语法来使使用能够输入各种高级条件的Query。比方: "Hello AND world"会被解析为一个AND关系的BooleanQuery,他包括两个TermQuery(Hellworld)。这些语法尽管强大,但都针对英文设计,对我们须要中文搜索来说都不须要了解太多的Query类型,一般几个简单的就够用了。QueryParser的使用例如以下
    QueryParser.parse(String query, String field, Analyzer analyzer) throws ParseException
    当中:query是用户输入的内容,field是搜索默认的field(其它field须要显式指定),analyzer是用来将用户输入的内容也作分析处理(分词),普通情况下这里的anaylyzerindex的时候採用的同一analyzer
    另外我们也能够自己构造一个QueryParser: new QueryParser(String field, Analyzer a)(含义同上),这样做的优点是能够自定义调整一些參数.
    搜索结果的处理:Hits对象
    Hits对象是搜索结果的集合 主要有以下几个方法
    length() ,这种方法记录有多少条结果返回(lazy loading)
    doc(n) 返回第n个记录
    id(in) 返回第n个记录的Document ID
    score(n) n个记录的相关度(积分)
    由于搜索的结果一般比較大,从性能上考虑,Hits对象并不会真正把全部的结果全部取回,默认情况下是保留前100个记录(对于一般的搜索引擎,100个记录足够了).
    分页的处理
    100条记录还是太多,我们多半会每页显示20条记录,然后分为若干页显示,对于分页,一般有两个办法
    session中保留indexreader对象和hit对象,翻页的时候提取内容
    不使用session,每次都简单处理为又一次查询
    lucene推荐先使用第二个办法,即每次都又一次查询,这样做的优点是简单方便,不须要考虑session的问题,lucene的查询效率也能保证每次查询时间不长,除非真正有了性能问题,否则不用考虑第一个办法。
    缓存:RAMDirectory的使用方法
    RAMDirectory对象非常好用,通过它,我们能够把一个普通的index全然读取到内存中,使用方法例如以下:
    RAMDirectory ramDir = new RAMDirectory(dir);
    这种ramdir效率自然比真正的文件系统快非常多
    Lucenescoring算法
    lucence查询的纪录默认依照相关度排序,这个相关度就是score,scoring的算法是比較复杂的,对于我们做应用的人似乎没有什么帮助,(先说一下Term: 我的理解是Term为一个独立的查询词,用户输入的的查询通过各种分词,大写和小写处理(正规化),消除stopwords等)以后,会已Term为基本单位),几个关键參数略微留意一下就可以。
    Term在文章中出现的频率量,包括同一个Term的文章的频率
    field中的boosting參数
    term的长度
    term在文章中的数量
    一般来说,这些參数我们都不可能去调整假设你想了解很多其它,IndexSearcher还提供了一个explain方法通过传入一个Querydocument ID,你能够得到一个Explaination对象,他是对内部算法信息的简单封装,toString()一下就能够看到详细的说明

    :创建Query:各种query介绍
    最普通的TermQuery
    TermQuery最普通Term t=new Term("contents","cap"); new TermQuery(t)就能够构造
    TermQuery把查询条件视为一个key, 要求和查询内容全然匹配,比方Field.Keyword类型就能够使用TermQuery
    RangeQuery
    RangeQuery表示一个范围的搜索条件,RangeQuery query = new RangeQuery(begin, end, included);
    最后一个boolean值表示是否包括边界条件本身用字符表示为"[begin TO end]" 或者"{begin TO end}"
    PrefixQuery
    顾名思义,就是表示以某某开头的查询字符表示为"something*"
    BooleanQuery
    这个是一个组合的Query,你能够把各种Query加入进去并标明他们的逻辑关系,加入条件用
    public void add(Query query, boolean required, boolean prohibited)
    方法后两个boolean变量是标示AND or NOT三种关系 字符表示为" AND or NOT" 或 "+ -" ,一个BooleanQuery中能够加入多个Query, 假设超过setMaxClauseCount(int)的值(默认1024)的话,会抛出TooManyClauses错误.
    PhraseQuery
    表示不严格语句的查询,比方"red pig"要匹配"red fat pig","red fat big pig",PhraseQuery所以提供了一个setSlop()參数,在查询中,lucene会尝试调整单词的距离和位置,这个參数表示能够接受调整次数限制,假设实际的内容能够在这么多步内调整为全然匹配,那么就被视为匹配.在默认情况下slop的值是0, 所以默认是不支持非严格匹配的通过设置slop參数(比方"red pig"匹配"red fat pig"就须要1slop来把pig后移动1),我们能够让lucene来模糊查询值得注意的是,PhraseQuery不保证前后单词的次序,在上面的样例中,"pig red"须要2slop,也就是假设slop假设大于等于2,那么"pig red"也会被觉得是匹配的.
    WildcardQuery
    使用?*来表示一个或多个字母比方wil*能够匹配 wild ,wila ,wilxaaaa...,值得注意的是,wildcard,仅仅要是匹配上的纪录,他们的相关度都是一样的,比方wilxaaaawild的对于wil*的相关度就是一样的.
    FuzzyQuery
    这个Query对中文没有什么用处,他能模糊匹配英文单词(前面的都是词组),比方fuzzywuzzy他们能够看成相似对于英文的各种时态变化和复数形式,这个FuzzyQuery还算实用,匹配结果的相关度是不一样的.字符表示为 "fuzzy~"

    :QueryParser使用
    对于搜索引擎非常多情况下用户仅仅须要一个输入框就要输入全部的查询条件(比方google), 这时,QueryParser就派上用场了,他的作用就是把各种用户输入转为Query或者Query他把上面提到的Query的字符表示(Query.toString)转化为实际的Query对象,比方"wuzzy~"就会转换为FuzzyQuery, 只是QueryParser用到了Analyzer,所以QueryParser parse过后的QuerytoString未必和原来的一样.Query额外的语法有:
    分组:Groupping
    比方"(a AND b) or C",就是括号分组,非常easy理解
    FieldSelectiong
    QueryParser的查询条件是对默认的Field进行的它在QueryParser解析的时候编码指定假设用户须要在查询条件中选用另外的Field, 能够使用例如以下语法: fieldname:fielda, 假设是多个分组,能够用fieldname:(fielda fieldb fieldc)表示.
    *号问题
    QueryParse默认不同意*号出如今開始部分,这样做的目的主要是为了防止用户误输入*来头导致严重的性能问题(会把全部记录读出)
    boosting
    通过hello^2.0 能够对hello这个term进行boosting(我想不到什么用户会这样么bt)
    QueryParser是一个准备好的,马上能够工作的帮助类,只是他还是提供了非常多參数供程序猿调整,首先,我们须要自己构造一个新的QueryParser,然后对他的各种參数来定制化

    Lucene分析

    1.创建索引的步骤:

    1)把要转换为索引的磁盘上的文件转换为Luncene文档:

    Document doc = File2DocumentUtils.file2Document(filePath);

    转换代码

    public static Document file2Document(String filePath) {

    // TODO Auto-generated method stub

    File file = new File(filePath);

    Document doc = new Document();

    doc.add(new Field("name", file.getName(), Store.YES, Index.ANALYZED));

    doc.add(new Field("content", readFileContent(file), Store.YES,

    Index.ANALYZED));

    doc.add(new Field("size", String.valueOf(file.length()), Store.YES,

    Index.ANALYZED));

    doc.add(new Field("path", file.getAbsolutePath(), Store.YES,

    Index.ANALYZED));

    return doc;

    }

    读取文件内容代码

    public static String readFileContent(File file) {

    // TODO Auto-generated method stub

    try {

    BufferedReader br = new BufferedReader(new InputStreamReader(

    new FileInputStream(file)));

    StringBuffer buffer = new StringBuffer();

    for (String line; (line = br.readLine()) != null;) {

    buffer.append(line).append(" ");

    }

    return buffer.toString();

    } catch (FileNotFoundException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    return null ;

       

    }

    2)创建IndexWriter

    IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, true,

    new MaxFieldLength(10000));

    IndexWriter是用来操作(增、删、改)索引库的

    3)把document文档加到IndexWriter

    indexWriter.addDocument(doc);

    4)关闭IndexWriter

    IndexwriterClose();

    2.在索引库的搜素步骤

    1)把要搜索的索引解析为query

    String querystring="document";

    String []fields={"name","content"};

    QueryParser parser=new MultiFieldQueryParser(fields,analyzer);

    //QueryParser是一个解析用户输入的工具,能够扫描用户输入的字符串,生成query对象。

    Query query=parser.parse(querystring);

    2)进行查询

    IndexSearcher indexSearcher=new IndexSearcher(indexPath);

    Filter filter=null;

    TopDocs  topDocs=indexSearcher.search(query,(org.apache.lucene.search.Filter) filter,10000);

          System.out.println("总共同拥有【"+topDocs.totalHits+"】条匹配结果");

    注:TopDocs 依据keyword搜索整个索引库,然后对全部结果进行排序,然后取前10000条结果

    3)输出搜索结果

    for(ScoreDoc scoreDoc:topDocs.scoreDocs){

         int docSn=scoreDoc.doc;//文档内部编号

         Document doc=indexSearcher.doc(docSn);//依据编号取出对应的文档

         File2DocumentUtils.printDocumentInfo(doc);//打印出文档信息

    }

    /**

    获取name属性的值的两种方法

     1.Filed f=doc.getFiled("name");

        f.stringValue();

     2.doc.get("name")

    */

         public static void printDocumentInfo(Document doc){

          //Filed f=doc.getFiled("name");

         // f.stringValue();

          System.out.println("-------------------------------------------");

          System.out.println("name    ="+doc.get("name"));

          System.out.println("content ="+doc.get("content"));

          System.out.println("size     ="+doc.get("size"));

          System.out.println("path     ="+doc.get("path"));

         }


    本文章首次公布于我的微信公众平台,想看到很多其它最新文章,欢迎关注我的公众账号“欢子说事”,账号:‘huanzi_talk’专注于:互联网分析,读者解惑,技术分析,业界新闻分析。#欢子解惑#是为读者提供一个疑惑解答平台。假设你想提问,直接复:“#欢子解惑#+你的问题进行提问。以后我每天会选择四五个问题进行回答。在查找公众账号中查询“欢子说事”关注本账号


  • 相关阅读:
    Oracle 11g SQL Fundamentals Training Introduction02
    Chapter 05Reporting Aggregated data Using the Group Functions 01
    Chapter 01Restriicting Data Using The SQL SELECT Statemnt01
    Oracle 11g SQL Fundamentals Training Introduction01
    Chapter 04Using Conversion Functions and Conditional ExpressionsConditional Expressions
    Unix时代的开创者Ken Thompson (zz.is2120.bg57iv3)
    我心目中计算机软件科学最小必读书目 (zz.is2120)
    北京将评估分时分区单双号限行 推进错时上下班 (zz)
    佳能G系列领军相机G1X
    选购单反相机的新建议——心民谈宾得K5(转)
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4517092.html
Copyright © 2011-2022 走看看