1.加入高亮的架包
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.et</groupId>
<artifactId>Lucene</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- spring boot 必需的 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<!-- 加载IKAnalyzer的架包 -->
<dependency>
<groupId>com.janeluo</groupId>
<artifactId>ikanalyzer</artifactId>
<version>2012_u6</version>
</dependency>
<!-- springboot每一个框架的集成都是一个starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 查看数据库 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 要连接的数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>
<!-- 集成mybaits -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 添加高亮的架包 -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>4.7.2</version>
</dependency>
</dependencies>
</project>
2.测试代码
package cn.et.ceshi;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
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.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wltea.analyzer.lucene.IKAnalyzer;
import cn.et.ceshi.service.LuceService;
@RestController
public class IndexDemo {
@Autowired
LuceService ls;
static String drc="E:\\index";
//定义存储目录
static Analyzer aly= new IKAnalyzer();
//搜索
@GetMapping("/solr")
public List<Map> search(String foodname) throws Exception {
Directory dr= FSDirectory.open(new File(drc));
//读取存储目录
DirectoryReader ird=DirectoryReader.open(dr);
//搜索类
IndexSearcher isearcher=new IndexSearcher(ird);
//Lucene查询解析 用于指定查询的属性名和分词器
QueryParser parser = new QueryParser(Version.LUCENE_47,"foodname", aly);
//开始搜索
Query query=parser.parse(foodname);
//最终的结果被分词后添加前缀和后缀的处理类 默认是<B></B>
SimpleHTMLFormatter htmlFormatter =new SimpleHTMLFormatter("<font color=red>","</font>");
//将高亮搜索的词 添加到高亮处理器中
Highlighter highlighter=new Highlighter(htmlFormatter,new QueryScorer(query));
//获取搜索的结果指定返回的docuemnt个数
ScoreDoc[] hits= isearcher.search(query, null, 10).scoreDocs;
List<Map> list= new ArrayList<Map>();
for(int i=0;i<hits.length;i++){
//获取单独的document
int id=hits[i].doc;
Document hitDoc = isearcher.doc(hits[i].doc);
Map map= new HashMap();
map.put("foodid", hitDoc.get("foodid"));
String foodname1 = hitDoc.get("foodname");
//将查询的结果和搜索词匹配 匹配到添加前缀的后缀高亮
TokenStream tokenStream=TokenSources.getAnyTokenStream(isearcher.getIndexReader(), id, "foodname", aly);
//传入的第二个参数是查询到的值
TextFragment [] frag=highlighter.getBestTextFragments(tokenStream, foodname1, false, 10);
String foodnamehign="";
for(int j=0;j<frag.length;j++){
if((frag[j]!=null)&&(frag[j].getScore()>0)){
foodnamehign=frag[j].toString();
}
}
map.put("foodname",foodnamehign);
map.put("price", hitDoc.get("price"));
map.put("imagepath", hitDoc.get("imagepath"));
list.add(map);
}
ird.close();
dr.close();
return list;
}
//创建索引库
@GetMapping("/writer")
public String write(){
try{
//索引库的存储目录
Directory dr= FSDirectory.open(new File(drc));
//管联Lucene版本和当前分词器
IndexWriterConfig cfi= new IndexWriterConfig(Version.LUCENE_47,aly);
//传入目录和分词器
IndexWriter iwriter = new IndexWriter(dr,cfi);
//获取总数据的个数
int queryCount=ls.queryFoodCount();
int startIndex=0;
int rows=2;
//获取数据库里的数据
while(startIndex<=queryCount){
List<Map<String, Object>> lt= ls.query(startIndex,rows);
for(Map f:lt){
//document对象Field属性
Document doc= new Document();
//TextField.TYPE_STORED 写入存储目录
Field field= new Field("foodid",f.get("foodid").toString(),TextField.TYPE_STORED);
Field field1= new Field("foodname",f.get("foodname").toString(),TextField.TYPE_STORED);
Field field2= new Field("price",f.get("price").toString(),TextField.TYPE_STORED);
Field field3= new Field("imagepath",f.get("imagepath").toString(),TextField.TYPE_STORED);
doc.add(field);
doc.add(field1);
doc.add(field2);
doc.add(field3);
//写入存储目录
iwriter.addDocument(doc);
}
startIndex+=rows;
}
iwriter.commit();
iwriter.close();
}catch(Exception e){
e.printStackTrace();
return "0";
}
return "1";
}
}
3.运行
package cn.et.ceshi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//必须添加SpringbootApplication 启用Spring的自动配置功能
//要扫描添加@ComponentScan(扫描的包名)
@SpringBootApplication
public class CeShiMain {
public static void main(String[] args) {
SpringApplication.run(CeShiMain.class, args);
}
}