Spring-Boot-连接-Elasticsearch-备忘

以下备忘 Spring Boot 项目使用 transport client 连接 Elasticsearch 的方式。

1. Pom.xml

添加如下依赖:

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.1</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.4.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>

注意,这里对 log4j 的依赖引用,是为了解决以下报错:

NoClassDefFoundError: org/apache/logging/log4j/Logger

2. 添加 Client Bean

@Slf4j
@Configuration
public class ESClientConfiguration {

    @Bean
    public Client client() {
        TransportClient client = null;
        try {
            Settings settings = Settings.builder()
                    .put("client.transport.sniff", true)
                    .put("cluster.name", "xxxx")
                    .put("client.transport.ping_timeout", "3s")
                    .build();
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300)))
                    .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300)))
                    .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxx.xxx.xxx.xxx", 9300)));
            return client;
        } catch (Throwable e) {
            log.error("@@@@", e);
        }
        return client;
    }
}

注:Elasticsearch Http 端口和 TCP 端口不同,切勿写错。

3. 使用

@Autowired
private Client client;

SearchResponse searchResponse = client.prepareSearch("index").setQuery(
        QueryBuilders.boolQuery().should(xxx).should(xxx)
).get();
SearchHit[] hits = searchResponse.getHits().getHits();

参考连接

  1. elasticsearch bool query combine must with OR – Stack Overflow
  2. How to query for null values? – Elasticsearch – Grafana Community
  3. elasticsearch – How to connect Elastic search 5.4 to tcp in java? – Stack Overflow
  4. Issue with elastic search 5.0.0 – NoClassDefFoundError: org/apache/logging/log4j/Logger – Elasticsearch – Discuss the Elastic Stack
  5. How to use Java API to build a nested query with filter query combination in 5.6.x? – Elasticsearch – Discuss the Elastic Stack
  6. Combining bool and range queries – Elasticsearch – Discuss the Elastic Stack
  7. [](https://blog.csdn.net/qq_3216…
  8. [](https://blog.csdn.net/c511362…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理