目录
SpringBoot整合ES
在SpringBoot中提供了一个类RestHight,该类封装了对ES操作的方法
1.1导入依赖
<?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.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.funian</groupId>
<artifactId>SpringBoot-ES</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-ES</name>
<description>SpringBoot-ES</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2创建一个配置类
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 EsConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
new HttpHost("localhost", 9200, "http")
));
return client;
}
}
1.3操作ES索引
@Autowired
private RestHighLevelClient client;
1.得到索引对象
2.操作索引对象
1.3.1创建索引
//创建索引 PUT /索引名 _doc7.x及以后不再添加类型
@Test
void testCreateIndex() throws IOException {
//得到索引对象
IndicesClient indices = client.indices();
//创建索引的请求对象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("funian-es02");
CreateIndexResponse indexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = indexResponse.isAcknowledged();
System.out.println("是否创建索引成功:"+acknowledged);
}
1.3.2查询索引是否存在
//判断索引是否存在
@Test
public void testIndexExists() throws IOException {
GetIndexRequest getIndexRequest = new GetIndexRequest("funian-es02");
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println("索引是否存在:"+exists);
}
2.3.3删除索引
```java
//删除索引 DELETE /索引名
@Test
public void testDeleteIndex() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("funian-es02");
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = delete.isAcknowledged();
System.out.println("是否删除成功:"+acknowledged);
}
1.4操作ES文档
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private Integer age;
private String hobby;
private String address;
}
1.4.1添加文档
//添加文档
@Test
public void testSaveDoc() throws IOException {
IndexRequest indexRequest = new IndexRequest("funian-es02");
//若没有添加id,则ES自动生成id的值
indexRequest.id("1");
User user = new User("孔夫子", 36, "抡语", "鲁国");
indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
DocWriteResponse.Result result = indexResponse.getResult();
System.out.println(result);//created成功
}
1.4.2获取文档
//获取文档 id
@Test
public void testGetDoc() throws IOException {
GetRequest getRequest = new GetRequest("funian-es02");
getRequest.id("1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//Map<String, Object> source = getResponse.getSource();
Map<String, Object> source = getResponse.getSourceAsMap();
//String source = getResponse.getSourceAsString();
System.out.println(source);
}
1.4.3修改文档
#POST允许部分修改
POST /funian-es02/_update/1
{
"doc": {
"name":"孟轲"
}
}
//修改文档
@Test
public void testUpdateDoc() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("funian-es02","1");
User user = new User();
user.setName("少司命");
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.getResult());
}
1.4.4删除文档
//删除文档
@Test
public void testDeleteDoc() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("funian-es02","1");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.getResult());
}
1.4.5批量添加文档
//批量添加
@Test
public void testBulkDoc() throws IOException {
BulkRequest bulkRequest = new BulkRequest("funian-es02");
List<User> list = new ArrayList<>();
list.add(new User("岳不群-华山掌门", 5, "君子", "华山"));
list.add(new User("宁中则-华山掌门夫人", 4, "君子", "华山"));
list.add(new User("令狐冲-华山弃徒", 3, "独孤", "恒山"));
list.add(new User("岳灵珊-华山掌门独女", 2, "冲灵", "抚远镖局"));
list.add(new User("冲虚-武当掌门", 5, "太极", "武当山"));
list.add(new User("方证-少林方丈", 5, "般若", "少林寺"));
list.add(new User("天门道长-泰山掌门", 4, "岱宗", "泰山派"));
for (User user:list) {
IndexRequest indexRequest = new IndexRequest("funian-es02");
indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.hasFailures());
}
1.4.6搜索文档
//搜索查询
@Test
public void testSearchDoc() throws IOException {
SearchRequest searchRequest = new SearchRequest("funian-es02");
//构建一个条件类对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//查询参数
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "岳则");
searchSourceBuilder.query(matchQueryBuilder);
//高亮查询
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name");
highlightBuilder.requireFieldMatch(false); //多个单词高亮的话,要把这个设置为trues
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
//构建分页
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest,RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println("获取高亮字段:");
for (SearchHit hit : hits) {
System.out.println(hit.getHighlightFields());
}
System.out.println("满足条件的总条数:"+hits.getTotalHits().value);
System.out.println("获取当前页的记录:");
SearchHit[] hitsHits = hits.getHits();
System.out.println(Arrays.toString(hitsHits));
}