话不多说直接上代码,首先关注点Springboot相关ES相关的版本对应
找到对应的版本号,我这里对应7.17.1 对应的springboot版本 2.3.* 即可
上图为Springboot相关依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>7.17.1</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.17.1</version>
<exclusions>
<exclusion>
<artifactId>elasticsearch</artifactId>
<groupId>org.elasticsearch</groupId>
</exclusion>
<exclusion>
<artifactId>elasticsearch-core</artifactId>
<groupId>org.elasticsearch</groupId>
</exclusion>
</exclusions>
</dependency>
1.2创建连接
es6.0以后废除 ElasticsearchTemplate
原来9300,连接方式 换成了9200,yml/properties 切记配置文件中端口号要改成9200,9300不支持
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 lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Value("${http.port}")
private String httpPort;
两种连接方式,用那种都可以
## **第一种:**
@Bean
public ElasticsearchClient elasticsearchClient() {
HttpHost[] httpHosts = getHttpHosts();
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//账号密码
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));
RestClientBuilder builder = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestClient restClient = builder.build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
**
## 第二种:
**
@Bean
public RestHighLevelClient RestHighLevelClient() {
HttpHost[] httpHosts = getHttpHosts();
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//账号密码
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));
return new RestHighLevelClient(
RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
);
}
private HttpHost[] getHttpHosts() {
return Arrays.stream(httpPort.split(",")).map(x -> {
String[] hostInfo = x.split(":");
return new HttpHost(hostInfo[0], Integer.parseInt(hostInfo[1]));
}).toArray(HttpHost[]::new);
}
ES
创建索引以及映射相关(首先映射分词要保持环境中Es下的分词器安装正确)
//创建索引
public Boolean createEsIndex(String indexName) {
try {
// 创建索引
ElasticsearchClient client = esClientConfig.elasticsearchClient();
CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index(indexName));
// 响应状态
log.debug("增加索引操作 ===={} " + createIndexResponse.acknowledged());
} catch (IOException e) {
log.error("es InsertError----{}", e);
}
return true;
}
//删除索引
@Override
public Boolean delIndex(String indexName) {
try {
ElasticsearchClient client = esClientConfig.elasticsearchClient();
// 删除索引
DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index(indexName));
log.debug("删除操作 ===={} " + deleteIndexResponse.toString());
} catch (IOException e) {
log.error("es delError----{}", e);
}
return true;
}
对应的增删改查
//增加 文档
@Override
public Boolean createDocument() {
String indexName = "test";
try {
RestHighLevelClient restHighLevelClient = esClientConfig.RestHighLevelClient();
CreateIndexRequest request = new CreateIndexRequest(indexName);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("id");
{
builder.field("type", "long");
}
builder.endObject();
builder.startObject("title");
{
builder.field("type", "text")
//插入时分词
.field("analyzer", "ik_smart")
//搜索时分词
.field("search_analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.mapping(builder);
org.elasticsearch.client.indices.CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
log.debug("insertArticleIndex{}", createIndexResponse.toString());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
//删除文档文章来源:https://www.toymoban.com/news/detail-514845.html
@Override
public Boolean delDocument(String id,String index) {
//两种方式都可以
try {
ElasticsearchClient client = esClientConfig.elasticsearchClient();
// 构建请求
DeleteResponse delete = client.delete(e -> e.index(index).id(id));
log.debug("deleteResponse.result() = " + delete.toString());
/* RestHighLevelClient restHighLevelClient = esClientConfig.RestHighLevelClient();
DeleteRequest deleteRequest=new DeleteRequest(index);
deleteRequest.id(id);
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
log.debug("deleteResponse.result() = " + delete.getResult());*/
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
//模糊查询 增加高亮可以自行按照条件拼接文章来源地址https://www.toymoban.com/news/detail-514845.html
@Override
public List<Long> testQuery(String str, int page, int size) {
try {
if (page < 1) {
page = 1;
}
if (size < 0) {
size = 5;
}
int start = (page - 1) * size;
int end = page * size - 1;
String index = "test";
ElasticsearchClient client = esClientConfig.elasticsearchClient();
// 模糊查询,fuzziness表示差几个可以查询出来
SearchResponse<ArticleEsDO> searchResponse =
client.search(s -> s.index(index).query(q -> q.wildcard(f -> f.field("title").value("*" + str + "*"))).from(start).size(end)
, Test.class);
List<Test> collect = searchResponse.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
return collect.stream().map(ArticleEsDO::getId).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
到了这里,关于Java SpringBoot整合elasticsearch 7.17相关问题记录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!