目錄
一、Maven項目集成Easticsearch
1)客戶端對象
2)索引操作
3)文檔操作
4)高級查詢
二、springboot項目集成Spring Data操作Elasticsearch
1)pom文件
2)yaml
3)數(shù)據(jù)實體類
4)配置類
5)Dao數(shù)據(jù)訪問對象
6)索引操作
7)文檔操作
8)文檔搜索
三、springboot項目集成bboss操作elasticsearch
1)pom文件和配置
2)getConfigRestClientUtil和getRestClientUtil區(qū)別
3)創(chuàng)建索引
4)刪除索引
5)判斷索引是否存在
6)判斷索引類型是否存在
7)添加單個文檔
8)批量添加文檔
9)查詢單個文檔
一、Maven項目集成Easticsearch
????????Elasticsearch軟件是由 Java 語言開發(fā)的,所以也可以通過 Java API 的方式對 Elasticsearch服務(wù)進行訪問。 ?修改pom 文件,增加 Maven 依賴關(guān)系。
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.4.2</elasticsearch.version>
</properties>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
1)客戶端對象
????????創(chuàng)建類,代碼中創(chuàng)建 Elasticsearch 客戶端對象因為早期版本的客戶端對象已經(jīng)不再推薦使用,且在未來版本中會被刪除,所以這里我們采用高級 REST 客戶端對象;
public static void main(String[] args) throws IOException {
// 創(chuàng)建客戶端對象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
// 關(guān)閉客戶端連接
client.close();
}
2)索引操作
????????ES服務(wù)器正常啟動后,可以通過 Java API 客戶端對象對 ES 索引進行操作 ;
public class EsIndex {
public static void main(String[] args) throws IOException {
// 創(chuàng)建客戶端對象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
// 關(guān)閉客戶端連接
client.close();
}
// 創(chuàng)建索引
public static void createIndex(RestHighLevelClient client) throws IOException {
// 創(chuàng)建索引 - 請求對象
CreateIndexRequest request = new CreateIndexRequest("user");
// 發(fā)送請求,獲取響應(yīng)
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = response.isAcknowledged();
// 響應(yīng)狀態(tài)
System.out.println("操作狀態(tài) = " + acknowledged);
}
// 查看索引
public static void getIndex(RestHighLevelClient client) throws IOException {
// 查詢索引 - 請求對象
GetIndexRequest request = new GetIndexRequest("user");
// 發(fā)送請求,獲取響應(yīng)
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
System.out.println("aliases: " + response.getAliases());
System.out.println("mappings: " + response.getMappings());
System.out.println("settings: " + response.getSettings());
}
// 刪除索引
public static void deleteIndex(RestHighLevelClient client) throws IOException {
// 刪除索引 - 請求對象
DeleteIndexRequest request = new DeleteIndexRequest("user");
// 發(fā)送請求,獲取響應(yīng)
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
// 操作結(jié)果
System.out.println("操作結(jié)果: " + response.isAcknowledged());
}
}
3)文檔操作
public class EsDoc {
public static void main(String[] args) throws IOException {
// 創(chuàng)建客戶端對象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
// 關(guān)閉客戶端連接
client.close();
}
// 創(chuàng)建文檔
public static void createDoc(RestHighLevelClient client) throws IOException {
// 新增文檔 - 請求對象
IndexRequest request = new IndexRequest();
// 設(shè)置索引及唯一性標識
request.index("user").id("1001");
// 創(chuàng)建數(shù)據(jù)對象
User user = new User();
user.setAge(26);
user.setSex("男");
user.setName("jak");
ObjectMapper objectMapper = new ObjectMapper();
String productJson = objectMapper.writeValueAsString(user);
// 添加文檔數(shù)據(jù), 數(shù)據(jù)格式為Json格式
request.source(productJson, XContentType.JSON);
// 客戶端發(fā)送請求,獲取響應(yīng)對象
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("_index: " + response.getIndex());
System.out.println("id: " + response.getId());
System.out.println("_result: " + response.getResult());
}
// 修改文檔
public static void updateDoc(RestHighLevelClient client) throws IOException {
// 修改文檔 - 請求對象
UpdateRequest request = new UpdateRequest();
// 配置修改參數(shù)
request.index("user").id("1001");
// 設(shè)置請求體,對數(shù)據(jù)進行修改
request.doc(XContentType.JSON, "sex", "女");
// 客戶端發(fā)送請求,獲取響應(yīng)對象
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println("_index: " + response.getIndex());
System.out.println("_id: " + response.getId());
System.out.println("_result: " + response.getResult());
}
// 查詢文檔
public static void getDoc(RestHighLevelClient client) throws IOException {
// 創(chuàng)建請求對象
GetRequest request = new GetRequest().index("user").id("1001");
// 客戶端發(fā)送請求,獲取響應(yīng)對象
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("_index: " + response.getIndex());
System.out.println("_type: " + response.getType());
System.out.println("_id: " + response.getId());
System.out.println("source: " + response.getSourceAsString());
}
// 刪除文檔
public static void deleteDoc(RestHighLevelClient client) throws IOException {
// 創(chuàng)建請求對象
DeleteRequest request = new DeleteRequest().index("user").id("1");
// 客戶端發(fā)送請求,獲取響應(yīng)對象
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
// 打印信息
System.out.println(response.toString());
}
// 批量新增
public static void bulkCreateDoc(RestHighLevelClient client) throws IOException {
// 創(chuàng)建批量新增請求對象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu"));
// 客戶端發(fā)送請求,獲取響應(yīng)對象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("took: " + responses.getTook());
System.out.println("items: " + Arrays.toString(responses.getItems()));
}
// 批量刪除
public static void bulkDeleteDoc(RestHighLevelClient client) throws IOException {
// 創(chuàng)建批量刪除請求對象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
// 客戶端發(fā)送請求,獲取響應(yīng)對象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("took: " + responses.getTook());
System.out.println("items: " + Arrays.toString(responses.getItems()));
}
}
4)高級查詢
public class EsSearch {
public static void main(String[] args) throws IOException {
// 創(chuàng)建客戶端對象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
// 關(guān)閉客戶端連接
client.close();
}
// 查詢所有索引數(shù)據(jù)
public static void matchAllQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.matchAllQuery());
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// term查詢,查詢條件為關(guān)鍵字
public static void termQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.termQuery("age", "30"));
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 分頁查詢
public static void pageQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 分頁查詢
// 當前頁起始索引(第一條數(shù)據(jù)的順序號),from
sourceBuilder.from(0);
// 每頁顯示多少條size
sourceBuilder.size(2);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 數(shù)據(jù)排序
public static void sortOrderQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 排序
sourceBuilder.sort("age", SortOrder.ASC);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 過濾字段
public static void filterFieldsQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 查詢字段過濾
String[] excludes = {};
String[] includes = {"name", "age"};
sourceBuilder.fetchSource(includes, excludes);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// Bool查詢
public static void boolQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必須包含
boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
// 一定不含
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
// 可能包含
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
// 查詢所有數(shù)據(jù)
sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 范圍查詢
public static void rangeQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
// 大于等于
rangeQuery.gte("30");
// 小于等于
rangeQuery.lte("40");
// 查詢所有數(shù)據(jù)
sourceBuilder.query(rangeQuery);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 范圍查詢
public static void fuzzyQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查詢所有數(shù)據(jù)
sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE));
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 高亮查詢
public static void highLightQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 構(gòu)建查詢方式: 高亮查詢
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
// 設(shè)置查詢方式
sourceBuilder.query(termsQueryBuilder);
// 構(gòu)建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 設(shè)置標簽前綴
highlightBuilder.preTags("<font color='red'>");
// 設(shè)置標簽后綴
highlightBuilder.postTags("</font>");
// 設(shè)置高亮字段
highlightBuilder.field("name");
// 設(shè)置高亮構(gòu)建對象
sourceBuilder.highlighter(highlightBuilder);
// 設(shè)置請求體
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 聚合查詢
public static void AggrQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
// 設(shè)置請求體
request.source(sourceBuilder);
// 客戶端發(fā)送請求,獲取響應(yīng)對象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
// 分組統(tǒng)計
public static void groupQuery(RestHighLevelClient client) throws IOException {
// 創(chuàng)建搜索請求對象
SearchRequest request = new SearchRequest();
request.indices("student");
// 構(gòu)建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(AggregationBuilders.terms("age_group_by").field("age"));
// 設(shè)置請求體
request.source(sourceBuilder);
// 客戶端發(fā)送請求,獲取響應(yīng)對象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查詢匹配
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook());
System.out.println("timeout: " + response.isTimedOut());
System.out.println("total: " + hits.getTotalHits());
System.out.println("MaxScore: " + hits.getMaxScore());
System.out.println("hits------------->");
for (SearchHit hit : hits) {
// 輸出每條查詢的結(jié)果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<-----------------");
}
}
二、springboot項目集成Spring Data操作Elasticsearch
????????Spring Data是一個用于簡化數(shù)據(jù)庫、非關(guān)系型數(shù)據(jù)庫、索引庫訪問,并支持云服務(wù)的開源框架。 ?其主要目標是使得對數(shù)據(jù)的訪問變得方便快捷,并支持 map reduce 框架和云計算數(shù)據(jù)服務(wù)。 Spring Data 可以極大的簡化 JPA Elasticsearch …)的寫法,可以在幾乎不用寫實現(xiàn)的情況下,實現(xiàn)對數(shù)據(jù)的訪問和操作。 ?除了 CRUD 外,還包括如分頁、排序等一些常用的功能。官網(wǎng)地址:https://spring.io/projects/spring-data
????????Spring Data Elasticsearch基于 spring data API 簡化 Elasticsearch 操作,將原始操作Elasticsearch 的客戶端 API 進行封裝 。 Spring Data 為 Elasticsearch 項目提供集成搜索引擎。 ?Spring Data Elasticsearch POJO 的關(guān)鍵功能區(qū)域為中心的模型與 Elastichsearch 交互文檔和輕松地編寫一個存儲索引庫數(shù)據(jù)訪問層。
1)pom文件
<?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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.best</groupId>
<artifactId>best-es</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>best-es</name>
<description>Demo project for Spring Boot</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</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-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2)yaml
# 端口號
server:
port: 8080
# es服務(wù)地址與端口
elasticsearch:
host: 127.0.0.1
port: 9200
# 配置日志級別,開啟debug日志
logging:
level:
com:
best: debug
3)數(shù)據(jù)實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "shopping", shards = 3, replicas = 1)
public class Product {
// 商品唯一標識, 必須有id, 這里的id 是全局唯一的標識,等同于es中的"_id"
@Id
private Long id;
/**
* type: 字段數(shù)據(jù)類型
* analyzer: 分詞器類型
* index: 是否索引(默認:true)
* Keyword: 短語, 不進行分詞
*/
// 商品名稱
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title;
// 分類名稱
@Field(type = FieldType.Keyword)
private String category;
// 商品價格
@Field(type = FieldType.Double)
private Double price;
// 圖片地址
@Field(type = FieldType.Keyword, index = false)
private String images;
}
4)配置類
????????ElasticsearchRestTemplate是spring-data-elasticsearch項目中的一個類,和其他spring項目中的 template類似。在新版的spring-data-elasticsearch 中,ElasticsearchRestTemplate 代替了原來的ElasticsearchTemplate。原因是ElasticsearchTemplate基于TransportClient,TransportClient即將在8.x 以后的版本中移除。
????????我們推薦使用ElasticsearchRestTemplate。ElasticsearchRestTemplate基于RestHighLevelClient客戶端的。需要自定義配置類,繼承AbstractElasticsearchConfiguration,并實現(xiàn)elasticsearchClient()抽象方法,創(chuàng)建RestHighLevelClient對象。
AbstractElasticsearchConfiguration源碼:
public abstract class AbstractElasticsearchConfiguration extends ElasticsearchConfigurationSupport {
//需重寫本方法
public abstract RestHighLevelClient elasticsearchClient();
@Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
}
}
????????需要自定義配置類,繼承AbstractElasticsearchConfiguration,并實現(xiàn)elasticsearchClient()抽象方法,創(chuàng)建RestHighLevelClient對象。?
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
private String host;
private Integer port;
@Override
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
return new RestHighLevelClient(builder);
}
}
5)Dao數(shù)據(jù)訪問對象
@Repository
public interface ProductDao extends ElasticsearchRepository<Product, Long> {
}
6)索引操作
@SpringBootTest
class BestEsApplicationTests {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
public void creatIndex() {
// 創(chuàng)建索引并增加映射配置
// 創(chuàng)建索引,系統(tǒng)初始化會自動創(chuàng)建索引
System.out.println("創(chuàng)建索引");
}
@Test
public void deleteIndex() {
boolean flag = elasticsearchRestTemplate.deleteIndex(Product.class);
System.out.println("刪除索引: " + flag);
}
}
7)文檔操作
@SpringBootTest
public class SpringDataEsProductDaoTest {
@Autowired
private ProductDao productDao;
/**
* 新增
*/
@Test
public void save(){
Product product = new Product();
product.setId(2L);
product.setTitle("華為手機");
product.setCategory("手機");
product.setPrice(2999.0);
product.setImages("http://www.test/hw.jpg");
productDao.save(product);
}
//POSTMAN, GET http://localhost:9200/shopping/_doc/2
//修改
@Test
public void update(){
Product product = new Product();
product.setId(2L);
product.setTitle("小米 2 手機");
product.setCategory("手機");
product.setPrice(9999.0);
product.setImages("http://www.test/xm.jpg");
productDao.save(product);
}
//POSTMAN, GET http://localhost:9200/shopping/_doc/2
//根據(jù) id 查詢
@Test
public void findById(){
Product product = productDao.findById(2L).get();
System.out.println(product);
}
@Test
public void findAll(){
Iterable<Product> products = productDao.findAll();
for (Product product : products) {
System.out.println(product);
}
}
//刪除
@Test
public void delete(){
Product product = new Product();
product.setId(2L);
productDao.delete(product);
}
//POSTMAN, GET http://localhost:9200/shopping/_doc/2
//批量新增
@Test
public void saveAll(){
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Product product = new Product();
product.setId(Long.valueOf(i));
product.setTitle("["+i+"]小米手機");
product.setCategory("手機");
product.setPrice(1999.0 + i);
product.setImages("http://www.test/xm.jpg");
productList.add(product);
}
productDao.saveAll(productList);
}
//分頁查詢
@Test
public void findByPageable(){
//設(shè)置排序(排序方式,正序還是倒序,排序的 id)
Sort sort = Sort.by(Sort.Direction.DESC,"id");
int currentPage=0;//當前頁,第一頁從 0 開始, 1 表示第二頁
int pageSize = 5;//每頁顯示多少條
//設(shè)置查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
//分頁查詢
Page<Product> productPage = productDao.findAll(pageRequest);
for (Product Product : productPage.getContent()) {
System.out.println(Product);
}
}
}
8)文檔搜索
@SpringBootTest
public class SpringDataEsSearchTest {
@Autowired
private ProductDao productDao;
/**
* term 查詢
* search(termQueryBuilder) 調(diào)用搜索方法,參數(shù)查詢構(gòu)建器對象
*/
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
Iterable<Product> products = productDao.search(termQueryBuilder);
for (Product product : products) {
System.out.println(product);
}
}
/**
* term 查詢加分頁
*/
@Test
public void termQueryByPage(){
int currentPage= 0 ;
int pageSize = 5;
//設(shè)置查詢分頁
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手機");
Iterable<Product> products =
productDao.search(termQueryBuilder,pageRequest);
for (Product product : products) {
System.out.println(product);
}
}
}
參考原文地址:?
三、springboot項目集成bboss操作elasticsearch
1)pom文件和配置
pom文件引入依賴:
<dependency>
<groupId>com.bbossgroups.plugins</groupId>
<artifactId>bboss-elasticsearch-rest-jdbc</artifactId>
<version>6.1.8</version>
</dependency>
<dependency>
<groupId>com.bbossgroups.plugins</groupId>
<artifactId>bboss-elasticsearch-spring-boot-starter</artifactId>
<version>6.1.8</version>
</dependency>
application.properties配置:
##ES集群配置,支持x-pack和searchguard
#spring.elasticsearch.bboss.elasticUser=elastic
#spring.elasticsearch.bboss.elasticPassword=changeme
spring.elasticsearch.bboss.elasticsearch.rest.hostNames=192.168.57.128:9200
#spring.elasticsearch.bboss.elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
##https配置,添加https://協(xié)議頭
#spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=https://10.180.211.27:9280,https://10.180.211.27:9281,https://10.180.211.27:9282
spring.elasticsearch.bboss.elasticsearch.dateFormat=yyyy.MM.dd
spring.elasticsearch.bboss.elasticsearch.timeZone=Asia/Shanghai
spring.elasticsearch.bboss.elasticsearch.ttl=2d
#在控制臺輸出腳本調(diào)試開關(guān)showTemplate,false關(guān)閉,true打開,同時log4j至少是info級別
spring.elasticsearch.bboss.elasticsearch.showTemplate=true
spring.elasticsearch.bboss.elasticsearch.discoverHost=false
# dsl配置文件熱加載掃描時間間隔,毫秒為單位,默認5秒掃描一次,<= 0時關(guān)閉掃描機制
spring.elasticsearch.bboss.dslfile.refreshInterval = -1
##es client http連接池配置
spring.elasticsearch.bboss.http.timeoutConnection = 50000
spring.elasticsearch.bboss.http.timeoutSocket = 50000
spring.elasticsearch.bboss.http.connectionRequestTimeout=50000
spring.elasticsearch.bboss.http.retryTime = 1
spring.elasticsearch.bboss.http.maxLineLength = -1
spring.elasticsearch.bboss.http.maxHeaderCount = 200
spring.elasticsearch.bboss.http.maxTotal = 400
spring.elasticsearch.bboss.http.defaultMaxPerRoute = 200
spring.elasticsearch.bboss.http.soReuseAddress = false
spring.elasticsearch.bboss.http.soKeepAlive = false
spring.elasticsearch.bboss.http.timeToLive = 3600000
spring.elasticsearch.bboss.http.keepAlive = 3600000
spring.elasticsearch.bboss.http.keystore =
spring.elasticsearch.bboss.http.keyPassword =
# ssl 主機名稱校驗,是否采用default配置,
# 如果指定為default,就采用DefaultHostnameVerifier,否則采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
spring.elasticsearch.bboss.http.hostnameVerifier =
2)getConfigRestClientUtil和getRestClientUtil區(qū)別
1. getConfigRestClientUtil獲取在配置文件中根據(jù)DSL名稱定義的DSL并執(zhí)行它:
<properties>
<!--
sql query
-->
<property name="sqlQuery">
<!\[CDATA\[
{"query": "SELECT * FROM dbclobdemo where channelId=#\[channelId\]"}
\]\]>
</property>
</properties>
寫入的params參數(shù)在xml文件中通過 #[參數(shù)名] 來自動注入到?DSL中
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/sql.xml");//define an instanceof ConfigRestClientUtil,It's single instance, multithreaded secure.
Map params = new HashMap();
params.put("channelId",1);
List<Map> json = clientUtil.sql(Map.class,"sqlQuery",params);
2. getRestClientUtil直接執(zhí)行代碼中定義的DSL:
ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();//define an instanceof RestClientUtil,It's single instance, multithreaded secure.
List<Map> json = clientUtil.sql(Map.class,"{\\"query\\": \\"SELECT * FROM demo\\"}");
3)創(chuàng)建索引
1.普通創(chuàng)建
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*創(chuàng)建索引
*/
@Test
public void createIndex(){
String result = bbossESStarter.getRestClient().createIndiceMapping("blog","");
System.out.println(result);
}
}
2.自定義mapping
先創(chuàng)建一個dsl腳本文件,在里面自定義mapping規(guī)則:
<propertys>
<property name="create51jobIndex">//每個property中的name屬性表示當前mapping的命名,一個xml文件里可設(shè)置多個dsl腳本
<![CDATA[{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"index.refresh_interval": "5s"
},
"mappings": {
"properties": {
"job":{
"type":"text"
},
"company": {
"type": "text"
},
"place": {
"type": "text"
},
"salar": {
"type": "text"
},
"data": {
"type": "date",
"format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
}
}
}
}]]>
</property>
</propertys>
然后創(chuàng)建客戶端,并且調(diào)用創(chuàng)建索引api:文章來源:http://www.zghlxwxcb.cn/news/detail-408012.html
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*創(chuàng)建索引
*/
@Test
public void createIndex(){
ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/job.xml");
String result = clientUtil.createIndiceMapping("51job","create51jobIndex");
System.out.println(result);
}
}
4)刪除索引
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*刪除索引
*/
@Test
public void dropIndex(){
String result = bbossESStarter.getRestClient().dropIndice("blog");
System.out.println(result);
}
}
5)判斷索引是否存在
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*判斷索引是否存在
*/
@Test
public void indexIsExists(){
boolean exist = bbossESStarter.getRestClient().existIndice("51job");
System.out.println(exist);
}
}
6)判斷索引類型是否存在
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*判斷索引類型是否存在
*/
@Test
public void typeIsExists(){
boolean exist = bbossESStarter.getRestClient().existIndiceType("51job","_doc");
System.out.println(exist);
}
}
7)添加單個文檔
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*指定索引添加單個文檔
*/
@Test
public void addDocument(){
Qcpage qcpage=new Qcpage();
qcpage.setCompany("xxxxxx有限公司").setData("2022-11-22 21:18:12").setJob("Java開發(fā)工程師").setPlace("深圳南山").setSalar("13000/月");
String result = bbossESStarter.getRestClient().addDocument("51job",qcpage);
System.out.println(result);
}
}
8)批量添加文檔
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
@Autowired
QcpageService qcpageService;
/**
*批量添加文檔(此處從mysql取出來1300條數(shù)據(jù)測試)
*/
@Test
public void batchAddDocument(){
List<Qcpage> list=qcpageService.list();
long startTime = System.currentTimeMillis();
String result = bbossESStarter.getRestClient().addDocuments("51job",list);
long endTime = System.currentTimeMillis();
System.out.println("添加"+list.size()+"條數(shù)據(jù)耗時:" + (endTime - startTime)/1000 + "s");
System.out.println(result);
}
}
9)查詢單個文檔
@SpringBootTest
class EsBbossTest {
@Autowired
private BBossESStarter bbossESStarter;
/**
*查詢一個文檔
*/
@Test
public void getDocument(){
String result = bbossESStarter.getRestClient().getDocument("51job","7pJsGXMBBreT5daW4X1w");
System.out.println(result);
}
}
參考原文地址:http://t.csdn.cn/hm0y7文章來源地址http://www.zghlxwxcb.cn/news/detail-408012.html
到了這里,關(guān)于【Elasticsearch學(xué)習(xí)筆記五】es常用的JAVA API、es整合SpringBoot項目中使用、利用JAVA代碼操作es、RestHighLevelClient客戶端對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!