九、SpringBoot整合Elasticsearch
上一篇文章《ElasticSearch - 過(guò)濾查詢》
9.1 基本環(huán)境配置
- 創(chuàng)建一個(gè)springboot工程springboot-elasticsearch
- 在
pom.xml
導(dǎo)入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
【注意】使用的springboot需要根當(dāng)前ES版本兼容
- 配置
application.yml
文件
# 應(yīng)用名稱
spring:
application:
name: springboot-elasticsearch
# web端口號(hào)
server:
port: 3035
# 自定義es主機(jī)和端口號(hào):
es:
host: 192.168.159.100:9200
- 配置客戶端
創(chuàng)建config包,添加配置類RestClientConfiguration.class
package com.vinjcent.config;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
// ES 配置類
@Configuration
public class RestClientConfiguration extends AbstractElasticsearchConfiguration {
@Value("${es.host}")
private String host;
@Bean
@Override // ES 兩個(gè)端口,一個(gè)是9200(rest方式通信),一個(gè)是9300(tcp方式通信)
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(host)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
配置完之后,該配置類不僅會(huì)創(chuàng)建RestHighLevelClient的bean,還會(huì)幫我們創(chuàng)建一個(gè)叫做ElasticsearchOperations客戶端對(duì)象
為什么要提供這兩個(gè)對(duì)象呢?
因?yàn)镾pring Data在封裝ES操作的時(shí)候,完全站在了兩個(gè)角度去考慮
- ElasticsearchOperations這個(gè)bean在操作ES的時(shí)候,主要以對(duì)象作為基礎(chǔ)去操作,ElasticsearchOperations序列化對(duì)象之后傳遞給ES,ES在查詢到結(jié)果之后,反序列化傳遞給ElasticsearchOperations
- RestHighLevelClient更像于可視化的Kibana,通過(guò)rest的方式與ES進(jìn)行交互(企業(yè)多用,推薦使用)
9.2 ElasticsearchOperations
- 特點(diǎn):始終使用面向?qū)ο蠓绞讲僮鱁S
- 索引:用來(lái)存放相似文檔的集合
- 映射:用來(lái)決定放入文檔的每個(gè)字段以什么樣方式錄入到ES中,字段類型、字段分詞器…
- 文檔:可以被索引最小單元,json數(shù)據(jù)格式
使用ElasticsearchOperations進(jìn)行增刪查改操作
- 創(chuàng)建一個(gè)Product實(shí)體類
package com.vinjcent.pojo;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
/**
* @Document: 將這個(gè)類對(duì)象轉(zhuǎn)為 es 中一條文檔進(jìn)行錄入
* indexName: 用來(lái)指定文檔的索引名稱
* createIndex: 用來(lái)指定是否創(chuàng)建索引,默認(rèn)為false
*/
@Document(indexName = "products", createIndex = true)
public class Product implements Serializable {
@Id // 用來(lái)將放入對(duì)象id值作為文檔_id進(jìn)行映射
private Integer id;
@Field(type = FieldType.Keyword) // 字段映射類型
private String title;
@Field(type = FieldType.Double)
private Double price;
@Field(type = FieldType.Text)
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", title='" + title + '\'' +
", price=" + price +
", description='" + description + '\'' +
'}';
}
}
- 在使用SpringBoot操作之前,將索引記錄刪除
# 查詢索引
GET /_cat/indices?v
# 刪除索引
DELETE /product
# 查看索引映射
GET /products/_mapping
# 查看數(shù)據(jù)
GET /products/_search
{
"query": {
"match_all": {}
}
}
- 使用Java操作ES進(jìn)行增、刪、查、改、
package com.vinjcent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vinjcent.pojo.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;
@SpringBootTest
public class ElasticSearchOperationsTest{
private final ElasticsearchOperations elasticsearchOperations;
@Autowired
public ElasticSearchOperationsTest(ElasticsearchOperations elasticsearchOperations) {
this.elasticsearchOperations = elasticsearchOperations;
}
/**
* save 索引一條文檔 或 更新一條文檔
* save 方法當(dāng)文檔id不存在時(shí)添加文檔,當(dāng)文檔id存在時(shí)候更新文檔
*/
@Test
public void testSave() {
Product product = new Product();
product.setId(1);
product.setPrice(2.5);
product.setTitle("vinjcent的妙妙屋");
product.setDescription("真是米奇妙妙屋,妙到了家");
elasticsearchOperations.save(product);
}
/**
* query 根據(jù)id查詢一條文檔
*/
@Test
public void testQuery() {
Product product = elasticsearchOperations.get("1", Product.class);
System.out.println(product);
}
/**
* delete 根據(jù)id刪除一條文檔
*/
@Test
public void testDelete() {
Product product = new Product();
product.setId(1);
String delete = elasticsearchOperations.delete(product);
System.out.println(delete);
}
/**
* delete 刪除所有
*/
@Test
public void testDeleteAll() {
elasticsearchOperations.delete(Query.findAll(), Product.class);
}
/**
* 查詢所有
*/
@Test
public void testQueryAll() throws JsonProcessingException {
SearchHits<Product> productSearchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
System.out.println("總分?jǐn)?shù): " + productSearchHits.getMaxScore());
System.out.println("符合條件總數(shù): " + productSearchHits.getTotalHits());
for (SearchHit<Product> productSearchHit : productSearchHits) {
System.out.println(new ObjectMapper().writeValueAsString(productSearchHit.getContent()));
}
}
}
9.3 RestHighLevelClient
使用RestHighLevelClient進(jìn)行索引操作
- 在使用SpringBoot操作之前,將索引記錄刪除
# 查詢索引
GET /_cat/indices?v
# 刪除索引
DELETE /products
# 查看數(shù)據(jù)
GET /products/_search
{
"query": {
"match_all": {}
}
}
- 測(cè)試類RestHighLevelClientTests.class
package com.vinjcent;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class RestHighLevelClientTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* 創(chuàng)建索引、映射
*/
@Test
public void testIndexAndMapping() throws IOException {
// 1.創(chuàng)建索引請(qǐng)求對(duì)象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
// 2.指定映射,參數(shù)1: 指定映射json結(jié)構(gòu) 參數(shù)2: 指定映射類型
createIndexRequest.mapping("{\n" +
" \"properties\": {\n" +
" \"title\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"price\": {\n" +
" \"type\": \"double\"\n" +
" },\n" +
" \"create_time\": {\n" +
" \"type\": \"date\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"text\", \n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" }", XContentType.JSON);
// 參數(shù)1: 創(chuàng)建索引請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("創(chuàng)建狀態(tài): " + createIndexResponse.isAcknowledged());
restHighLevelClient.close(); // 關(guān)閉資源
}
/**
* 刪除索引
* @throws IOException
*/
@Test
public void testDeleteIndex() throws IOException {
// 參數(shù)1: 創(chuàng)建索引請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
System.out.println(acknowledgedResponse.isAcknowledged());
}
}
使用RestHighLevelClient進(jìn)文檔操作文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-625501.html
package com.vinjcent;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class RestHighLevelClientForDocumentTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* 創(chuàng)建一條文檔
* @throws IOException
*/
@Test
public void testCreateDocu() throws IOException {
// 1.創(chuàng)建索引對(duì)象
IndexRequest indexRequest = new IndexRequest("products");
// 2.配置創(chuàng)建的文檔對(duì)象
indexRequest.id("1") // 手動(dòng)指定文檔的id
.source("{\n" + // 文檔的數(shù)據(jù)內(nèi)容
" \"title\": \"vinjcent米奇妙妙屋\",\n" +
" \"price\": 21.5,\n" +
" \"create_time\": \"2022-09-16\",\n" +
" \"description\": \"真是妙到家了!\"\n" +
"}",XContentType.JSON);
// 3.接收請(qǐng)求后的索引響應(yīng)對(duì)象,參數(shù)1: 索引請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.status());
}
/**
* 更新一條文檔
* @throws IOException
*/
@Test
public void testUpdateDocu() throws IOException {
// 1.創(chuàng)建更新請(qǐng)求對(duì)象
UpdateRequest updateRequest = new UpdateRequest("products", "2");
// 2.配置doc文檔對(duì)象
updateRequest.doc("{\n" +
" \"title\": \"totoro--的米奇妙妙屋\"\n" +
" }", XContentType.JSON);
// 參數(shù)1: 更新請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
/**
* 刪除一條文檔
* @throws IOException
*/
@Test
public void testDeleteDocu() throws IOException {
// 參數(shù)1: 更新請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
DeleteResponse deleteResponse = restHighLevelClient.delete(new DeleteRequest("products", "2"), RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
/**
* 基于id查詢一條文檔
* @throws IOException
*/
@Test
public void testQueryByIdDocu() throws IOException {
// 1.聲明get請(qǐng)求對(duì)象
GetRequest getRequest = new GetRequest("products", "1");
// 2.接收響應(yīng)對(duì)象 參數(shù)1: 獲取請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println("id: " + getResponse.getId());
System.out.println("source: " + getResponse.getSourceAsString());
}
}
9.4 RestHighLevelClient 查詢操作
package com.vinjcent;
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.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class RestHighLevelClientForDocumentTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* 查詢所有
*/
@Test
public void testMatchAll() throws IOException {
// 1.搜索請(qǐng)求對(duì)象
SearchRequest searchRequest = new SearchRequest("products");
// 2.指定條件對(duì)象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3.配置請(qǐng)求對(duì)象中的條件對(duì)象
searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 查詢所有
searchRequest.source(searchSourceBuilder);
// 參數(shù)1: 搜索的請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象 返回值: 擦汗尋結(jié)果對(duì)象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());
// 獲取結(jié)果
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
String id = hit.getId();
System.out.println("source: " + hit.getSourceAsString());
}
}
/**
* 關(guān)鍵字查詢 term
*/
@Test
public void testTerm() throws IOException {
query(QueryBuilders.termQuery("description","真是"));
}
/**
* 范圍查詢 range
*/
@Test
public void testRange() throws IOException {
query(QueryBuilders.rangeQuery("price").gt(0).lt(50));
}
/**
* 前綴查詢 prefix
*/
@Test
public void testPrefix() throws IOException {
query(QueryBuilders.prefixQuery("title", "vinjcent"));
}
/**
* 通配符查詢 wildcard
*/
@Test
public void testWildcard() throws IOException {
// "*"代表多個(gè)字符,"?"代表一個(gè)字符
query(QueryBuilders.wildcardQuery("title", "vinjcent*"));
}
/**
* 多id查詢 ids
*/
@Test
public void testIds() throws IOException {
// "*"代表多個(gè)字符,"?"代表一個(gè)字符
query(QueryBuilders.idsQuery().addIds("1","2"));
}
/**
* 多字段查詢 multi_match
*/
@Test
public void testMultiMatch() throws IOException {
// 如果查的字段分詞,會(huì)先進(jìn)行分詞處理,否則不進(jìn)行分詞處理
query(QueryBuilders.multiMatchQuery("妙", "title","description"));
}
public void query(QueryBuilder queryBuilder) throws IOException {
// 1.搜索請(qǐng)求對(duì)象
SearchRequest searchRequest = new SearchRequest("products");
// 2.指定條件對(duì)象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3.配置請(qǐng)求對(duì)象中的條件對(duì)象
searchSourceBuilder.query(queryBuilder); // 關(guān)鍵字
searchRequest.source(searchSourceBuilder);
// 參數(shù)1: 搜索的請(qǐng)求對(duì)象 參數(shù)2: 請(qǐng)求配置對(duì)象 返回值: 擦汗尋結(jié)果對(duì)象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());
// 獲取結(jié)果
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
}
}
}
9.5 RestHighLevelClient 高亮、分頁(yè)、排序
package com.vinjcent;
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.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.Map;
@SpringBootTest
public class RestHighLevelClientForDocumentTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* 分頁(yè)查詢 from 起始位置 size 分頁(yè)大小
* 排序查詢 sort
* 指定字段獲取 _source
* 高亮查詢 highlight
* @throws IOException
*/
@Test
public void testSearch() throws IOException {
// 1.創(chuàng)建請(qǐng)求索引對(duì)象
SearchRequest searchRequest = new SearchRequest("products");
// 2.創(chuàng)建搜索條件對(duì)象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3.創(chuàng)建高亮對(duì)象
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.requireFieldMatch(false) // 注意: 開(kāi)啟高亮的字段必須可以分詞,不然查詢結(jié)果無(wú)效
.preTags("<span style='color: red;'>") // 配置高亮包裹前綴
.postTags("</span>") // 配置高亮包裹后綴
.field("description") // 指定高亮字段
.field("title"); // 指定高亮字段
searchSourceBuilder.query(QueryBuilders.termQuery("description", "妙"))
.from(0) // 起始位置
.size(2) // 分頁(yè)大小,默認(rèn)返回是10條
.sort("price", SortOrder.DESC) // 指定排序字段以及排序方式
.fetchSource(null, new String[]{"create_time"}) // 參數(shù)1: 包含字段數(shù)組 參數(shù)2: 排除字段數(shù)組 注意,當(dāng)兩者結(jié)合使用時(shí),只有前者會(huì)生效
.highlighter(highlightBuilder);
// 4.為請(qǐng)求對(duì)象配置搜素對(duì)象
searchRequest.source(searchSourceBuilder);
// 5.接收響應(yīng)對(duì)象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());
// 獲取結(jié)果
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
// 獲取高亮字段description
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (highlightFields.containsKey("description")) {
System.out.println("description高亮結(jié)果: " + highlightFields.get("description").fragments()[0]); // 獲取的字段為數(shù)組形式
}
// 獲取高亮字段title
if (highlightFields.containsKey("title")) {
System.out.println("title高亮結(jié)果: " + highlightFields.get("title").fragments()[0]); // 獲取的字段為數(shù)組形式
}
}
}
}
9.6 RestHighLevelClient 過(guò)濾查詢
package com.vinjcent;
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.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.Map;
@SpringBootTest
public class RestHighLevelClientForDocumentTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* query 精確查詢,查詢計(jì)算文檔得分,并根據(jù)文檔得分進(jìn)行返回
* filter query 過(guò)濾查詢,用來(lái)在大量數(shù)據(jù)中篩選出本地查詢相關(guān)數(shù)據(jù),不會(huì)計(jì)算文檔得分,會(huì)對(duì)數(shù)據(jù)進(jìn)行緩存
* 注意: 當(dāng)兩種查詢一起使用時(shí),ES優(yōu)先執(zhí)行filter query,后執(zhí)行query
*/
@Test
public void testFilterQuery() throws IOException {
// 1.創(chuàng)建請(qǐng)求索引對(duì)象
SearchRequest searchRequest = new SearchRequest("products");
// 2.創(chuàng)建搜索條件對(duì)象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3.配置查詢條件
searchSourceBuilder
.query(QueryBuilders.matchAllQuery())
// ids、exists、term、terms、range等等都可以修改
.postFilter(QueryBuilders.termQuery("description", "妙"));
// 4.為請(qǐng)求對(duì)象配置搜素對(duì)象
searchRequest.source(searchSourceBuilder);
// 5.接收響應(yīng)對(duì)象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());
// 獲取結(jié)果
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
}
}
}
9.7 RestHighLevelClient 應(yīng)用使用JSON
package com.vinjcent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vinjcent.pojo.Product;
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.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SpringBootTest
public class RestHighLevelClientForDocumentTests {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* 在有索引映射的條件下
* 將對(duì)象放入ES中,進(jìn)行序列化操作
*/
@Test
public void testAddDoc() throws IOException {
Product product = new Product();
product.setId(2);
product.setPrice(5.2);
product.setTitle("vinjcent米奇妙妙屋");
product.setDescription("我的心可不冷");
IndexRequest indexRequest = new IndexRequest("products");
indexRequest.id(product.getId().toString())
.source(new ObjectMapper().writeValueAsString(product), XContentType.JSON); // 使用spring中自帶的json對(duì)象轉(zhuǎn)換
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.status());
}
/**
* 將對(duì)象從ES中讀取,進(jìn)行反序列化
*/
@Test
public void testGetDoc() throws IOException {
// 1.創(chuàng)建請(qǐng)求對(duì)象
SearchRequest searchRequest = new SearchRequest("products");
// 2.創(chuàng)建搜索條件對(duì)象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3. 高亮對(duì)象
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder
.requireFieldMatch(false)
.field("description")
.preTags("<span style='color: red;'>")
.postTags("</span>");
// 4.指定查詢條件
searchSourceBuilder
.query(QueryBuilders.termQuery("description", "絕境"))
.from(0)
.size(10)
.highlighter(highlightBuilder);
// 5.為請(qǐng)求對(duì)象配置條件對(duì)象
searchRequest.source(searchSourceBuilder);
// 6.接收響應(yīng)對(duì)象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());
List<Product> products = new ArrayList<>();
// 獲取響應(yīng)結(jié)果對(duì)象
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString()); // json格式
Product product = new ObjectMapper().readValue(hit.getSourceAsString(), Product.class); // 將json轉(zhuǎn)為Product對(duì)象
// 處理高亮
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (highlightFields.containsKey("description")) {
// 獲取高亮后的屬性值,進(jìn)行修改
product.setDescription(highlightFields.get("description").fragments()[0].toString());
}
products.add(product);
}
for (Product product : products) {
System.out.println(product);
}
}
}
下一篇文章《ElasticSearch - 聚合查詢》文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-625501.html
到了這里,關(guān)于ElasticSearch(九)【SpringBoot整合】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!