此筆記內(nèi)容為狂神說SpringBoot整合ElasticSearch部分
目錄
一、SpringBoot整合
1、創(chuàng)建工程
2、導(dǎo)入依賴
導(dǎo)入elasticsearch依賴
提前導(dǎo)入fastjson、lombok
3、創(chuàng)建并編寫配置類
4、創(chuàng)建并編寫實體類
5、測試
索引的操作
文檔的操作
二、ElasticSearch實戰(zhàn)
防京東商城搜索(高亮)
1、工程創(chuàng)建(springboot)
2、基本編碼
①導(dǎo)入依賴
②導(dǎo)入前端素材
③編寫?application.preperties配置文件?
④測試controller和view
⑤編寫Config?
⑥編寫service
⑦編寫controller
⑧測試結(jié)果
3、爬蟲(jsoup)
①搜索京東搜索頁面,并分析頁面
②爬取數(shù)據(jù)(獲取請求返回的頁面信息,篩選出可用的)
4、搜索高亮
①ContentService
②ContentController
③結(jié)果展示
5、前后端分離(簡單使用Vue)
①下載并引入Vue.min.js和axios.js
②修改靜態(tài)頁面
使用term(精確查詢)時遇到的問題
一、SpringBoot整合
1、創(chuàng)建工程
創(chuàng)建一個springboot項目
目錄結(jié)構(gòu)
2、導(dǎo)入依賴
注意依賴版本和安裝的版本一致
<properties>
<java.version>1.8</java.version>
<!-- 統(tǒng)一版本 -->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
導(dǎo)入elasticsearch依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
提前導(dǎo)入fastjson、lombok
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!-- lombok需要安裝插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
3、創(chuàng)建并編寫配置類
@Configuration
public class ElasticSearchConfig {
// 注冊 rest高級客戶端
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")
)
);
return client;
}
}
4、創(chuàng)建并編寫實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = -3843548915035470817L;
private String name;
private Integer age;
}
5、測試
所有測試均在?SpringbootElasticsearchApplicationTests
中編寫
注入?RestHighLevelClient
@Autowired
public RestHighLevelClient restHighLevelClient;
索引的操作
1、索引的創(chuàng)建
// 測試索引的創(chuàng)建, Request PUT liuyou_index
@Test
public void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("liuyou_index");
CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());// 查看是否創(chuàng)建成功
System.out.println(response);// 查看返回對象
restHighLevelClient.close();
}
2、索引的獲取,并判斷其是否存在
// 測試獲取索引,并判斷其是否存在
@Test
public void testIndexIsExists() throws IOException {
GetIndexRequest request = new GetIndexRequest("index");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);// 索引是否存在
restHighLevelClient.close();
}
3、索引的刪除
// 測試索引刪除
@Test
public void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("liuyou_index");
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());// 是否刪除成功
restHighLevelClient.close();
}
文檔的操作
1、文檔的添加
// 測試添加文檔(先創(chuàng)建一個User實體類,添加fastjson依賴)
@Test
public void testAddDocument() throws IOException {
// 創(chuàng)建一個User對象
User liuyou = new User("liuyou", 18);
// 創(chuàng)建請求
IndexRequest request = new IndexRequest("liuyou_index");
// 制定規(guī)則 PUT /liuyou_index/_doc/1
request.id("1");// 設(shè)置文檔ID
request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
// 將我們的數(shù)據(jù)放入請求中
request.source(JSON.toJSONString(liuyou), XContentType.JSON);
// 客戶端發(fā)送請求,獲取響應(yīng)的結(jié)果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.status());// 獲取建立索引的狀態(tài)信息 CREATED
System.out.println(response);// 查看返回內(nèi)容 IndexResponse[index=liuyou_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
}
2、文檔信息的獲取
// 測試獲得文檔信息
@Test
public void testGetDocument() throws IOException {
GetRequest request = new GetRequest("liuyou_index","1");
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());// 打印文檔內(nèi)容
System.out.println(request);// 返回的全部內(nèi)容和命令是一樣的
restHighLevelClient.close();
}
3、文檔的獲取,并判斷其是否存在
// 獲取文檔,判斷是否存在 get /liuyou_index/_doc/1
@Test
public void testDocumentIsExists() throws IOException {
GetRequest request = new GetRequest("liuyou_index", "1");
// 不獲取返回的 _source的上下文了
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");
boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
4、文檔的更新
// 測試更新文檔內(nèi)容
@Test
public void testUpdateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("liuyou_index", "1");
User user = new User("lmk",11);
request.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.status()); // OK
restHighLevelClient.close();
}
5、文檔的刪除
// 測試刪除文檔
@Test
public void testDeleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("liuyou_index", "1");
request.timeout("1s");
DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status());// OK
}
6、文檔的查詢
// 查詢
// SearchRequest 搜索請求
// SearchSourceBuilder 條件構(gòu)造
// HighlightBuilder 高亮
// TermQueryBuilder 精確查詢
// MatchAllQueryBuilder
// xxxQueryBuilder ...
@Test
public void testSearch() throws IOException {
// 1.創(chuàng)建查詢請求對象
SearchRequest searchRequest = new SearchRequest();
// 2.構(gòu)建搜索條件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// (1)查詢條件 使用QueryBuilders工具類創(chuàng)建
// 精確查詢
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "liuyou");
// // 匹配查詢
// MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
// (2)其他<可有可無>:(可以參考 SearchSourceBuilder 的字段部分)
// 設(shè)置高亮
searchSourceBuilder.highlighter(new HighlightBuilder());
// // 分頁
// searchSourceBuilder.from();
// searchSourceBuilder.size();
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// (3)條件投入
searchSourceBuilder.query(termQueryBuilder);
// 3.添加條件到請求
searchRequest.source(searchSourceBuilder);
// 4.客戶端查詢請求
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 5.查看返回結(jié)果
SearchHits hits = search.getHits();
System.out.println(JSON.toJSONString(hits));
System.out.println("=======================");
for (SearchHit documentFields : hits.getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}
前面的操作都無法批量添加數(shù)據(jù)
// 上面的這些api無法批量增加數(shù)據(jù)(只會保留最后一個source)
@Test
public void test() throws IOException {
IndexRequest request = new IndexRequest("bulk");// 沒有id會自動生成一個隨機ID
request.source(JSON.toJSONString(new User("liu",1)),XContentType.JSON);
request.source(JSON.toJSONString(new User("min",2)),XContentType.JSON);
request.source(JSON.toJSONString(new User("kai",3)),XContentType.JSON);
IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(index.status());// created
}
7、批量添加數(shù)據(jù)
// 特殊的,真的項目一般會 批量插入數(shù)據(jù)
@Test
public void testBulk() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> users = new ArrayList<>();
users.add(new User("liuyou-1",1));
users.add(new User("liuyou-2",2));
users.add(new User("liuyou-3",3));
users.add(new User("liuyou-4",4));
users.add(new User("liuyou-5",5));
users.add(new User("liuyou-6",6));
// 批量請求處理
for (int i = 0; i < users.size(); i++) {
bulkRequest.add(
// 這里是數(shù)據(jù)信息
new IndexRequest("bulk")
.id(""+(i + 1)) // 沒有設(shè)置id 會自定生成一個隨機id
.source(JSON.toJSONString(users.get(i)),XContentType.JSON)
);
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.status());// ok
}
二、ElasticSearch實戰(zhàn)
防京東商城搜索(高亮)
1、工程創(chuàng)建(springboot)
創(chuàng)建一個springboot工程
2、基本編碼
①導(dǎo)入依賴
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
<!-- jsoup解析頁面 -->
<!-- 解析網(wǎng)頁 爬視頻可 研究tiko -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!-- ElasticSearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- devtools熱部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- lombok 需要安裝插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
②導(dǎo)入前端素材
導(dǎo)入statis和templates里的文件
鏈接:百度網(wǎng)盤 請輸入提取碼
提取碼:qk8p
③編寫?application.preperties
配置文件?
# 更改端口,防止沖突
server.port=9999
# 關(guān)閉thymeleaf緩存
spring.thymeleaf.cache=false
④測試controller和view
@Controller
public class IndexController {
@GetMapping({"/","index"})
public String index(){
return "index";
}
}
?訪問 localhost:9999
到這里可以先去編寫爬蟲,編寫之后,回到這里
⑤編寫Config?
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")
)
);
return client;
}
}
⑥編寫service
因為是爬取的數(shù)據(jù),那么就不走Dao,以下編寫都不會編寫接口,開發(fā)中必須嚴格要求編寫?
ContentService?
@Service
public class ContentService {
@Autowired
private RestHighLevelClient restHighLevelClient;
// 1、解析數(shù)據(jù)放入 es 索引中
public Boolean parseContent(String keyword) throws IOException {
// 獲取內(nèi)容
List<Content> contents = HtmlParseUtil.parseJD(keyword);
// 內(nèi)容放入 es 中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m"); // 可更具實際業(yè)務(wù)是指
for (int i = 0; i < contents.size(); i++) {
bulkRequest.add(
new IndexRequest("jd_goods")
.id(""+(i+1))
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
);
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
restHighLevelClient.close();
return !bulk.hasFailures();
}
// 2、根據(jù)keyword分頁查詢結(jié)果
public List<Map<String, Object>> search(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
if (pageIndex < 0){
pageIndex = 0;
}
SearchRequest jd_goods = new SearchRequest("jd_goods");
// 創(chuàng)建搜索源建造者對象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 條件采用:精確查詢 通過keyword查字段name
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));// 60s
// 分頁
searchSourceBuilder.from(pageIndex);
searchSourceBuilder.size(pageSize);
// 高亮
// ....
// 搜索源放入搜索請求中
jd_goods.source(searchSourceBuilder);
// 執(zhí)行查詢,返回結(jié)果
SearchResponse searchResponse = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
restHighLevelClient.close();
// 解析結(jié)果
SearchHits hits = searchResponse.getHits();
List<Map<String,Object>> results = new ArrayList<>();
for (SearchHit documentFields : hits.getHits()) {
Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
results.add(sourceAsMap);
}
// 返回查詢的結(jié)果
return results;
}
}
⑦編寫controller
@Controller
public class ContentController {
@Autowired
private ContentService contentService;
@ResponseBody
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {
return contentService.parseContent(keyword);
}
@ResponseBody
@GetMapping("/search/{keyword}/{pageIndex}/{pageSize}")
public List<Map<String, Object>> parse(@PathVariable("keyword") String keyword,
@PathVariable("pageIndex") Integer pageIndex,
@PathVariable("pageSize") Integer pageSize) throws IOException {
return contentService.search(keyword,pageIndex,pageSize);
}
}
⑧測試結(jié)果
1、解析數(shù)據(jù)放入 es 索引中?
根據(jù)keyword分頁查詢結(jié)果
3、爬蟲(jsoup)
數(shù)據(jù)獲?。簲?shù)據(jù)庫、消息隊列、爬蟲、…
①搜索京東搜索頁面,并分析頁面
java - 商品搜索 - 京東
頁面如下
?審查頁面元素
頁面列表id:J_goodsList
目標元素:img、price、name
②爬取數(shù)據(jù)(獲取請求返回的頁面信息,篩選出可用的)
創(chuàng)建HtmlParseUtil,并簡單編寫
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
/// 使用前需要聯(lián)網(wǎng)
// 請求url
String url = "http://search.jd.com/search?keyword=java";
// 1.解析網(wǎng)頁(jsoup 解析返回的對象是瀏覽器Document對象)
Document document = Jsoup.parse(new URL(url), 30000);
// 使用document可以使用在js對document的所有操作
// 2.獲取元素(通過id)
Element j_goodsList = document.getElementById("J_goodsList");
// 3.獲取J_goodsList ul 每一個 li
Elements lis = j_goodsList.getElementsByTag("li");
// 4.獲取li下的 img、price、name
for (Element li : lis) {
String img = li.getElementsByTag("img").eq(0).attr("src");// 獲取li下 第一張圖片
String name = li.getElementsByClass("p-name").eq(0).text();
String price = li.getElementsByClass("p-price").eq(0).text();
System.out.println("=======================");
System.out.println("img : " + img);
System.out.println("name : " + name);
System.out.println("price : " + price);
}
}
}
運行結(jié)果
一般圖片特別多的網(wǎng)站,所有的圖片都是通過延遲加載的
// 打印標簽內(nèi)容
Elements lis = j_goodsList.getElementsByTag("li");
System.out.println(lis);
?打印所有l(wèi)i標簽,發(fā)現(xiàn)img標簽中并沒有屬性src的設(shè)置,只是data-lazy-ing設(shè)置圖片加載的地址
創(chuàng)建HtmlParseUtil、改寫
-
更改圖片獲取屬性為?
data-lazy-img
-
與實體類結(jié)合,實體類如下
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Content implements Serializable {
private static final long serialVersionUID = -8049497962627482693L;
private String name;
private String img;
private String price;
}
-
封裝為方法
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
System.out.println(parseJD("java"));
}
public static List<Content> parseJD(String keyword) throws IOException {
/// 使用前需要聯(lián)網(wǎng)
// 請求url
String url = "http://search.jd.com/search?keyword=" + keyword;
// 1.解析網(wǎng)頁(jsoup 解析返回的對象是瀏覽器Document對象)
Document document = Jsoup.parse(new URL(url), 30000);
// 使用document可以使用在js對document的所有操作
// 2.獲取元素(通過id)
Element j_goodsList = document.getElementById("J_goodsList");
// 3.獲取J_goodsList ul 每一個 li
Elements lis = j_goodsList.getElementsByTag("li");
// System.out.println(lis);
// 4.獲取li下的 img、price、name
// list存儲所有l(wèi)i下的內(nèi)容
List<Content> contents = new ArrayList<Content>();
for (Element li : lis) {
// 由于網(wǎng)站圖片使用懶加載,將src屬性替換為data-lazy-img
String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");// 獲取li下 第一張圖片
String name = li.getElementsByClass("p-name").eq(0).text();
String price = li.getElementsByClass("p-price").eq(0).text();
// 封裝為對象
Content content = new Content(name,img,price);
// 添加到list中
contents.add(content);
}
// System.out.println(contents);
// 5.返回 list
return contents;
}
}
結(jié)果展示
4、搜索高亮
在3、的基礎(chǔ)上添加內(nèi)容
①ContentService
// 3、 在2的基礎(chǔ)上進行高亮查詢
public List<Map<String, Object>> highlightSearch(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 精確查詢,添加查詢條件
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchSourceBuilder.query(termQueryBuilder);
// 分頁
searchSourceBuilder.from(pageIndex);
searchSourceBuilder.size(pageSize);
// 高亮 =========
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name");
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
// 執(zhí)行查詢
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 解析結(jié)果 ==========
SearchHits hits = searchResponse.getHits();
List<Map<String, Object>> results = new ArrayList<>();
for (SearchHit documentFields : hits.getHits()) {
// 使用新的字段值(高亮),覆蓋舊的字段值
Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
// 高亮字段
Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
HighlightField name = highlightFields.get("name");
// 替換
if (name != null){
Text[] fragments = name.fragments();
StringBuilder new_name = new StringBuilder();
for (Text text : fragments) {
new_name.append(text);
}
sourceAsMap.put("name",new_name.toString());
}
results.add(sourceAsMap);
}
return results;
}
②ContentController
@ResponseBody
@GetMapping("/h_search/{keyword}/{pageIndex}/{pageSize}")
public List<Map<String, Object>> highlightParse(@PathVariable("keyword") String keyword,
@PathVariable("pageIndex") Integer pageIndex,
@PathVariable("pageSize") Integer pageSize) throws IOException {
return contentService.highlightSearch(keyword,pageIndex,pageSize);
}
③結(jié)果展示
5、前后端分離(簡單使用Vue)
刪除Controller 方法上的?@ResponseBody注解
①下載并引入Vue.min.js和axios.js
如果安裝了nodejs,可以按如下步驟,沒有的素材里有
打開電腦cmd命令窗口,執(zhí)行以下命令
npm init
npm install vue
npm install axios
沒有axios和vue文件的網(wǎng)上下載一個就行,然后復(fù)制到項目里
?
②修改靜態(tài)頁面
引入js
<script th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
修改后的index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>狂神說Java-ES仿京東實戰(zhàn)</title>
<link rel="stylesheet" th:href="@{/css/style.css}"/>
<script th:src="@{/js/jquery.min.js}"></script>
</head>
<body class="pg">
<div class="page">
<div id="app" class=" mallist tmall- page-not-market ">
<!-- 頭部搜索 -->
<div id="header" class=" header-list-app">
<div class="headerLayout">
<div class="headerCon ">
<!-- Logo-->
<h1 id="mallLogo">
<img th:src="@{/images/jdlogo.png}" alt="">
</h1>
<div class="header-extra">
<!--搜索-->
<div id="mallSearch" class="mall-search">
<form name="searchTop" class="mallSearch-form clearfix">
<fieldset>
<legend>天貓搜索</legend>
<div class="mallSearch-input clearfix">
<div class="s-combobox" id="s-combobox-685">
<div class="s-combobox-input-wrap">
<input v-model="keyword" type="text" autocomplete="off" id="mq"
class="s-combobox-input" aria-haspopup="true">
</div>
</div>
<button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
</div>
</fieldset>
</form>
<ul class="relKeyTop">
<li><a>狂神說Java</a></li>
<li><a>狂神說前端</a></li>
<li><a>狂神說Linux</a></li>
<li><a>狂神說大數(shù)據(jù)</a></li>
<li><a>狂神聊理財</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- 商品詳情頁面 -->
<div id="content">
<div class="main">
<!-- 品牌分類 -->
<form class="navAttrsForm">
<div class="attrs j_NavAttrs" style="display:block">
<div class="brandAttr j_nav_brand">
<div class="j_Brand attr">
<div class="attrKey">
品牌
</div>
<div class="attrValues">
<ul class="av-collapse row-2">
<li><a href="#"> 狂神說 </a></li>
<li><a href="#"> Java </a></li>
</ul>
</div>
</div>
</div>
</div>
</form>
<!-- 排序規(guī)則 -->
<div class="filter clearfix">
<a class="fSort fSort-cur">綜合<i class="f-ico-arrow-d"></i></a>
<a class="fSort">人氣<i class="f-ico-arrow-d"></i></a>
<a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
<a class="fSort">銷量<i class="f-ico-arrow-d"></i></a>
<a class="fSort">價格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
</div>
<!-- 商品詳情 -->
<div class="view grid-nosku" >
<div class="product" v-for="result in results">
<div class="product-iWrap">
<!--商品封面-->
<div class="productImg-wrap">
<a class="productImg">
<img :src="result.img">
</a>
</div>
<!--價格-->
<p class="productPrice">
<em v-text="result.price"></em>
</p>
<!--標題-->
<p class="productTitle">
<a v-html="result.name"></a>
</p>
<!-- 店鋪名 -->
<div class="productShop">
<span>店鋪: 狂神說Java </span>
</div>
<!-- 成交信息 -->
<p class="productStatus">
<span>月成交<em>999筆</em></span>
<span>評價 <a>3</a></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
<script>
new Vue({
el:"#app",
data:{
"keyword": '', // 搜索的關(guān)鍵字
"results":[] // 后端返回的結(jié)果
},
methods:{
searchKey(){
var keyword = this.keyword;
console.log(keyword);
axios.get('h_search/'+keyword+'/0/20').then(response=>{
console.log(response.data);
this.results=response.data;
})
}
}
});
</script>
</body>
</html>
測試
使用term(精確查詢)時遇到的問題
字段值必須是一個詞(索引中存在的詞),才能匹配
問題:中文字符串,term查詢時無法查詢到數(shù)據(jù)(比如,“編程”兩字在文檔中存在,但是搜索不到)
原因:索引為配置中文分詞器(默認使用standard,即所有中文字符串都會被切分為單個中文漢字作為單詞),所以沒有超過1個漢字的詞,也就無法匹配,進而查不到數(shù)據(jù)
解決:創(chuàng)建索引時配置中文分詞器,如
PUT example { "mappings": { "properties": { "name":{ "type": "text", "analyzer": "ik_max_word" // ik分詞器 } } } }
查詢的英文字符只能是小寫,大寫都無效
查詢時英文單詞必須是完整的
最后附上我自己用的依賴文章來源:http://www.zghlxwxcb.cn/news/detail-475181.html
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 的客戶端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 依賴 2.x 的 log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- junit 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
?結(jié)束!文章來源地址http://www.zghlxwxcb.cn/news/detail-475181.html
到了這里,關(guān)于【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!