SpringBoot整合ElasticSearch 入門demo學習筆記
1、概述
Elaticsearch ,簡稱為es,es是一個開源的高擴 展的基於java開發的分散式全文檢索引擎,它可以近乎實時的儲存、檢索資料;本身擴充套件性很好可以擴充套件到上百臺伺服器,處理PB級別的資料。es也使用Java開發並使用Lucene作為其核心來實現所有索引和搜尋的功能,但是它的目的是通過簡單的RESTful API來隱藏Lucene的複雜性,從而讓全文搜尋變得簡單。
2、SpringBoot整合ES
pom.xml:引入ES客戶端
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
程式碼框架圖:
package com.jason.es.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MallElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient()
{
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
package com.jason.es.bean;
import java.util.Date;
public class Info {
private int age;
private double money;
private String address;
private Date birthday;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.jason.es.bean;
public class ResponseBean {
//狀態碼
private Integer code;
//返回資訊
private String message;
//返回的資料
private Object data;
public ResponseBean(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
package com.jason.es.controller;
import com.alibaba.fastjson.JSONObject;
import com.jason.es.Service.InfoService;
import com.jason.es.bean.ResponseBean;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
@RestController
@RequestMapping(value="/info",produces = "application/json;charset=utf-8")
public class InfoController {
public Logger logger= LoggerFactory.getLogger(InfoController.class);
@Autowired
private RestHighLevelClient client;
@Autowired
public InfoService infoService;
@RequestMapping("save")
public ResponseBean save() throws IOException {
return infoService.save(client);
}
@RequestMapping("query")
public ResponseBean query(HttpServletRequest request) throws IOException {
Map<String, String[]> parameterMap = request.getParameterMap();
return infoService.query(client,parameterMap);
}
}
package com.jason.es.Service;
import com.alibaba.fastjson.JSONObject;
import com.jason.es.bean.Info;
import com.jason.es.bean.ResponseBean;
import com.jason.util.Sequence;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
@Service
public class InfoService {
public Logger logger= LoggerFactory.getLogger(InfoService.class);
public ResponseBean save(RestHighLevelClient client) {
IndexRequest indexRequest = new IndexRequest("info","info");
//indexRequest.id(""+ Sequence.getNextCurval());
// indexRequest.source("userName", "zhangsan", "age", "18");
Info info=new Info();
info.setName("jason");
info.setAge(18);
info.setMoney(18);
info.setAddress("易購樓");
info.setBirthday(new Date(System.currentTimeMillis()));
String jsonString = JSONObject.toJSONString(info);
// 必須指定XContentType
indexRequest.source(jsonString, XContentType.JSON);
ResponseBean responseBean=null;
// 執行
try{
logger.info("--"+client);
client.index(indexRequest, RequestOptions.DEFAULT);
responseBean=new ResponseBean(200,"success",null);
}catch (Exception e)
{
e.printStackTrace();
responseBean=new ResponseBean(300,"exception",e);
}
return responseBean;
}
public ResponseBean query(RestHighLevelClient client, Map<String, String[]> parameterMap) {
ResponseBean responseBean=null;
if(parameterMap==null)
{
return responseBean=new ResponseBean(300,"查詢入參為空,請輸入查詢條件重新提交!!!",null);
}
// 建立檢索請求
Se
archRequest searchRequest = new SearchRequest();
// 指定索引
searchRequest.indices("info");
String age[]=parameterMap.get("age");
// 指定DSL
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("age", age[0]));
// // 按照年齡的值分佈進行聚合
// searchSourceBuilder.aggregation(AggregationBuilders.terms("aggAge").field("age").size(10));
// // 計算平均薪資
// searchSourceBuilder.aggregation(AggregationBuilders.avg("balanceAvg").field("balance"));
logger.info("檢索條件"+searchSourceBuilder.toString());
searchRequest.source(searchSourceBuilder);
// 同步執行(也可以使用非同步)
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = searchResponse.getHits().getHits();
responseBean=new ResponseBean(200,"success",hits);
} catch (IOException e) {
responseBean=new ResponseBean(300,"exception",e);
}
return responseBean;
}
}
索引查詢:
相關文章
- Elasticsearch入門學習重點筆記Elasticsearch筆記
- Elasticsearch學習(三)springboot整合ElasticSearchElasticsearchSpring Boot
- 『Material Design入門學習筆記』動畫(含demo)Material Design筆記動畫
- 『Material Design入門學習筆記』RecyclerView與CardView(附demo)Material Design筆記View
- Elasticsearch學習<四>SpringBoot整合esElasticsearchSpring Boot
- Elasticsearch學習筆記Elasticsearch筆記
- 『Material Design入門學習筆記』TabLayout與NestedScrollView(附demo)Material Design筆記TabLayoutView
- TS入門學習筆記筆記
- 【PostgreSQL】入門學習筆記SQL筆記
- git入門學習筆記Git筆記
- Docker入門學習筆記Docker筆記
- Unity學習筆記--入門Unity筆記
- ActionScript 學習筆記(入門)筆記
- Ajax學習筆記demo筆記
- JavaScript入門學習學習筆記(上)JavaScript筆記
- Go 入門指南學習筆記Go筆記
- React入門指南(學習筆記)React筆記
- pandas 學習筆記 (入門篇)筆記
- HTML入門學習筆記(二)HTML筆記
- MySQL學習筆記---入門使用MySql筆記
- JavaScript入門-學習筆記(一)JavaScript筆記
- Dubbo學習筆記(一) 入門筆記
- golang入門學習筆記(一)Golang筆記
- Kotlin 入門學習筆記Kotlin筆記
- LDA入門級學習筆記LDA筆記
- 『Material Design入門學習筆記』主題與AppCompatActivity(附demo)Material Design筆記APP
- 『Material Design 入門學習筆記』CollapsingToolbarLayout 與 AppBarLayout(附 demo)Material Design筆記APP
- Nacos整合學習入門
- Elasticsearch的配置學習筆記Elasticsearch筆記
- 【MongoDB學習筆記】MongoDB 快速入門MongoDB筆記
- java學習筆記1(入門級)Java筆記
- JavaScript學習筆記1—快速入門JavaScript筆記
- 安卓學習筆記20:Fragment入門安卓筆記Fragment
- 爬蟲入門學習筆記3爬蟲筆記
- node 學習筆記 基礎入門筆記
- webpack 學習筆記:入門介紹Web筆記
- 【Laravel 入門教程】學習筆記 1Laravel筆記
- 微信小程式入門學習筆記微信小程式筆記