lucene(五) 中文分词和高亮显示



1.建立索引

package com.ljl.lucene.demo.chineseanalyzer;


import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.nio.file.Paths;

public class Indexer {

   private Integer ids[]={1,2,3};
   private String citys[]={"青岛","南京","上海"};
   private String descs[]={
         "青岛是一个美丽的城市。",
         "南京是一个有文化的城市。南京是一个文化的城市南京,简称宁,是江苏省会,地处中国东部地区,长江下游,濒江近海。全市下辖11个区,总面积6597平方公里,2013年建成区面积752.83平方公里,常住人口818.78万,其中城镇人口659.1万人。[1-4] “江南佳丽地,金陵帝王州”,南京拥有着6000多年文明史、近2600年建城史和近500年的建都史,是中国四大古都之一,有“六朝古都”、“十朝都会”之称,是中华文明的重要发祥地,历史上曾数次庇佑华夏之正朔,长期是中国南方的政治、经济、文化中心,拥有厚重的文化底蕴和丰富的历史遗存。[5-7] 南京是国家重要的科教中心,自古以来就是一座崇文重教的城市,有“天下文枢”、“东南第一学”的美誉。截至2013年,南京有高等院校75所,其中211高校8所,仅次于北京上海;国家重点实验室25所、国家重点学科169个、两院院士83人,均居中国第三。[8-10] 。",
         "上海是一个繁华的城市。"
   };

   private Directory dir;

   /**
    * 获取IndexWriter实例
    * @return
    * @throws Exception
    */
   private IndexWriter getWriter()throws Exception{
      //Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
      SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
      IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
      IndexWriter writer=new IndexWriter(dir, iwc);
      return writer;
   }

   /**
    * 生成索引
    * @param indexDir
    * @throws Exception
    */
   private void index(String indexDir)throws Exception{
      dir=FSDirectory.open(Paths.get(indexDir));
      IndexWriter writer=getWriter();
      for(int i=0;i<ids.length;i++){
         Document doc=new Document();
         //http://blog.csdn.net/john1337/article/details/62844780
         //lucene6淘汰了早期版本的IntField类,为了保持兼容早期版本采用了LegacyIntField类,但是这个类也不是推荐类,
            //lucene6推荐使用的是IntPoint类用来存储整形Field,这个类在使用时有以下几点需要注意:
//       1.如果要存储,必须创建同名的StoredField类
//       2.如果要排序使用,必须同时创建同名的StoredField类与NumericDocValuesField类
//       Demo 如下:
//       doc.add(new NumericDocValuesField("price",price));
//       doc.add(new IntPoint("price",price));
//       doc.add(new StoredField("price",price));
         doc.add(new NumericDocValuesField("id", ids[i]));
         doc.add(new IntPoint("id", ids[i]));
         doc.add(new StoredField("id",  ids[i].toString()));
         doc.add(new StringField("city",citys[i],Field.Store.YES));
         doc.add(new TextField("desc", descs[i], Field.Store.YES));
         writer.addDocument(doc); // 添加文档
      }
      writer.close();
   }


   public static void main(String[] args) throws Exception {
      new Indexer().index("D:\\lucene6");
   }

}


2.中文分词和高亮显示


package com.ljl.lucene.demo.chineseanalyzer;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
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.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

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

public class Searcher {

   public static void search(String indexDir,String q)throws Exception{
      Directory dir=FSDirectory.open(Paths.get(indexDir));
      IndexReader reader=DirectoryReader.open(dir);
      IndexSearcher is=new IndexSearcher(reader);
      // Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
      SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
      QueryParser parser=new QueryParser("desc", analyzer);
      Query query=parser.parse(q);
      long start=System.currentTimeMillis();
      TopDocs hits=is.search(query, 10);
      long end=System.currentTimeMillis();
      System.out.println("匹配 "+q+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");

      QueryScorer scorer=new QueryScorer(query);
      Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);
      SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color='red'>","</font></b>");
      Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
      highlighter.setTextFragmenter(fragmenter);
      for(ScoreDoc scoreDoc:hits.scoreDocs){
         Document doc=is.doc(scoreDoc.doc);
         System.out.println(doc.get("city"));
         System.out.println(doc.get("desc"));
         String desc=doc.get("desc");
         if(desc!=null){
            TokenStream tokenStream=analyzer.tokenStream("desc", new StringReader(desc));
            System.out.println(highlighter.getBestFragment(tokenStream, desc));
         }
      }
      reader.close();
   }

   public static void main(String[] args) {
      String indexDir="D:\\lucene6";
      String q="南京文明";
      try {
         search(indexDir,q);
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值