lucene封裝的web應用
目錄
一.提供的訪問接口
創建內部一個叫做index01的索引,添加easydb中商品數據的document到索引文件;
訪問一個叫做index01的索引,利用field值和value值傳遞的參數,做一個搜索商品數據返回的功能;TermQuery
二.創建一個springboot的工程
1.springboot標準工程
1.相關依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql -->
<!-- mybatis -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency> <!-- 查詢相關jar包 -->
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>6.0.0</version>
</dependency>
<dependency> <!-- lucene自帶只能中文分詞器jar包 -->
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-smartcn</artifactId>
<version>6.0.0</version>
</dependency>
<dependency> <!-- 測試用到的lucene工具包 -->
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>6.0.0</version>
</dependency>
<dependency> <!-- 測試用到的lucene核心包 -->
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
2.application.properties
server.port=8093
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///easydb?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
mybatis.configuration.mapUnderscoreToCamelCase=true
mybatis.mapperLocations=classpath:mapper/*.xml
mybatis.typeAliasesPackage=com.jt.pojo
3.啓動類StarterLucene
package com.jt;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.jt.mapper")
public class StarterLucene {
public static void main(String[] args) {
SpringApplication.run(StarterLucene.class, args);
}
}
4.引入lucene依賴
查看上次博客寫的關於Lucene博客,手動配置
三.編寫具體功能
3.1.1創建 IndexController類
@RestController
public class IndexController {
@Autowired
private IndexService indexService;
//根據參數創建本地文件夾索引文件位置輸入數據庫數據
@RequestMapping("{indexName}/add")
public String createIndex(@PathVariable String indexName) throws Exception{
indexService.addIndex(indexName);
return "success";
}
3.1.2IndexService類
@Service
public class IndexService {
@Autowired
private IndexMapper indexMapper;
public void addIndex(String indexName) throws Exception {
//指向這個文件 定義當前工程根目錄
FSDirectory dir =
FSDirectory.open(Paths.get(indexName)); //相對路徑Paths.get(indexName)
//準備一個輸入流對象
Analyzer a=new SmartChineseAnalyzer(); //分詞器
IndexWriterConfig config=new IndexWriterConfig(a);
//追加或者創建,有就追加沒有就創建
config.setOpenMode(OpenMode.CREATE);
IndexWriter writer=new IndexWriter(dir,config);
//準備document數據寫入到索引文件中
//調用持久層將t_product表格數據封裝成document寫入索引
//查詢數據庫數據 select * from t_product
List<Product> pList=indexMapper.queryProducts(); //去數據庫查詢
for (Product product : pList) {
//name,id,image,price 數據庫裏面的數據 大概60來條
Document doc=new Document();
doc.add(new TextField("name",product.getProductName(),Store.YES));
doc.add(new StringField("id", product.getProductId(), Store.YES));
doc.add(new StringField("image",product.getProductImgurl(),Store.YES));
doc.add(new StringField("price",product.getProductPrice()+"",Store.YES));
doc.add(new DoublePoint("price",product.getProductPrice()));//搜到,還要拿到
//添加到索引中
writer.addDocument(doc);
}
writer.commit();
}
3.1.3IndexMapper接口
package com.jt.mapper;
import java.util.List;
import com.jt.pojo.Product;
public interface IndexMapper {
List<Product> queryProducts();
}
3.1.4IndexMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jt.mapper.IndexMapper">
<select id="queryProducts" resultType="Product">
select * from t_product;
</select>
</mapper>
3.1.5測試結果:
3.2.1 現實查詢條件功能
利用termquery查詢返回查詢的結果集 List<product>
3.2.2IndexController類
@RequestMapping("{indexName}/search")
public List<Product> search(@PathVariable String indexName,String field,String value){
List<Product> pList=indexService.search(indexName,field,value);
return pList;
}
3.2.3IndexService類
public List<Product> search(String indexName,String field, String value) {
try{
Path path = Paths.get(indexName);
FSDirectory dir = FSDirectory.open(path);
//2 構造一個搜索對象,包裝一個reader輸入流
IndexReader reader=DirectoryReader.open(dir);
IndexSearcher search=new IndexSearcher(reader);
//3 構造詞項查詢條件TermQuery
//查詢的對應域名稱,和使用的詞語,封裝詞項對象
Term term=new Term(field,value);//content name
Query query=new TermQuery(term);
//4查詢獲取結果集,從結果集中獲取document的id
TopDocs topDocs = search.search(query, 10);//results 從結果中查到最前的幾條
//遍歷獲取id,通過id獲取整整的數據對象document,觀察每個document
//對不不同查詢條件的評分是不一樣的;
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//獲取的document封裝productList
List<Product> pList=new ArrayList<Product>();
for (ScoreDoc scoreDoc : scoreDocs) {
Product p=new Product();
int id = scoreDoc.doc;
Document doc=search.doc(id);
p.setProductId(doc.get("id"));
p.setProductName(doc.get("name"));
p.setProductImgurl(doc.get("image"));
p.setProductPrice(Double.parseDouble(doc.get("price")+""));
pList.add(p);
}
return pList;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
3.2.4測試結果
ps:可以使用多域查詢
總結:
只是爲了拋磚引玉Elasticsearch,通過自己定義的Web應用方式實現提供對外的兩個接口簡單功能,瞭解整體流程即可