elasticsearch 7.17.3下载地址:
链接:https://pan.baidu.com/s/1o30iawcZPhV6sYcd9jym9g?pwd=0nt0
提取码:0nt0
前提:需要安装elasticsearch工具
在这里插入图片描述
默认的(Developer Tools)都需要勾选,最主要的是NoSQL中选中ElasticSearch
配置编译版本
<dependency>
<groupId>co.elastic.clientsgroupId>
<artifactId>elasticsearch-javaartifactId>
<version>8.0.1version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.3version>
dependency>
<dependency>
<groupId>jakarta.jsongroupId>
<artifactId>jakarta.json-apiartifactId>
<version>2.0.1version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.12.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.12.3version>
dependency>
最终的pom文件如下
"1.0" encoding="UTF-8"?>
"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">
4.0.0</modelVersion>
org.springframework.boot</groupId>
spring-boot-starter-parent</artifactId>
2.3.4.RELEASE</version>
<!-- lookup parent from repository -->
</parent>
com.example</groupId>
es-api</artifactId>
0.0.1-SNAPSHOT</version>
es-api</name>
Demo project for Spring Boot</description>
.version>8</java.version>
</properties>
org.springframework.boot</groupId>
spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
org.springframework.boot</groupId>
spring-boot-starter-web</artifactId>
</dependency>
org.springframework.boot</groupId>
spring-boot-devtools</artifactId>
runtime</scope>
true</optional>
</dependency>
org.springframework.boot</groupId>
spring-boot-configuration-processor</artifactId>
true</optional>
</dependency>
org.projectlombok</groupId>
lombok</artifactId>
true</optional>
</dependency>
org.springframework.boot</groupId>
spring-boot-starter-test</artifactId>
test</scope>
</dependency>
co.elastic.clients</groupId>
elasticsearch-java</artifactId>
8.0.1</version>
</dependency>
com.fasterxml.jackson.core</groupId>
jackson-databind</artifactId>
2.12.3</version>
</dependency>
jakarta.json</groupId>
jakarta.json-api</artifactId>
2.0.1</version>
</dependency>
com.fasterxml.jackson.core</groupId>
jackson-annotations</artifactId>
2.12.3</version>
</dependency>
com.fasterxml.jackson.core</groupId>
jackson-core</artifactId>
2.12.3</version>
</dependency>
</dependencies>
org.springframework.boot</groupId>
spring-boot-maven-plugin</artifactId>
org.projectlombok</groupId>
lombok</artifactId>
</exclude>
</excludes>
paketobuildpacks/builder:tiny</builder>
true</BP_NATIVE_IMAGE>
</env>
</image>
</configuration>
</plugin>
</plugins>
</build>
spring-releases</id>
Spring Releases</name>
https://repo.spring.io/release</url>
false</enabled>
</snapshots>
</repository>
</repositories>
spring-releases</id>
Spring Releases</name>
https://repo.spring.io/release</url>
false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
native</id>
.classifier>exec</repackage.classifier>
.version>0.9.11</native-buildtools.version>
</properties>
</profile>
</profiles>
</project>
package com.example.esapi.common;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.ElasticsearchTransport;
import lombok.Data;
import org.elasticsearch.client.RestClient;
@Data
public class ElasticSearchResult {
private RestClient restClient;
private ElasticsearchTransport elasticsearchTransport;
private ElasticsearchClient elasticsearchClient;
public ElasticSearchResult(RestClient restClient, ElasticsearchTransport elasticsearchTransport, ElasticsearchClient elasticsearchClient) {
this.restClient = restClient;
this.elasticsearchTransport = elasticsearchTransport;
this.elasticsearchClient = elasticsearchClient;
}
}
package com.example.esapi.common;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.stereotype.Component;
@Component
public class ElasticSearchClientConnect {
public ElasticSearchResult restClient(){
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200,"http")).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
ElasticSearchResult elasticSearchResult=new ElasticSearchResult(restClient,transport,client);
return elasticSearchResult;
}
}
自此springboot集成elasticSearch已经完成,下边是应用操作。
新建User对象
package com.example.esapi.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String sex;
private Integer age;
}
应用实例
package com.example.esapi.controller;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.json.JsonData;
import com.example.esapi.common.ElasticSearchClientConnect;
import com.example.esapi.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class Testcontroller {
@Autowired
private ElasticSearchClientConnect elasticSearchClientConfig;
/**
* 新建jing_index索引
* @return
* @throws IOException
*/
@GetMapping("/getConnect")
public Boolean withdrawQueue() throws IOException {
CreateIndexResponse createIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().create(c -> c.index("jing_index"));
// 打印结果
System.out.println(createIndexResponse.acknowledged());
// 关闭连接
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
return createIndexResponse.acknowledged();
}
/**
* 查询索引
* @throws IOException
*/
@GetMapping("/select")
public void select() throws IOException {
GetIndexResponse getIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().get(e -> e.index("jing_index"));
// 打印结果
System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());
// 关闭连接
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 删除索引
* @return
* @throws IOException
*/
@GetMapping("/delete")
public Boolean delete() throws IOException {
// 删除索引
DeleteIndexResponse deleteIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().delete(e -> e.index("jing_index"));
System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());
// 关闭连接
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
return deleteIndexResponse.acknowledged();
}
/**
* 添加document
* @throws IOException
*/
@GetMapping("/addDocument")
public void addDocument() throws IOException {
// 向user对象中添加数据
User user = new User("java客户端", "男", 18);
// 向索引中添加数据
CreateResponse createResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().create(e -> e.index("jing_index").id("1001").document(user));
System.out.println("createResponse.result() = " + createResponse.result());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 查询document
* @throws IOException
*/
@GetMapping("/queryDocument")
public void queryDocument() throws IOException {
// 构建请求
GetResponse<User> getResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().get(e -> e.index("jing_index").id("1001"), User.class);
System.out.println("getResponse.source().toString() = " + getResponse.source().toString());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 修改document
* @throws IOException
*/
@GetMapping("/modifyDocument")
public void modifyDocument() throws IOException {
// 使用map集合封装需要修改的内容
Map<String, Object> map = new HashMap<>();
map.put("name", "java客户端aaa");
// 构建请求
UpdateResponse<User> updateResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().update(e -> e.index("jing_index").id("1001").doc(map), User.class);
System.out.println("updateResponse.result() = " + updateResponse.result());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 删除document
* @throws IOException
*/
@GetMapping("/removeDocument")
public void removeDocument() throws IOException {
// 构建请求
DeleteResponse deleteResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().delete(e -> e.index("jing_index").id("1001"));
System.out.println("deleteResponse.result() = " + deleteResponse.result());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 批量添加document
* @throws IOException
*/
@GetMapping("/batchAddDocument")
public void batchAddDocument() throws IOException {
// 构建一个批量数据集合
List<BulkOperation> list = new ArrayList<>();
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
// 调用bulk方法执行批量插入操作
BulkResponse bulkResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().bulk(e -> e.index("user_test").operations(list));
System.out.println("bulkResponse.items() = " + bulkResponse.items());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 批量删除document
* @throws IOException
*/
@GetMapping("/batchDeleteDocument")
public void batchDeleteDocument() throws IOException {
// 构建一个批量数据集合
List<BulkOperation> list = new ArrayList<>();
list.add(new BulkOperation.Builder().delete(
d -> d.id("1002").index("user_test")).build());
list.add(new BulkOperation.Builder().delete(
d -> d.id("1003").index("user_test")).build());
// 调用bulk方法执行批量插入操作
BulkResponse bulkResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().bulk(e -> e.index("user_test").operations(list));
System.out.println("bulkResponse.items() = " + bulkResponse.items());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 全量查询document
* @throws IOException
*/
@GetMapping("/queryAllDocument")
public void queryAllDocument() throws IOException {
// 全量查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);
HitsMetadata<User> hits = searchResponse.hits();
for (Hit<User> hit : hits.hits()) {
System.out.println("user = " + hit.source().toString());
}
System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 分页查询document
* @throws IOException
*/
@GetMapping("/pagingQueryDocument")
public void pagingQueryDocument() throws IOException {
// 分页查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(
s -> s.index("user_test")
.query(q -> q.matchAll(m -> m))
.from(0)
.size(2)
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 排序查询document
* @throws IOException
*/
@GetMapping("/sortQueryDocument")
public void sortQueryDocument() throws IOException {
// 排序查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(
s -> s.index("user_test")
.query(q -> q.matchAll(m -> m))
.sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 条件查询document
* @throws IOException
*/
@GetMapping("/conditionQueryDocument")
public void conditionQueryDocument() throws IOException {
// 条件查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(
s -> s.index("user_test").query(q -> q.matchAll(m -> m))
.sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
.source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 组合查询 must是必须满足所有条件,should只要满足一个就行
* @throws IOException
*/
@GetMapping("/combinationQueryDocument")
public void combinationQueryDocument() throws IOException {
// 组合查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(
s -> s.index("user_test").query(q -> q.bool(b -> b
.must(m -> m.match(u -> u.field("age").query(21)))
.must(m -> m.match(u -> u.field("sex").query("男")))
.mustNot(m -> m.match(u -> u.field("sex").query("女")))
))
, User.class);
//SearchResponse searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(
// s -> s.index("user_test").query(q -> q.bool(b -> b
// .should(h -> h.match(u -> u.field("age").query(19)))
// .should(h -> h.match(u -> u.field("sex").query("男")))
// ))
// , User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 范围查询
* @throws IOException
*/
@GetMapping("/scopeQueryDocument2")
public void scopeQueryDocument2() throws IOException {
// 范围查询,gte()表示取大于等于,gt()表示大于,lte()表示小于等于
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(s -> s.index("user_test").query(q -> q
.range(r -> r.field("age").gte(JsonData.of(20)).lt(JsonData.of(21))))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 模糊查询
* @throws IOException
*/
@GetMapping("/fuzzyQueryDocument2")
public void fuzzyQueryDocument2() throws IOException {
// 模糊查询,fuzziness表示差几个可以查询出来
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(s -> s.index("user_test").query(q -> q
.fuzzy(f -> f.field("name").value("tst").fuzziness("2")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 高亮查询
* @throws IOException
*/
@GetMapping("/highlightQueryDocument2")
public void highlightQueryDocument2() throws IOException {
// 高亮查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(s -> s.index("user_test").query(q -> q
.term(t -> t.field("name").value("test4")))
.highlight(h -> h.fields("name", f -> f.preTags("").postTags("")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 聚合查询
* @throws IOException
*/
@GetMapping("/aggregateQueryDocument2")
public void aggregateQueryDocument2() throws IOException {
// 聚合查询,取最大年龄
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(s -> s.index("user_test").aggregations("maxAge", a ->a.max(m -> m.field("age")))
, User.class);
searchResponse.aggregations().entrySet().forEach(f -> System.out.println(f.getKey() + ":" + f.getValue().max().value()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
/**
* 分组查询
* @throws IOException
*/
@GetMapping("/groupQueryDocument2")
public void groupQueryDocument2() throws IOException {
// 分组查询
SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().search(s -> s.index("user_test")
.aggregations("ageGroup", a ->a.terms(t -> t.field("age")))
, User.class);
searchResponse.aggregations().get("ageGroup").lterms().buckets().array().forEach(f -> System.out.println(f.key() + ":" + f.docCount()));
elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
elasticSearchClientConfig.restClient().getRestClient().close();
}
}