spring 如何使用稳定的RestHighLevelClient与ElasticSearch?

im9ewurl  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(320)

我已经搜索了这么多的职位,但我找不到一个适当的方式来使用ElasticSearch与Spring Boot 应用程序,因为我是完全新的ElasticSearch。
我唯一的依赖项是: Boot
我的配置类是:

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@Configuration
@EnableElasticsearchRepositories(basePackages = "com.backend.repository.elasticsearchrepository")
@ComponentScan(basePackages = {"com.backend.model.elasticsearchmodel"})
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {

    @Value("${spring.elasticsearch.url}")
    public String elasticsearchUrl;

    @Value("${spring.elasticsearch.username}")
    public String username;

    @Value("${spring.elasticsearch.password}")
    public String password;

    @Bean
    @Override
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration config = ClientConfiguration.builder()
                .connectedTo(elasticsearchUrl)
                .withBasicAuth(username, password)
                .build();

        return RestClients.create(config).rest();
    }
}

在这里,RestHighLevelClient显示为已弃用。我的存储库类是:

package com.backend.repository.elasticsearchrepository;

import com.backend.model.elasticsearchmodel.EsOffice;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.UUID;

public interface ESOfficeRepository extends ElasticsearchRepository<EsOffice, UUID> {
}

当我调用这个存储库的方法时,它工作正常,但是在存储数据时,它返回错误消息,即使它成功地添加了数据。

2022-10-15 00:00:15.608 ERROR 51607 --- [nio-8080-exec-2] c.a.a.exception.GlobalExceptionHandler   : Unable to parse response body for Response{requestLine=POST /office/_doc?timeout=1m HTTP/1.1, host=http://localhost:9200, response=HTTP/1.1 201 Created}; nested exception is java.lang.RuntimeException: Unable to parse response body for Response{requestLine=POST /office/_doc?timeout=1m HTTP/1.1, host=http://localhost:9200, response=HTTP/1.1 201 Created}

我应该使用哪个POM依赖项+什么类型的仓库,以及我如何在我的配置文件中配置它?我需要这3个相互兼容的仓库?

cvxl0en2

cvxl0en21#

Spring Data Elasticsearch 4.4(由Sping Boot 2.7.3引入)是使用版本7.17中的Elasticsearch库构建的,当在版本8中的Elasticsearch集群上运行时,这是有问题的。您基本上有两种选择:
1.如果可能,请将群集降级到版本7.17.6(当前可用的最新版本7.17)。
1.您可以尝试设置兼容性头(更多信息请参见Spring Data Elasticsearch文档的5.3.1节)。这应该可以工作,但是我遇到了来自集群的响应仍然无法用7.17客户端读取的情况。-我用Elasticsearch打开了一些问题,这些问题已经解决了,但是仍然可能存在隐藏的陷阱。

相关问题