lucene 中文分词和结果高亮显示

要使用中文分词要加入新的依赖  smartcn

<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-smartcn -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-analyzers-smartcn</artifactId>
    <version>5.3.1</version>
</dependency>

高亮显示需要依赖 highlighter

<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-highlighter -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-highlighter</artifactId>
    <version>5.3.1</version>

</dependency>


下面是需要的所有的依赖:

<dependencies>
  <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-core -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>5.3.1</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-queryparser -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-queryparser</artifactId>
    <version>5.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-common -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-analyzers-common</artifactId>
    <version>5.3.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-smartcn -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-analyzers-smartcn</artifactId>
    <version>5.3.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-highlighter -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-highlighter</artifactId>
    <version>5.3.1</version>
</dependency>

  </dependencies>


中文要实现中文分词SmartChineseAnalyze  使用标准分词分的结果就是将每个汉字都拆分开。

下面是实例:

    首先准备文档内容,建立索引。

        private Integer[] ids = {1,2,3};
private String[] citys = {"北京","上海","广州"};
private String[] descs = {
"北京是一个美丽的城市。",
"上海,简称“沪”或“申”,是中国共产党的诞生地,中华人民共和国直辖市,国家中心城市,超大城市,沪杭甬大湾区核心城市,国际经济、金融、贸易、航运、科技创新中心[1-2]  ,首批沿海开放城市。上海地处长江入海口,是长江经济带的龙头城市,隔东中国海与日本九州岛相望,南濒杭州湾,北、西与江苏、浙江两省相接。[3-5] 春秋战国时期,上海是楚国春申君黄歇的封邑,故别称申。四、五世纪晋朝时期,因渔民创造捕鱼工具“扈”,江流入海处称“渎”,因此松江下游一带称为“扈渎”,以后又改“沪”,故上海简称“沪”。[6-7]  唐朝置华亭县。上海是国家历史文化名城,拥有深厚的近代城市文化底蕴和众多历史古迹。江浙吴越文化与西方传入的工业文化相融合形成上海特有的海派文化。[8-9]  1843年后上海成为对外开放的商埠并迅速发展成为远东第一大城市。[10-11]。",
"广州是一个繁华的城市。"
};

private Directory dir;

/**
* 获取到IndexWriter的实例
* @return
*/
private IndexWriter getWriter() throws Exception{
// TODO Auto-generated method stub
//Analyzer analyzer = new StandardAnalyzer();  //标准分词器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();  //中文分词器
IndexWriterConfig conf = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(dir, conf);
return writer;
}

/**
* 生成索引
* @throws Exception
*/
public void index(String indexDir) throws Exception {
//获取到索引输出的目录
dir = FSDirectory.open(Paths.get(indexDir));
IndexWriter writer = getWriter();
//新建document对象  将数据加入
for(int i = 0; i < ids.length; i++){
Document document = new Document();
document.add(new IntField("id", ids[i], Field.Store.YES));
document.add(new StringField("city", citys[i], Field.Store.YES));
document.add(new TextField("desc",descs[i], Field.Store.YES));
writer.addDocument(document);
}
writer.close();
}

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

}


建立索引之后就开始查询,查询结果高亮显示。

        /**
* 查询关键字
* @param indexDir  传入索引的目录
* @param str
* @throws Exception
*/
public static void search(String indexDir,String str) 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(str);
long start = System.currentTimeMillis();
TopDocs hits = is.search(query, 10);  //查询前10条数据
long end = System.currentTimeMillis();
System.out.println("查询"+str+" 一共花费"+(end-start)+"毫秒,一共出现了"+hits.totalHits+"次");

//高亮显示
SimpleHTMLFormatter shf = new SimpleHTMLFormatter("<b><font color='red'>","</font></b>");  // 默认不传参数是粗体显示
QueryScorer scorer = new QueryScorer(query);  //计算得分  将得分高的片段显示出来
Fragmenter fragmenter = new SimpleSpanFragmenter(scorer); //显示部分内容
Highlighter highlighter = new Highlighter(shf, scorer); 
highlighter.setTextFragmenter(fragmenter); 


//便利查询到的doc
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 && !"".equals(desc)){
TokenStream tokenStream = analyzer.tokenStream("desc", new StringReader(desc));
String result = highlighter.getBestFragment(tokenStream, desc);

System.out.println(result);
}
}
reader.close();
}

public static void main(String[] args) {
String indexDir = "D:\\lucene2";
String str = "上海城市 ";
try {
search(indexDir,str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


最终查询的结果:


猜你喜欢

转载自blog.csdn.net/csdn_wangchen/article/details/79361213