ES概述
Elaticsearch簡稱爲es, es是一個開源的高擴展的分佈式全文檢索引擎,它可以近乎實時的存儲、檢索數據;本身擴展性很好,可以擴展到上百臺服務器,處理PB級別(大數據時代)的數據。es也使用 Java開發並使用Lucene作爲其核心來實現所有索引和搜索的功能,但是它的目的是通過簡單的RESTful API來隱藏Lucene的複雜性,從而讓全文搜索變得簡單。 據國際權威的數據庫產品評測機構DB Engines的統計,在2016年1月,ElasticSearch已超過Solr等,成 爲排名第一的搜索引擎類應用。
集成到Spring Boot
此爲原生依賴
注意:elasticsearch的依賴需要與下載的ES版本一致,本次使用的7.6.2的!!!
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
不過在SpringBoot中無需如此,直接導入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
也有最簡單的方式,在創建SpringBoot項目時直接勾選依賴組件。
導入後的項目依賴pom.xml文件爲如下,同學順便導入jackJson方便傳輸數據!!
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>top.hcode</groupId>
<artifactId>hcode-es-api-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hcode-es-api-1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!--自定義依賴版本-->
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
然後編寫配置文件,注入到Spring容器中
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(
//有幾個集羣寫幾個!!
new HttpHost("127.0.0.1",9200,"http"),
new HttpHost("127.0.0.1",9100,"http")
)
);
}
}
SpringBoot中使用ES
注入RestHighLevelClient
@Autowired
private RestHighLevelClient restHighLevelClient;
創建索引
void createIndex() throws IOException {
//創建索引請求
CreateIndexRequest index = new CreateIndexRequest("hcode_index"); //hcode_index爲索引名
//執行請求,獲得響應
CreateIndexResponse response = restHighLevelClient.indices().create(index, RequestOptions.DEFAULT);
System.out.println(response);
}
判斷索引是否存在
void ExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("hcode_index");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
刪除索引
void DeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("hcode_index");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged()); //爲true表示刪除成功
}
添加文檔
void AddDocument() throws IOException {
User user = new User("hcode", 22);
//創建索引請求
IndexRequest request = new IndexRequest("hcode_index");
//設置規則 例如相當於 PUT /hcode_index/_doc/1 命令
request.id("1").timeout(TimeValue.timeValueSeconds(1));//設置id,1秒超時
request.timeout("1s");
// 數據轉換成json 放入請求
request.source(JSON.toJSONString(user), XContentType.JSON);
//將請求發出去,獲取響應結果
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.status()); // 返回當前操作的類型:CREATE
System.out.println(indexResponse.toString()); //響應內容
}
判斷文檔是否存在
void IsExists() throws IOException {
GetRequest getRequest = new GetRequest("hcode_index", "1");
// 不獲取返回的_source 的上下文,會提高速度
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
獲取文檔的信息 GET /hcode_index/_doc/1
//相當於 GET /hcode_index/_doc/1
void getDocument() throws IOException {
GetRequest getRequest = new GetRequest("hcode_index", "1");
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString()); //獲取文檔的內容
}
更新文檔信息
void updateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("hcode_index", "1");
request.timeout("1s");
User user = new User("hzh", 18);
request.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.status()); //成功返回 OK
System.out.println(response.toString());
}
刪除文檔信息
void deleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("hcode_index", "1");
request.timeout("1s");
DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status()); //成功返回 OK
System.out.println(response.toString());
}
批量操作
void BulkRequest() throws IOException {
BulkRequest request = new BulkRequest();
request.timeout("10s");
ArrayList<Object> list = new ArrayList<>();
list.add(new User("hcode", 1));
list.add(new User("himit", 2));
list.add(new User("youth", 3));
//批量請求,批量更新,刪除都差不多!!!不設置id就會自動生成隨機id,演示爲批量插入
for (int i = 0; i < list.size(); i++) {
request.add(new IndexRequest("hcode_index")
.id("" + (i + 1))
.source(JSON.toJSONString(list.get(i)), XContentType.JSON));
}
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.hasFailures());//是否失敗,false表示成功,true表示失敗
}
搜索查詢+高亮
void Query() throws IOException {
SearchRequest request = new SearchRequest();
//創建查詢條件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 使用QueryBuilders工具,精確查詢term
//QueryBuilders.matchAllQuery() 匹配所有
TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "hcode");
//配置高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name"); //綁定屬性
highlightBuilder.requireFieldMatch(false); //關閉多個高亮,只顯示一個高亮
highlightBuilder.preTags("<p style='color:red'>"); //設置前綴
highlightBuilder.postTags("</p>"); //設置後綴
sourceBuilder.highlighter(highlightBuilder);
sourceBuilder.query(termQuery);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
request.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//獲取結果對象
SearchHits hits = response.getHits();
System.out.println(JSON.toJSONString(hits));
for (SearchHit searchHit : hits) {
//獲取高亮的html
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField name = highlightFields.get("name");
//替換原有的字段
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
if (name != null) {
Text[] fragments = name.fragments();
String light_name = "";
for (Text fragment : fragments) {
light_name += fragment;
}
sourceAsMap.put("name", light_name); //進行替換
}
System.out.println(searchHit.getSourceAsMap());
}
}